BindingFlags.Public needed here as Exception.HResult is now public in .NET 4.5. This...
[mono.git] / mono / mini / aot-compiler.c
1 /*
2  * aot-compiler.c: mono Ahead of Time compiler
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Zoltan Varga (vargaz@gmail.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  * Copyright 2003-2011 Novell, Inc 
10  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
11  */
12
13 /* Remaining AOT-only work:
14  * - optimize the trampolines, generate more code in the arch files.
15  * - make things more consistent with how elf works, for example, use ELF 
16  *   relocations.
17  * Remaining generics sharing work:
18  * - optimize the size of the data which is encoded.
19  * - optimize the runtime loading of data:
20  *   - the trampoline code calls mono_jit_info_table_find () to find the rgctx, 
21  *     which loads the debugging+exception handling info for the method. This is a 
22  *     huge waste of time and code, since the rgctx structure is currently empty.
23  */
24 #include "config.h"
25 #include <sys/types.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #ifdef HAVE_STDINT_H
30 #include <stdint.h>
31 #endif
32 #include <fcntl.h>
33 #include <ctype.h>
34 #include <string.h>
35 #ifndef HOST_WIN32
36 #include <sys/time.h>
37 #else
38 #include <winsock2.h>
39 #include <windows.h>
40 #endif
41
42 #include <errno.h>
43 #include <sys/stat.h>
44
45
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger-internal.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
64
65 #include "mini.h"
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
68
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
70
71 #if defined(__linux__) || defined(__native_client_codegen__)
72 #define RODATA_SECT ".rodata"
73 #else
74 #define RODATA_SECT ".text"
75 #endif
76
77 #define TV_DECLARE(name) gint64 name
78 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
79 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
80
81 #ifdef TARGET_WIN32
82 #define SHARED_EXT ".dll"
83 #elif defined(__ppc__) && defined(__APPLE__)
84 #define SHARED_EXT ".dylib"
85 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
86 #define SHARED_EXT ".dylib"
87 #else
88 #define SHARED_EXT ".so"
89 #endif
90
91 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
92 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
93 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
94
95 /* predefined values for static readonly fields without needed to run the .cctor */
96 typedef struct _ReadOnlyValue ReadOnlyValue;
97 struct _ReadOnlyValue {
98         ReadOnlyValue *next;
99         char *name;
100         int type; /* to be used later for typechecking to prevent user errors */
101         union {
102                 guint8 i1;
103                 guint16 i2;
104                 guint32 i4;
105                 guint64 i8;
106                 gpointer ptr;
107         } value;
108 };
109 static ReadOnlyValue *readonly_values = NULL;
110
111 typedef struct MonoAotOptions {
112         char *outfile;
113         gboolean save_temps;
114         gboolean write_symbols;
115         gboolean metadata_only;
116         gboolean bind_to_runtime_version;
117         gboolean full_aot;
118         gboolean no_dlsym;
119         gboolean static_link;
120         gboolean asm_only;
121         gboolean asm_writer;
122         gboolean nodebug;
123         gboolean soft_debug;
124         gboolean log_generics;
125         gboolean direct_pinvoke;
126         gboolean direct_icalls;
127         int nthreads;
128         int ntrampolines;
129         int nrgctx_trampolines;
130         int nimt_trampolines;
131         gboolean print_skipped_methods;
132         gboolean stats;
133         char *tool_prefix;
134         gboolean autoreg;
135         char *mtriple;
136         char *llvm_path;
137 } MonoAotOptions;
138
139 typedef struct MonoAotStats {
140         int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
141         int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
142         int methods_without_got_slots, direct_calls, all_calls, llvm_count;
143         int got_slots, offsets_size;
144         int got_slot_types [MONO_PATCH_INFO_NONE];
145         int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
146         int jit_time, gen_time, link_time;
147 } MonoAotStats;
148
149 typedef struct MonoAotCompile {
150         MonoImage *image;
151         GPtrArray *methods;
152         GHashTable *method_indexes;
153         GHashTable *method_depth;
154         MonoCompile **cfgs;
155         int cfgs_size;
156         GHashTable *patch_to_plt_entry;
157         GHashTable *plt_offset_to_entry;
158         GHashTable *patch_to_got_offset;
159         GHashTable **patch_to_got_offset_by_type;
160         GPtrArray *got_patches;
161         GHashTable *image_hash;
162         GHashTable *method_to_cfg;
163         GHashTable *token_info_hash;
164         GHashTable *method_to_pinvoke_import;
165         GPtrArray *extra_methods;
166         GPtrArray *image_table;
167         GPtrArray *globals;
168         GPtrArray *method_order;
169         GHashTable *export_names;
170         /* Maps MonoClass* -> blob offset */
171         GHashTable *klass_blob_hash;
172         /* Maps MonoMethod* -> blob offset */
173         GHashTable *method_blob_hash;
174         guint32 *plt_got_info_offsets;
175         guint32 got_offset, plt_offset, plt_got_offset_base;
176         guint32 final_got_size;
177         /* Number of GOT entries reserved for trampolines */
178         guint32 num_trampoline_got_entries;
179
180         guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
181         guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
182         guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
183
184         MonoAotOptions aot_opts;
185         guint32 nmethods;
186         guint32 opts;
187         MonoMemPool *mempool;
188         MonoAotStats stats;
189         int method_index;
190         char *static_linking_symbol;
191         CRITICAL_SECTION mutex;
192         gboolean use_bin_writer;
193         MonoImageWriter *w;
194         MonoDwarfWriter *dwarf;
195         FILE *fp;
196         char *tmpfname;
197         GSList *cie_program;
198         GHashTable *unwind_info_offsets;
199         GPtrArray *unwind_ops;
200         guint32 unwind_info_offset;
201         char *got_symbol_base;
202         char *got_symbol;
203         char *plt_symbol;
204         GHashTable *method_label_hash;
205         const char *temp_prefix;
206         const char *llvm_label_prefix;
207         guint32 label_generator;
208         gboolean llvm;
209         MonoAotFileFlags flags;
210         MonoDynamicStream blob;
211         MonoClass **typespec_classes;
212         GString *llc_args;
213         GString *as_args;
214         char *assembly_name_sym;
215         GHashTable *plt_entry_debug_sym_cache;
216         gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
217         GHashTable *ginst_hash;
218 } MonoAotCompile;
219
220 typedef struct {
221         int plt_offset;
222         char *symbol, *llvm_symbol, *debug_sym;
223         MonoJumpInfo *ji;
224         gboolean jit_used, llvm_used;
225 } MonoPltEntry;
226
227 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
228 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
229
230 /* This points to the current acfg in LLVM mode */
231 static MonoAotCompile *llvm_acfg;
232
233 #ifdef HAVE_ARRAY_ELEM_INIT
234 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
235 #define MSGSTRFIELD1(line) str##line
236 static const struct msgstr_t {
237 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
238 #include "patch-info.h"
239 #undef PATCH_INFO
240 } opstr = {
241 #define PATCH_INFO(a,b) b,
242 #include "patch-info.h"
243 #undef PATCH_INFO
244 };
245 static const gint16 opidx [] = {
246 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
247 #include "patch-info.h"
248 #undef PATCH_INFO
249 };
250
251 static G_GNUC_UNUSED const char*
252 get_patch_name (int info)
253 {
254         return (const char*)&opstr + opidx [info];
255 }
256
257 #else
258 #define PATCH_INFO(a,b) b,
259 static const char* const
260 patch_types [MONO_PATCH_INFO_NUM + 1] = {
261 #include "patch-info.h"
262         NULL
263 };
264
265 static G_GNUC_UNUSED const char*
266 get_patch_name (int info)
267 {
268         return patch_types [info];
269 }
270
271 #endif
272
273 static char*
274 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
275
276 /* Wrappers around the image writer functions */
277
278 static inline void
279 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
280 {
281         img_writer_emit_section_change (acfg->w, section_name, subsection_index);
282 }
283
284 static inline void
285 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
286 {
287         img_writer_emit_push_section (acfg->w, section_name, subsection);
288 }
289
290 static inline void
291 emit_pop_section (MonoAotCompile *acfg)
292 {
293         img_writer_emit_pop_section (acfg->w);
294 }
295
296 static inline void
297 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
298
299         img_writer_emit_local_symbol (acfg->w, name, end_label, func); 
300 }
301
302 static inline void
303 emit_label (MonoAotCompile *acfg, const char *name) 
304
305         img_writer_emit_label (acfg->w, name); 
306 }
307
308 static inline void
309 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
310
311         img_writer_emit_bytes (acfg->w, buf, size); 
312 }
313
314 static inline void
315 emit_string (MonoAotCompile *acfg, const char *value) 
316
317         img_writer_emit_string (acfg->w, value); 
318 }
319
320 static inline void
321 emit_line (MonoAotCompile *acfg) 
322
323         img_writer_emit_line (acfg->w); 
324 }
325
326 static inline void
327 emit_alignment (MonoAotCompile *acfg, int size) 
328
329         img_writer_emit_alignment (acfg->w, size); 
330 }
331
332 static inline void
333 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target) 
334
335         img_writer_emit_pointer_unaligned (acfg->w, target); 
336 }
337
338 static inline void
339 emit_pointer (MonoAotCompile *acfg, const char *target) 
340
341         img_writer_emit_pointer (acfg->w, target); 
342 }
343
344 static inline void
345 emit_int16 (MonoAotCompile *acfg, int value) 
346
347         img_writer_emit_int16 (acfg->w, value); 
348 }
349
350 static inline void
351 emit_int32 (MonoAotCompile *acfg, int value) 
352
353         img_writer_emit_int32 (acfg->w, value); 
354 }
355
356 static inline void
357 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
358
359         img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
360 }
361
362 static inline void
363 emit_zero_bytes (MonoAotCompile *acfg, int num) 
364
365         img_writer_emit_zero_bytes (acfg->w, num); 
366 }
367
368 static inline void
369 emit_byte (MonoAotCompile *acfg, guint8 val) 
370
371         img_writer_emit_byte (acfg->w, val); 
372 }
373
374 #ifdef __native_client_codegen__
375 static inline void
376 emit_nacl_call_alignment (MonoAotCompile *acfg)
377 {
378         img_writer_emit_nacl_call_alignment (acfg->w);
379 }
380 #endif
381
382 static G_GNUC_UNUSED void
383 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
384 {
385         img_writer_emit_global (acfg->w, name, func);
386 }
387
388 static void
389 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
390 {
391         if (acfg->aot_opts.no_dlsym) {
392                 g_ptr_array_add (acfg->globals, g_strdup (name));
393                 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
394         } else {
395                 img_writer_emit_global (acfg->w, name, func);
396         }
397 }
398
399 static void
400 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
401 {
402         img_writer_emit_symbol_size (acfg->w, name, end_label);
403 }
404
405 static void
406 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
407 {
408         img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
409 #ifdef __APPLE__
410         /* On apple, all symbols need to be aligned to avoid warnings from ld */
411         emit_alignment (acfg, 4);
412 #endif
413         img_writer_emit_label (acfg->w, name);
414         img_writer_emit_string (acfg->w, value);
415 }
416
417 static G_GNUC_UNUSED void
418 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
419 {
420         do {
421                 guint8 b = value & 0x7f;
422                 value >>= 7;
423                 if (value != 0) /* more bytes to come */
424                         b |= 0x80;
425                 emit_byte (acfg, b);
426         } while (value);
427 }
428
429 static G_GNUC_UNUSED void
430 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
431 {
432         gboolean more = 1;
433         gboolean negative = (value < 0);
434         guint32 size = 64;
435         guint8 byte;
436
437         while (more) {
438                 byte = value & 0x7f;
439                 value >>= 7;
440                 /* the following is unnecessary if the
441                  * implementation of >>= uses an arithmetic rather
442                  * than logical shift for a signed left operand
443                  */
444                 if (negative)
445                         /* sign extend */
446                         value |= - ((gint64)1 <<(size - 7));
447                 /* sign bit of byte is second high order bit (0x40) */
448                 if ((value == 0 && !(byte & 0x40)) ||
449                         (value == -1 && (byte & 0x40)))
450                         more = 0;
451                 else
452                         byte |= 0x80;
453                 emit_byte (acfg, byte);
454         }
455 }
456
457 static G_GNUC_UNUSED void
458 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
459 {
460         guint8 *p = buf;
461
462         do {
463                 guint8 b = value & 0x7f;
464                 value >>= 7;
465                 if (value != 0) /* more bytes to come */
466                         b |= 0x80;
467                 *p ++ = b;
468         } while (value);
469
470         *endbuf = p;
471 }
472
473 static G_GNUC_UNUSED void
474 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
475 {
476         gboolean more = 1;
477         gboolean negative = (value < 0);
478         guint32 size = 32;
479         guint8 byte;
480         guint8 *p = buf;
481
482         while (more) {
483                 byte = value & 0x7f;
484                 value >>= 7;
485                 /* the following is unnecessary if the
486                  * implementation of >>= uses an arithmetic rather
487                  * than logical shift for a signed left operand
488                  */
489                 if (negative)
490                         /* sign extend */
491                         value |= - (1 <<(size - 7));
492                 /* sign bit of byte is second high order bit (0x40) */
493                 if ((value == 0 && !(byte & 0x40)) ||
494                         (value == -1 && (byte & 0x40)))
495                         more = 0;
496                 else
497                         byte |= 0x80;
498                 *p ++= byte;
499         }
500
501         *endbuf = p;
502 }
503
504 /* ARCHITECTURE SPECIFIC CODE */
505
506 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
507 #define EMIT_DWARF_INFO 1
508 #endif
509
510 #if defined(TARGET_ARM)
511 #define AOT_FUNC_ALIGNMENT 4
512 #else
513 #define AOT_FUNC_ALIGNMENT 16
514 #endif
515 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
516 #undef AOT_FUNC_ALIGNMENT
517 #define AOT_FUNC_ALIGNMENT 32
518 #endif
519  
520 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
521 #define PPC_LD_OP "ld"
522 #define PPC_LDX_OP "ldx"
523 #else
524 #define PPC_LD_OP "lwz"
525 #define PPC_LDX_OP "lwzx"
526 #endif
527
528 #ifdef TARGET_AMD64
529 #define AOT_TARGET_STR "AMD64"
530 #endif
531
532 #ifdef TARGET_ARM
533 #ifdef __MACH__
534 #define AOT_TARGET_STR "ARM (MACH)"
535 #else
536 #define AOT_TARGET_STR "ARM (!MACH)"
537 #endif
538 #endif
539
540 #ifdef TARGET_POWERPC64
541 #ifdef __mono_ilp32__
542 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
543 #else
544 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
545 #endif
546 #else
547 #ifdef TARGET_POWERPC
548 #ifdef __mono_ilp32__
549 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
550 #else
551 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
552 #endif
553 #endif
554 #endif
555
556 #ifdef TARGET_X86
557 #ifdef TARGET_WIN32
558 #define AOT_TARGET_STR "X86 (WIN32)"
559 #elif defined(__native_client_codegen__)
560 #define AOT_TARGET_STR "X86 (native client codegen)"
561 #else
562 #define AOT_TARGET_STR "X86 (!native client codegen)"
563 #endif
564 #endif
565
566 #ifndef AOT_TARGET_STR
567 #define AOT_TARGET_STR ""
568 #endif
569
570 static void
571 arch_init (MonoAotCompile *acfg)
572 {
573         acfg->llc_args = g_string_new ("");
574         acfg->as_args = g_string_new ("");
575
576         /*
577          * The prefix LLVM likes to put in front of symbol names on darwin.
578          * The mach-os specs require this for globals, but LLVM puts them in front of all
579          * symbols. We need to handle this, since we need to refer to LLVM generated
580          * symbols.
581          */
582         acfg->llvm_label_prefix = "";
583
584 #ifdef TARGET_ARM
585         if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
586                 g_string_append (acfg->llc_args, "-mattr=+v6");
587         } else {
588 #ifdef ARM_FPU_VFP
589                 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
590                 g_string_append (acfg->as_args, " -mfpu=vfp3");
591 #else
592                 g_string_append (acfg->llc_args, " -soft-float");
593 #endif
594         }
595         if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
596                 acfg->thumb_mixed = TRUE;
597
598         if (acfg->aot_opts.mtriple)
599                 mono_arch_set_target (acfg->aot_opts.mtriple);
600 #endif
601
602 #ifdef __APPLE__
603         acfg->llvm_label_prefix = "_";
604         acfg->need_no_dead_strip = TRUE;
605 #endif
606
607 #if defined(__linux__) && !defined(TARGET_ARM)
608         acfg->need_pt_gnu_stack = TRUE;
609 #endif
610 }
611
612 /*
613  * arch_emit_direct_call:
614  *
615  *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
616  * calling code.
617  */
618 static void
619 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
620 {
621 #if defined(TARGET_X86) || defined(TARGET_AMD64)
622         /* Need to make sure this is exactly 5 bytes long */
623         if (FALSE && !acfg->use_bin_writer) {
624                 img_writer_emit_unset_mode (acfg->w);
625                 fprintf (acfg->fp, "call %s\n", target);
626         } else {
627                 emit_byte (acfg, '\xe8');
628                 emit_symbol_diff (acfg, target, ".", -4);
629         }
630         *call_size = 5;
631 #elif defined(TARGET_ARM)
632         if (acfg->use_bin_writer) {
633                 guint8 buf [4];
634                 guint8 *code;
635
636                 code = buf;
637                 ARM_BL (code, 0);
638
639                 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
640                 emit_bytes (acfg, buf, 4);
641         } else {
642                 img_writer_emit_unset_mode (acfg->w);
643                 fprintf (acfg->fp, "bl %s\n", target);
644         }
645         *call_size = 4;
646 #elif defined(TARGET_POWERPC)
647         if (acfg->use_bin_writer) {
648                 g_assert_not_reached ();
649         } else {
650                 img_writer_emit_unset_mode (acfg->w);
651                 fprintf (acfg->fp, "bl %s\n", target);
652                 *call_size = 4;
653         }
654 #else
655         g_assert_not_reached ();
656 #endif
657 }
658
659 /*
660  * PPC32 design:
661  * - we use an approach similar to the x86 abi: reserve a register (r30) to hold 
662  *   the GOT pointer.
663  * - The full-aot trampolines need access to the GOT of mscorlib, so we store
664  *   in in the 2. slot of every GOT, and require every method to place the GOT
665  *   address in r30, even when it doesn't access the GOT otherwise. This way,
666  *   the trampolines can compute the mscorlib GOT address by loading 4(r30).
667  */
668
669 /*
670  * PPC64 design:
671  * PPC64 uses function descriptors which greatly complicate all code, since
672  * these are used very inconsistently in the runtime. Some functions like 
673  * mono_compile_method () return ftn descriptors, while others like the
674  * trampoline creation functions do not.
675  * We assume that all GOT slots contain function descriptors, and create 
676  * descriptors in aot-runtime.c when needed.
677  * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
678  * from function descriptors, we could do the same, but it would require 
679  * rewriting all the ppc/aot code to handle function descriptors properly.
680  * So instead, we use the same approach as on PPC32.
681  * This is a horrible mess, but fixing it would probably lead to an even bigger
682  * one.
683  */
684
685 /*
686  * X86 design:
687  * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
688  */
689
690 #ifdef MONO_ARCH_AOT_SUPPORTED
691 /*
692  * arch_emit_got_offset:
693  *
694  *   The memory pointed to by CODE should hold native code for computing the GOT
695  * address. Emit this code while patching it with the offset between code and
696  * the GOT. CODE_SIZE is set to the number of bytes emitted.
697  */
698 static void
699 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
700 {
701 #if defined(TARGET_POWERPC64)
702         g_assert (!acfg->use_bin_writer);
703         img_writer_emit_unset_mode (acfg->w);
704         /* 
705          * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
706          * unsupported relocations. So we store the got address into the .Lgot_addr
707          * symbol which is in the text segment, compute its address, and load it.
708          */
709         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
710         fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
711         fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
712         fprintf (acfg->fp, "add 30, 30, 0\n");
713         fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
714         acfg->label_generator ++;
715         *code_size = 16;
716 #elif defined(TARGET_POWERPC)
717         g_assert (!acfg->use_bin_writer);
718         img_writer_emit_unset_mode (acfg->w);
719         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
720         fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
721         fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
722         acfg->label_generator ++;
723         *code_size = 8;
724 #else
725         guint32 offset = mono_arch_get_patch_offset (code);
726         emit_bytes (acfg, code, offset);
727         emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
728
729         *code_size = offset + 4;
730 #endif
731 }
732
733 /*
734  * arch_emit_got_access:
735  *
736  *   The memory pointed to by CODE should hold native code for loading a GOT
737  * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
738  * CODE_SIZE is set to the number of bytes emitted.
739  */
740 static void
741 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
742 {
743         /* Emit beginning of instruction */
744         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
745
746         /* Emit the offset */
747 #ifdef TARGET_AMD64
748         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
749         *code_size = mono_arch_get_patch_offset (code) + 4;
750 #elif defined(TARGET_X86)
751         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
752         *code_size = mono_arch_get_patch_offset (code) + 4;
753 #elif defined(TARGET_ARM)
754         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
755         *code_size = mono_arch_get_patch_offset (code) + 4;
756 #elif defined(TARGET_POWERPC)
757         {
758                 guint8 buf [32];
759                 guint8 *code;
760
761                 code = buf;
762                 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
763                 g_assert (code - buf == 8);
764                 emit_bytes (acfg, buf, code - buf);
765                 *code_size = code - buf;
766         }
767 #else
768         g_assert_not_reached ();
769 #endif
770 }
771
772 #endif
773
774 /*
775  * arch_emit_plt_entry:
776  *
777  *   Emit code for the PLT entry with index INDEX.
778  */
779 static void
780 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
781 {
782 #if defined(TARGET_X86)
783                 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
784 #if defined(__default_codegen__)
785                 /* jmp *<offset>(%ebx) */
786                 emit_byte (acfg, 0xff);
787                 emit_byte (acfg, 0xa3);
788                 emit_int32 (acfg, offset);
789                 /* Used by mono_aot_get_plt_info_offset */
790                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
791 #elif defined(__native_client_codegen__)
792                 const guint8 kSizeOfNaClJmp = 11;
793                 guint8 bytes[kSizeOfNaClJmp];
794                 guint8 *pbytes = &bytes[0];
795                 
796                 x86_jump_membase32 (pbytes, X86_EBX, offset);
797                 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
798                 /* four bytes of data, used by mono_arch_patch_plt_entry              */
799                 /* For Native Client, make this work with data embedded in push.      */
800                 emit_byte (acfg, 0x68);  /* hide data in a push */
801                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
802                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
803 #endif /*__native_client_codegen__*/
804 #elif defined(TARGET_AMD64)
805 #if defined(__default_codegen__)
806                 /*
807                  * We can't emit jumps because they are 32 bits only so they can't be patched.
808                  * So we make indirect calls through GOT entries which are patched by the AOT 
809                  * loader to point to .Lpd entries. 
810                  */
811                 /* jmpq *<offset>(%rip) */
812                 emit_byte (acfg, '\xff');
813                 emit_byte (acfg, '\x25');
814                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
815                 /* Used by mono_aot_get_plt_info_offset */
816                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
817 #elif defined(__native_client_codegen__)
818                 guint8 buf [256];
819                 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
820                 guint8 *code = buf_aligned;
821
822                 /* mov <OFFSET>(%rip), %r11d */
823                 emit_byte (acfg, '\x45');
824                 emit_byte (acfg, '\x8b');
825                 emit_byte (acfg, '\x1d');
826                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
827
828                 amd64_jump_reg (code, AMD64_R11);
829                 /* This should be constant for the plt patch */
830                 g_assert ((size_t)(code-buf_aligned) == 10);
831                 emit_bytes (acfg, buf_aligned, code - buf_aligned);
832
833                 /* Hide data in a push imm32 so it passes validation */
834                 emit_byte (acfg, 0x68);  /* push */
835                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
836                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
837 #endif /*__native_client_codegen__*/
838 #elif defined(TARGET_ARM)
839                 guint8 buf [256];
840                 guint8 *code;
841
842                 code = buf;
843                 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
844                 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
845                 emit_bytes (acfg, buf, code - buf);
846                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
847                 /* Used by mono_aot_get_plt_info_offset */
848                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
849 #elif defined(TARGET_POWERPC)
850                 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
851
852                 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
853                 g_assert (!acfg->use_bin_writer);
854                 img_writer_emit_unset_mode (acfg->w);
855                 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
856                 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
857                 fprintf (acfg->fp, "add 11, 11, 30\n");
858                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
859 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
860                 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
861                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
862 #endif
863                 fprintf (acfg->fp, "mtctr 11\n");
864                 fprintf (acfg->fp, "bctr\n");
865                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
866 #else
867                 g_assert_not_reached ();
868 #endif
869 }
870
871 static void
872 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
873 {
874 #if defined(TARGET_ARM)
875 #if 0
876         /* LLVM calls the PLT entries using bl, so emit a stub */
877         /* FIXME: Too much overhead on every call */
878         fprintf (acfg->fp, ".thumb_func\n");
879         fprintf (acfg->fp, "bx pc\n");
880         fprintf (acfg->fp, "nop\n");
881         fprintf (acfg->fp, ".arm\n");
882 #endif
883         /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
884         /* The caller already transitioned to thumb */
885         /* The code below should be 12 bytes long */
886         fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
887         /* thumb can't encode ld pc, [pc, ip] */
888         fprintf (acfg->fp, "add ip, pc, ip\n");
889         fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
890         fprintf (acfg->fp, "bx ip\n");
891         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
892         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
893 #else
894         g_assert_not_reached ();
895 #endif
896 }
897
898 /*
899  * arch_emit_specific_trampoline:
900  *
901  *   Emit code for a specific trampoline. OFFSET is the offset of the first of
902  * two GOT slots which contain the generic trampoline address and the trampoline
903  * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
904  */
905 static void
906 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
907 {
908         /*
909          * The trampolines created here are variations of the specific 
910          * trampolines created in mono_arch_create_specific_trampoline (). The 
911          * differences are:
912          * - the generic trampoline address is taken from a got slot.
913          * - the offset of the got slot where the trampoline argument is stored
914          *   is embedded in the instruction stream, and the generic trampoline
915          *   can load the argument by loading the offset, adding it to the
916          *   address of the trampoline to get the address of the got slot, and
917          *   loading the argument from there.
918          * - all the trampolines should be of the same length.
919          */
920 #if defined(TARGET_AMD64)
921 #if defined(__default_codegen__)
922         /* This should be exactly 16 bytes long */
923         *tramp_size = 16;
924         /* call *<offset>(%rip) */
925         emit_byte (acfg, '\x41');
926         emit_byte (acfg, '\xff');
927         emit_byte (acfg, '\x15');
928         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
929         /* This should be relative to the start of the trampoline */
930         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
931         emit_zero_bytes (acfg, 5);
932 #elif defined(__native_client_codegen__)
933         guint8 buf [256];
934         guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
935         guint8 *code = buf_aligned;
936         guint8 *call_start;
937         size_t call_len;
938         int got_offset;
939
940         /* Emit this call in 'code' so we can find out how long it is. */
941         amd64_call_reg (code, AMD64_R11);
942         call_start = mono_arch_nacl_skip_nops (buf_aligned);
943         call_len = code - call_start;
944
945         /* The tramp_size is twice the NaCl alignment because it starts with */ 
946         /* a call which needs to be aligned to the end of the boundary.      */
947         *tramp_size = kNaClAlignment*2;
948         {
949                 /* Emit nops to align call site below which is 7 bytes plus */
950                 /* the length of the call sequence emitted above.           */
951                 /* Note: this requires the specific trampoline starts on a  */
952                 /* kNaclAlignedment aligned address, which it does because  */
953                 /* it's its own function that is aligned.                   */
954                 guint8 nop_buf[256];
955                 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
956                 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
957                 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
958         }
959         /* The trampoline is stored at the offset'th pointer, the -4 is  */
960         /* present because RIP relative addressing starts at the end of  */
961         /* the current instruction, while the label "." is relative to   */
962         /* the beginning of the current asm location, which in this case */
963         /* is not the mov instruction, but the offset itself, due to the */
964         /* way the bytes and ints are emitted here.                      */
965         got_offset = (offset * sizeof(gpointer)) - 4;
966
967         /* mov <OFFSET>(%rip), %r11d */
968         emit_byte (acfg, '\x45');
969         emit_byte (acfg, '\x8b');
970         emit_byte (acfg, '\x1d');
971         emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
972
973         /* naclcall %r11 */
974         emit_bytes (acfg, call_start, call_len);
975
976         /* The arg is stored at the offset+1 pointer, relative to beginning */
977         /* of trampoline: 7 for mov, plus the call length, and 1 for push.  */
978         got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
979
980         /* We can't emit this data directly, hide in a "push imm32" */
981         emit_byte (acfg, '\x68'); /* push */
982         emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
983         emit_alignment (acfg, kNaClAlignment);
984 #endif /*__native_client_codegen__*/
985 #elif defined(TARGET_ARM)
986         guint8 buf [128];
987         guint8 *code;
988
989         /* This should be exactly 20 bytes long */
990         *tramp_size = 20;
991         code = buf;
992         ARM_PUSH (code, 0x5fff);
993         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
994         /* Load the value from the GOT */
995         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
996         /* Branch to it */
997         ARM_BLX_REG (code, ARMREG_R1);
998
999         g_assert (code - buf == 16);
1000
1001         /* Emit it */
1002         emit_bytes (acfg, buf, code - buf);
1003         /* 
1004          * Only one offset is needed, since the second one would be equal to the
1005          * first one.
1006          */
1007         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1008         //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1009 #elif defined(TARGET_POWERPC)
1010         guint8 buf [128];
1011         guint8 *code;
1012
1013         *tramp_size = 4;
1014         code = buf;
1015
1016         g_assert (!acfg->use_bin_writer);
1017
1018         /*
1019          * PPC has no ip relative addressing, so we need to compute the address
1020          * of the mscorlib got. That is slow and complex, so instead, we store it
1021          * in the second got slot of every aot image. The caller already computed
1022          * the address of its got and placed it into r30.
1023          */
1024         img_writer_emit_unset_mode (acfg->w);
1025         /* Load mscorlib got address */
1026         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1027         /* Load generic trampoline address */
1028         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1029         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1030         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1031 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1032         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1033 #endif
1034         fprintf (acfg->fp, "mtctr 11\n");
1035         /* Load trampoline argument */
1036         /* On ppc, we pass it normally to the generic trampoline */
1037         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1038         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1039         fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1040         /* Branch to generic trampoline */
1041         fprintf (acfg->fp, "bctr\n");
1042
1043 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1044         *tramp_size = 10 * 4;
1045 #else
1046         *tramp_size = 9 * 4;
1047 #endif
1048 #elif defined(TARGET_X86)
1049         guint8 buf [128];
1050         guint8 *code;
1051
1052         /* Similar to the PPC code above */
1053
1054         /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1055
1056         /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1057 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1058         g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1059 #endif
1060
1061         code = buf;
1062         /* Load mscorlib got address */
1063         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1064         /* Push trampoline argument */
1065         x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1066         /* Load generic trampoline address */
1067         x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1068         /* Branch to generic trampoline */
1069         x86_jump_reg (code, X86_ECX);
1070
1071 #ifdef __native_client_codegen__
1072         {
1073                 /* emit nops to next 32 byte alignment */
1074                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1075                 while (code < (buf + a)) x86_nop(code);
1076         }
1077 #endif
1078         emit_bytes (acfg, buf, code - buf);
1079
1080         *tramp_size = NACL_SIZE(17, kNaClAlignment);
1081         g_assert (code - buf == *tramp_size);
1082 #else
1083         g_assert_not_reached ();
1084 #endif
1085 }
1086
1087 /*
1088  * arch_emit_unbox_trampoline:
1089  *
1090  *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
1091  * CALL_TARGET is the symbol pointing to the native code of METHOD.
1092  */
1093 static void
1094 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1095 {
1096 #if defined(TARGET_AMD64)
1097         guint8 buf [32];
1098         guint8 *code;
1099         int this_reg;
1100
1101         this_reg = mono_arch_get_this_arg_reg (NULL);
1102         code = buf;
1103         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1104
1105         emit_bytes (acfg, buf, code - buf);
1106         /* jump <method> */
1107         emit_byte (acfg, '\xe9');
1108         emit_symbol_diff (acfg, call_target, ".", -4);
1109 #elif defined(TARGET_X86)
1110         guint8 buf [32];
1111         guint8 *code;
1112         int this_pos = 4;
1113
1114         code = buf;
1115
1116         x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1117
1118         emit_bytes (acfg, buf, code - buf);
1119
1120         /* jump <method> */
1121         emit_byte (acfg, '\xe9');
1122         emit_symbol_diff (acfg, call_target, ".", -4);
1123 #elif defined(TARGET_ARM)
1124         guint8 buf [128];
1125         guint8 *code;
1126
1127         if (acfg->thumb_mixed && cfg->compile_llvm) {
1128                 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1129                 fprintf (acfg->fp, "b %s\n", call_target);
1130                 fprintf (acfg->fp, ".arm\n");
1131                 return;
1132         }
1133
1134         code = buf;
1135
1136         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1137
1138         emit_bytes (acfg, buf, code - buf);
1139         /* jump to method */
1140         if (acfg->use_bin_writer) {
1141                 guint8 buf [4];
1142                 guint8 *code;
1143
1144                 code = buf;
1145                 ARM_B (code, 0);
1146
1147                 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1148                 emit_bytes (acfg, buf, 4);
1149         } else {
1150                 if (acfg->thumb_mixed && cfg->compile_llvm)
1151                         fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1152                 else
1153                         fprintf (acfg->fp, "\n\tb %s\n", call_target);
1154         }
1155 #elif defined(TARGET_POWERPC)
1156         int this_pos = 3;
1157
1158         g_assert (!acfg->use_bin_writer);
1159
1160         fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1161         fprintf (acfg->fp, "\n\tb %s\n", call_target);
1162 #else
1163         g_assert_not_reached ();
1164 #endif
1165 }
1166
1167 /*
1168  * arch_emit_static_rgctx_trampoline:
1169  *
1170  *   Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1171  * two GOT slots which contain the rgctx argument, and the method to jump to.
1172  * TRAMP_SIZE is set to the size of the emitted trampoline.
1173  * These kinds of trampolines cannot be enumerated statically, since there could
1174  * be one trampoline per method instantiation, so we emit the same code for all
1175  * trampolines, and parameterize them using two GOT slots.
1176  */
1177 static void
1178 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1179 {
1180 #if defined(TARGET_AMD64)
1181 #if defined(__default_codegen__)
1182         /* This should be exactly 13 bytes long */
1183         *tramp_size = 13;
1184
1185         /* mov <OFFSET>(%rip), %r10 */
1186         emit_byte (acfg, '\x4d');
1187         emit_byte (acfg, '\x8b');
1188         emit_byte (acfg, '\x15');
1189         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1190
1191         /* jmp *<offset>(%rip) */
1192         emit_byte (acfg, '\xff');
1193         emit_byte (acfg, '\x25');
1194         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1195 #elif defined(__native_client_codegen__)
1196         guint8 buf [128];
1197         guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1198         guint8 *code = buf_aligned;
1199
1200         /* mov <OFFSET>(%rip), %r10d */
1201         emit_byte (acfg, '\x45');
1202         emit_byte (acfg, '\x8b');
1203         emit_byte (acfg, '\x15');
1204         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1205
1206         /* mov <OFFSET>(%rip), %r11d */
1207         emit_byte (acfg, '\x45');
1208         emit_byte (acfg, '\x8b');
1209         emit_byte (acfg, '\x1d');
1210         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1211
1212         /* nacljmp *%r11 */
1213         amd64_jump_reg (code, AMD64_R11);
1214         emit_bytes (acfg, buf_aligned, code - buf_aligned);
1215
1216         emit_alignment (acfg, kNaClAlignment);
1217         *tramp_size = kNaClAlignment;
1218 #endif /*__native_client_codegen__*/
1219
1220 #elif defined(TARGET_ARM)
1221         guint8 buf [128];
1222         guint8 *code;
1223
1224         /* This should be exactly 24 bytes long */
1225         *tramp_size = 24;
1226         code = buf;
1227         /* Load rgctx value */
1228         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1229         ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1230         /* Load branch addr + branch */
1231         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1232         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1233
1234         g_assert (code - buf == 16);
1235
1236         /* Emit it */
1237         emit_bytes (acfg, buf, code - buf);
1238         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1239         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1240 #elif defined(TARGET_POWERPC)
1241         guint8 buf [128];
1242         guint8 *code;
1243
1244         *tramp_size = 4;
1245         code = buf;
1246
1247         g_assert (!acfg->use_bin_writer);
1248
1249         /*
1250          * PPC has no ip relative addressing, so we need to compute the address
1251          * of the mscorlib got. That is slow and complex, so instead, we store it
1252          * in the second got slot of every aot image. The caller already computed
1253          * the address of its got and placed it into r30.
1254          */
1255         img_writer_emit_unset_mode (acfg->w);
1256         /* Load mscorlib got address */
1257         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1258         /* Load rgctx */
1259         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1260         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1261         fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1262         /* Load target address */
1263         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1264         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1265         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1266 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1267         fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1268         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1269 #endif
1270         fprintf (acfg->fp, "mtctr 11\n");
1271         /* Branch to the target address */
1272         fprintf (acfg->fp, "bctr\n");
1273
1274 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1275         *tramp_size = 11 * 4;
1276 #else
1277         *tramp_size = 9 * 4;
1278 #endif
1279
1280 #elif defined(TARGET_X86)
1281         guint8 buf [128];
1282         guint8 *code;
1283
1284         /* Similar to the PPC code above */
1285
1286         g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1287
1288         code = buf;
1289         /* Load mscorlib got address */
1290         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1291         /* Load arg */
1292         x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1293         /* Branch to the target address */
1294         x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1295
1296 #ifdef __native_client_codegen__
1297         {
1298                 /* emit nops to next 32 byte alignment */
1299                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1300                 while (code < (buf + a)) x86_nop(code);
1301         }
1302 #endif
1303
1304         emit_bytes (acfg, buf, code - buf);
1305
1306         *tramp_size = NACL_SIZE (15, kNaClAlignment);
1307         g_assert (code - buf == *tramp_size);
1308 #else
1309         g_assert_not_reached ();
1310 #endif
1311 }       
1312
1313 /*
1314  * arch_emit_imt_thunk:
1315  *
1316  *   Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1317  * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1318  * key is the IMT key, and ptr holds the address of a memory location holding
1319  * the address to branch to if the IMT arg matches the key. The array is 
1320  * terminated by a pair whose key is NULL, and whose ptr is the address of the 
1321  * fail_tramp.
1322  * TRAMP_SIZE is set to the size of the emitted trampoline.
1323  */
1324 static void
1325 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1326 {
1327 #if defined(TARGET_AMD64)
1328         guint8 *buf, *code;
1329 #if defined(__native_client_codegen__)
1330         guint8 *buf_alloc;
1331 #endif
1332         guint8 *labels [3];
1333         guint8 mov_buf[3];
1334         guint8 *mov_buf_ptr = mov_buf;
1335
1336         const int kSizeOfMove = 7;
1337 #if defined(__default_codegen__)
1338         code = buf = g_malloc (256);
1339 #elif defined(__native_client_codegen__)
1340         buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1341         buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1342         /* The RIP relative move below is emitted first */
1343         buf += kSizeOfMove;
1344         code = buf;
1345 #endif
1346
1347         /* FIXME: Optimize this, i.e. use binary search etc. */
1348         /* Maybe move the body into a separate function (slower, but much smaller) */
1349
1350         /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1351
1352         labels [0] = code;
1353         amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1354         labels [1] = code;
1355         amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1356
1357         /* Check key */
1358         amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1359         labels [2] = code;
1360         amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1361
1362         /* Loop footer */
1363         amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1364         amd64_jump_code (code, labels [0]);
1365
1366         /* Match */
1367         mono_amd64_patch (labels [2], code);
1368         amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1369         amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1370
1371         /* No match */
1372         /* FIXME: */
1373         mono_amd64_patch (labels [1], code);
1374         x86_breakpoint (code);
1375
1376         /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1377         amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1378         *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1379         x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1380         emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1381         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1382
1383         emit_bytes (acfg, buf, code - buf);
1384         
1385         *tramp_size = code - buf + kSizeOfMove;
1386 #if defined(__native_client_codegen__)
1387         /* The tramp will be padded to the next kNaClAlignment bundle. */
1388         *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1389 #endif
1390
1391 #if defined(__default_codegen__)
1392         g_free (buf);
1393 #elif defined(__native_client_codegen__)
1394         g_free (buf_alloc); 
1395 #endif
1396
1397 #elif defined(TARGET_X86)
1398         guint8 *buf, *code;
1399 #ifdef __native_client_codegen__
1400         guint8 *buf_alloc;
1401 #endif
1402         guint8 *labels [3];
1403
1404 #if defined(__default_codegen__)
1405         code = buf = g_malloc (256);
1406 #elif defined(__native_client_codegen__)
1407         buf_alloc = g_malloc (256 + kNaClAlignment);
1408         code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1409 #endif
1410
1411         /* Allocate a temporary stack slot */
1412         x86_push_reg (code, X86_EAX);
1413         /* Save EAX */
1414         x86_push_reg (code, X86_EAX);
1415
1416         /* Load mscorlib got address */
1417         x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1418         /* Load arg */
1419         x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1420
1421         labels [0] = code;
1422         x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1423         labels [1] = code;
1424         x86_branch8 (code, X86_CC_Z, FALSE, 0);
1425
1426         /* Check key */
1427         x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1428         labels [2] = code;
1429         x86_branch8 (code, X86_CC_Z, FALSE, 0);
1430
1431         /* Loop footer */
1432         x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1433         x86_jump_code (code, labels [0]);
1434
1435         /* Match */
1436         mono_x86_patch (labels [2], code);
1437         x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1438         x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1439         /* Save the target address to the temporary stack location */
1440         x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1441         /* Restore EAX */
1442         x86_pop_reg (code, X86_EAX);
1443         /* Jump to the target address */
1444         x86_ret (code);
1445
1446         /* No match */
1447         /* FIXME: */
1448         mono_x86_patch (labels [1], code);
1449         x86_breakpoint (code);
1450
1451 #ifdef __native_client_codegen__
1452         {
1453                 /* emit nops to next 32 byte alignment */
1454                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1455                 while (code < (buf + a)) x86_nop(code);
1456         }
1457 #endif
1458         emit_bytes (acfg, buf, code - buf);
1459         
1460         *tramp_size = code - buf;
1461
1462 #if defined(__default_codegen__)
1463         g_free (buf);
1464 #elif defined(__native_client_codegen__)
1465         g_free (buf_alloc); 
1466 #endif
1467
1468 #elif defined(TARGET_ARM)
1469         guint8 buf [128];
1470         guint8 *code, *code2, *labels [16];
1471
1472         code = buf;
1473
1474         /* The IMT method is in v5 */
1475
1476         /* Need at least two free registers, plus a slot for storing the pc */
1477         ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1478         labels [0] = code;
1479         /* Load the parameter from the GOT */
1480         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1481         ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1482
1483         labels [1] = code;
1484         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1485         ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1486         labels [2] = code;
1487         ARM_B_COND (code, ARMCOND_EQ, 0);
1488
1489         /* End-of-loop check */
1490         ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1491         labels [3] = code;
1492         ARM_B_COND (code, ARMCOND_EQ, 0);
1493
1494         /* Loop footer */
1495         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1496         labels [4] = code;
1497         ARM_B (code, 0);
1498         arm_patch (labels [4], labels [1]);
1499
1500         /* Match */
1501         arm_patch (labels [2], code);
1502         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1503         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1504         /* Save it to the third stack slot */
1505         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1506         /* Restore the registers and branch */
1507         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1508
1509         /* No match */
1510         arm_patch (labels [3], code);
1511         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1512         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1513         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1514
1515         /* Fixup offset */
1516         code2 = labels [0];
1517         ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1518
1519         emit_bytes (acfg, buf, code - buf);
1520         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1521
1522         *tramp_size = code - buf + 4;
1523 #elif defined(TARGET_POWERPC)
1524         guint8 buf [128];
1525         guint8 *code, *labels [16];
1526
1527         code = buf;
1528
1529         /* Load the mscorlib got address */
1530         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1531         /* Load the parameter from the GOT */
1532         ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1533         ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1534
1535         /* Load and check key */
1536         labels [1] = code;
1537         ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1538         ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1539         labels [2] = code;
1540         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1541
1542         /* End-of-loop check */
1543         ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1544         labels [3] = code;
1545         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1546
1547         /* Loop footer */
1548         ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1549         labels [4] = code;
1550         ppc_b (code, 0);
1551         mono_ppc_patch (labels [4], labels [1]);
1552
1553         /* Match */
1554         mono_ppc_patch (labels [2], code);
1555         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1556         /* r11 now contains the value of the vtable slot */
1557         /* this is not a function descriptor on ppc64 */
1558         ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1559         ppc_mtctr (code, ppc_r11);
1560         ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1561
1562         /* Fail */
1563         mono_ppc_patch (labels [3], code);
1564         /* FIXME: */
1565         ppc_break (code);
1566
1567         *tramp_size = code - buf;
1568
1569         emit_bytes (acfg, buf, code - buf);
1570 #else
1571         g_assert_not_reached ();
1572 #endif
1573 }
1574
1575 static void
1576 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1577 {
1578 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1579         /* Based on code generated by gcc */
1580         img_writer_emit_unset_mode (acfg->w);
1581
1582         fprintf (acfg->fp,
1583 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE) 
1584                          ".section      .ctors,\"aw\",@progbits\n"
1585                          ".align 2\n"
1586                          ".globl        %s\n"
1587                          ".long %s\n"
1588                          ".section      .opd,\"aw\"\n"
1589                          ".align 2\n"
1590                          "%s:\n"
1591                          ".long .%s,.TOC.@tocbase32\n"
1592                          ".size %s,.-%s\n"
1593                          ".section .text\n"
1594                          ".type .%s,@function\n"
1595                          ".align 2\n"
1596                          ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1597 #else
1598                          ".section      .ctors,\"aw\",@progbits\n"
1599                          ".align 2\n"
1600                          ".globl        %1$s\n"
1601                          ".long %1$s\n"
1602                          ".section      .opd,\"aw\"\n"
1603                          ".align 2\n"
1604                          "%1$s:\n"
1605                          ".long .%1$s,.TOC.@tocbase32\n"
1606                          ".size %1$s,.-%1$s\n"
1607                          ".section .text\n"
1608                          ".type .%1$s,@function\n"
1609                          ".align 2\n"
1610                          ".%1$s:\n", symbol);
1611 #endif
1612
1613
1614         fprintf (acfg->fp,
1615                          "stdu 1,-128(1)\n"
1616                          "mflr 0\n"
1617                          "std 31,120(1)\n"
1618                          "std 0,144(1)\n"
1619
1620                          ".Lautoreg:\n"
1621                          "lis 3, .Lglobals@h\n"
1622                          "ori 3, 3, .Lglobals@l\n"
1623                          "bl .mono_aot_register_module\n"
1624                          "ld 11,0(1)\n"
1625                          "ld 0,16(11)\n"
1626                          "mtlr 0\n"
1627                          "ld 31,-8(11)\n"
1628                          "mr 1,11\n"
1629                          "blr\n"
1630                          );
1631 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE) 
1632                 fprintf (acfg->fp,
1633                          ".size .%s,.-.%s\n", symbol, symbol);
1634 #else
1635         fprintf (acfg->fp,
1636                          ".size .%1$s,.-.%1$s\n", symbol);
1637 #endif
1638 #else
1639 #endif
1640 }
1641
1642 /* END OF ARCH SPECIFIC CODE */
1643
1644 static guint32
1645 mono_get_field_token (MonoClassField *field) 
1646 {
1647         MonoClass *klass = field->parent;
1648         int i;
1649
1650         for (i = 0; i < klass->field.count; ++i) {
1651                 if (field == &klass->fields [i])
1652                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1653         }
1654
1655         g_assert_not_reached ();
1656         return 0;
1657 }
1658
1659 static inline void
1660 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1661 {
1662         guint8 *p = buf;
1663
1664         //printf ("ENCODE: %d 0x%x.\n", value, value);
1665
1666         /* 
1667          * Same encoding as the one used in the metadata, extended to handle values
1668          * greater than 0x1fffffff.
1669          */
1670         if ((value >= 0) && (value <= 127))
1671                 *p++ = value;
1672         else if ((value >= 0) && (value <= 16383)) {
1673                 p [0] = 0x80 | (value >> 8);
1674                 p [1] = value & 0xff;
1675                 p += 2;
1676         } else if ((value >= 0) && (value <= 0x1fffffff)) {
1677                 p [0] = (value >> 24) | 0xc0;
1678                 p [1] = (value >> 16) & 0xff;
1679                 p [2] = (value >> 8) & 0xff;
1680                 p [3] = value & 0xff;
1681                 p += 4;
1682         }
1683         else {
1684                 p [0] = 0xff;
1685                 p [1] = (value >> 24) & 0xff;
1686                 p [2] = (value >> 16) & 0xff;
1687                 p [3] = (value >> 8) & 0xff;
1688                 p [4] = value & 0xff;
1689                 p += 5;
1690         }
1691         if (endbuf)
1692                 *endbuf = p;
1693 }
1694
1695 static void
1696 stream_init (MonoDynamicStream *sh)
1697 {
1698         sh->index = 0;
1699         sh->alloc_size = 4096;
1700         sh->data = g_malloc (4096);
1701
1702         /* So offsets are > 0 */
1703         sh->data [0] = 0;
1704         sh->index ++;
1705 }
1706
1707 static void
1708 make_room_in_stream (MonoDynamicStream *stream, int size)
1709 {
1710         if (size <= stream->alloc_size)
1711                 return;
1712         
1713         while (stream->alloc_size <= size) {
1714                 if (stream->alloc_size < 4096)
1715                         stream->alloc_size = 4096;
1716                 else
1717                         stream->alloc_size *= 2;
1718         }
1719         
1720         stream->data = g_realloc (stream->data, stream->alloc_size);
1721 }
1722
1723 static guint32
1724 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1725 {
1726         guint32 idx;
1727         
1728         make_room_in_stream (stream, stream->index + len);
1729         memcpy (stream->data + stream->index, data, len);
1730         idx = stream->index;
1731         stream->index += len;
1732         return idx;
1733 }
1734
1735 /*
1736  * add_to_blob:
1737  *
1738  *   Add data to the binary blob inside the aot image. Returns the offset inside the
1739  * blob where the data was stored.
1740  */
1741 static guint32
1742 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1743 {
1744         if (acfg->blob.alloc_size == 0)
1745                 stream_init (&acfg->blob);
1746
1747         return add_stream_data (&acfg->blob, (char*)data, data_len);
1748 }
1749
1750 static guint32
1751 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1752 {
1753         char buf [4] = {0};
1754         guint32 count;
1755
1756         if (acfg->blob.alloc_size == 0)
1757                 stream_init (&acfg->blob);
1758
1759         count = acfg->blob.index % align;
1760
1761         /* we assume the stream data will be aligned */
1762         if (count)
1763                 add_stream_data (&acfg->blob, buf, 4 - count);
1764
1765         return add_stream_data (&acfg->blob, (char*)data, data_len);
1766 }
1767
1768 /*
1769  * emit_offset_table:
1770  *
1771  *   Emit a table of increasing offsets in a compact form using differential encoding.
1772  * There is an index entry for each GROUP_SIZE number of entries. The greater the
1773  * group size, the more compact the table becomes, but the slower it becomes to compute
1774  * a given entry. Returns the size of the table.
1775  */
1776 static guint32
1777 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1778 {
1779         gint32 current_offset;
1780         int i, buf_size, ngroups, index_entry_size;
1781         guint8 *p, *buf;
1782         guint32 *index_offsets;
1783
1784         ngroups = (noffsets + (group_size - 1)) / group_size;
1785
1786         index_offsets = g_new0 (guint32, ngroups);
1787
1788         buf_size = noffsets * 4;
1789         p = buf = g_malloc0 (buf_size);
1790
1791         current_offset = 0;
1792         for (i = 0; i < noffsets; ++i) {
1793                 //printf ("D: %d -> %d\n", i, offsets [i]);
1794                 if ((i % group_size) == 0) {
1795                         index_offsets [i / group_size] = p - buf;
1796                         /* Emit the full value for these entries */
1797                         encode_value (offsets [i], p, &p);
1798                 } else {
1799                         /* The offsets are allowed to be non-increasing */
1800                         //g_assert (offsets [i] >= current_offset);
1801                         encode_value (offsets [i] - current_offset, p, &p);
1802                 }
1803                 current_offset = offsets [i];
1804         }
1805
1806         if (ngroups && index_offsets [ngroups - 1] < 65000)
1807                 index_entry_size = 2;
1808         else
1809                 index_entry_size = 4;
1810
1811         /* Emit the header */
1812         emit_int32 (acfg, noffsets);
1813         emit_int32 (acfg, group_size);
1814         emit_int32 (acfg, ngroups);
1815         emit_int32 (acfg, index_entry_size);
1816
1817         /* Emit the index */
1818         for (i = 0; i < ngroups; ++i) {
1819                 if (index_entry_size == 2)
1820                         emit_int16 (acfg, index_offsets [i]);
1821                 else
1822                         emit_int32 (acfg, index_offsets [i]);
1823         }
1824
1825         /* Emit the data */
1826         emit_bytes (acfg, buf, p - buf);
1827
1828     return (int)(p - buf) + (ngroups * 4);
1829 }
1830
1831 static guint32
1832 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1833 {
1834         guint32 index;
1835
1836         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1837         if (index)
1838                 return index - 1;
1839         else {
1840                 index = g_hash_table_size (cfg->image_hash);
1841                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1842                 g_ptr_array_add (cfg->image_table, image);
1843                 return index;
1844         }
1845 }
1846
1847 static guint32
1848 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1849 {
1850         int i;
1851         int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1852
1853         /* FIXME: Search referenced images as well */
1854         if (!acfg->typespec_classes) {
1855                 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1856                 for (i = 0; i < len; ++i) {
1857                         acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1858                 }
1859         }
1860         for (i = 0; i < len; ++i) {
1861                 if (acfg->typespec_classes [i] == klass)
1862                         break;
1863         }
1864
1865         if (i < len)
1866                 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1867         else
1868                 return 0;
1869 }
1870
1871 static void
1872 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1873
1874 static void
1875 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
1876
1877 static void
1878 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
1879
1880 static void
1881 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
1882
1883 static void
1884 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1885 {
1886         guint8 *p = buf;
1887
1888         /*
1889          * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
1890          * information.
1891          */
1892
1893         if (klass->generic_class) {
1894                 guint32 token;
1895                 g_assert (klass->type_token);
1896
1897                 /* Find a typespec for a class if possible */
1898                 token = find_typespec_for_class (acfg, klass);
1899                 if (token) {
1900                         encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
1901                         encode_value (token, p, &p);
1902                 } else {
1903                         MonoClass *gclass = klass->generic_class->container_class;
1904                         MonoGenericInst *inst = klass->generic_class->context.class_inst;
1905                         static int count = 0;
1906                         guint8 *p1 = p;
1907
1908                         encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
1909                         encode_klass_ref (acfg, gclass, p, &p);
1910                         encode_ginst (acfg, inst, p, &p);
1911
1912                         count += p - p1;
1913                 }
1914         } else if (klass->type_token) {
1915                 int iindex = get_image_index (acfg, klass->image);
1916
1917                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1918                 if (iindex == 0) {
1919                         encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
1920                         encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1921                 } else {
1922                         encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
1923                         encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1924                         encode_value (get_image_index (acfg, klass->image), p, &p);
1925                 }
1926         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1927                 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1928                 g_assert (container);
1929
1930                 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
1931                 encode_value (klass->byval_arg.type, p, &p);
1932                 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1933                 
1934                 encode_value (container->is_method, p, &p);
1935                 if (container->is_method)
1936                         encode_method_ref (acfg, container->owner.method, p, &p);
1937                 else
1938                         encode_klass_ref (acfg, container->owner.klass, p, &p);
1939         } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
1940                 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
1941                 encode_type (acfg, &klass->byval_arg, p, &p);
1942         } else {
1943                 /* Array class */
1944                 g_assert (klass->rank > 0);
1945                 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
1946                 encode_value (klass->rank, p, &p);
1947                 encode_klass_ref (acfg, klass->element_class, p, &p);
1948         }
1949         *endbuf = p;
1950 }
1951
1952 /*
1953  * encode_klass_ref:
1954  *
1955  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
1956  * standard metadata encoding.
1957  */
1958 static void
1959 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1960 {
1961         gboolean shared = FALSE;
1962
1963         /* 
1964          * The encoding of generic instances is large so emit them only once.
1965          */
1966         if (klass->generic_class) {
1967                 guint32 token;
1968                 g_assert (klass->type_token);
1969
1970                 /* Find a typespec for a class if possible */
1971                 token = find_typespec_for_class (acfg, klass);
1972                 if (!token)
1973                         shared = TRUE;
1974         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1975                 shared = TRUE;
1976         }
1977
1978         if (shared) {
1979                 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
1980                 guint8 *buf2, *p;
1981
1982                 if (!offset) {
1983                         buf2 = g_malloc (1024);
1984                         p = buf2;
1985
1986                         encode_klass_ref_inner (acfg, klass, p, &p);
1987                         g_assert (p - buf2 < 1024);
1988
1989                         offset = add_to_blob (acfg, buf2, p - buf2);
1990                         g_free (buf2);
1991
1992                         g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
1993                 } else {
1994                         offset --;
1995                 }
1996
1997                 p = buf;
1998                 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
1999                 encode_value (offset, p, &p);
2000                 *endbuf = p;
2001                 return;
2002         }
2003
2004         encode_klass_ref_inner (acfg, klass, buf, endbuf);
2005 }
2006
2007 static void
2008 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2009 {
2010         guint32 token = mono_get_field_token (field);
2011         guint8 *p = buf;
2012
2013         encode_klass_ref (cfg, field->parent, p, &p);
2014         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2015         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2016         *endbuf = p;
2017 }
2018
2019 static void
2020 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2021 {
2022         guint8 *p = buf;
2023         int i;
2024
2025         encode_value (inst->type_argc, p, &p);
2026         for (i = 0; i < inst->type_argc; ++i)
2027                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2028         *endbuf = p;
2029 }
2030
2031 static void
2032 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2033 {
2034         guint8 *p = buf;
2035         MonoGenericInst *inst;
2036
2037         inst = context->class_inst;
2038         if (inst) {
2039                 g_assert (inst->type_argc);
2040                 encode_ginst (acfg, inst, p, &p);
2041         } else {
2042                 encode_value (0, p, &p);
2043         }
2044         inst = context->method_inst;
2045         if (inst) {
2046                 g_assert (inst->type_argc);
2047                 encode_ginst (acfg, inst, p, &p);
2048         } else {
2049                 encode_value (0, p, &p);
2050         }
2051         *endbuf = p;
2052 }
2053
2054 static void
2055 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2056 {
2057         guint8 *p = buf;
2058
2059         g_assert (t->num_mods == 0);
2060         /* t->attrs can be ignored */
2061         //g_assert (t->attrs == 0);
2062
2063         if (t->pinned) {
2064                 *p = MONO_TYPE_PINNED;
2065                 ++p;
2066         }
2067         if (t->byref) {
2068                 *p = MONO_TYPE_BYREF;
2069                 ++p;
2070         }
2071
2072         *p = t->type;
2073         p ++;
2074
2075         switch (t->type) {
2076         case MONO_TYPE_VOID:
2077         case MONO_TYPE_BOOLEAN:
2078         case MONO_TYPE_CHAR:
2079         case MONO_TYPE_I1:
2080         case MONO_TYPE_U1:
2081         case MONO_TYPE_I2:
2082         case MONO_TYPE_U2:
2083         case MONO_TYPE_I4:
2084         case MONO_TYPE_U4:
2085         case MONO_TYPE_I8:
2086         case MONO_TYPE_U8:
2087         case MONO_TYPE_R4:
2088         case MONO_TYPE_R8:
2089         case MONO_TYPE_I:
2090         case MONO_TYPE_U:
2091         case MONO_TYPE_STRING:
2092         case MONO_TYPE_OBJECT:
2093         case MONO_TYPE_TYPEDBYREF:
2094                 break;
2095         case MONO_TYPE_VALUETYPE:
2096         case MONO_TYPE_CLASS:
2097                 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2098                 break;
2099         case MONO_TYPE_SZARRAY:
2100                 encode_klass_ref (acfg, t->data.klass, p, &p);
2101                 break;
2102         case MONO_TYPE_PTR:
2103                 encode_type (acfg, t->data.type, p, &p);
2104                 break;
2105         case MONO_TYPE_GENERICINST: {
2106                 MonoClass *gclass = t->data.generic_class->container_class;
2107                 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2108
2109                 encode_klass_ref (acfg, gclass, p, &p);
2110                 encode_ginst (acfg, inst, p, &p);
2111                 break;
2112         }
2113         case MONO_TYPE_ARRAY: {
2114                 MonoArrayType *array = t->data.array;
2115                 int i;
2116
2117                 encode_klass_ref (acfg, array->eklass, p, &p);
2118                 encode_value (array->rank, p, &p);
2119                 encode_value (array->numsizes, p, &p);
2120                 for (i = 0; i < array->numsizes; ++i)
2121                         encode_value (array->sizes [i], p, &p);
2122                 encode_value (array->numlobounds, p, &p);
2123                 for (i = 0; i < array->numlobounds; ++i)
2124                         encode_value (array->lobounds [i], p, &p);
2125                 break;
2126         }
2127         default:
2128                 g_assert_not_reached ();
2129         }
2130
2131         *endbuf = p;
2132 }
2133
2134 static void
2135 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2136 {
2137         guint8 *p = buf;
2138         guint32 flags = 0;
2139         int i;
2140
2141         /* Similar to the metadata encoding */
2142         if (sig->generic_param_count)
2143                 flags |= 0x10;
2144         if (sig->hasthis)
2145                 flags |= 0x20;
2146         if (sig->explicit_this)
2147                 flags |= 0x40;
2148         flags |= (sig->call_convention & 0x0F);
2149
2150         *p = flags;
2151         ++p;
2152         if (sig->generic_param_count)
2153                 encode_value (sig->generic_param_count, p, &p);
2154         encode_value (sig->param_count, p, &p);
2155
2156         encode_type (acfg, sig->ret, p, &p);
2157         for (i = 0; i < sig->param_count; ++i) {
2158                 if (sig->sentinelpos == i) {
2159                         *p = MONO_TYPE_SENTINEL;
2160                         ++p;
2161                 }
2162                 encode_type (acfg, sig->params [i], p, &p);
2163         }
2164
2165         *endbuf = p;
2166 }
2167
2168 #define MAX_IMAGE_INDEX 250
2169
2170 static void
2171 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2172 {
2173         guint32 image_index = get_image_index (acfg, method->klass->image);
2174         guint32 token = method->token;
2175         MonoJumpInfoToken *ji;
2176         guint8 *p = buf;
2177
2178         /*
2179          * The encoding for most methods is as follows:
2180          * - image index encoded as a leb128
2181          * - token index encoded as a leb128
2182          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2183          * types of method encodings.
2184          */
2185
2186         g_assert (image_index < MONO_AOT_METHODREF_MIN);
2187
2188         /* Mark methods which can't use aot trampolines because they need the further 
2189          * processing in mono_magic_trampoline () which requires a MonoMethod*.
2190          */
2191         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2192                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2193                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2194
2195         if (method->wrapper_type) {
2196                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2197
2198                 encode_value (method->wrapper_type, p, &p);
2199
2200                 switch (method->wrapper_type) {
2201                 case MONO_WRAPPER_REMOTING_INVOKE:
2202                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2203                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2204                         MonoMethod *m;
2205
2206                         m = mono_marshal_method_from_wrapper (method);
2207                         g_assert (m);
2208                         encode_method_ref (acfg, m, p, &p);
2209                         break;
2210                 }
2211                 case MONO_WRAPPER_PROXY_ISINST:
2212                 case MONO_WRAPPER_LDFLD:
2213                 case MONO_WRAPPER_LDFLDA:
2214                 case MONO_WRAPPER_STFLD:
2215                 case MONO_WRAPPER_ISINST: {
2216                         MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2217                         encode_klass_ref (acfg, proxy_class, p, &p);
2218                         break;
2219                 }
2220                 case MONO_WRAPPER_LDFLD_REMOTE:
2221                 case MONO_WRAPPER_STFLD_REMOTE:
2222                         break;
2223                 case MONO_WRAPPER_ALLOC: {
2224                         AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2225
2226                         /* The GC name is saved once in MonoAotFileInfo */
2227                         g_assert (info->alloc_type != -1);
2228                         encode_value (info->alloc_type, p, &p);
2229                         break;
2230                 }
2231                 case MONO_WRAPPER_WRITE_BARRIER:
2232                         break;
2233                 case MONO_WRAPPER_STELEMREF: {
2234                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2235
2236                         g_assert (info);
2237                         encode_value (info->subtype, p, &p);
2238                         if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2239                                 encode_value (info->d.virtual_stelemref.kind, p, &p);
2240                         break;
2241                 }
2242                 case MONO_WRAPPER_UNKNOWN: {
2243                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2244
2245                         g_assert (info);
2246                         encode_value (info->subtype, p, &p);
2247                         if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2248                                 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2249                                 encode_klass_ref (acfg, method->klass, p, &p);
2250                         else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2251                                 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2252                         break;
2253                 }
2254                 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2255                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2256
2257                         g_assert (info);
2258                         encode_value (info->subtype, p, &p);
2259                         if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2260                                 strcpy ((char*)p, method->name);
2261                                 p += strlen (method->name) + 1;
2262                         } else {
2263                                 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2264                                 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2265                         }
2266                         break;
2267                 }
2268                 case MONO_WRAPPER_SYNCHRONIZED: {
2269                         MonoMethod *m;
2270
2271                         m = mono_marshal_method_from_wrapper (method);
2272                         g_assert (m);
2273                         g_assert (m != method);
2274                         encode_method_ref (acfg, m, p, &p);
2275                         break;
2276                 }
2277                 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2278                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2279
2280                         g_assert (info);
2281                         encode_value (info->subtype, p, &p);
2282
2283                         if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2284                                 encode_value (info->d.element_addr.rank, p, &p);
2285                                 encode_value (info->d.element_addr.elem_size, p, &p);
2286                         } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2287                                 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2288                         } else {
2289                                 g_assert_not_reached ();
2290                         }
2291                         break;
2292                 }
2293                 case MONO_WRAPPER_CASTCLASS: {
2294                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2295
2296                         g_assert (info);
2297                         encode_value (info->subtype, p, &p);
2298                         break;
2299                 }
2300                 case MONO_WRAPPER_RUNTIME_INVOKE: {
2301                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2302
2303                         if (info) {
2304                                 encode_value (info->subtype, p, &p);
2305                                 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2306                                         encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2307                         } else {
2308                                 MonoMethodSignature *sig;
2309
2310                                 encode_value (0, p, &p);
2311
2312                                 sig = mono_method_signature (method);
2313                                 encode_signature (acfg, sig, p, &p);
2314                         }
2315                         break;
2316                 }
2317                 case MONO_WRAPPER_DELEGATE_INVOKE:
2318                 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2319                 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2320                         MonoMethodSignature *sig = mono_method_signature (method);
2321                         encode_signature (acfg, sig, p, &p);
2322                         break;
2323                 }
2324                 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2325                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2326
2327                         g_assert (info);
2328                         encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2329                         encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2330                         break;
2331                 }
2332                 default:
2333                         g_assert_not_reached ();
2334                 }
2335         } else if (mono_method_signature (method)->is_inflated) {
2336                 /* 
2337                  * This is a generic method, find the original token which referenced it and
2338                  * encode that.
2339                  * Obtain the token from information recorded by the JIT.
2340                  */
2341                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2342                 if (ji) {
2343                         image_index = get_image_index (acfg, ji->image);
2344                         g_assert (image_index < MAX_IMAGE_INDEX);
2345                         token = ji->token;
2346
2347                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2348                         encode_value (image_index, p, &p);
2349                         encode_value (token, p, &p);
2350                 } else {
2351                         MonoMethod *declaring;
2352                         MonoGenericContext *context = mono_method_get_context (method);
2353
2354                         g_assert (method->is_inflated);
2355                         declaring = ((MonoMethodInflated*)method)->declaring;
2356
2357                         /*
2358                          * This might be a non-generic method of a generic instance, which 
2359                          * doesn't have a token since the reference is generated by the JIT 
2360                          * like Nullable:Box/Unbox, or by generic sharing.
2361                          */
2362
2363                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2364                         /* Encode the klass */
2365                         encode_klass_ref (acfg, method->klass, p, &p);
2366                         /* Encode the method */
2367                         image_index = get_image_index (acfg, method->klass->image);
2368                         g_assert (image_index < MAX_IMAGE_INDEX);
2369                         g_assert (declaring->token);
2370                         token = declaring->token;
2371                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2372                         encode_value (image_index, p, &p);
2373                         encode_value (token, p, &p);
2374                         encode_generic_context (acfg, context, p, &p);
2375                 }
2376         } else if (token == 0) {
2377                 /* This might be a method of a constructed type like int[,].Set */
2378                 /* Obtain the token from information recorded by the JIT */
2379                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2380                 if (ji) {
2381                         image_index = get_image_index (acfg, ji->image);
2382                         g_assert (image_index < MAX_IMAGE_INDEX);
2383                         token = ji->token;
2384
2385                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2386                         encode_value (image_index, p, &p);
2387                         encode_value (token, p, &p);
2388                 } else {
2389                         /* Array methods */
2390                         g_assert (method->klass->rank);
2391
2392                         /* Encode directly */
2393                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2394                         encode_klass_ref (acfg, method->klass, p, &p);
2395                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2396                                 encode_value (0, p, &p);
2397                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2398                                 encode_value (1, p, &p);
2399                         else if (!strcmp (method->name, "Get"))
2400                                 encode_value (2, p, &p);
2401                         else if (!strcmp (method->name, "Address"))
2402                                 encode_value (3, p, &p);
2403                         else if (!strcmp (method->name, "Set"))
2404                                 encode_value (4, p, &p);
2405                         else
2406                                 g_assert_not_reached ();
2407                 }
2408         } else {
2409                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2410                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2411         }
2412         *endbuf = p;
2413 }
2414
2415 static gint
2416 compare_patches (gconstpointer a, gconstpointer b)
2417 {
2418         int i, j;
2419
2420         i = (*(MonoJumpInfo**)a)->ip.i;
2421         j = (*(MonoJumpInfo**)b)->ip.i;
2422
2423         if (i < j)
2424                 return -1;
2425         else
2426                 if (i > j)
2427                         return 1;
2428         else
2429                 return 0;
2430 }
2431
2432 static G_GNUC_UNUSED char*
2433 patch_to_string (MonoJumpInfo *patch_info)
2434 {
2435         GString *str;
2436
2437         str = g_string_new ("");
2438
2439         g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2440
2441         switch (patch_info->type) {
2442         case MONO_PATCH_INFO_VTABLE:
2443                 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2444                 break;
2445         default:
2446                 break;
2447         }
2448         g_string_append_printf (str, ")");
2449         return g_string_free (str, FALSE);
2450 }
2451
2452 /*
2453  * is_plt_patch:
2454  *
2455  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
2456  * PLT entry.
2457  */
2458 static inline gboolean
2459 is_plt_patch (MonoJumpInfo *patch_info)
2460 {
2461         switch (patch_info->type) {
2462         case MONO_PATCH_INFO_METHOD:
2463         case MONO_PATCH_INFO_INTERNAL_METHOD:
2464         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2465         case MONO_PATCH_INFO_ICALL_ADDR:
2466         case MONO_PATCH_INFO_CLASS_INIT:
2467         case MONO_PATCH_INFO_RGCTX_FETCH:
2468         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2469         case MONO_PATCH_INFO_MONITOR_ENTER:
2470         case MONO_PATCH_INFO_MONITOR_EXIT:
2471         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2472                 return TRUE;
2473         default:
2474                 return FALSE;
2475         }
2476 }
2477
2478 /*
2479  * get_plt_symbol:
2480  *
2481  *   Return the symbol identifying the plt entry PLT_OFFSET.
2482  */
2483 static char*
2484 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2485 {
2486 #ifdef __APPLE__
2487         /* 
2488          * The Apple linker reorganizes object files, so it doesn't like branches to local
2489          * labels, since those have no relocations.
2490          */
2491         return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2492 #else
2493         return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2494 #endif
2495 }
2496
2497 /*
2498  * get_plt_entry:
2499  *
2500  *   Return a PLT entry which belongs to the method identified by PATCH_INFO.
2501  */
2502 static MonoPltEntry*
2503 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2504 {
2505         MonoPltEntry *res;
2506
2507         if (!is_plt_patch (patch_info))
2508                 return NULL;
2509
2510         res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2511
2512         // FIXME: This breaks the calculation of final_got_size         
2513         if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2514                 /* 
2515                  * Allocate a separate PLT slot for each such patch, since some plt
2516                  * entries will refer to the method itself, and some will refer to the
2517                  * wrapper.
2518                  */
2519                 res = NULL;
2520         }
2521
2522         if (!res) {
2523                 MonoJumpInfo *new_ji;
2524
2525                 g_assert (!acfg->final_got_size);
2526
2527                 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2528
2529                 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2530                 res->plt_offset = acfg->plt_offset;
2531                 res->ji = new_ji;
2532                 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2533                 if (acfg->aot_opts.write_symbols)
2534                         res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2535                 if (res->debug_sym)
2536                         res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2537                 else
2538                         res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2539
2540                 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2541
2542                 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2543
2544                 acfg->plt_offset ++;
2545         }
2546
2547         return res;
2548 }
2549
2550 /**
2551  * get_got_offset:
2552  *
2553  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
2554  * JI could be found if it exists, otherwise allocates a new one.
2555  */
2556 static guint32
2557 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2558 {
2559         guint32 got_offset;
2560
2561         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2562         if (got_offset)
2563                 return got_offset - 1;
2564
2565         got_offset = acfg->got_offset;
2566         acfg->got_offset ++;
2567
2568         if (acfg->final_got_size)
2569                 g_assert (got_offset < acfg->final_got_size);
2570
2571         acfg->stats.got_slots ++;
2572         acfg->stats.got_slot_types [ji->type] ++;
2573
2574         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2575         g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2576         g_ptr_array_add (acfg->got_patches, ji);
2577
2578         return got_offset;
2579 }
2580
2581 /* Add a method to the list of methods which need to be emitted */
2582 static void
2583 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2584 {
2585         g_assert (method);
2586         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2587                 g_ptr_array_add (acfg->methods, method);
2588                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2589                 acfg->nmethods = acfg->methods->len + 1;
2590         }
2591
2592         if (method->wrapper_type || extra)
2593                 g_ptr_array_add (acfg->extra_methods, method);
2594 }
2595
2596 static guint32
2597 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2598 {
2599         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2600         
2601         g_assert (index);
2602
2603         return index - 1;
2604 }
2605
2606 static int
2607 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2608 {
2609         int index;
2610
2611         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2612         if (index)
2613                 return index - 1;
2614
2615         index = acfg->method_index;
2616         add_method_with_index (acfg, method, index, extra);
2617
2618         g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2619
2620         g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2621
2622         acfg->method_index ++;
2623
2624         return index;
2625 }
2626
2627 static int
2628 add_method (MonoAotCompile *acfg, MonoMethod *method)
2629 {
2630         return add_method_full (acfg, method, FALSE, 0);
2631 }
2632
2633 static void
2634 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2635 {
2636         add_method_full (acfg, method, TRUE, 0);
2637 }
2638
2639 static void
2640 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2641 {
2642         if (acfg->aot_opts.log_generics)
2643                 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2644
2645         add_method_full (acfg, method, TRUE, depth);
2646 }
2647
2648 static void
2649 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2650 {
2651         MonoAotCompile *acfg = user_data;
2652         MonoJitICallInfo *callinfo = value;
2653         MonoMethod *wrapper;
2654         char *name;
2655
2656         if (!callinfo->sig)
2657                 return;
2658
2659         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2660         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2661         g_free (name);
2662
2663         add_method (acfg, wrapper);
2664 }
2665
2666 static MonoMethod*
2667 get_runtime_invoke_sig (MonoMethodSignature *sig)
2668 {
2669         MonoMethodBuilder *mb;
2670         MonoMethod *m;
2671
2672         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2673         m = mono_mb_create_method (mb, sig, 16);
2674         return mono_marshal_get_runtime_invoke (m, FALSE);
2675 }
2676
2677 static gboolean
2678 can_marshal_struct (MonoClass *klass)
2679 {
2680         MonoClassField *field;
2681         gboolean can_marshal = TRUE;
2682         gpointer iter = NULL;
2683
2684         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2685                 return FALSE;
2686
2687         /* Only allow a few field types to avoid asserts in the marshalling code */
2688         while ((field = mono_class_get_fields (klass, &iter))) {
2689                 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2690                         continue;
2691
2692                 switch (field->type->type) {
2693                 case MONO_TYPE_I4:
2694                 case MONO_TYPE_U4:
2695                 case MONO_TYPE_I1:
2696                 case MONO_TYPE_U1:
2697                 case MONO_TYPE_BOOLEAN:
2698                 case MONO_TYPE_I2:
2699                 case MONO_TYPE_U2:
2700                 case MONO_TYPE_CHAR:
2701                 case MONO_TYPE_I8:
2702                 case MONO_TYPE_U8:
2703                 case MONO_TYPE_I:
2704                 case MONO_TYPE_U:
2705                 case MONO_TYPE_PTR:
2706                 case MONO_TYPE_R4:
2707                 case MONO_TYPE_R8:
2708                 case MONO_TYPE_STRING:
2709                         break;
2710                 case MONO_TYPE_VALUETYPE:
2711                         if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2712                                 can_marshal = FALSE;
2713                         break;
2714                 default:
2715                         can_marshal = FALSE;
2716                         break;
2717                 }
2718         }
2719
2720         /* Special cases */
2721         /* Its hard to compute whenever these can be marshalled or not */
2722         if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2723                 return TRUE;
2724
2725         return can_marshal;
2726 }
2727
2728 static void
2729 add_wrappers (MonoAotCompile *acfg)
2730 {
2731         MonoMethod *method, *m;
2732         int i, j;
2733         MonoMethodSignature *sig, *csig;
2734         guint32 token;
2735
2736         /* 
2737          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2738          * so there is only one wrapper of a given type, or inlining their contents into their
2739          * callers.
2740          */
2741
2742         /* 
2743          * FIXME: This depends on the fact that different wrappers have different 
2744          * names.
2745          */
2746
2747         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2748                 MonoMethod *method;
2749                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2750                 gboolean skip = FALSE;
2751
2752                 method = mono_get_method (acfg->image, token, NULL);
2753
2754                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2755                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2756                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2757                         skip = TRUE;
2758
2759                 if (method->is_generic || method->klass->generic_container)
2760                         skip = TRUE;
2761
2762                 /* Skip methods which can not be handled by get_runtime_invoke () */
2763                 sig = mono_method_signature (method);
2764                 if (!sig)
2765                         continue;
2766                 if ((sig->ret->type == MONO_TYPE_PTR) ||
2767                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2768                         skip = TRUE;
2769
2770                 for (j = 0; j < sig->param_count; j++) {
2771                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2772                                 skip = TRUE;
2773                 }
2774
2775 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2776                 if (!method->klass->contextbound) {
2777                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2778                         gboolean has_nullable = FALSE;
2779
2780                         for (j = 0; j < sig->param_count; j++) {
2781                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2782                                         has_nullable = TRUE;
2783                         }
2784
2785                         if (info && !has_nullable) {
2786                                 /* Supported by the dynamic runtime-invoke wrapper */
2787                                 skip = TRUE;
2788                                 g_free (info);
2789                         }
2790                 }
2791 #endif
2792
2793                 if (!skip) {
2794                         //printf ("%s\n", mono_method_full_name (method, TRUE));
2795                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2796                 }
2797         }
2798
2799         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2800 #ifdef MONO_ARCH_HAVE_TLS_GET
2801                 MonoMethodDesc *desc;
2802                 MonoMethod *orig_method;
2803                 int nallocators;
2804 #endif
2805
2806                 /* Runtime invoke wrappers */
2807
2808                 /* void runtime-invoke () [.cctor] */
2809                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2810                 csig->ret = &mono_defaults.void_class->byval_arg;
2811                 add_method (acfg, get_runtime_invoke_sig (csig));
2812
2813                 /* void runtime-invoke () [Finalize] */
2814                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2815                 csig->hasthis = 1;
2816                 csig->ret = &mono_defaults.void_class->byval_arg;
2817                 add_method (acfg, get_runtime_invoke_sig (csig));
2818
2819                 /* void runtime-invoke (string) [exception ctor] */
2820                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2821                 csig->hasthis = 1;
2822                 csig->ret = &mono_defaults.void_class->byval_arg;
2823                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2824                 add_method (acfg, get_runtime_invoke_sig (csig));
2825
2826                 /* void runtime-invoke (string, string) [exception ctor] */
2827                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2828                 csig->hasthis = 1;
2829                 csig->ret = &mono_defaults.void_class->byval_arg;
2830                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2831                 csig->params [1] = &mono_defaults.string_class->byval_arg;
2832                 add_method (acfg, get_runtime_invoke_sig (csig));
2833
2834                 /* string runtime-invoke () [Exception.ToString ()] */
2835                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2836                 csig->hasthis = 1;
2837                 csig->ret = &mono_defaults.string_class->byval_arg;
2838                 add_method (acfg, get_runtime_invoke_sig (csig));
2839
2840                 /* void runtime-invoke (string, Exception) [exception ctor] */
2841                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2842                 csig->hasthis = 1;
2843                 csig->ret = &mono_defaults.void_class->byval_arg;
2844                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2845                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2846                 add_method (acfg, get_runtime_invoke_sig (csig));
2847
2848                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2849                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2850                 csig->hasthis = 1;
2851                 csig->ret = &(mono_class_from_name (
2852                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2853                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2854                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2855                 add_method (acfg, get_runtime_invoke_sig (csig));
2856
2857                 /* runtime-invoke used by finalizers */
2858                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2859
2860                 /* This is used by mono_runtime_capture_context () */
2861                 method = mono_get_context_capture_method ();
2862                 if (method)
2863                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2864
2865 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2866                 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2867 #endif
2868
2869                 /* JIT icall wrappers */
2870                 /* FIXME: locking */
2871                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2872
2873                 /* stelemref */
2874                 add_method (acfg, mono_marshal_get_stelemref ());
2875
2876 #ifdef MONO_ARCH_HAVE_TLS_GET
2877                 /* Managed Allocators */
2878                 nallocators = mono_gc_get_managed_allocator_types ();
2879                 for (i = 0; i < nallocators; ++i) {
2880                         m = mono_gc_get_managed_allocator_by_type (i);
2881                         if (m)
2882                                 add_method (acfg, m);
2883                 }
2884
2885                 /* Monitor Enter/Exit */
2886                 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2887                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2888                 /* This is a v4 method */
2889                 if (orig_method) {
2890                         method = mono_monitor_get_fast_path (orig_method);
2891                         if (method)
2892                         add_method (acfg, method);
2893                 }
2894                 mono_method_desc_free (desc);
2895
2896                 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
2897                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2898                 g_assert (orig_method);
2899                 mono_method_desc_free (desc);
2900                 method = mono_monitor_get_fast_path (orig_method);
2901                 if (method)
2902                         add_method (acfg, method);
2903 #endif
2904
2905                 /* Stelemref wrappers */
2906                 /* There is only a constant number of these, iterating over all types should handle them all */
2907                 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2908                         MonoClass *klass;
2909                 
2910                         token = MONO_TOKEN_TYPE_DEF | (i + 1);
2911                         klass = mono_class_get (acfg->image, token);
2912                         if (klass)
2913                                 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2914                         else
2915                                 mono_loader_clear_error ();
2916                 }
2917
2918                 /* castclass_with_check wrapper */
2919                 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2920                 /* isinst_with_check wrapper */
2921                 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2922
2923 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
2924                 {
2925                         MonoMethodDesc *desc;
2926                         MonoMethod *m;
2927
2928                         desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2929                         m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2930                         mono_method_desc_free (desc);
2931                         if (m) {
2932                                 m = mono_monitor_get_fast_path (m);
2933                                 if (m)
2934                                         add_method (acfg, m);
2935                         }
2936                 }
2937 #endif
2938         }
2939
2940         /* 
2941          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2942          * we use the original method instead at runtime.
2943          * Since full-aot doesn't support remoting, this is not a problem.
2944          */
2945 #if 0
2946         /* remoting-invoke wrappers */
2947         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2948                 MonoMethodSignature *sig;
2949                 
2950                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2951                 method = mono_get_method (acfg->image, token, NULL);
2952
2953                 sig = mono_method_signature (method);
2954
2955                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2956                         m = mono_marshal_get_remoting_invoke_with_check (method);
2957
2958                         add_method (acfg, m);
2959                 }
2960         }
2961 #endif
2962
2963         /* delegate-invoke wrappers */
2964         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2965                 MonoClass *klass;
2966                 
2967                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2968                 klass = mono_class_get (acfg->image, token);
2969
2970                 if (!klass) {
2971                         mono_loader_clear_error ();
2972                         continue;
2973                 }
2974
2975                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2976                         method = mono_get_delegate_invoke (klass);
2977
2978                         m = mono_marshal_get_delegate_invoke (method, NULL);
2979
2980                         add_method (acfg, m);
2981
2982                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2983                         if (method)
2984                                 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2985
2986                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2987                         if (method)
2988                                 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2989                 }
2990         }
2991
2992         /* Synchronized wrappers */
2993         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2994                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2995                 method = mono_get_method (acfg->image, token, NULL);
2996
2997                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2998                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2999         }
3000
3001         /* pinvoke wrappers */
3002         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3003                 MonoMethod *method;
3004                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3005
3006                 method = mono_get_method (acfg->image, token, NULL);
3007
3008                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3009                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3010                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3011                 }
3012         }
3013  
3014         /* native-to-managed wrappers */
3015         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3016                 MonoMethod *method;
3017                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3018                 MonoCustomAttrInfo *cattr;
3019                 int j;
3020
3021                 method = mono_get_method (acfg->image, token, NULL);
3022
3023                 /* 
3024                  * Only generate native-to-managed wrappers for methods which have an
3025                  * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3026                  * name to avoid defining a new assembly to contain it.
3027                  */
3028                 cattr = mono_custom_attrs_from_method (method);
3029
3030                 if (cattr) {
3031                         for (j = 0; j < cattr->num_attrs; ++j)
3032                                 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3033                                         break;
3034                         if (j < cattr->num_attrs) {
3035                                 MonoCustomAttrEntry *e = &cattr->attrs [j];
3036                                 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3037                                 const char *p = (const char*)e->data;
3038                                 const char *named;
3039                                 int slen, num_named, named_type, data_type;
3040                                 char *n;
3041                                 MonoType *t;
3042                                 MonoClass *klass;
3043                                 char *export_name = NULL;
3044                                 MonoMethod *wrapper;
3045
3046                                 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3047                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3048                                         g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks", 
3049                                                 mono_method_full_name (method, TRUE));
3050                                         exit (1);
3051                                 }
3052
3053                                 g_assert (sig->param_count == 1);
3054                                 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3055
3056                                 /* 
3057                                  * Decode the cattr manually since we can't create objects
3058                                  * during aot compilation.
3059                                  */
3060                                         
3061                                 /* Skip prolog */
3062                                 p += 2;
3063
3064                                 /* From load_cattr_value () in reflection.c */
3065                                 slen = mono_metadata_decode_value (p, &p);
3066                                 n = g_memdup (p, slen + 1);
3067                                 n [slen] = 0;
3068                                 t = mono_reflection_type_from_name (n, acfg->image);
3069                                 g_assert (t);
3070                                 g_free (n);
3071
3072                                 klass = mono_class_from_mono_type (t);
3073                                 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3074
3075                                 p += slen;
3076
3077                                 num_named = read16 (p);
3078                                 p += 2;
3079
3080                                 g_assert (num_named < 2);
3081                                 if (num_named == 1) {
3082                                         int name_len;
3083                                         char *name;
3084                                         MonoType *prop_type;
3085
3086                                         /* parse ExportSymbol attribute */
3087                                         named = p;
3088                                         named_type = *named;
3089                                         named += 1;
3090                                         data_type = *named;
3091                                         named += 1;
3092
3093                                         name_len = mono_metadata_decode_blob_size (named, &named);
3094                                         name = g_malloc (name_len + 1);
3095                                         memcpy (name, named, name_len);
3096                                         name [name_len] = 0;
3097                                         named += name_len;
3098
3099                                         g_assert (named_type == 0x54);
3100                                         g_assert (!strcmp (name, "ExportSymbol"));
3101
3102                                         prop_type = &mono_defaults.string_class->byval_arg;
3103
3104                                         /* load_cattr_value (), string case */
3105                                         g_assert (*named != (char)0xff);
3106                                         slen = mono_metadata_decode_value (named, &named);
3107                                         export_name = g_malloc (slen + 1);
3108                                         memcpy (export_name, named, slen);
3109                                         export_name [slen] = 0;
3110                                         named += slen;
3111                                 }
3112
3113                                 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3114                                 add_method (acfg, wrapper);
3115                                 if (export_name)
3116                                         g_hash_table_insert (acfg->export_names, wrapper, export_name);
3117                         }
3118                 }
3119
3120                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3121                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3122                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3123                 }
3124         }
3125
3126         /* StructureToPtr/PtrToStructure wrappers */
3127         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3128                 MonoClass *klass;
3129                 
3130                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3131                 klass = mono_class_get (acfg->image, token);
3132
3133                 if (!klass) {
3134                         mono_loader_clear_error ();
3135                         continue;
3136                 }
3137
3138                 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
3139                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3140                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3141                 }
3142         }
3143 }
3144
3145 static gboolean
3146 has_type_vars (MonoClass *klass)
3147 {
3148         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3149                 return TRUE;
3150         if (klass->rank)
3151                 return has_type_vars (klass->element_class);
3152         if (klass->generic_class) {
3153                 MonoGenericContext *context = &klass->generic_class->context;
3154                 if (context->class_inst) {
3155                         int i;
3156
3157                         for (i = 0; i < context->class_inst->type_argc; ++i)
3158                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3159                                         return TRUE;
3160                 }
3161         }
3162         return FALSE;
3163 }
3164
3165 static gboolean
3166 method_has_type_vars (MonoMethod *method)
3167 {
3168         if (has_type_vars (method->klass))
3169                 return TRUE;
3170
3171         if (method->is_inflated) {
3172                 MonoGenericContext *context = mono_method_get_context (method);
3173                 if (context->method_inst) {
3174                         int i;
3175
3176                         for (i = 0; i < context->method_inst->type_argc; ++i)
3177                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3178                                         return TRUE;
3179                 }
3180         }
3181         return FALSE;
3182 }
3183
3184 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3185
3186 static void
3187 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3188 {
3189         /* This might lead to a huge code blowup so only do it if neccesary */
3190         if (!acfg->aot_opts.full_aot && !force)
3191                 return;
3192
3193         add_generic_class_with_depth (acfg, klass, 0, ref);
3194 }
3195
3196 static gboolean
3197 check_type_depth (MonoType *t, int depth)
3198 {
3199         int i;
3200
3201         if (depth > 8)
3202                 return TRUE;
3203
3204         switch (t->type) {
3205         case MONO_TYPE_GENERICINST: {
3206                 MonoGenericClass *gklass = t->data.generic_class;
3207                 MonoGenericInst *ginst = gklass->context.class_inst;
3208
3209                 if (ginst) {
3210                         for (i = 0; i < ginst->type_argc; ++i) {
3211                                 if (check_type_depth (ginst->type_argv [i], depth + 1))
3212                                         return TRUE;
3213                         }
3214                 }
3215                 break;
3216         }
3217         default:
3218                 break;
3219         }
3220
3221         return FALSE;
3222 }
3223
3224 /*
3225  * add_generic_class:
3226  *
3227  *   Add all methods of a generic class.
3228  */
3229 static void
3230 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3231 {
3232         MonoMethod *method;
3233         gpointer iter;
3234
3235         if (!acfg->ginst_hash)
3236                 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3237
3238         mono_class_init (klass);
3239
3240         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3241                 return;
3242
3243         if (has_type_vars (klass))
3244                 return;
3245
3246         if (!klass->generic_class && !klass->rank)
3247                 return;
3248
3249         if (!acfg->ginst_hash)
3250                 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3251
3252         if (g_hash_table_lookup (acfg->ginst_hash, klass))
3253                 return;
3254
3255         if (check_type_depth (&klass->byval_arg, 0))
3256                 return;
3257
3258         if (acfg->aot_opts.log_generics)
3259                 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3260
3261         g_hash_table_insert (acfg->ginst_hash, klass, klass);
3262
3263         iter = NULL;
3264         while ((method = mono_class_get_methods (klass, &iter))) {
3265                 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3266                         /* Already added */
3267                         continue;
3268
3269                 if (method->is_generic)
3270                         /* FIXME: */
3271                         continue;
3272
3273                 /*
3274                  * FIXME: Instances which are referenced by these methods are not added,
3275                  * for example Array.Resize<int> for List<int>.Add ().
3276                  */
3277                 add_extra_method_with_depth (acfg, method, depth + 1);
3278         }
3279
3280         if (klass->delegate) {
3281                 method = mono_get_delegate_invoke (klass);
3282
3283                 method = mono_marshal_get_delegate_invoke (method, NULL);
3284
3285                 if (acfg->aot_opts.log_generics)
3286                         printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3287
3288                 add_method (acfg, method);
3289         }
3290
3291         /* Add superclasses */
3292         if (klass->parent)
3293                 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3294
3295         /* 
3296          * For ICollection<T>, add instances of the helper methods
3297          * in Array, since a T[] could be cast to ICollection<T>.
3298          */
3299         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3300                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
3301                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3302                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3303                 gpointer iter;
3304                 char *name_prefix;
3305
3306                 if (!strcmp (klass->name, "IEnumerator`1"))
3307                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3308                 else
3309                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3310
3311                 /* Add the T[]/InternalEnumerator class */
3312                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3313                         MonoClass *nclass;
3314
3315                         iter = NULL;
3316                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3317                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3318                                         break;
3319                         }
3320                         g_assert (nclass);
3321                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3322                         add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3323                 }
3324
3325                 iter = NULL;
3326                 while ((method = mono_class_get_methods (array_class, &iter))) {
3327                         if (strstr (method->name, name_prefix)) {
3328                                 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3329
3330                                 add_extra_method_with_depth (acfg, m, depth);
3331                         }
3332                 }
3333
3334                 g_free (name_prefix);
3335         }
3336
3337         /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3338         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3339                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3340                 MonoClass *icomparable, *gcomparer;
3341                 MonoGenericContext ctx;
3342                 MonoType *args [16];
3343
3344                 memset (&ctx, 0, sizeof (ctx));
3345
3346                 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3347                 g_assert (icomparable);
3348                 args [0] = &tclass->byval_arg;
3349                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3350
3351                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3352                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3353                         g_assert (gcomparer);
3354                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3355                 }
3356         }
3357
3358         /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3359         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3360                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3361                 MonoClass *iface, *gcomparer;
3362                 MonoGenericContext ctx;
3363                 MonoType *args [16];
3364
3365                 memset (&ctx, 0, sizeof (ctx));
3366
3367                 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3368                 g_assert (iface);
3369                 args [0] = &tclass->byval_arg;
3370                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3371
3372                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3373                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3374                         g_assert (gcomparer);
3375                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3376                 }
3377         }
3378 }
3379
3380 static void
3381 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3382 {
3383         int i;
3384         MonoGenericContext ctx;
3385         MonoType *args [16];
3386
3387         memset (&ctx, 0, sizeof (ctx));
3388
3389         for (i = 0; i < ninsts; ++i) {
3390                 args [0] = insts [i];
3391                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3392                 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3393         }
3394 }
3395
3396 static void
3397 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3398 {
3399         MonoMethodHeader *header;
3400         MonoMethodSignature *sig;
3401         int j, depth;
3402
3403         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3404
3405         sig = mono_method_signature (method);
3406
3407         if (sig) {
3408                 for (j = 0; j < sig->param_count; ++j)
3409                         if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3410                                 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3411         }
3412
3413         header = mono_method_get_header (method);
3414
3415         if (header) {
3416                 for (j = 0; j < header->num_locals; ++j)
3417                         if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3418                                 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3419         }
3420 }
3421
3422 /*
3423  * add_generic_instances:
3424  *
3425  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
3426  */
3427 static void
3428 add_generic_instances (MonoAotCompile *acfg)
3429 {
3430         int i;
3431         guint32 token;
3432         MonoMethod *method;
3433         MonoGenericContext *context;
3434
3435         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3436                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3437                 method = mono_get_method (acfg->image, token, NULL);
3438
3439                 if (!method)
3440                         continue;
3441
3442                 if (method->klass->image != acfg->image)
3443                         continue;
3444
3445                 context = mono_method_get_context (method);
3446
3447                 if (context && ((context->class_inst && context->class_inst->is_open)))
3448                         continue;
3449
3450                 /*
3451                  * For open methods, create an instantiation which can be passed to the JIT.
3452                  * FIXME: Handle class_inst as well.
3453                  */
3454                 if (context && context->method_inst && context->method_inst->is_open) {
3455                         MonoGenericContext shared_context;
3456                         MonoGenericInst *inst;
3457                         MonoType **type_argv;
3458                         int i;
3459                         MonoMethod *declaring_method;
3460                         gboolean supported = TRUE;
3461
3462                         /* Check that the context doesn't contain open constructed types */
3463                         if (context->class_inst) {
3464                                 inst = context->class_inst;
3465                                 for (i = 0; i < inst->type_argc; ++i) {
3466                                         if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3467                                                 continue;
3468                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3469                                                 supported = FALSE;
3470                                 }
3471                         }
3472                         if (context->method_inst) {
3473                                 inst = context->method_inst;
3474                                 for (i = 0; i < inst->type_argc; ++i) {
3475                                         if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3476                                                 continue;
3477                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3478                                                 supported = FALSE;
3479                                 }
3480                         }
3481
3482                         if (!supported)
3483                                 continue;
3484
3485                         memset (&shared_context, 0, sizeof (MonoGenericContext));
3486
3487                         inst = context->class_inst;
3488                         if (inst) {
3489                                 type_argv = g_new0 (MonoType*, inst->type_argc);
3490                                 for (i = 0; i < inst->type_argc; ++i) {
3491                                         if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3492                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
3493                                         else
3494                                                 type_argv [i] = inst->type_argv [i];
3495                                 }
3496                                 
3497                                 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3498                                 g_free (type_argv);
3499                         }
3500
3501                         inst = context->method_inst;
3502                         if (inst) {
3503                                 type_argv = g_new0 (MonoType*, inst->type_argc);
3504                                 for (i = 0; i < inst->type_argc; ++i) {
3505                                         if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3506                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
3507                                         else
3508                                                 type_argv [i] = inst->type_argv [i];
3509                                 }
3510
3511                                 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3512                                 g_free (type_argv);
3513                         }
3514
3515                         if (method->is_generic || method->klass->generic_container)
3516                                 declaring_method = method;
3517                         else
3518                                 declaring_method = mono_method_get_declaring_generic_method (method);
3519
3520                         method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3521                 }
3522
3523                 /* 
3524                  * If the method is fully sharable, it was already added in place of its
3525                  * generic definition.
3526                  */
3527                 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3528                         continue;
3529
3530                 /*
3531                  * FIXME: Partially shared methods are not shared here, so we end up with
3532                  * many identical methods.
3533                  */
3534                 add_extra_method (acfg, method);
3535         }
3536
3537         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3538                 MonoClass *klass;
3539
3540                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3541
3542                 klass = mono_class_get (acfg->image, token);
3543                 if (!klass || klass->rank) {
3544                         mono_loader_clear_error ();
3545                         continue;
3546                 }
3547
3548                 add_generic_class (acfg, klass, FALSE, "typespec");
3549         }
3550
3551         /* Add types of args/locals */
3552         for (i = 0; i < acfg->methods->len; ++i) {
3553                 method = g_ptr_array_index (acfg->methods, i);
3554                 add_types_from_method_header (acfg, method);
3555         }
3556
3557         if (acfg->image == mono_defaults.corlib) {
3558                 MonoClass *klass;
3559                 MonoType *insts [256];
3560                 int ninsts = 0;
3561
3562                 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3563                 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3564                 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3565                 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3566                 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3567                 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3568                 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3569                 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3570                 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3571                 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3572                 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3573                 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3574
3575                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3576                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3577                 if (klass)
3578                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3579                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3580                 if (klass)
3581                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3582
3583                 /* Add instances of the array generic interfaces for primitive types */
3584                 /* This will add instances of the InternalArray_ helper methods in Array too */
3585                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3586                 if (klass)
3587                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3588                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3589                 if (klass)
3590                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3591                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3592                 if (klass)
3593                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3594
3595                 /* 
3596                  * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3597                  * used for all instances of GetGenericValueImpl by the AOT runtime.
3598                  */
3599                 {
3600                         MonoGenericContext ctx;
3601                         MonoType *args [16];
3602                         MonoMethod *get_method;
3603                         MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3604
3605                         get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3606
3607                         if (get_method) {
3608                                 memset (&ctx, 0, sizeof (ctx));
3609                                 args [0] = &mono_defaults.object_class->byval_arg;
3610                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3611                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3612                         }
3613                 }
3614
3615                 /* Same for CompareExchange<T>/Exchange<T> */
3616                 {
3617                         MonoGenericContext ctx;
3618                         MonoType *args [16];
3619                         MonoMethod *m;
3620                         MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3621                         gpointer iter = NULL;
3622
3623                         while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
3624                                 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
3625                                         memset (&ctx, 0, sizeof (ctx));
3626                                         args [0] = &mono_defaults.object_class->byval_arg;
3627                                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3628                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
3629                                 }
3630                         }
3631                 }
3632         }
3633 }
3634
3635 /*
3636  * is_direct_callable:
3637  *
3638  *   Return whenever the method identified by JI is directly callable without 
3639  * going through the PLT.
3640  */
3641 static gboolean
3642 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3643 {
3644         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3645                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3646                 if (callee_cfg) {
3647                         gboolean direct_callable = TRUE;
3648
3649                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3650                                 direct_callable = FALSE;
3651                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3652                                 // FIXME: Maybe call the wrapper directly ?
3653                                 direct_callable = FALSE;
3654
3655                         if (acfg->aot_opts.soft_debug) {
3656                                 /* Disable this so all calls go through load_method (), see the
3657                                  * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
3658                                  * mono_debugger_agent_init ().
3659                                  */
3660                                 direct_callable = FALSE;
3661                         }
3662
3663                         if (direct_callable)
3664                                 return TRUE;
3665                 }
3666         } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3667                 if (acfg->aot_opts.direct_pinvoke)
3668                         return TRUE;
3669         } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3670                 if (acfg->aot_opts.direct_icalls)
3671                         return TRUE;
3672                 return FALSE;
3673         }
3674
3675         return FALSE;
3676 }
3677
3678 static const char *
3679 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
3680 {
3681         MonoImage *image = method->klass->image;
3682         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
3683         MonoTableInfo *tables = image->tables;
3684         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3685         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3686         guint32 im_cols [MONO_IMPLMAP_SIZE];
3687         char *import;
3688
3689         import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
3690         if (import != NULL)
3691                 return import;
3692
3693         if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
3694                 return NULL;
3695
3696         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3697
3698         if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
3699                 return NULL;
3700
3701         import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
3702
3703         g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
3704         
3705         return import;
3706 }
3707
3708 /*
3709  * emit_and_reloc_code:
3710  *
3711  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3712  * is true, calls are made through the GOT too. This is used for emitting trampolines
3713  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3714  * since trampolines are needed to make PTL work.
3715  */
3716 static void
3717 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3718 {
3719         int i, pindex, start_index, method_index;
3720         GPtrArray *patches;
3721         MonoJumpInfo *patch_info;
3722         MonoMethodHeader *header;
3723         gboolean skip, direct_call;
3724         guint32 got_slot;
3725         char direct_call_target [1024];
3726         const char *direct_pinvoke;
3727
3728         if (method) {
3729                 header = mono_method_get_header (method);
3730
3731                 method_index = get_method_index (acfg, method);
3732         }
3733
3734         /* Collect and sort relocations */
3735         patches = g_ptr_array_new ();
3736         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3737                 g_ptr_array_add (patches, patch_info);
3738         g_ptr_array_sort (patches, compare_patches);
3739
3740         start_index = 0;
3741         for (i = 0; i < code_len; i++) {
3742                 patch_info = NULL;
3743                 for (pindex = start_index; pindex < patches->len; ++pindex) {
3744                         patch_info = g_ptr_array_index (patches, pindex);
3745                         if (patch_info->ip.i >= i)
3746                                 break;
3747                 }
3748
3749 #ifdef MONO_ARCH_AOT_SUPPORTED
3750                 skip = FALSE;
3751                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3752                         start_index = pindex;
3753
3754                         switch (patch_info->type) {
3755                         case MONO_PATCH_INFO_NONE:
3756                                 break;
3757                         case MONO_PATCH_INFO_GOT_OFFSET: {
3758                                 int code_size;
3759  
3760                                 arch_emit_got_offset (acfg, code + i, &code_size);
3761                                 i += code_size - 1;
3762                                 skip = TRUE;
3763                                 patch_info->type = MONO_PATCH_INFO_NONE;
3764                                 break;
3765                         }
3766                         default: {
3767                                 /*
3768                                  * If this patch is a call, try emitting a direct call instead of
3769                                  * through a PLT entry. This is possible if the called method is in
3770                                  * the same assembly and requires no initialization.
3771                                  */
3772                                 direct_call = FALSE;
3773                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3774                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3775                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3776                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3777                                                 direct_call = TRUE;
3778                                                 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3779                                                 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3780                                         }
3781
3782                                         acfg->stats.all_calls ++;
3783                                 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3784                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3785                                                 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
3786                                                         direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
3787                                                 else
3788                                                         direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
3789                                                 if (direct_pinvoke) {
3790                                                         const char*prefix;
3791 #if defined(__APPLE__)
3792                                                         prefix = "_";
3793 #else
3794                                                         prefix = "";
3795 #endif
3796                                                         direct_call = TRUE;
3797                                                         g_assert (strlen (direct_pinvoke) < 1000);
3798                                                         sprintf (direct_call_target, "%s%s", prefix, direct_pinvoke);
3799                                                 }
3800                                         }
3801                                 }
3802
3803                                 if (direct_call) {
3804                                         patch_info->type = MONO_PATCH_INFO_NONE;
3805                                         acfg->stats.direct_calls ++;
3806                                 }
3807
3808                                 if (!got_only && !direct_call) {
3809                                         MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3810                                         if (plt_entry) {
3811                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3812                                                 direct_call = TRUE;
3813                                                 sprintf (direct_call_target, "%s", plt_entry->symbol);
3814                 
3815                                                 /* Nullify the patch */
3816                                                 patch_info->type = MONO_PATCH_INFO_NONE;
3817                                                 plt_entry->jit_used = TRUE;
3818                                         }
3819                                 }
3820
3821                                 if (direct_call) {
3822                                         int call_size;
3823
3824                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
3825                                         i += call_size - 1;
3826                                 } else {
3827                                         int code_size;
3828
3829                                         got_slot = get_got_offset (acfg, patch_info);
3830
3831                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3832                                         i += code_size - 1;
3833                                 }
3834                                 skip = TRUE;
3835                         }
3836                         }
3837                 }
3838 #endif /* MONO_ARCH_AOT_SUPPORTED */
3839
3840                 if (!skip) {
3841                         /* Find next patch */
3842                         patch_info = NULL;
3843                         for (pindex = start_index; pindex < patches->len; ++pindex) {
3844                                 patch_info = g_ptr_array_index (patches, pindex);
3845                                 if (patch_info->ip.i >= i)
3846                                         break;
3847                         }
3848
3849                         /* Try to emit multiple bytes at once */
3850                         if (pindex < patches->len && patch_info->ip.i > i) {
3851                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3852                                 i = patch_info->ip.i - 1;
3853                         } else {
3854                                 emit_bytes (acfg, code + i, 1);
3855                         }
3856                 }
3857         }
3858 }
3859
3860 /*
3861  * sanitize_symbol:
3862  *
3863  *   Modify SYMBOL so it only includes characters permissible in symbols.
3864  */
3865 static void
3866 sanitize_symbol (char *symbol)
3867 {
3868         int i, len = strlen (symbol);
3869
3870         for (i = 0; i < len; ++i)
3871                 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3872                         symbol [i] = '_';
3873 }
3874
3875 static char*
3876 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3877 {
3878         char *name1, *name2, *cached;
3879         int i, j, len, count;
3880
3881         name1 = mono_method_full_name (method, TRUE);
3882         len = strlen (name1);
3883         name2 = malloc (strlen (prefix) + len + 16);
3884         memcpy (name2, prefix, strlen (prefix));
3885         j = strlen (prefix);
3886         for (i = 0; i < len; ++i) {
3887                 if (isalnum (name1 [i])) {
3888                         name2 [j ++] = name1 [i];
3889                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3890                         i += 2;
3891                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3892                         name2 [j ++] = '_';
3893                         i++;
3894                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3895                 } else
3896                         name2 [j ++] = '_';
3897         }
3898         name2 [j] = '\0';
3899
3900         g_free (name1);
3901
3902         count = 0;
3903         while (g_hash_table_lookup (cache, name2)) {
3904                 sprintf (name2 + j, "_%d", count);
3905                 count ++;
3906         }
3907
3908         cached = g_strdup (name2);
3909         g_hash_table_insert (cache, cached, cached);
3910
3911         return name2;
3912 }
3913
3914 static void
3915 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3916 {
3917         MonoMethod *method;
3918         int method_index;
3919         guint8 *code;
3920         char *debug_sym = NULL;
3921         char symbol [128];
3922         int func_alignment = AOT_FUNC_ALIGNMENT;
3923         MonoMethodHeader *header;
3924         char *export_name;
3925
3926         method = cfg->orig_method;
3927         code = cfg->native_code;
3928         header = cfg->header;
3929
3930         method_index = get_method_index (acfg, method);
3931
3932         /* Make the labels local */
3933         sprintf (symbol, "%s", cfg->asm_symbol);
3934
3935         emit_section_change (acfg, ".text", 0);
3936         emit_alignment (acfg, func_alignment);
3937         emit_label (acfg, symbol);
3938
3939         if (acfg->aot_opts.write_symbols) {
3940                 /* 
3941                  * Write a C style symbol for every method, this has two uses:
3942                  * - it works on platforms where the dwarf debugging info is not
3943                  *   yet supported.
3944                  * - it allows the setting of breakpoints of aot-ed methods.
3945                  */
3946                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3947
3948                 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3949                 if (acfg->need_no_dead_strip)
3950                         fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
3951                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3952                 emit_label (acfg, debug_sym);
3953         }
3954
3955         export_name = g_hash_table_lookup (acfg->export_names, method);
3956         if (export_name) {
3957                 /* Emit a global symbol for the method */
3958                 emit_global_inner (acfg, export_name, TRUE);
3959                 emit_label (acfg, export_name);
3960         }
3961
3962         if (cfg->verbose_level > 0)
3963                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3964
3965         acfg->stats.code_size += cfg->code_len;
3966
3967         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3968
3969         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3970
3971         emit_line (acfg);
3972
3973         if (acfg->aot_opts.write_symbols) {
3974                 emit_symbol_size (acfg, debug_sym, ".");
3975                 g_free (debug_sym);
3976         }
3977
3978         sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3979         emit_label (acfg, symbol);
3980 }
3981
3982 /**
3983  * encode_patch:
3984  *
3985  *  Encode PATCH_INFO into its disk representation.
3986  */
3987 static void
3988 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3989 {
3990         guint8 *p = buf;
3991
3992         switch (patch_info->type) {
3993         case MONO_PATCH_INFO_NONE:
3994                 break;
3995         case MONO_PATCH_INFO_IMAGE:
3996                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3997                 break;
3998         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3999         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4000         case MONO_PATCH_INFO_CASTCLASS_CACHE:
4001                 break;
4002         case MONO_PATCH_INFO_METHOD_REL:
4003                 encode_value ((gint)patch_info->data.offset, p, &p);
4004                 break;
4005         case MONO_PATCH_INFO_SWITCH: {
4006                 gpointer *table = (gpointer *)patch_info->data.table->table;
4007                 int k;
4008
4009                 encode_value (patch_info->data.table->table_size, p, &p);
4010                 for (k = 0; k < patch_info->data.table->table_size; k++)
4011                         encode_value ((int)(gssize)table [k], p, &p);
4012                 break;
4013         }
4014         case MONO_PATCH_INFO_METHODCONST:
4015         case MONO_PATCH_INFO_METHOD:
4016         case MONO_PATCH_INFO_METHOD_JUMP:
4017         case MONO_PATCH_INFO_ICALL_ADDR:
4018         case MONO_PATCH_INFO_METHOD_RGCTX:
4019                 encode_method_ref (acfg, patch_info->data.method, p, &p);
4020                 break;
4021         case MONO_PATCH_INFO_INTERNAL_METHOD:
4022         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4023                 guint32 len = strlen (patch_info->data.name);
4024
4025                 encode_value (len, p, &p);
4026
4027                 memcpy (p, patch_info->data.name, len);
4028                 p += len;
4029                 *p++ = '\0';
4030                 break;
4031         }
4032         case MONO_PATCH_INFO_LDSTR: {
4033                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4034                 guint32 token = patch_info->data.token->token;
4035                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4036                 encode_value (image_index, p, &p);
4037                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4038                 break;
4039         }
4040         case MONO_PATCH_INFO_RVA:
4041         case MONO_PATCH_INFO_DECLSEC:
4042         case MONO_PATCH_INFO_LDTOKEN:
4043         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4044                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4045                 encode_value (patch_info->data.token->token, p, &p);
4046                 encode_value (patch_info->data.token->has_context, p, &p);
4047                 if (patch_info->data.token->has_context)
4048                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4049                 break;
4050         case MONO_PATCH_INFO_EXC_NAME: {
4051                 MonoClass *ex_class;
4052
4053                 ex_class =
4054                         mono_class_from_name (mono_defaults.exception_class->image,
4055                                                                   "System", patch_info->data.target);
4056                 g_assert (ex_class);
4057                 encode_klass_ref (acfg, ex_class, p, &p);
4058                 break;
4059         }
4060         case MONO_PATCH_INFO_R4:
4061                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4062                 break;
4063         case MONO_PATCH_INFO_R8:
4064                 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4065                 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4066                 break;
4067         case MONO_PATCH_INFO_VTABLE:
4068         case MONO_PATCH_INFO_CLASS:
4069         case MONO_PATCH_INFO_IID:
4070         case MONO_PATCH_INFO_ADJUSTED_IID:
4071                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4072                 break;
4073         case MONO_PATCH_INFO_CLASS_INIT:
4074         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4075                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4076                 break;
4077         case MONO_PATCH_INFO_FIELD:
4078         case MONO_PATCH_INFO_SFLDA:
4079                 encode_field_info (acfg, patch_info->data.field, p, &p);
4080                 break;
4081         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4082                 break;
4083         case MONO_PATCH_INFO_RGCTX_FETCH: {
4084                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4085                 guint32 offset;
4086                 guint8 *buf2, *p2;
4087
4088                 /* 
4089                  * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4090                  * reference the same method, so encode the method only once.
4091                  */
4092                 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4093                 if (!offset) {
4094                         buf2 = g_malloc (1024);
4095                         p2 = buf2;
4096
4097                         encode_method_ref (acfg, entry->method, p2, &p2);
4098                         g_assert (p2 - buf2 < 1024);
4099
4100                         offset = add_to_blob (acfg, buf2, p2 - buf2);
4101                         g_free (buf2);
4102
4103                         g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4104                 } else {
4105                         offset --;
4106                 }
4107
4108                 encode_value (offset, p, &p);
4109                 g_assert (entry->info_type < 256);
4110                 g_assert (entry->data->type < 256);
4111                 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4112                 encode_patch (acfg, entry->data, p, &p);
4113                 break;
4114         }
4115         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4116         case MONO_PATCH_INFO_MONITOR_ENTER:
4117         case MONO_PATCH_INFO_MONITOR_EXIT:
4118         case MONO_PATCH_INFO_SEQ_POINT_INFO:
4119                 break;
4120         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4121                 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4122                 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4123                 break;
4124         case MONO_PATCH_INFO_SIGNATURE:
4125                 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4126                 break;
4127         default:
4128                 g_warning ("unable to handle jump info %d", patch_info->type);
4129                 g_assert_not_reached ();
4130         }
4131
4132         *endbuf = p;
4133 }
4134
4135 static void
4136 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4137 {
4138         guint8 *p = buf;
4139         guint32 pindex, offset;
4140         MonoJumpInfo *patch_info;
4141
4142         encode_value (n_patches, p, &p);
4143
4144         for (pindex = 0; pindex < patches->len; ++pindex) {
4145                 patch_info = g_ptr_array_index (patches, pindex);
4146
4147                 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4148                         /* Nothing to do */
4149                         continue;
4150
4151                 offset = get_got_offset (acfg, patch_info);
4152                 encode_value (offset, p, &p);
4153         }
4154
4155         *endbuf = p;
4156 }
4157
4158 static void
4159 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4160 {
4161         MonoMethod *method;
4162         GList *l;
4163         int pindex, buf_size, n_patches;
4164         GPtrArray *patches;
4165         MonoJumpInfo *patch_info;
4166         MonoMethodHeader *header;
4167         guint32 method_index;
4168         guint8 *p, *buf;
4169         guint32 first_got_offset;
4170
4171         method = cfg->orig_method;
4172         header = mono_method_get_header (method);
4173
4174         method_index = get_method_index (acfg, method);
4175
4176         /* Sort relocations */
4177         patches = g_ptr_array_new ();
4178         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4179                 g_ptr_array_add (patches, patch_info);
4180         g_ptr_array_sort (patches, compare_patches);
4181
4182         first_got_offset = acfg->cfgs [method_index]->got_offset;
4183
4184         /**********************/
4185         /* Encode method info */
4186         /**********************/
4187
4188         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4189         p = buf = g_malloc (buf_size);
4190
4191         if (mono_class_get_cctor (method->klass))
4192                 encode_klass_ref (acfg, method->klass, p, &p);
4193         else
4194                 /* Not needed when loading the method */
4195                 encode_value (0, p, &p);
4196
4197         /* String table */
4198         if (cfg->opt & MONO_OPT_SHARED) {
4199                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4200                 for (l = cfg->ldstr_list; l; l = l->next) {
4201                         encode_value ((long)l->data, p, &p);
4202                 }
4203         }
4204         else
4205                 /* Used only in shared mode */
4206                 g_assert (!cfg->ldstr_list);
4207
4208         n_patches = 0;
4209         for (pindex = 0; pindex < patches->len; ++pindex) {
4210                 patch_info = g_ptr_array_index (patches, pindex);
4211                 
4212                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4213                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
4214                         patch_info->type = MONO_PATCH_INFO_NONE;
4215                         /* Nothing to do */
4216                         continue;
4217                 }
4218
4219                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4220                         /* Stored in a GOT slot initialized at module load time */
4221                         patch_info->type = MONO_PATCH_INFO_NONE;
4222                         continue;
4223                 }
4224
4225                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4226                         /* Stored in a GOT slot initialized at module load time */
4227                         patch_info->type = MONO_PATCH_INFO_NONE;
4228                         continue;
4229                 }
4230
4231                 if (is_plt_patch (patch_info)) {
4232                         /* Calls are made through the PLT */
4233                         patch_info->type = MONO_PATCH_INFO_NONE;
4234                         continue;
4235                 }
4236
4237                 n_patches ++;
4238         }
4239
4240         if (n_patches)
4241                 g_assert (cfg->has_got_slots);
4242
4243         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4244
4245         acfg->stats.info_size += p - buf;
4246
4247         g_assert (p - buf < buf_size);
4248
4249         cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4250         g_free (buf);
4251 }
4252
4253 static guint32
4254 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4255 {
4256         guint32 cache_index;
4257         guint32 offset;
4258
4259         /* Reuse the unwind module to canonize and store unwind info entries */
4260         cache_index = mono_cache_unwind_info (encoded, encoded_len);
4261
4262         /* Use +/- 1 to distinguish 0s from missing entries */
4263         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4264         if (offset)
4265                 return offset - 1;
4266         else {
4267                 guint8 buf [16];
4268                 guint8 *p;
4269
4270                 /* 
4271                  * It would be easier to use assembler symbols, but the caller needs an
4272                  * offset now.
4273                  */
4274                 offset = acfg->unwind_info_offset;
4275                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4276                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4277
4278                 p = buf;
4279                 encode_value (encoded_len, p, &p);
4280
4281                 acfg->unwind_info_offset += encoded_len + (p - buf);
4282                 return offset;
4283         }
4284 }
4285
4286 static void
4287 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4288 {
4289         MonoMethod *method;
4290         int i, k, buf_size, method_index;
4291         guint32 debug_info_size;
4292         guint8 *code;
4293         MonoMethodHeader *header;
4294         guint8 *p, *buf, *debug_info;
4295         MonoJitInfo *jinfo = cfg->jit_info;
4296         guint32 flags;
4297         gboolean use_unwind_ops = FALSE;
4298         MonoSeqPointInfo *seq_points;
4299
4300         method = cfg->orig_method;
4301         code = cfg->native_code;
4302         header = cfg->header;
4303
4304         method_index = get_method_index (acfg, method);
4305
4306         if (!acfg->aot_opts.nodebug) {
4307                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4308         } else {
4309                 debug_info = NULL;
4310                 debug_info_size = 0;
4311         }
4312
4313         seq_points = cfg->seq_point_info;
4314
4315         buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4316         p = buf = g_malloc (buf_size);
4317
4318 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4319         use_unwind_ops = cfg->unwind_ops != NULL;
4320 #endif
4321
4322         flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0) | (jinfo->has_arch_eh_info ? 128 : 0);
4323
4324         encode_value (flags, p, &p);
4325
4326         if (use_unwind_ops) {
4327                 guint32 encoded_len;
4328                 guint8 *encoded;
4329
4330                 /* 
4331                  * This is a duplicate of the data in the .debug_frame section, but that
4332                  * section cannot be accessed using the dl interface.
4333                  */
4334                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4335                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4336                 g_free (encoded);
4337         } else {
4338                 encode_value (jinfo->used_regs, p, &p);
4339         }
4340
4341         /*Encode the number of holes before the number of clauses to make decoding easier*/
4342         if (jinfo->has_try_block_holes) {
4343                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4344                 encode_value (table->num_holes, p, &p);
4345         }
4346
4347         /* Exception table */
4348         if (cfg->compile_llvm) {
4349                 /*
4350                  * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4351                  * since the information is only available to llc. Instead, we let llc save the data
4352                  * into the LSDA, and read it from there at runtime.
4353                  */
4354                 /* The assembly might be CIL stripped so emit the data ourselves */
4355                 if (header->num_clauses)
4356                         encode_value (header->num_clauses, p, &p);
4357
4358                 for (k = 0; k < header->num_clauses; ++k) {
4359                         MonoExceptionClause *clause;
4360
4361                         clause = &header->clauses [k];
4362
4363                         encode_value (clause->flags, p, &p);
4364                         if (clause->data.catch_class) {
4365                                 encode_value (1, p, &p);
4366                                 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4367                         } else {
4368                                 encode_value (0, p, &p);
4369                         }
4370
4371                         /* Emit a list of nesting clauses */
4372                         for (i = 0; i < header->num_clauses; ++i) {
4373                                 gint32 cindex1 = k;
4374                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4375                                 gint32 cindex2 = i;
4376                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4377
4378                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4379                                         encode_value (i, p, &p);
4380                         }
4381                         encode_value (-1, p, &p);
4382                 }
4383         } else {
4384                 if (jinfo->num_clauses)
4385                         encode_value (jinfo->num_clauses, p, &p);
4386
4387                 for (k = 0; k < jinfo->num_clauses; ++k) {
4388                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4389
4390                         encode_value (ei->flags, p, &p);
4391                         encode_value (ei->exvar_offset, p, &p);
4392
4393                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4394                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4395                         else {
4396                                 if (ei->data.catch_class) {
4397                                         encode_value (1, p, &p);
4398                                         encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4399                                 } else {
4400                                         encode_value (0, p, &p);
4401                                 }
4402                         }
4403
4404                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4405                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4406                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4407                 }
4408         }
4409
4410         if (jinfo->has_generic_jit_info) {
4411                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4412                 guint8 *p1;
4413
4414                 p1 = p;
4415                 encode_value (gi->nlocs, p, &p);
4416                 if (gi->nlocs) {
4417                         for (i = 0; i < gi->nlocs; ++i) {
4418                                 MonoDwarfLocListEntry *entry = &gi->locations [i];
4419
4420                                 encode_value (entry->is_reg ? 1 : 0, p, &p);
4421                                 encode_value (entry->reg, p, &p);
4422                                 if (!entry->is_reg)
4423                                         encode_value (entry->offset, p, &p);
4424                                 if (i == 0)
4425                                         g_assert (entry->from == 0);
4426                                 else
4427                                         encode_value (entry->from, p, &p);
4428                                 encode_value (entry->to, p, &p);
4429                         }
4430                 } else {
4431                         if (!cfg->compile_llvm) {
4432                                 encode_value (gi->has_this ? 1 : 0, p, &p);
4433                                 encode_value (gi->this_reg, p, &p);
4434                                 encode_value (gi->this_offset, p, &p);
4435                         }
4436                 }
4437
4438                 /* 
4439                  * Need to encode jinfo->method too, since it is not equal to 'method'
4440                  * when using generic sharing.
4441                  */
4442                 encode_method_ref (acfg, jinfo->method, p, &p);
4443         }
4444
4445         if (jinfo->has_try_block_holes) {
4446                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4447                 for (i = 0; i < table->num_holes; ++i) {
4448                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4449                         encode_value (hole->clause, p, &p);
4450                         encode_value (hole->length, p, &p);
4451                         encode_value (hole->offset, p, &p);
4452                 }
4453         }
4454
4455         if (jinfo->has_arch_eh_info) {
4456                 MonoArchEHJitInfo *eh_info;
4457
4458                 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
4459                 encode_value (eh_info->stack_size, p, &p);
4460         }
4461
4462         if (seq_points) {
4463                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4464
4465                 encode_value (seq_points->len, p, &p);
4466                 last_il_offset = last_native_offset = 0;
4467                 for (i = 0; i < seq_points->len; ++i) {
4468                         SeqPoint *sp = &seq_points->seq_points [i];
4469                         il_offset = sp->il_offset;
4470                         native_offset = sp->native_offset;
4471                         encode_value (il_offset - last_il_offset, p, &p);
4472                         encode_value (native_offset - last_native_offset, p, &p);
4473                         last_il_offset = il_offset;
4474                         last_native_offset = native_offset;
4475
4476                         encode_value (sp->next_len, p, &p);
4477                         for (j = 0; j < sp->next_len; ++j)
4478                                 encode_value (sp->next [j], p, &p);
4479                 }
4480         }
4481                 
4482         g_assert (debug_info_size < buf_size);
4483
4484         encode_value (debug_info_size, p, &p);
4485         if (debug_info_size) {
4486                 memcpy (p, debug_info, debug_info_size);
4487                 p += debug_info_size;
4488                 g_free (debug_info);
4489         }
4490
4491         /* GC Map */
4492         if (cfg->gc_map) {
4493                 encode_value (cfg->gc_map_size, p, &p);
4494                 /* The GC map requires 4 bytes of alignment */
4495                 while ((gsize)p % 4)
4496                         p ++;
4497                 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4498                 p += cfg->gc_map_size;
4499         }
4500
4501         acfg->stats.ex_info_size += p - buf;
4502
4503         g_assert (p - buf < buf_size);
4504
4505         /* Emit info */
4506         /* The GC Map requires 4 byte alignment */
4507         cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4508         g_free (buf);
4509 }
4510
4511 static guint32
4512 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4513 {
4514         MonoClass *klass = mono_class_get (acfg->image, token);
4515         guint8 *p, *buf;
4516         int i, buf_size, res;
4517         gboolean no_special_static, cant_encode;
4518         gpointer iter = NULL;
4519
4520         if (!klass) {
4521                 mono_loader_clear_error ();
4522
4523                 buf_size = 16;
4524
4525                 p = buf = g_malloc (buf_size);
4526
4527                 /* Mark as unusable */
4528                 encode_value (-1, p, &p);
4529
4530                 res = add_to_blob (acfg, buf, p - buf);
4531                 g_free (buf);
4532
4533                 return res;
4534         }
4535                 
4536         buf_size = 10240 + (klass->vtable_size * 16);
4537         p = buf = g_malloc (buf_size);
4538
4539         g_assert (klass);
4540
4541         mono_class_init (klass);
4542
4543         mono_class_get_nested_types (klass, &iter);
4544         g_assert (klass->nested_classes_inited);
4545
4546         mono_class_setup_vtable (klass);
4547
4548         /* 
4549          * Emit all the information which is required for creating vtables so
4550          * the runtime does not need to create the MonoMethod structures which
4551          * take up a lot of space.
4552          */
4553
4554         no_special_static = !mono_class_has_special_static_fields (klass);
4555
4556         /* Check whenever we have enough info to encode the vtable */
4557         cant_encode = FALSE;
4558         for (i = 0; i < klass->vtable_size; ++i) {
4559                 MonoMethod *cm = klass->vtable [i];
4560
4561                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4562                         cant_encode = TRUE;
4563         }
4564
4565         mono_class_has_finalizer (klass);
4566
4567         if (klass->generic_container || cant_encode) {
4568                 encode_value (-1, p, &p);
4569         } else {
4570                 encode_value (klass->vtable_size, p, &p);
4571                 encode_value ((klass->generic_container ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | ((klass->ext && klass->ext->nested_classes) ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
4572                 if (klass->has_cctor)
4573                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4574                 if (klass->has_finalize)
4575                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4576  
4577                 encode_value (klass->instance_size, p, &p);
4578                 encode_value (mono_class_data_size (klass), p, &p);
4579                 encode_value (klass->packing_size, p, &p);
4580                 encode_value (klass->min_align, p, &p);
4581
4582                 for (i = 0; i < klass->vtable_size; ++i) {
4583                         MonoMethod *cm = klass->vtable [i];
4584
4585                         if (cm)
4586                                 encode_method_ref (acfg, cm, p, &p);
4587                         else
4588                                 encode_value (0, p, &p);
4589                 }
4590         }
4591
4592         acfg->stats.class_info_size += p - buf;
4593
4594         g_assert (p - buf < buf_size);
4595         res = add_to_blob (acfg, buf, p - buf);
4596         g_free (buf);
4597
4598         return res;
4599 }
4600
4601 static char*
4602 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4603 {
4604         char *debug_sym = NULL;
4605
4606         switch (ji->type) {
4607         case MONO_PATCH_INFO_METHOD:
4608                 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4609                 break;
4610         case MONO_PATCH_INFO_INTERNAL_METHOD:
4611                 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4612                 break;
4613         case MONO_PATCH_INFO_CLASS_INIT:
4614                 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4615                 sanitize_symbol (debug_sym);
4616                 break;
4617         case MONO_PATCH_INFO_RGCTX_FETCH:
4618                 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4619                 break;
4620         case MONO_PATCH_INFO_ICALL_ADDR: {
4621                 char *s = get_debug_sym (ji->data.method, "", cache);
4622                 
4623                 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4624                 g_free (s);
4625                 break;
4626         }
4627         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4628                 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4629                 break;
4630         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4631                 debug_sym = g_strdup_printf ("plt__generic_class_init");
4632                 break;
4633         default:
4634                 break;
4635         }
4636
4637         return debug_sym;
4638 }
4639
4640 /*
4641  * Calls made from AOTed code are routed through a table of jumps similar to the
4642  * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4643  * control to the AOT runtime through a trampoline.
4644  */
4645 static void
4646 emit_plt (MonoAotCompile *acfg)
4647 {
4648         char symbol [128];
4649         int i;
4650
4651         emit_line (acfg);
4652         sprintf (symbol, "plt");
4653
4654         emit_section_change (acfg, ".text", 0);
4655         emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4656         emit_label (acfg, symbol);
4657         emit_label (acfg, acfg->plt_symbol);
4658
4659         for (i = 0; i < acfg->plt_offset; ++i) {
4660                 char *debug_sym = NULL;
4661                 MonoPltEntry *plt_entry = NULL;
4662                 MonoJumpInfo *ji;
4663
4664                 if (i == 0)
4665                         /* 
4666                          * The first plt entry is unused.
4667                          */
4668                         continue;
4669
4670                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4671                 ji = plt_entry->ji;
4672
4673                 if (acfg->llvm) {
4674                         /*
4675                          * If the target is directly callable, alias the plt symbol to point to
4676                          * the method code.
4677                          * FIXME: Use this to simplify emit_and_reloc_code ().
4678                          * FIXME: Avoid the got slot.
4679                          * FIXME: Add support to the binary writer.
4680                          */
4681                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4682                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4683
4684                                 if (callee_cfg) {
4685                                         if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4686                                                 /* LLVM calls the PLT entries using bl, so emit a stub */
4687                                                 fprintf (acfg->fp, "\n.thumb_func\n");
4688                                                 emit_label (acfg, plt_entry->llvm_symbol);
4689                                                 fprintf (acfg->fp, "bx pc\n");
4690                                                 fprintf (acfg->fp, "nop\n");
4691                                                 fprintf (acfg->fp, ".arm\n");
4692                                                 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4693                                         } else {
4694                                                 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4695                                         }
4696                                         continue;
4697                                 }
4698                         }
4699                 }
4700
4701                 debug_sym = plt_entry->debug_sym;
4702
4703                 if (acfg->thumb_mixed && !plt_entry->jit_used)
4704                         /* Emit only a thumb version */
4705                         continue;
4706
4707                 if (!acfg->thumb_mixed)
4708                         emit_label (acfg, plt_entry->llvm_symbol);
4709
4710                 if (debug_sym) {
4711                         if (acfg->need_no_dead_strip)
4712                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
4713                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4714                         emit_label (acfg, debug_sym);
4715                 }
4716
4717                 emit_label (acfg, plt_entry->symbol);
4718
4719                 arch_emit_plt_entry (acfg, i);
4720
4721                 if (debug_sym)
4722                         emit_symbol_size (acfg, debug_sym, ".");
4723         }
4724
4725         if (acfg->thumb_mixed) {
4726                 /* Make sure the ARM symbols don't alias the thumb ones */
4727                 emit_zero_bytes (acfg, 16);
4728
4729                 /* 
4730                  * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4731                  * code.
4732                  */
4733                 for (i = 0; i < acfg->plt_offset; ++i) {
4734                         char *debug_sym = NULL;
4735                         MonoPltEntry *plt_entry = NULL;
4736                         MonoJumpInfo *ji;
4737
4738                         if (i == 0)
4739                                 continue;
4740
4741                         plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4742                         ji = plt_entry->ji;
4743
4744                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4745                                 continue;
4746
4747                         /* Skip plt entries not actually called by LLVM code */
4748                         if (!plt_entry->llvm_used)
4749                                 continue;
4750
4751                         if (acfg->aot_opts.write_symbols) {
4752                                 if (plt_entry->debug_sym)
4753                                         debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4754                         }
4755
4756                         if (debug_sym) {
4757 #if defined(__APPLE__)
4758                                 fprintf (acfg->fp, "    .thumb_func %s\n", debug_sym);
4759                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
4760 #endif
4761                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4762                                 emit_label (acfg, debug_sym);
4763                         }
4764                         fprintf (acfg->fp, "\n.thumb_func\n");
4765
4766                         emit_label (acfg, plt_entry->llvm_symbol);
4767
4768                         arch_emit_llvm_plt_entry (acfg, i);
4769
4770                         if (debug_sym) {
4771                                 emit_symbol_size (acfg, debug_sym, ".");
4772                                 g_free (debug_sym);
4773                         }
4774                 }
4775         }
4776
4777         emit_symbol_size (acfg, acfg->plt_symbol, ".");
4778
4779         sprintf (symbol, "plt_end");
4780         emit_label (acfg, symbol);
4781 }
4782
4783 static G_GNUC_UNUSED void
4784 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4785 {
4786         char start_symbol [256];
4787         char symbol [256];
4788         guint32 buf_size, info_offset;
4789         MonoJumpInfo *patch_info;
4790         guint8 *buf, *p;
4791         GPtrArray *patches;
4792         char *name;
4793         guint8 *code;
4794         guint32 code_size;
4795         MonoJumpInfo *ji;
4796         GSList *unwind_ops;
4797
4798         name = info->name;
4799         code = info->code;
4800         code_size = info->code_size;
4801         ji = info->ji;
4802         unwind_ops = info->unwind_ops;
4803
4804 #ifdef __native_client_codegen__
4805         mono_nacl_fix_patches (code, ji);
4806 #endif
4807
4808         /* Emit code */
4809
4810         sprintf (start_symbol, "%s", name);
4811
4812         emit_section_change (acfg, ".text", 0);
4813         emit_global (acfg, start_symbol, TRUE);
4814         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4815         emit_label (acfg, start_symbol);
4816
4817         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4818         emit_label (acfg, symbol);
4819
4820         /* 
4821          * The code should access everything through the GOT, so we pass
4822          * TRUE here.
4823          */
4824         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4825
4826         emit_symbol_size (acfg, start_symbol, ".");
4827
4828         /* Emit info */
4829
4830         /* Sort relocations */
4831         patches = g_ptr_array_new ();
4832         for (patch_info = ji; patch_info; patch_info = patch_info->next)
4833                 if (patch_info->type != MONO_PATCH_INFO_NONE)
4834                         g_ptr_array_add (patches, patch_info);
4835         g_ptr_array_sort (patches, compare_patches);
4836
4837         buf_size = patches->len * 128 + 128;
4838         buf = g_malloc (buf_size);
4839         p = buf;
4840
4841         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4842         g_assert (p - buf < buf_size);
4843
4844         sprintf (symbol, "%s_p", name);
4845
4846         info_offset = add_to_blob (acfg, buf, p - buf);
4847
4848         emit_section_change (acfg, RODATA_SECT, 0);
4849         emit_global (acfg, symbol, FALSE);
4850         emit_label (acfg, symbol);
4851
4852         emit_int32 (acfg, info_offset);
4853
4854         /* Emit debug info */
4855         if (unwind_ops) {
4856                 char symbol2 [256];
4857
4858                 sprintf (symbol, "%s", name);
4859                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4860
4861                 if (acfg->dwarf)
4862                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4863         }
4864 }
4865
4866 static void
4867 emit_trampolines (MonoAotCompile *acfg)
4868 {
4869         char symbol [256];
4870         char end_symbol [256];
4871         int i, tramp_got_offset;
4872         MonoAotTrampoline ntype;
4873 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4874         int tramp_type;
4875 #endif
4876
4877         if (!acfg->aot_opts.full_aot)
4878                 return;
4879         
4880         g_assert (acfg->image->assembly);
4881
4882         /* Currently, we emit most trampolines into the mscorlib AOT image. */
4883         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4884 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4885                 MonoTrampInfo *info;
4886
4887                 /*
4888                  * Emit the generic trampolines.
4889                  *
4890                  * We could save some code by treating the generic trampolines as a wrapper
4891                  * method, but that approach has its own complexities, so we choose the simpler
4892                  * method.
4893                  */
4894                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4895                         mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4896                         emit_trampoline (acfg, acfg->got_offset, info);
4897                 }
4898
4899                 mono_arch_get_nullified_class_init_trampoline (&info);
4900                 emit_trampoline (acfg, acfg->got_offset, info);
4901 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4902                 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4903                 emit_trampoline (acfg, acfg->got_offset, info);
4904                 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4905                 emit_trampoline (acfg, acfg->got_offset, info);
4906 #endif
4907
4908                 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4909                 emit_trampoline (acfg, acfg->got_offset, info);
4910
4911                 /* Emit the exception related code pieces */
4912                 mono_arch_get_restore_context (&info, TRUE);
4913                 emit_trampoline (acfg, acfg->got_offset, info);
4914                 mono_arch_get_call_filter (&info, TRUE);
4915                 emit_trampoline (acfg, acfg->got_offset, info);
4916                 mono_arch_get_throw_exception (&info, TRUE);
4917                 emit_trampoline (acfg, acfg->got_offset, info);
4918                 mono_arch_get_rethrow_exception (&info, TRUE);
4919                 emit_trampoline (acfg, acfg->got_offset, info);
4920                 mono_arch_get_throw_corlib_exception (&info, TRUE);
4921                 emit_trampoline (acfg, acfg->got_offset, info);
4922
4923 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4924                 {
4925                         GSList *l = mono_arch_get_trampolines (TRUE);
4926
4927                         while (l) {
4928                                 MonoTrampInfo *info = l->data;
4929
4930                                 emit_trampoline (acfg, acfg->got_offset, info);
4931                                 l = l->next;
4932                         }
4933                 }
4934 #endif
4935
4936                 for (i = 0; i < 128; ++i) {
4937                         int offset;
4938
4939                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4940                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4941                         emit_trampoline (acfg, acfg->got_offset, info);
4942
4943                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4944                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4945                         emit_trampoline (acfg, acfg->got_offset, info);
4946                 }
4947
4948                 {
4949                         GSList *l;
4950
4951                         /* delegate_invoke_impl trampolines */
4952                         l = mono_arch_get_delegate_invoke_impls ();
4953                         while (l) {
4954                                 MonoTrampInfo *info = l->data;
4955
4956                                 emit_trampoline (acfg, acfg->got_offset, info);
4957                                 l = l->next;
4958                         }
4959                 }
4960
4961 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4962
4963                 /* Emit trampolines which are numerous */
4964
4965                 /*
4966                  * These include the following:
4967                  * - specific trampolines
4968                  * - static rgctx invoke trampolines
4969                  * - imt thunks
4970                  * These trampolines have the same code, they are parameterized by GOT 
4971                  * slots. 
4972                  * They are defined in this file, in the arch_... routines instead of
4973                  * in tramp-<ARCH>.c, since it is easier to do it this way.
4974                  */
4975
4976                 /*
4977                  * When running in aot-only mode, we can't create specific trampolines at 
4978                  * runtime, so we create a few, and save them in the AOT file. 
4979                  * Normal trampolines embed their argument as a literal inside the 
4980                  * trampoline code, we can't do that here, so instead we embed an offset
4981                  * which needs to be added to the trampoline address to get the address of
4982                  * the GOT slot which contains the argument value.
4983                  * The generated trampolines jump to the generic trampolines using another
4984                  * GOT slot, which will be setup by the AOT loader to point to the 
4985                  * generic trampoline code of the given type.
4986                  */
4987
4988                 /*
4989                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4990                  * each class).
4991                  */
4992
4993                 emit_section_change (acfg, ".text", 0);
4994
4995                 tramp_got_offset = acfg->got_offset;
4996
4997                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4998                         switch (ntype) {
4999                         case MONO_AOT_TRAMP_SPECIFIC:
5000                                 sprintf (symbol, "specific_trampolines");
5001                                 break;
5002                         case MONO_AOT_TRAMP_STATIC_RGCTX:
5003                                 sprintf (symbol, "static_rgctx_trampolines");
5004                                 break;
5005                         case MONO_AOT_TRAMP_IMT_THUNK:
5006                                 sprintf (symbol, "imt_thunks");
5007                                 break;
5008                         default:
5009                                 g_assert_not_reached ();
5010                         }
5011
5012                         sprintf (end_symbol, "%s_e", symbol);
5013
5014                         if (acfg->aot_opts.write_symbols)
5015                                 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5016
5017                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5018                         emit_label (acfg, symbol);
5019
5020                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5021
5022                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5023                                 int tramp_size = 0;
5024
5025                                 switch (ntype) {
5026                                 case MONO_AOT_TRAMP_SPECIFIC:
5027                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5028                                         tramp_got_offset += 2;
5029                                 break;
5030                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
5031                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
5032                                         tramp_got_offset += 2;
5033                                         break;
5034                                 case MONO_AOT_TRAMP_IMT_THUNK:
5035                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5036                                         tramp_got_offset += 1;
5037                                         break;
5038                                 default:
5039                                         g_assert_not_reached ();
5040                                 }
5041 #ifdef __native_client_codegen__
5042                                 /* align to avoid 32-byte boundary crossings */
5043                                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5044 #endif
5045
5046                                 if (!acfg->trampoline_size [ntype]) {
5047                                         g_assert (tramp_size);
5048                                         acfg->trampoline_size [ntype] = tramp_size;
5049                                 }
5050                         }
5051
5052                         emit_label (acfg, end_symbol);
5053                 }
5054
5055                 /* Reserve some entries at the end of the GOT for our use */
5056                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5057         }
5058
5059         acfg->got_offset += acfg->num_trampoline_got_entries;
5060 }
5061
5062 static gboolean
5063 str_begins_with (const char *str1, const char *str2)
5064 {
5065         int len = strlen (str2);
5066         return strncmp (str1, str2, len) == 0;
5067 }
5068
5069 void*
5070 mono_aot_readonly_field_override (MonoClassField *field)
5071 {
5072         ReadOnlyValue *rdv;
5073         for (rdv = readonly_values; rdv; rdv = rdv->next) {
5074                 char *p = rdv->name;
5075                 int len;
5076                 len = strlen (field->parent->name_space);
5077                 if (strncmp (p, field->parent->name_space, len))
5078                         continue;
5079                 p += len;
5080                 if (*p++ != '.')
5081                         continue;
5082                 len = strlen (field->parent->name);
5083                 if (strncmp (p, field->parent->name, len))
5084                         continue;
5085                 p += len;
5086                 if (*p++ != '.')
5087                         continue;
5088                 if (strcmp (p, field->name))
5089                         continue;
5090                 switch (rdv->type) {
5091                 case MONO_TYPE_I1:
5092                         return &rdv->value.i1;
5093                 case MONO_TYPE_I2:
5094                         return &rdv->value.i2;
5095                 case MONO_TYPE_I4:
5096                         return &rdv->value.i4;
5097                 default:
5098                         break;
5099                 }
5100         }
5101         return NULL;
5102 }
5103
5104 static void
5105 add_readonly_value (MonoAotOptions *opts, const char *val)
5106 {
5107         ReadOnlyValue *rdv;
5108         const char *fval;
5109         const char *tval;
5110         /* the format of val is:
5111          * namespace.typename.fieldname=type/value
5112          * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5113          */
5114         fval = strrchr (val, '/');
5115         if (!fval) {
5116                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5117                 exit (1);
5118         }
5119         tval = strrchr (val, '=');
5120         if (!tval) {
5121                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5122                 exit (1);
5123         }
5124         rdv = g_new0 (ReadOnlyValue, 1);
5125         rdv->name = g_malloc0 (tval - val + 1);
5126         memcpy (rdv->name, val, tval - val);
5127         tval++;
5128         fval++;
5129         if (strncmp (tval, "i1", 2) == 0) {
5130                 rdv->value.i1 = atoi (fval);
5131                 rdv->type = MONO_TYPE_I1;
5132         } else if (strncmp (tval, "i2", 2) == 0) {
5133                 rdv->value.i2 = atoi (fval);
5134                 rdv->type = MONO_TYPE_I2;
5135         } else if (strncmp (tval, "i4", 2) == 0) {
5136                 rdv->value.i4 = atoi (fval);
5137                 rdv->type = MONO_TYPE_I4;
5138         } else {
5139                 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5140                 exit (1);
5141         }
5142         rdv->next = readonly_values;
5143         readonly_values = rdv;
5144 }
5145
5146 static void
5147 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5148 {
5149         gchar **args, **ptr;
5150
5151         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5152         for (ptr = args; ptr && *ptr; ptr ++) {
5153                 const char *arg = *ptr;
5154
5155                 if (str_begins_with (arg, "outfile=")) {
5156                         opts->outfile = g_strdup (arg + strlen ("outfile="));
5157                 } else if (str_begins_with (arg, "save-temps")) {
5158                         opts->save_temps = TRUE;
5159                 } else if (str_begins_with (arg, "keep-temps")) {
5160                         opts->save_temps = TRUE;
5161                 } else if (str_begins_with (arg, "write-symbols")) {
5162                         opts->write_symbols = TRUE;
5163                 } else if (str_begins_with (arg, "no-write-symbols")) {
5164                         opts->write_symbols = FALSE;
5165                 } else if (str_begins_with (arg, "metadata-only")) {
5166                         opts->metadata_only = TRUE;
5167                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5168                         opts->bind_to_runtime_version = TRUE;
5169                 } else if (str_begins_with (arg, "full")) {
5170                         opts->full_aot = TRUE;
5171                 } else if (str_begins_with (arg, "threads=")) {
5172                         opts->nthreads = atoi (arg + strlen ("threads="));
5173                 } else if (str_begins_with (arg, "static")) {
5174                         opts->static_link = TRUE;
5175                         opts->no_dlsym = TRUE;
5176                 } else if (str_begins_with (arg, "asmonly")) {
5177                         opts->asm_only = TRUE;
5178                 } else if (str_begins_with (arg, "asmwriter")) {
5179                         opts->asm_writer = TRUE;
5180                 } else if (str_begins_with (arg, "nodebug")) {
5181                         opts->nodebug = TRUE;
5182                 } else if (str_begins_with (arg, "ntrampolines=")) {
5183                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5184                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5185                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5186                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5187                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5188                 } else if (str_begins_with (arg, "autoreg")) {
5189                         opts->autoreg = TRUE;
5190                 } else if (str_begins_with (arg, "tool-prefix=")) {
5191                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5192                 } else if (str_begins_with (arg, "soft-debug")) {
5193                         opts->soft_debug = TRUE;
5194                 } else if (str_begins_with (arg, "direct-pinvoke")) {
5195                         opts->direct_pinvoke = TRUE;
5196                 } else if (str_begins_with (arg, "direct-icalls")) {
5197                         opts->direct_icalls = TRUE;
5198                 } else if (str_begins_with (arg, "print-skipped")) {
5199                         opts->print_skipped_methods = TRUE;
5200                 } else if (str_begins_with (arg, "stats")) {
5201                         opts->stats = TRUE;
5202                 } else if (str_begins_with (arg, "log-generics")) {
5203                         opts->log_generics = TRUE;
5204                 } else if (str_begins_with (arg, "mtriple=")) {
5205                         opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5206                 } else if (str_begins_with (arg, "llvm-path=")) {
5207                         opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5208                 } else if (str_begins_with (arg, "readonly-value=")) {
5209                         add_readonly_value (opts, arg + strlen ("readonly-value="));
5210                 } else if (str_begins_with (arg, "info")) {
5211                         printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5212                         exit (0);
5213                 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5214                         printf ("Supported options for --aot:\n");
5215                         printf ("    outfile=\n");
5216                         printf ("    save-temps\n");
5217                         printf ("    keep-temps\n");
5218                         printf ("    write-symbols\n");
5219                         printf ("    metadata-only\n");
5220                         printf ("    bind-to-runtime-version\n");
5221                         printf ("    full\n");
5222                         printf ("    threads=\n");
5223                         printf ("    static\n");
5224                         printf ("    asmonly\n");
5225                         printf ("    asmwriter\n");
5226                         printf ("    nodebug\n");
5227                         printf ("    ntrampolines=\n");
5228                         printf ("    nrgctx-trampolines=\n");
5229                         printf ("    nimt-trampolines=\n");
5230                         printf ("    autoreg\n");
5231                         printf ("    tool-prefix=\n");
5232                         printf ("    readonly-value=\n");
5233                         printf ("    soft-debug\n");
5234                         printf ("    print-skipped\n");
5235                         printf ("    stats\n");
5236                         printf ("    info\n");
5237                         printf ("    help/?\n");
5238                         exit (0);
5239                 } else {
5240                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5241                         exit (1);
5242                 }
5243         }
5244
5245         g_strfreev (args);
5246 }
5247
5248 static void
5249 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5250 {
5251         MonoMethod *method = (MonoMethod*)key;
5252         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5253         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5254         MonoAotCompile *acfg = user_data;
5255
5256         new_ji->image = ji->image;
5257         new_ji->token = ji->token;
5258         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5259 }
5260
5261 static gboolean
5262 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5263 {
5264         if (klass->type_token)
5265                 return TRUE;
5266         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5267                 return TRUE;
5268         if (klass->rank)
5269                 return can_encode_class (acfg, klass->element_class);
5270         return FALSE;
5271 }
5272
5273 static gboolean
5274 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5275 {
5276         switch (patch_info->type) {
5277         case MONO_PATCH_INFO_METHOD:
5278         case MONO_PATCH_INFO_METHODCONST: {
5279                 MonoMethod *method = patch_info->data.method;
5280
5281                 if (method->wrapper_type) {
5282                         switch (method->wrapper_type) {
5283                         case MONO_WRAPPER_NONE:
5284                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5285                         case MONO_WRAPPER_XDOMAIN_INVOKE:
5286                         case MONO_WRAPPER_STFLD:
5287                         case MONO_WRAPPER_LDFLD:
5288                         case MONO_WRAPPER_LDFLDA:
5289                         case MONO_WRAPPER_LDFLD_REMOTE:
5290                         case MONO_WRAPPER_STFLD_REMOTE:
5291                         case MONO_WRAPPER_STELEMREF:
5292                         case MONO_WRAPPER_ISINST:
5293                         case MONO_WRAPPER_PROXY_ISINST:
5294                         case MONO_WRAPPER_ALLOC:
5295                         case MONO_WRAPPER_REMOTING_INVOKE:
5296                         case MONO_WRAPPER_UNKNOWN:
5297                         case MONO_WRAPPER_WRITE_BARRIER:
5298                                 break;
5299                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
5300                         case MONO_WRAPPER_CASTCLASS: {
5301                                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5302
5303                                 if (info)
5304                                         return TRUE;
5305                                 else
5306                                         return FALSE;
5307                                 break;
5308                         }
5309                         default:
5310                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5311                                 return FALSE;
5312                         }
5313                 } else {
5314                         if (!method->token) {
5315                                 /* The method is part of a constructed type like Int[,].Set (). */
5316                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5317                                         if (method->klass->rank)
5318                                                 return TRUE;
5319                                         return FALSE;
5320                                 }
5321                         }
5322                 }
5323                 break;
5324         }
5325         case MONO_PATCH_INFO_VTABLE:
5326         case MONO_PATCH_INFO_CLASS_INIT:
5327         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5328         case MONO_PATCH_INFO_CLASS:
5329         case MONO_PATCH_INFO_IID:
5330         case MONO_PATCH_INFO_ADJUSTED_IID:
5331                 if (!can_encode_class (acfg, patch_info->data.klass)) {
5332                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5333                         return FALSE;
5334                 }
5335                 break;
5336         case MONO_PATCH_INFO_RGCTX_FETCH: {
5337                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5338
5339                 if (!can_encode_patch (acfg, entry->data))
5340                         return FALSE;
5341                 break;
5342         }
5343         default:
5344                 break;
5345         }
5346
5347         return TRUE;
5348 }
5349
5350 /*
5351  * compile_method:
5352  *
5353  *   AOT compile a given method.
5354  * This function might be called by multiple threads, so it must be thread-safe.
5355  */
5356 static void
5357 compile_method (MonoAotCompile *acfg, MonoMethod *method)
5358 {
5359         MonoCompile *cfg;
5360         MonoJumpInfo *patch_info;
5361         gboolean skip;
5362         int index, depth;
5363         MonoMethod *wrapped;
5364
5365         if (acfg->aot_opts.metadata_only)
5366                 return;
5367
5368         mono_acfg_lock (acfg);
5369         index = get_method_index (acfg, method);
5370         mono_acfg_unlock (acfg);
5371
5372         /* fixme: maybe we can also precompile wrapper methods */
5373         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5374                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5375                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
5376                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
5377                 return;
5378         }
5379
5380         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5381                 return;
5382
5383         wrapped = mono_marshal_method_from_wrapper (method);
5384         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
5385                 // FIXME: The wrapper should be generic too, but it is not
5386                 return;
5387
5388         if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
5389                 return;
5390
5391         InterlockedIncrement (&acfg->stats.mcount);
5392
5393 #if 0
5394         if (method->is_generic || method->klass->generic_container) {
5395                 InterlockedIncrement (&acfg->stats.genericcount);
5396                 return;
5397         }
5398 #endif
5399
5400         //acfg->aot_opts.print_skipped_methods = TRUE;
5401
5402         /*
5403          * Since these methods are the only ones which are compiled with
5404          * AOT support, and they are not used by runtime startup/shutdown code,
5405          * the runtime will not see AOT methods during AOT compilation,so it
5406          * does not need to support them by creating a fake GOT etc.
5407          */
5408         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
5409         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
5410                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
5411                 InterlockedIncrement (&acfg->stats.genericcount);
5412                 return;
5413         }
5414         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
5415                 if (acfg->aot_opts.print_skipped_methods)
5416                         printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
5417                 /* Let the exception happen at runtime */
5418                 return;
5419         }
5420
5421         if (cfg->disable_aot) {
5422                 if (acfg->aot_opts.print_skipped_methods)
5423                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
5424                 InterlockedIncrement (&acfg->stats.ocount);
5425                 mono_destroy_compile (cfg);
5426                 return;
5427         }
5428
5429         /* Nullify patches which need no aot processing */
5430         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5431                 switch (patch_info->type) {
5432                 case MONO_PATCH_INFO_LABEL:
5433                 case MONO_PATCH_INFO_BB:
5434                         patch_info->type = MONO_PATCH_INFO_NONE;
5435                         break;
5436                 default:
5437                         break;
5438                 }
5439         }
5440
5441         /* Collect method->token associations from the cfg */
5442         mono_acfg_lock (acfg);
5443         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
5444         mono_acfg_unlock (acfg);
5445
5446         /*
5447          * Check for absolute addresses.
5448          */
5449         skip = FALSE;
5450         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5451                 switch (patch_info->type) {
5452                 case MONO_PATCH_INFO_ABS:
5453                         /* unable to handle this */
5454                         skip = TRUE;    
5455                         break;
5456                 default:
5457                         break;
5458                 }
5459         }
5460
5461         if (skip) {
5462                 if (acfg->aot_opts.print_skipped_methods)
5463                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
5464                 InterlockedIncrement (&acfg->stats.abscount);
5465                 mono_destroy_compile (cfg);
5466                 return;
5467         }
5468
5469         /* Lock for the rest of the code */
5470         mono_acfg_lock (acfg);
5471
5472         /*
5473          * Check for methods/klasses we can't encode.
5474          */
5475         skip = FALSE;
5476         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5477                 if (!can_encode_patch (acfg, patch_info))
5478                         skip = TRUE;
5479         }
5480
5481         if (skip) {
5482                 if (acfg->aot_opts.print_skipped_methods)
5483                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
5484                 acfg->stats.ocount++;
5485                 mono_destroy_compile (cfg);
5486                 mono_acfg_unlock (acfg);
5487                 return;
5488         }
5489
5490         /* Adds generic instances referenced by this method */
5491         /* 
5492          * The depth is used to avoid infinite loops when generic virtual recursion is 
5493          * encountered.
5494          */
5495         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5496         if (depth < 32) {
5497                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5498                         switch (patch_info->type) {
5499                         case MONO_PATCH_INFO_METHOD: {
5500                                 MonoMethod *m = patch_info->data.method;
5501                                 if (m->is_inflated) {
5502                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
5503                                                   mono_method_is_generic_sharable_impl (m, FALSE)) &&
5504                                                 !method_has_type_vars (m)) {
5505                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5506                                                         if (acfg->aot_opts.full_aot)
5507                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
5508                                                 } else {
5509                                                         add_extra_method_with_depth (acfg, m, depth + 1);
5510                                                         add_types_from_method_header (acfg, m);
5511                                                 }
5512                                         }
5513                                         add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
5514                                 }
5515                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
5516                                         add_extra_method_with_depth (acfg, m, depth + 1);
5517                                 break;
5518                         }
5519                         case MONO_PATCH_INFO_VTABLE: {
5520                                 MonoClass *klass = patch_info->data.klass;
5521
5522                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
5523                                         add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
5524                                 break;
5525                         }
5526                         case MONO_PATCH_INFO_SFLDA: {
5527                                 MonoClass *klass = patch_info->data.field->parent;
5528
5529                                 /* The .cctor needs to run at runtime. */
5530                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
5531                                         add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
5532                                 break;
5533                         }
5534                         default:
5535                                 break;
5536                         }
5537                 }
5538         }
5539
5540         /* Determine whenever the method has GOT slots */
5541         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5542                 switch (patch_info->type) {
5543                 case MONO_PATCH_INFO_GOT_OFFSET:
5544                 case MONO_PATCH_INFO_NONE:
5545                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5546                         break;
5547                 case MONO_PATCH_INFO_IMAGE:
5548                         /* The assembly is stored in GOT slot 0 */
5549                         if (patch_info->data.image != acfg->image)
5550                                 cfg->has_got_slots = TRUE;
5551                         break;
5552                 default:
5553                         if (!is_plt_patch (patch_info))
5554                                 cfg->has_got_slots = TRUE;
5555                         break;
5556                 }
5557         }
5558
5559         if (!cfg->has_got_slots)
5560                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5561
5562         /* 
5563          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5564          */
5565         /* Make a copy of the patch info which is in the mempool */
5566         {
5567                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5568
5569                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5570                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5571
5572                         if (!patches)
5573                                 patches = new_patch_info;
5574                         else
5575                                 patches_end->next = new_patch_info;
5576                         patches_end = new_patch_info;
5577                 }
5578                 cfg->patch_info = patches;
5579         }
5580         /* Make a copy of the unwind info */
5581         {
5582                 GSList *l, *unwind_ops;
5583                 MonoUnwindOp *op;
5584
5585                 unwind_ops = NULL;
5586                 for (l = cfg->unwind_ops; l; l = l->next) {
5587                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5588                         memcpy (op, l->data, sizeof (MonoUnwindOp));
5589                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5590                 }
5591                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5592         }
5593         /* Make a copy of the argument/local info */
5594         {
5595                 MonoInst **args, **locals;
5596                 MonoMethodSignature *sig;
5597                 MonoMethodHeader *header;
5598                 int i;
5599                 
5600                 sig = mono_method_signature (method);
5601                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5602                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5603                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5604                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5605                 }
5606                 cfg->args = args;
5607
5608                 header = mono_method_get_header (method);
5609                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5610                 for (i = 0; i < header->num_locals; ++i) {
5611                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5612                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5613                 }
5614                 cfg->locals = locals;
5615         }
5616
5617         /* Free some fields used by cfg to conserve memory */
5618         mono_mempool_destroy (cfg->mempool);
5619         cfg->mempool = NULL;
5620         g_free (cfg->varinfo);
5621         cfg->varinfo = NULL;
5622         g_free (cfg->vars);
5623         cfg->vars = NULL;
5624         if (cfg->rs) {
5625                 mono_regstate_free (cfg->rs);
5626                 cfg->rs = NULL;
5627         }
5628
5629         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
5630
5631         while (index >= acfg->cfgs_size) {
5632                 MonoCompile **new_cfgs;
5633                 int new_size;
5634
5635                 new_size = acfg->cfgs_size * 2;
5636                 new_cfgs = g_new0 (MonoCompile*, new_size);
5637                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5638                 g_free (acfg->cfgs);
5639                 acfg->cfgs = new_cfgs;
5640                 acfg->cfgs_size = new_size;
5641         }
5642         acfg->cfgs [index] = cfg;
5643
5644         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5645
5646         /*
5647         if (cfg->orig_method->wrapper_type)
5648                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5649         */
5650
5651         mono_acfg_unlock (acfg);
5652
5653         InterlockedIncrement (&acfg->stats.ccount);
5654 }
5655  
5656 static void
5657 compile_thread_main (gpointer *user_data)
5658 {
5659         MonoDomain *domain = user_data [0];
5660         MonoAotCompile *acfg = user_data [1];
5661         GPtrArray *methods = user_data [2];
5662         int i;
5663
5664         mono_thread_attach (domain);
5665
5666         for (i = 0; i < methods->len; ++i)
5667                 compile_method (acfg, g_ptr_array_index (methods, i));
5668 }
5669
5670 static void
5671 load_profile_files (MonoAotCompile *acfg)
5672 {
5673         FILE *infile;
5674         char *tmp;
5675         int file_index, res, method_index, i;
5676         char ver [256];
5677         guint32 token;
5678         GList *unordered, *l;
5679         gboolean found;
5680
5681         file_index = 0;
5682         while (TRUE) {
5683                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5684
5685                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5686                         g_free (tmp);
5687                         break;
5688                 }
5689
5690                 infile = fopen (tmp, "r");
5691                 g_assert (infile);
5692
5693                 printf ("Using profile data file '%s'\n", tmp);
5694                 g_free (tmp);
5695
5696                 file_index ++;
5697
5698                 res = fscanf (infile, "%32s\n", ver);
5699                 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5700                         printf ("Profile file has wrong version or invalid.\n");
5701                         fclose (infile);
5702                         continue;
5703                 }
5704
5705                 while (TRUE) {
5706                         char name [1024];
5707                         MonoMethodDesc *desc;
5708                         MonoMethod *method;
5709
5710                         if (fgets (name, 1023, infile) == NULL)
5711                                 break;
5712
5713                         /* Kill the newline */
5714                         if (strlen (name) > 0)
5715                                 name [strlen (name) - 1] = '\0';
5716
5717                         desc = mono_method_desc_new (name, TRUE);
5718
5719                         method = mono_method_desc_search_in_image (desc, acfg->image);
5720
5721                         if (method && mono_method_get_token (method)) {
5722                                 token = mono_method_get_token (method);
5723                                 method_index = mono_metadata_token_index (token) - 1;
5724
5725                                 found = FALSE;
5726                                 for (i = 0; i < acfg->method_order->len; ++i) {
5727                                         if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5728                                                 found = TRUE;
5729                                                 break;
5730                                         }
5731                                 }
5732                                 if (!found)
5733                                         g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5734                         } else {
5735                                 //printf ("No method found matching '%s'.\n", name);
5736                         }
5737                 }
5738                 fclose (infile);
5739         }
5740
5741         /* Add missing methods */
5742         unordered = NULL;
5743         for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5744                 found = FALSE;
5745                 for (i = 0; i < acfg->method_order->len; ++i) {
5746                         if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5747                                 found = TRUE;
5748                                 break;
5749                         }
5750                 }
5751                 if (!found)
5752                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5753         }
5754         unordered = g_list_reverse (unordered);
5755         for (l = unordered; l; l = l->next)
5756                 g_ptr_array_add (acfg->method_order, l->data);
5757 }
5758  
5759 /* Used by the LLVM backend */
5760 guint32
5761 mono_aot_get_got_offset (MonoJumpInfo *ji)
5762 {
5763         return get_got_offset (llvm_acfg, ji);
5764 }
5765
5766 char*
5767 mono_aot_get_method_name (MonoCompile *cfg)
5768 {
5769         if (llvm_acfg->aot_opts.static_link)
5770                 /* Include the assembly name too to avoid duplicate symbol errors */
5771                 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5772         else
5773                 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5774 }
5775
5776 char*
5777 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5778 {
5779         MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5780         MonoPltEntry *plt_entry;
5781
5782         ji->type = type;
5783         ji->data.target = data;
5784
5785         if (!can_encode_patch (llvm_acfg, ji))
5786                 return NULL;
5787
5788         plt_entry = get_plt_entry (llvm_acfg, ji);
5789         plt_entry->llvm_used = TRUE;
5790
5791 #if defined(__APPLE__)
5792         return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5793 #else
5794         return g_strdup_printf (plt_entry->llvm_symbol);
5795 #endif
5796 }
5797
5798 MonoJumpInfo*
5799 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5800 {
5801         MonoJumpInfo *res;
5802
5803         mono_acfg_lock (llvm_acfg);
5804         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5805         mono_acfg_unlock (llvm_acfg);
5806
5807         return res;
5808 }
5809
5810 #ifdef ENABLE_LLVM
5811
5812 /*
5813  * emit_llvm_file:
5814  *
5815  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5816  * tools.
5817  */
5818 static void
5819 emit_llvm_file (MonoAotCompile *acfg)
5820 {
5821         char *command, *opts;
5822         int i;
5823         MonoJumpInfo *patch_info;
5824
5825         /*
5826          * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5827          * to it.
5828          */
5829
5830         /* Compute the final size of the got */
5831         for (i = 0; i < acfg->nmethods; ++i) {
5832                 if (acfg->cfgs [i]) {
5833                         for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5834                                 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5835                                         if (!is_plt_patch (patch_info))
5836                                                 get_got_offset (acfg, patch_info);
5837                                         else
5838                                                 get_plt_entry (acfg, patch_info);
5839                                 }
5840                         }
5841                 }
5842         }
5843
5844         acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5845
5846         if (acfg->aot_opts.full_aot) {
5847                 int ntype;
5848
5849                 /* 
5850                  * Need to add the got entries used by the trampolines.
5851                  * This is only a conservative approximation.
5852                  */
5853                 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5854                         /* For the generic + rgctx trampolines */
5855                         acfg->final_got_size += 200;
5856                         /* For the specific trampolines */
5857                         for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5858                                 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5859                 }
5860         }
5861
5862
5863         mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5864
5865         /*
5866          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5867          * a lot of time, and doesn't seem to save much space.
5868          * The following optimizations cannot be enabled:
5869          * - 'tailcallelim'
5870          * - 'jump-threading' changes our blockaddress references to int constants.
5871          * - 'basiccg' fails because it contains:
5872          * if (CS && !isa<IntrinsicInst>(II)) {
5873          * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
5874          * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
5875          * The opt list below was produced by taking the output of:
5876          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5877          * then removing tailcallelim + the global opts, and adding a second gvn.
5878          */
5879         opts = g_strdup ("-instcombine -simplifycfg");
5880         opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
5881 #if 1
5882         command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5883         printf ("Executing opt: %s\n", command);
5884         if (system (command) != 0) {
5885                 exit (1);
5886         }
5887 #endif
5888         g_free (opts);
5889
5890         if (!acfg->llc_args)
5891                 acfg->llc_args = g_string_new ("");
5892
5893         /* Verbose asm slows down llc greatly */
5894         g_string_append (acfg->llc_args, " -asm-verbose=false");
5895
5896         if (acfg->aot_opts.mtriple)
5897                 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5898
5899         if (llvm_acfg->aot_opts.static_link)
5900                 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5901         else
5902                 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5903         unlink (acfg->tmpfname);
5904
5905         command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname);
5906
5907         printf ("Executing llc: %s\n", command);
5908
5909         if (system (command) != 0) {
5910                 exit (1);
5911         }
5912 }
5913 #endif
5914
5915 static void
5916 emit_code (MonoAotCompile *acfg)
5917 {
5918         int oindex, i, prev_index;
5919         char symbol [256];
5920         char end_symbol [256];
5921
5922 #if defined(TARGET_POWERPC64)
5923         sprintf (symbol, ".Lgot_addr");
5924         emit_section_change (acfg, ".text", 0);
5925         emit_alignment (acfg, 8);
5926         emit_label (acfg, symbol);
5927         emit_pointer (acfg, acfg->got_symbol);
5928 #endif
5929
5930         /* 
5931          * This global symbol is used to compute the address of each method using the
5932          * code_offsets array. It is also used to compute the memory ranges occupied by
5933          * AOT code, so it must be equal to the address of the first emitted method.
5934          */
5935         sprintf (symbol, "methods");
5936         emit_section_change (acfg, ".text", 0);
5937         emit_alignment (acfg, 8);
5938         if (acfg->llvm) {
5939                 for (i = 0; i < acfg->nmethods; ++i) {
5940                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5941                                 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5942                                 break;
5943                         }
5944                 }
5945                 if (i == acfg->nmethods)
5946                         /* No LLVM compiled methods */
5947                         emit_label (acfg, symbol);
5948         } else {
5949                 emit_label (acfg, symbol);
5950         }
5951
5952         /* 
5953          * Emit some padding so the local symbol for the first method doesn't have the
5954          * same address as 'methods'.
5955          */
5956 #if defined(__default_codegen__)
5957         emit_zero_bytes (acfg, 16);
5958 #elif defined(__native_client_codegen__)
5959         {
5960                 const int kPaddingSize = 16;
5961                 guint8 pad_buffer[kPaddingSize];
5962                 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5963                 emit_bytes (acfg, pad_buffer, kPaddingSize);
5964         }
5965 #endif
5966
5967         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5968                 MonoCompile *cfg;
5969                 MonoMethod *method;
5970
5971                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5972
5973                 cfg = acfg->cfgs [i];
5974
5975                 if (!cfg)
5976                         continue;
5977
5978                 method = cfg->orig_method;
5979
5980                 /* Emit unbox trampoline */
5981                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5982                         sprintf (symbol, "ut_%d", get_method_index (acfg, method));
5983
5984                         emit_section_change (acfg, ".text", 0);
5985 #ifdef __native_client_codegen__
5986                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5987 #endif
5988
5989                         if (acfg->thumb_mixed && cfg->compile_llvm)
5990                                 fprintf (acfg->fp, "\n.thumb_func\n");
5991
5992                         emit_label (acfg, symbol);
5993
5994                         arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
5995                 }
5996
5997                 if (cfg->compile_llvm)
5998                         acfg->stats.llvm_count ++;
5999                 else
6000                         emit_method_code (acfg, cfg);
6001         }
6002
6003         sprintf (symbol, "methods_end");
6004         emit_section_change (acfg, ".text", 0);
6005         emit_alignment (acfg, 8);
6006         emit_label (acfg, symbol);
6007
6008         /* 
6009          * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6010          * from optimizing them away, since it doesn't see that code_offsets references them.
6011          * JITted methods don't need this since they are referenced using assembler local
6012          * symbols.
6013          * FIXME: This is why write-symbols doesn't work on OSX ?
6014          */
6015         if (acfg->llvm && acfg->need_no_dead_strip) {
6016                 fprintf (acfg->fp, "\n");
6017                 for (i = 0; i < acfg->nmethods; ++i) {
6018                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6019                                 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6020                 }
6021         }
6022
6023         sprintf (symbol, "code_offsets");
6024         emit_section_change (acfg, RODATA_SECT, 1);
6025         emit_alignment (acfg, 8);
6026         emit_label (acfg, symbol);
6027
6028         acfg->stats.offsets_size += acfg->nmethods * 4;
6029
6030         sprintf (end_symbol, "methods");
6031         for (i = 0; i < acfg->nmethods; ++i) {
6032                 if (acfg->cfgs [i]) {
6033                         emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6034                 } else {
6035                         emit_int32 (acfg, 0xffffffff);
6036                 }
6037         }
6038         emit_line (acfg);
6039
6040         /* Emit a sorted table mapping methods to their unbox trampolines */
6041         sprintf (symbol, "unbox_trampolines");
6042         emit_section_change (acfg, RODATA_SECT, 1);
6043         emit_alignment (acfg, 8);
6044         emit_label (acfg, symbol);
6045
6046         sprintf (end_symbol, "methods");
6047         prev_index = -1;
6048         for (i = 0; i < acfg->nmethods; ++i) {
6049                 MonoCompile *cfg;
6050                 MonoMethod *method;
6051                 int index;
6052
6053                 cfg = acfg->cfgs [i];
6054                 if (!cfg)
6055                         continue;
6056
6057                 method = cfg->orig_method;
6058
6059                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6060                         index = get_method_index (acfg, method);
6061                         sprintf (symbol, "ut_%d", index);
6062
6063                         emit_int32 (acfg, index);
6064                         emit_symbol_diff (acfg, symbol, end_symbol, 0);
6065                         /* Make sure the table is sorted by index */
6066                         g_assert (index > prev_index);
6067                         prev_index = index;
6068                 }
6069         }
6070         sprintf (symbol, "unbox_trampolines_end");
6071         emit_label (acfg, symbol);
6072 }
6073
6074 static void
6075 emit_info (MonoAotCompile *acfg)
6076 {
6077         int oindex, i;
6078         char symbol [256];
6079         gint32 *offsets;
6080
6081         offsets = g_new0 (gint32, acfg->nmethods);
6082
6083         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6084                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6085
6086                 if (acfg->cfgs [i]) {
6087                         emit_method_info (acfg, acfg->cfgs [i]);
6088                         offsets [i] = acfg->cfgs [i]->method_info_offset;
6089                 } else {
6090                         offsets [i] = 0;
6091                 }
6092         }
6093
6094         sprintf (symbol, "method_info_offsets");
6095         emit_section_change (acfg, RODATA_SECT, 1);
6096         emit_alignment (acfg, 8);
6097         emit_label (acfg, symbol);
6098
6099         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6100
6101         g_free (offsets);
6102 }
6103
6104 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6105
6106 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6107 #define mix(a,b,c) { \
6108         a -= c;  a ^= rot(c, 4);  c += b; \
6109         b -= a;  b ^= rot(a, 6);  a += c; \
6110         c -= b;  c ^= rot(b, 8);  b += a; \
6111         a -= c;  a ^= rot(c,16);  c += b; \
6112         b -= a;  b ^= rot(a,19);  a += c; \
6113         c -= b;  c ^= rot(b, 4);  b += a; \
6114 }
6115 #define final(a,b,c) { \
6116         c ^= b; c -= rot(b,14); \
6117         a ^= c; a -= rot(c,11); \
6118         b ^= a; b -= rot(a,25); \
6119         c ^= b; c -= rot(b,16); \
6120         a ^= c; a -= rot(c,4);  \
6121         b ^= a; b -= rot(a,14); \
6122         c ^= b; c -= rot(b,24); \
6123 }
6124
6125 static guint
6126 mono_aot_type_hash (MonoType *t1)
6127 {
6128         guint hash = t1->type;
6129
6130         hash |= t1->byref << 6; /* do not collide with t1->type values */
6131         switch (t1->type) {
6132         case MONO_TYPE_VALUETYPE:
6133         case MONO_TYPE_CLASS:
6134         case MONO_TYPE_SZARRAY:
6135                 /* check if the distribution is good enough */
6136                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6137         case MONO_TYPE_PTR:
6138                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6139         case MONO_TYPE_ARRAY:
6140                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6141         case MONO_TYPE_GENERICINST:
6142                 return ((hash << 5) - hash) ^ 0;
6143         default:
6144                 return hash;
6145         }
6146 }
6147
6148 /*
6149  * mono_aot_method_hash:
6150  *
6151  *   Return a hash code for methods which only depends on metadata.
6152  */
6153 guint32
6154 mono_aot_method_hash (MonoMethod *method)
6155 {
6156         MonoMethodSignature *sig;
6157         MonoClass *klass;
6158         int i, hindex;
6159         int hashes_count;
6160         guint32 *hashes_start, *hashes;
6161         guint32 a, b, c;
6162         MonoGenericInst *ginst = NULL;
6163
6164         /* Similar to the hash in mono_method_get_imt_slot () */
6165
6166         sig = mono_method_signature (method);
6167
6168         if (method->is_inflated)
6169                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6170
6171         hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6172         hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6173         hashes = hashes_start;
6174
6175         /* Some wrappers are assigned to random classes */
6176         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6177                 klass = method->klass;
6178         else
6179                 klass = mono_defaults.object_class;
6180
6181         if (!method->wrapper_type) {
6182                 char *full_name = mono_type_full_name (&klass->byval_arg);
6183
6184                 hashes [0] = mono_metadata_str_hash (full_name);
6185                 hashes [1] = 0;
6186                 g_free (full_name);
6187         } else {
6188                 hashes [0] = mono_metadata_str_hash (klass->name);
6189                 hashes [1] = mono_metadata_str_hash (klass->name_space);
6190         }
6191         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6192                 /* The method name includes a stringified pointer */
6193                 hashes [2] = 0;
6194         else
6195                 hashes [2] = mono_metadata_str_hash (method->name);
6196         hashes [3] = method->wrapper_type;
6197         hashes [4] = mono_aot_type_hash (sig->ret);
6198         hindex = 5;
6199         for (i = 0; i < sig->param_count; i++) {
6200                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6201         }
6202         if (ginst) {
6203                 for (i = 0; i < ginst->type_argc; ++i)
6204                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6205         }               
6206         g_assert (hindex == hashes_count);
6207
6208         /* Setup internal state */
6209         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6210
6211         /* Handle most of the hashes */
6212         while (hashes_count > 3) {
6213                 a += hashes [0];
6214                 b += hashes [1];
6215                 c += hashes [2];
6216                 mix (a,b,c);
6217                 hashes_count -= 3;
6218                 hashes += 3;
6219         }
6220
6221         /* Handle the last 3 hashes (all the case statements fall through) */
6222         switch (hashes_count) { 
6223         case 3 : c += hashes [2];
6224         case 2 : b += hashes [1];
6225         case 1 : a += hashes [0];
6226                 final (a,b,c);
6227         case 0: /* nothing left to add */
6228                 break;
6229         }
6230         
6231         free (hashes_start);
6232         
6233         return c;
6234 }
6235 #undef rot
6236 #undef mix
6237 #undef final
6238
6239 /*
6240  * mono_aot_wrapper_name:
6241  *
6242  *   Return a string which uniqely identifies the given wrapper method.
6243  */
6244 char*
6245 mono_aot_wrapper_name (MonoMethod *method)
6246 {
6247         char *name, *tmpsig, *klass_desc;
6248
6249         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6250
6251         switch (method->wrapper_type) {
6252         case MONO_WRAPPER_RUNTIME_INVOKE:
6253                 if (!strcmp (method->name, "runtime_invoke_dynamic"))
6254                         name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
6255                 else
6256                         name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
6257                 break;
6258         default:
6259                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
6260                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
6261                 g_free (klass_desc);
6262                 break;
6263         }
6264
6265         g_free (tmpsig);
6266
6267         return name;
6268 }
6269
6270 /*
6271  * mono_aot_get_array_helper_from_wrapper;
6272  *
6273  * Get the helper method in Array called by an array wrapper method.
6274  */
6275 MonoMethod*
6276 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6277 {
6278         MonoMethod *m;
6279         const char *prefix;
6280         MonoGenericContext ctx;
6281         MonoType *args [16];
6282         char *mname, *iname, *s, *s2, *helper_name = NULL;
6283
6284         prefix = "System.Collections.Generic";
6285         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6286         s2 = strstr (s, "`1.");
6287         g_assert (s2);
6288         s2 [0] = '\0';
6289         iname = s;
6290         mname = s2 + 3;
6291
6292         //printf ("X: %s %s\n", iname, mname);
6293
6294         if (!strcmp (iname, "IList"))
6295                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6296         else
6297                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6298         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6299         g_assert (m);
6300         g_free (helper_name);
6301         g_free (s);
6302
6303         if (m->is_generic) {
6304                 memset (&ctx, 0, sizeof (ctx));
6305                 args [0] = &method->klass->element_class->byval_arg;
6306                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6307                 m = mono_class_inflate_generic_method (m, &ctx);
6308         }
6309
6310         return m;
6311 }
6312
6313 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6314
6315 typedef struct HashEntry {
6316     guint32 key, value, index;
6317         struct HashEntry *next;
6318 } HashEntry;
6319
6320 /*
6321  * emit_extra_methods:
6322  *
6323  * Emit methods which are not in the METHOD table, like wrappers.
6324  */
6325 static void
6326 emit_extra_methods (MonoAotCompile *acfg)
6327 {
6328         int i, table_size, buf_size;
6329         char symbol [256];
6330         guint8 *p, *buf;
6331         guint32 *info_offsets;
6332         guint32 hash;
6333         GPtrArray *table;
6334         HashEntry *entry, *new_entry;
6335         int nmethods, max_chain_length;
6336         int *chain_lengths;
6337
6338         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
6339
6340         /* Emit method info */
6341         nmethods = 0;
6342         for (i = 0; i < acfg->extra_methods->len; ++i) {
6343                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6344                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6345
6346                 if (!cfg)
6347                         continue;
6348
6349                 buf_size = 10240;
6350                 p = buf = g_malloc (buf_size);
6351
6352                 nmethods ++;
6353
6354                 method = cfg->method_to_register;
6355
6356                 encode_method_ref (acfg, method, p, &p);
6357
6358                 g_assert ((p - buf) < buf_size);
6359
6360                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6361                 g_free (buf);
6362         }
6363
6364         /*
6365          * Construct a chained hash table for mapping indexes in extra_method_info to
6366          * method indexes.
6367          */
6368         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
6369         table = g_ptr_array_sized_new (table_size);
6370         for (i = 0; i < table_size; ++i)
6371                 g_ptr_array_add (table, NULL);
6372         chain_lengths = g_new0 (int, table_size);
6373         max_chain_length = 0;
6374         for (i = 0; i < acfg->extra_methods->len; ++i) {
6375                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6376                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6377                 guint32 key, value;
6378
6379                 if (!cfg)
6380                         continue;
6381
6382                 key = info_offsets [i];
6383                 value = get_method_index (acfg, method);
6384
6385                 hash = mono_aot_method_hash (method) % table_size;
6386
6387                 chain_lengths [hash] ++;
6388                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
6389
6390                 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
6391                 new_entry->key = key;
6392                 new_entry->value = value;
6393
6394                 entry = g_ptr_array_index (table, hash);
6395                 if (entry == NULL) {
6396                         new_entry->index = hash;
6397                         g_ptr_array_index (table, hash) = new_entry;
6398                 } else {
6399                         while (entry->next)
6400                                 entry = entry->next;
6401                         
6402                         entry->next = new_entry;
6403                         new_entry->index = table->len;
6404                         g_ptr_array_add (table, new_entry);
6405                 }
6406         }
6407
6408         //printf ("MAX: %d\n", max_chain_length);
6409
6410         /* Emit the table */
6411         sprintf (symbol, "extra_method_table");
6412         emit_section_change (acfg, RODATA_SECT, 0);
6413         emit_alignment (acfg, 8);
6414         emit_label (acfg, symbol);
6415
6416         emit_int32 (acfg, table_size);
6417         for (i = 0; i < table->len; ++i) {
6418                 HashEntry *entry = g_ptr_array_index (table, i);
6419
6420                 if (entry == NULL) {
6421                         emit_int32 (acfg, 0);
6422                         emit_int32 (acfg, 0);
6423                         emit_int32 (acfg, 0);
6424                 } else {
6425                         //g_assert (entry->key > 0);
6426                         emit_int32 (acfg, entry->key);
6427                         emit_int32 (acfg, entry->value);
6428                         if (entry->next)
6429                                 emit_int32 (acfg, entry->next->index);
6430                         else
6431                                 emit_int32 (acfg, 0);
6432                 }
6433         }
6434
6435         /* 
6436          * Emit a table reverse mapping method indexes to their index in extra_method_info.
6437          * This is used by mono_aot_find_jit_info ().
6438          */
6439         sprintf (symbol, "extra_method_info_offsets");
6440         emit_section_change (acfg, RODATA_SECT, 0);
6441         emit_alignment (acfg, 8);
6442         emit_label (acfg, symbol);
6443
6444         emit_int32 (acfg, acfg->extra_methods->len);
6445         for (i = 0; i < acfg->extra_methods->len; ++i) {
6446                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6447
6448                 emit_int32 (acfg, get_method_index (acfg, method));
6449                 emit_int32 (acfg, info_offsets [i]);
6450         }
6451 }       
6452
6453 static void
6454 emit_exception_info (MonoAotCompile *acfg)
6455 {
6456         int i;
6457         char symbol [256];
6458         gint32 *offsets;
6459
6460         offsets = g_new0 (gint32, acfg->nmethods);
6461         for (i = 0; i < acfg->nmethods; ++i) {
6462                 if (acfg->cfgs [i]) {
6463                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
6464                         offsets [i] = acfg->cfgs [i]->ex_info_offset;
6465                 } else {
6466                         offsets [i] = 0;
6467                 }
6468         }
6469
6470         sprintf (symbol, "ex_info_offsets");
6471         emit_section_change (acfg, RODATA_SECT, 1);
6472         emit_alignment (acfg, 8);
6473         emit_label (acfg, symbol);
6474
6475         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6476         g_free (offsets);
6477 }
6478
6479 static void
6480 emit_unwind_info (MonoAotCompile *acfg)
6481 {
6482         int i;
6483         char symbol [128];
6484
6485         /* 
6486          * The unwind info contains a lot of duplicates so we emit each unique
6487          * entry once, and only store the offset from the start of the table in the
6488          * exception info.
6489          */
6490
6491         sprintf (symbol, "unwind_info");
6492         emit_section_change (acfg, RODATA_SECT, 1);
6493         emit_alignment (acfg, 8);
6494         emit_label (acfg, symbol);
6495
6496         for (i = 0; i < acfg->unwind_ops->len; ++i) {
6497                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
6498                 guint8 *unwind_info;
6499                 guint32 unwind_info_len;
6500                 guint8 buf [16];
6501                 guint8 *p;
6502
6503                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
6504
6505                 p = buf;
6506                 encode_value (unwind_info_len, p, &p);
6507                 emit_bytes (acfg, buf, p - buf);
6508                 emit_bytes (acfg, unwind_info, unwind_info_len);
6509
6510                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
6511         }
6512 }
6513
6514 static void
6515 emit_class_info (MonoAotCompile *acfg)
6516 {
6517         int i;
6518         char symbol [256];
6519         gint32 *offsets;
6520
6521         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6522         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6523                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6524
6525         sprintf (symbol, "class_info_offsets");
6526         emit_section_change (acfg, RODATA_SECT, 1);
6527         emit_alignment (acfg, 8);
6528         emit_label (acfg, symbol);
6529
6530         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6531         g_free (offsets);
6532 }
6533
6534 typedef struct ClassNameTableEntry {
6535         guint32 token, index;
6536         struct ClassNameTableEntry *next;
6537 } ClassNameTableEntry;
6538
6539 static void
6540 emit_class_name_table (MonoAotCompile *acfg)
6541 {
6542         int i, table_size;
6543         guint32 token, hash;
6544         MonoClass *klass;
6545         GPtrArray *table;
6546         char *full_name;
6547         char symbol [256];
6548         ClassNameTableEntry *entry, *new_entry;
6549
6550         /*
6551          * Construct a chained hash table for mapping class names to typedef tokens.
6552          */
6553         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6554         table = g_ptr_array_sized_new (table_size);
6555         for (i = 0; i < table_size; ++i)
6556                 g_ptr_array_add (table, NULL);
6557         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6558                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6559                 klass = mono_class_get (acfg->image, token);
6560                 if (!klass) {
6561                         mono_loader_clear_error ();
6562                         continue;
6563                 }
6564                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6565                 hash = mono_metadata_str_hash (full_name) % table_size;
6566                 g_free (full_name);
6567
6568                 /* FIXME: Allocate from the mempool */
6569                 new_entry = g_new0 (ClassNameTableEntry, 1);
6570                 new_entry->token = token;
6571
6572                 entry = g_ptr_array_index (table, hash);
6573                 if (entry == NULL) {
6574                         new_entry->index = hash;
6575                         g_ptr_array_index (table, hash) = new_entry;
6576                 } else {
6577                         while (entry->next)
6578                                 entry = entry->next;
6579                         
6580                         entry->next = new_entry;
6581                         new_entry->index = table->len;
6582                         g_ptr_array_add (table, new_entry);
6583                 }
6584         }
6585
6586         /* Emit the table */
6587         sprintf (symbol, "class_name_table");
6588         emit_section_change (acfg, RODATA_SECT, 0);
6589         emit_alignment (acfg, 8);
6590         emit_label (acfg, symbol);
6591
6592         /* FIXME: Optimize memory usage */
6593         g_assert (table_size < 65000);
6594         emit_int16 (acfg, table_size);
6595         g_assert (table->len < 65000);
6596         for (i = 0; i < table->len; ++i) {
6597                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6598
6599                 if (entry == NULL) {
6600                         emit_int16 (acfg, 0);
6601                         emit_int16 (acfg, 0);
6602                 } else {
6603                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
6604                         if (entry->next)
6605                                 emit_int16 (acfg, entry->next->index);
6606                         else
6607                                 emit_int16 (acfg, 0);
6608                 }
6609         }
6610 }
6611
6612 static void
6613 emit_image_table (MonoAotCompile *acfg)
6614 {
6615         int i;
6616         char symbol [256];
6617
6618         /*
6619          * The image table is small but referenced in a lot of places.
6620          * So we emit it at once, and reference its elements by an index.
6621          */
6622
6623         sprintf (symbol, "image_table");
6624         emit_section_change (acfg, RODATA_SECT, 1);
6625         emit_alignment (acfg, 8);
6626         emit_label (acfg, symbol);
6627
6628         emit_int32 (acfg, acfg->image_table->len);
6629         for (i = 0; i < acfg->image_table->len; i++) {
6630                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6631                 MonoAssemblyName *aname = &image->assembly->aname;
6632
6633                 /* FIXME: Support multi-module assemblies */
6634                 g_assert (image->assembly->image == image);
6635
6636                 emit_string (acfg, image->assembly_name);
6637                 emit_string (acfg, image->guid);
6638                 emit_string (acfg, aname->culture ? aname->culture : "");
6639                 emit_string (acfg, (const char*)aname->public_key_token);
6640
6641                 emit_alignment (acfg, 8);
6642                 emit_int32 (acfg, aname->flags);
6643                 emit_int32 (acfg, aname->major);
6644                 emit_int32 (acfg, aname->minor);
6645                 emit_int32 (acfg, aname->build);
6646                 emit_int32 (acfg, aname->revision);
6647         }
6648 }
6649
6650 static void
6651 emit_got_info (MonoAotCompile *acfg)
6652 {
6653         char symbol [256];
6654         int i, first_plt_got_patch, buf_size;
6655         guint8 *p, *buf;
6656         guint32 *got_info_offsets;
6657
6658         /* Add the patches needed by the PLT to the GOT */
6659         acfg->plt_got_offset_base = acfg->got_offset;
6660         first_plt_got_patch = acfg->got_patches->len;
6661         for (i = 1; i < acfg->plt_offset; ++i) {
6662                 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6663
6664                 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6665
6666                 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
6667         }
6668
6669         acfg->got_offset += acfg->plt_offset;
6670
6671         /**
6672          * FIXME: 
6673          * - optimize offsets table.
6674          * - reduce number of exported symbols.
6675          * - emit info for a klass only once.
6676          * - determine when a method uses a GOT slot which is guaranteed to be already 
6677          *   initialized.
6678          * - clean up and document the code.
6679          * - use String.Empty in class libs.
6680          */
6681
6682         /* Encode info required to decode shared GOT entries */
6683         buf_size = acfg->got_patches->len * 128;
6684         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6685         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6686         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6687         /* Unused */
6688         if (acfg->plt_offset)
6689                 acfg->plt_got_info_offsets [0] = 0;
6690         for (i = 0; i < acfg->got_patches->len; ++i) {
6691                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6692                 guint8 *p2;
6693
6694                 p = buf;
6695
6696                 encode_value (ji->type, p, &p);
6697                 p2 = p;
6698                 encode_patch (acfg, ji, p, &p);
6699                 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
6700                 g_assert (p - buf <= buf_size);
6701                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6702
6703                 if (i >= first_plt_got_patch)
6704                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6705                 acfg->stats.got_info_size += p - buf;
6706         }
6707
6708         /* Emit got_info_offsets table */
6709         sprintf (symbol, "got_info_offsets");
6710         emit_section_change (acfg, RODATA_SECT, 1);
6711         emit_alignment (acfg, 8);
6712         emit_label (acfg, symbol);
6713
6714         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6715         acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6716 }
6717
6718 static void
6719 emit_got (MonoAotCompile *acfg)
6720 {
6721         char symbol [256];
6722
6723         if (!acfg->llvm) {
6724                 /* Don't make GOT global so accesses to it don't need relocations */
6725                 sprintf (symbol, "%s", acfg->got_symbol);
6726                 emit_section_change (acfg, ".bss", 0);
6727                 emit_alignment (acfg, 8);
6728                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6729                 emit_label (acfg, symbol);
6730                 if (acfg->got_offset > 0)
6731                         emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6732
6733                 sprintf (symbol, "got_end");
6734                 emit_label (acfg, symbol);
6735         }
6736 }
6737
6738 typedef struct GlobalsTableEntry {
6739         guint32 value, index;
6740         struct GlobalsTableEntry *next;
6741 } GlobalsTableEntry;
6742
6743 static void
6744 emit_globals (MonoAotCompile *acfg)
6745 {
6746         int i, table_size;
6747         guint32 hash;
6748         GPtrArray *table;
6749         char symbol [256];
6750         GlobalsTableEntry *entry, *new_entry;
6751
6752         if (!acfg->aot_opts.static_link)
6753                 return;
6754
6755         /* 
6756          * When static linking, we emit a table containing our globals.
6757          */
6758
6759         /*
6760          * Construct a chained hash table for mapping global names to their index in
6761          * the globals table.
6762          */
6763         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6764         table = g_ptr_array_sized_new (table_size);
6765         for (i = 0; i < table_size; ++i)
6766                 g_ptr_array_add (table, NULL);
6767         for (i = 0; i < acfg->globals->len; ++i) {
6768                 char *name = g_ptr_array_index (acfg->globals, i);
6769
6770                 hash = mono_metadata_str_hash (name) % table_size;
6771
6772                 /* FIXME: Allocate from the mempool */
6773                 new_entry = g_new0 (GlobalsTableEntry, 1);
6774                 new_entry->value = i;
6775
6776                 entry = g_ptr_array_index (table, hash);
6777                 if (entry == NULL) {
6778                         new_entry->index = hash;
6779                         g_ptr_array_index (table, hash) = new_entry;
6780                 } else {
6781                         while (entry->next)
6782                                 entry = entry->next;
6783                         
6784                         entry->next = new_entry;
6785                         new_entry->index = table->len;
6786                         g_ptr_array_add (table, new_entry);
6787                 }
6788         }
6789
6790         /* Emit the table */
6791         sprintf (symbol, ".Lglobals_hash");
6792         emit_section_change (acfg, RODATA_SECT, 0);
6793         emit_alignment (acfg, 8);
6794         emit_label (acfg, symbol);
6795
6796         /* FIXME: Optimize memory usage */
6797         g_assert (table_size < 65000);
6798         emit_int16 (acfg, table_size);
6799         for (i = 0; i < table->len; ++i) {
6800                 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6801
6802                 if (entry == NULL) {
6803                         emit_int16 (acfg, 0);
6804                         emit_int16 (acfg, 0);
6805                 } else {
6806                         emit_int16 (acfg, entry->value + 1);
6807                         if (entry->next)
6808                                 emit_int16 (acfg, entry->next->index);
6809                         else
6810                                 emit_int16 (acfg, 0);
6811                 }
6812         }
6813
6814         /* Emit the names */
6815         for (i = 0; i < acfg->globals->len; ++i) {
6816                 char *name = g_ptr_array_index (acfg->globals, i);
6817
6818                 sprintf (symbol, "name_%d", i);
6819                 emit_section_change (acfg, RODATA_SECT, 1);
6820 #ifdef __APPLE__
6821                 emit_alignment (acfg, 4);
6822 #endif
6823                 emit_label (acfg, symbol);
6824                 emit_string (acfg, name);
6825         }
6826
6827         /* Emit the globals table */
6828         sprintf (symbol, "globals");
6829         emit_section_change (acfg, ".data", 0);
6830         /* This is not a global, since it is accessed by the init function */
6831         emit_alignment (acfg, 8);
6832         emit_label (acfg, symbol);
6833
6834         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6835         emit_pointer (acfg, symbol);
6836
6837         for (i = 0; i < acfg->globals->len; ++i) {
6838                 char *name = g_ptr_array_index (acfg->globals, i);
6839
6840                 sprintf (symbol, "name_%d", i);
6841                 emit_pointer (acfg, symbol);
6842
6843                 sprintf (symbol, "%s", name);
6844                 emit_pointer (acfg, symbol);
6845         }
6846         /* Null terminate the table */
6847         emit_int32 (acfg, 0);
6848         emit_int32 (acfg, 0);
6849 }
6850
6851 static void
6852 emit_autoreg (MonoAotCompile *acfg)
6853 {
6854         char *symbol;
6855
6856         /*
6857          * Emit a function into the .ctor section which will be called by the ELF
6858          * loader to register this module with the runtime.
6859          */
6860         if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6861                 return;
6862
6863         symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6864
6865         arch_emit_autoreg (acfg, symbol);
6866
6867         g_free (symbol);
6868 }       
6869
6870 static void
6871 emit_mem_end (MonoAotCompile *acfg)
6872 {
6873         char symbol [128];
6874
6875         sprintf (symbol, "mem_end");
6876         emit_section_change (acfg, ".text", 1);
6877         emit_alignment (acfg, 8);
6878         emit_label (acfg, symbol);
6879 }
6880
6881 /*
6882  * Emit a structure containing all the information not stored elsewhere.
6883  */
6884 static void
6885 emit_file_info (MonoAotCompile *acfg)
6886 {
6887         char symbol [256];
6888         int i;
6889         int gc_name_offset;
6890         const char *gc_name;
6891         char *build_info;
6892
6893         emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6894
6895         if (acfg->aot_opts.bind_to_runtime_version) {
6896                 build_info = mono_get_runtime_build_info ();
6897                 emit_string_symbol (acfg, "runtime_version", build_info);
6898                 g_free (build_info);
6899         } else {
6900                 emit_string_symbol (acfg, "runtime_version", "");
6901         }
6902
6903         /* Emit a string holding the assembly name */
6904         emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6905
6906         /*
6907          * The managed allocators are GC specific, so can't use an AOT image created by one GC
6908          * in another.
6909          */
6910         gc_name = mono_gc_get_gc_name ();
6911         gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6912
6913         sprintf (symbol, "mono_aot_file_info");
6914         emit_section_change (acfg, ".data", 0);
6915         emit_alignment (acfg, 8);
6916         emit_label (acfg, symbol);
6917         if (!acfg->aot_opts.static_link)
6918                 emit_global (acfg, symbol, FALSE);
6919
6920         /* The data emitted here must match MonoAotFileInfo. */
6921
6922         emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6923         emit_int32 (acfg, 0);
6924
6925         /* 
6926          * We emit pointers to our data structures instead of emitting global symbols which
6927          * point to them, to reduce the number of globals, and because using globals leads to
6928          * various problems (i.e. arm/thumb).
6929          */
6930         emit_pointer (acfg, acfg->got_symbol);
6931         emit_pointer (acfg, "methods");
6932         if (acfg->llvm) {
6933                 /*
6934                  * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6935                  */
6936                 emit_pointer (acfg, "mono_eh_frame");
6937         } else {
6938                 emit_pointer (acfg, NULL);
6939         }
6940         emit_pointer (acfg, "blob");
6941         emit_pointer (acfg, "class_name_table");
6942         emit_pointer (acfg, "class_info_offsets");
6943         emit_pointer (acfg, "method_info_offsets");
6944         emit_pointer (acfg, "ex_info_offsets");
6945         emit_pointer (acfg, "code_offsets");
6946         emit_pointer (acfg, "extra_method_info_offsets");
6947         emit_pointer (acfg, "extra_method_table");
6948         emit_pointer (acfg, "got_info_offsets");
6949         emit_pointer (acfg, "methods_end");
6950         emit_pointer (acfg, "unwind_info");
6951         emit_pointer (acfg, "mem_end");
6952         emit_pointer (acfg, "image_table");
6953         emit_pointer (acfg, "plt");
6954         emit_pointer (acfg, "plt_end");
6955         emit_pointer (acfg, "assembly_guid");
6956         emit_pointer (acfg, "runtime_version");
6957         if (acfg->num_trampoline_got_entries) {
6958                 emit_pointer (acfg, "specific_trampolines");
6959                 emit_pointer (acfg, "static_rgctx_trampolines");
6960                 emit_pointer (acfg, "imt_thunks");
6961         } else {
6962                 emit_pointer (acfg, NULL);
6963                 emit_pointer (acfg, NULL);
6964                 emit_pointer (acfg, NULL);
6965         }
6966         if (acfg->thumb_mixed) {
6967                 emit_pointer (acfg, "thumb_end");
6968         } else {
6969                 emit_pointer (acfg, NULL);
6970         }
6971         if (acfg->aot_opts.static_link) {
6972                 emit_pointer (acfg, "globals");
6973         } else {
6974                 emit_pointer (acfg, NULL);
6975         }
6976         emit_pointer (acfg, "assembly_name");
6977         emit_pointer (acfg, "unbox_trampolines");
6978         emit_pointer (acfg, "unbox_trampolines_end");
6979
6980         emit_int32 (acfg, acfg->plt_got_offset_base);
6981         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6982         emit_int32 (acfg, acfg->plt_offset);
6983         emit_int32 (acfg, acfg->nmethods);
6984         emit_int32 (acfg, acfg->flags);
6985         emit_int32 (acfg, acfg->opts);
6986         emit_int32 (acfg, gc_name_offset);
6987
6988         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6989                 emit_int32 (acfg, acfg->num_trampolines [i]);
6990         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6991                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6992         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6993                 emit_int32 (acfg, acfg->trampoline_size [i]);
6994
6995 #if defined (TARGET_ARM) && defined (__APPLE__)
6996        {
6997                MonoType t;
6998                int align = 0;
6999
7000                t.type = MONO_TYPE_R8;
7001                mono_type_size (&t, &align);
7002
7003                emit_int32 (acfg, align);
7004
7005                t.type = MONO_TYPE_I8;
7006                mono_type_size (&t, &align);
7007
7008                emit_int32 (acfg, align);
7009        }
7010 #else
7011         emit_int32 (acfg, __alignof__ (double));
7012         emit_int32 (acfg, __alignof__ (gint64));
7013 #endif
7014
7015         if (acfg->aot_opts.static_link) {
7016                 char *p;
7017
7018                 /* 
7019                  * Emit a global symbol which can be passed by an embedding app to
7020                  * mono_aot_register_module (). The symbol points to a pointer to the the file info
7021                  * structure.
7022                  */
7023 #if defined(__APPLE__) && !defined(__native_client_codegen__)
7024                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7025 #else
7026                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7027 #endif
7028
7029                 /* Get rid of characters which cannot occur in symbols */
7030                 p = symbol;
7031                 for (p = symbol; *p; ++p) {
7032                         if (!(isalnum (*p) || *p == '_'))
7033                                 *p = '_';
7034                 }
7035                 acfg->static_linking_symbol = g_strdup (symbol);
7036                 emit_global_inner (acfg, symbol, FALSE);
7037                 emit_label (acfg, symbol);
7038                 emit_pointer (acfg, "mono_aot_file_info");
7039         }
7040 }
7041
7042 static void
7043 emit_blob (MonoAotCompile *acfg)
7044 {
7045         char symbol [128];
7046
7047         sprintf (symbol, "blob");
7048         emit_section_change (acfg, RODATA_SECT, 1);
7049         emit_alignment (acfg, 8);
7050         emit_label (acfg, symbol);
7051
7052         emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7053 }
7054
7055 static void
7056 emit_dwarf_info (MonoAotCompile *acfg)
7057 {
7058 #ifdef EMIT_DWARF_INFO
7059         int i;
7060         char symbol [128], symbol2 [128];
7061
7062         /* DIEs for methods */
7063         for (i = 0; i < acfg->nmethods; ++i) {
7064                 MonoCompile *cfg = acfg->cfgs [i];
7065
7066                 if (!cfg)
7067                         continue;
7068
7069                 // FIXME: LLVM doesn't define .Lme_...
7070                 if (cfg->compile_llvm)
7071                         continue;
7072
7073                 sprintf (symbol, "%s", cfg->asm_symbol);
7074                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7075
7076                 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
7077         }
7078 #endif
7079 }
7080
7081 static void
7082 collect_methods (MonoAotCompile *acfg)
7083 {
7084         int i;
7085         MonoImage *image = acfg->image;
7086
7087         /* Collect methods */
7088         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7089                 MonoMethod *method;
7090                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7091
7092                 method = mono_get_method (acfg->image, token, NULL);
7093
7094                 if (!method) {
7095                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7096                         exit (1);
7097                 }
7098                         
7099                 /* Load all methods eagerly to skip the slower lazy loading code */
7100                 mono_class_setup_methods (method->klass);
7101
7102                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7103                         /* Compile the wrapper instead */
7104                         /* We do this here instead of add_wrappers () because it is easy to do it here */
7105                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7106                         method = wrapper;
7107                 }
7108
7109                 /* FIXME: Some mscorlib methods don't have debug info */
7110                 /*
7111                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7112                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7113                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7114                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7115                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7116                                 if (!mono_debug_lookup_method (method)) {
7117                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7118                                         exit (1);
7119                                 }
7120                         }
7121                 }
7122                 */
7123
7124                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7125                 add_method_with_index (acfg, method, i, FALSE);
7126                 acfg->method_index ++;
7127         }
7128
7129         add_generic_instances (acfg);
7130
7131         if (acfg->aot_opts.full_aot)
7132                 add_wrappers (acfg);
7133 }
7134
7135 static void
7136 compile_methods (MonoAotCompile *acfg)
7137 {
7138         int i, methods_len;
7139
7140         if (acfg->aot_opts.nthreads > 0) {
7141                 GPtrArray *frag;
7142                 int len, j;
7143                 GPtrArray *threads;
7144                 HANDLE handle;
7145                 gpointer *user_data;
7146                 MonoMethod **methods;
7147
7148                 methods_len = acfg->methods->len;
7149
7150                 len = acfg->methods->len / acfg->aot_opts.nthreads;
7151                 g_assert (len > 0);
7152                 /* 
7153                  * Partition the list of methods into fragments, and hand it to threads to
7154                  * process.
7155                  */
7156                 threads = g_ptr_array_new ();
7157                 /* Make a copy since acfg->methods is modified by compile_method () */
7158                 methods = g_new0 (MonoMethod*, methods_len);
7159                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7160                 for (i = 0; i < methods_len; ++i)
7161                         methods [i] = g_ptr_array_index (acfg->methods, i);
7162                 i = 0;
7163                 while (i < methods_len) {
7164                         frag = g_ptr_array_new ();
7165                         for (j = 0; j < len; ++j) {
7166                                 if (i < methods_len) {
7167                                         g_ptr_array_add (frag, methods [i]);
7168                                         i ++;
7169                                 }
7170                         }
7171
7172                         user_data = g_new0 (gpointer, 3);
7173                         user_data [0] = mono_domain_get ();
7174                         user_data [1] = acfg;
7175                         user_data [2] = frag;
7176                         
7177                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7178                         g_ptr_array_add (threads, handle);
7179                 }
7180                 g_free (methods);
7181
7182                 for (i = 0; i < threads->len; ++i) {
7183                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7184                 }
7185         } else {
7186                 methods_len = 0;
7187         }
7188
7189         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7190         for (i = methods_len; i < acfg->methods->len; ++i) {
7191                 /* This can new methods to acfg->methods */
7192                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7193         }
7194 }
7195
7196 static int
7197 compile_asm (MonoAotCompile *acfg)
7198 {
7199         char *command, *objfile;
7200         char *outfile_name, *tmp_outfile_name;
7201         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7202
7203 #if defined(TARGET_AMD64)
7204 #define AS_OPTIONS "--64"
7205 #elif defined(TARGET_POWERPC64)
7206 #define AS_OPTIONS "-a64 -mppc64"
7207 #define LD_OPTIONS "-m elf64ppc"
7208 #elif defined(sparc) && SIZEOF_VOID_P == 8
7209 #define AS_OPTIONS "-xarch=v9"
7210 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
7211 #define AS_OPTIONS "-arch i386 -W"
7212 #else
7213 #define AS_OPTIONS ""
7214 #endif
7215
7216 #ifdef __native_client_codegen__
7217 #if defined(TARGET_AMD64)
7218 #define AS_NAME "nacl64-as"
7219 #else
7220 #define AS_NAME "nacl-as"
7221 #endif
7222 #else
7223 #define AS_NAME "as"
7224 #endif
7225
7226 #ifndef LD_OPTIONS
7227 #define LD_OPTIONS ""
7228 #endif
7229
7230 #define EH_LD_OPTIONS ""
7231
7232         if (acfg->aot_opts.asm_only) {
7233                 printf ("Output file: '%s'.\n", acfg->tmpfname);
7234                 if (acfg->aot_opts.static_link)
7235                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7236                 return 0;
7237         }
7238
7239         if (acfg->aot_opts.static_link) {
7240                 if (acfg->aot_opts.outfile)
7241                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7242                 else
7243                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
7244         } else {
7245                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7246         }
7247         command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
7248         printf ("Executing the native assembler: %s\n", command);
7249         if (system (command) != 0) {
7250                 g_free (command);
7251                 g_free (objfile);
7252                 return 1;
7253         }
7254
7255         g_free (command);
7256
7257         if (acfg->aot_opts.static_link) {
7258                 printf ("Output file: '%s'.\n", objfile);
7259                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7260                 g_free (objfile);
7261                 return 0;
7262         }
7263
7264         if (acfg->aot_opts.outfile)
7265                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7266         else
7267                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7268
7269         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7270
7271 #if defined(sparc)
7272         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7273 #elif defined(__ppc__) && defined(__APPLE__)
7274         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7275 #elif defined(HOST_WIN32)
7276         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7277 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
7278         command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7279 #else
7280         command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7281 #endif
7282         printf ("Executing the native linker: %s\n", command);
7283         if (system (command) != 0) {
7284                 g_free (tmp_outfile_name);
7285                 g_free (outfile_name);
7286                 g_free (command);
7287                 g_free (objfile);
7288                 return 1;
7289         }
7290
7291         g_free (command);
7292         unlink (objfile);
7293         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7294         printf ("Stripping the binary: %s\n", com);
7295         system (com);
7296         g_free (com);*/
7297
7298 #if defined(TARGET_ARM) && !defined(__APPLE__)
7299         /* 
7300          * gas generates 'mapping symbols' each time code and data is mixed, which 
7301          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7302          */
7303         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7304         printf ("Stripping the binary: %s\n", command);
7305         if (system (command) != 0) {
7306                 g_free (tmp_outfile_name);
7307                 g_free (outfile_name);
7308                 g_free (command);
7309                 g_free (objfile);
7310                 return 1;
7311         }
7312 #endif
7313
7314         rename (tmp_outfile_name, outfile_name);
7315
7316         g_free (tmp_outfile_name);
7317         g_free (outfile_name);
7318         g_free (objfile);
7319
7320         if (acfg->aot_opts.save_temps)
7321                 printf ("Retained input file.\n");
7322         else
7323                 unlink (acfg->tmpfname);
7324
7325         return 0;
7326 }
7327
7328 static MonoAotCompile*
7329 acfg_create (MonoAssembly *ass, guint32 opts)
7330 {
7331         MonoImage *image = ass->image;
7332         MonoAotCompile *acfg;
7333         int i;
7334
7335         acfg = g_new0 (MonoAotCompile, 1);
7336         acfg->methods = g_ptr_array_new ();
7337         acfg->method_indexes = g_hash_table_new (NULL, NULL);
7338         acfg->method_depth = g_hash_table_new (NULL, NULL);
7339         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
7340         acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7341         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7342         acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
7343         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7344                 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7345         acfg->got_patches = g_ptr_array_new ();
7346         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
7347         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7348         acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7349         acfg->image_hash = g_hash_table_new (NULL, NULL);
7350         acfg->image_table = g_ptr_array_new ();
7351         acfg->globals = g_ptr_array_new ();
7352         acfg->image = image;
7353         acfg->opts = opts;
7354         acfg->mempool = mono_mempool_new ();
7355         acfg->extra_methods = g_ptr_array_new ();
7356         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
7357         acfg->unwind_ops = g_ptr_array_new ();
7358         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7359         acfg->method_order = g_ptr_array_new ();
7360         acfg->export_names = g_hash_table_new (NULL, NULL);
7361         acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
7362         acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
7363         acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
7364         InitializeCriticalSection (&acfg->mutex);
7365
7366         return acfg;
7367 }
7368
7369 static void
7370 acfg_free (MonoAotCompile *acfg)
7371 {
7372         int i;
7373
7374         img_writer_destroy (acfg->w);
7375         for (i = 0; i < acfg->nmethods; ++i)
7376                 if (acfg->cfgs [i])
7377                         g_free (acfg->cfgs [i]);
7378         g_free (acfg->cfgs);
7379         g_free (acfg->static_linking_symbol);
7380         g_free (acfg->got_symbol);
7381         g_free (acfg->plt_symbol);
7382         g_ptr_array_free (acfg->methods, TRUE);
7383         g_ptr_array_free (acfg->got_patches, TRUE);
7384         g_ptr_array_free (acfg->image_table, TRUE);
7385         g_ptr_array_free (acfg->globals, TRUE);
7386         g_ptr_array_free (acfg->unwind_ops, TRUE);
7387         g_hash_table_destroy (acfg->method_indexes);
7388         g_hash_table_destroy (acfg->method_depth);
7389         g_hash_table_destroy (acfg->plt_offset_to_entry);
7390         g_hash_table_destroy (acfg->patch_to_plt_entry);
7391         g_hash_table_destroy (acfg->patch_to_got_offset);
7392         g_hash_table_destroy (acfg->method_to_cfg);
7393         g_hash_table_destroy (acfg->token_info_hash);
7394         g_hash_table_destroy (acfg->method_to_pinvoke_import);
7395         g_hash_table_destroy (acfg->image_hash);
7396         g_hash_table_destroy (acfg->unwind_info_offsets);
7397         g_hash_table_destroy (acfg->method_label_hash);
7398         g_hash_table_destroy (acfg->export_names);
7399         g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
7400         g_hash_table_destroy (acfg->klass_blob_hash);
7401         g_hash_table_destroy (acfg->method_blob_hash);
7402         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7403                 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
7404         g_free (acfg->patch_to_got_offset_by_type);
7405         mono_mempool_destroy (acfg->mempool);
7406         g_free (acfg);
7407 }
7408
7409 int
7410 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7411 {
7412         MonoImage *image = ass->image;
7413         int i, res;
7414         MonoAotCompile *acfg;
7415         char *outfile_name, *tmp_outfile_name, *p;
7416         TV_DECLARE (atv);
7417         TV_DECLARE (btv);
7418
7419         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
7420
7421         acfg = acfg_create (ass, opts);
7422
7423         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
7424         acfg->aot_opts.write_symbols = TRUE;
7425         acfg->aot_opts.ntrampolines = 1024;
7426         acfg->aot_opts.nrgctx_trampolines = 1024;
7427         acfg->aot_opts.nimt_trampolines = 128;
7428         acfg->aot_opts.llvm_path = g_strdup ("");
7429
7430         mono_aot_parse_options (aot_options, &acfg->aot_opts);
7431
7432         if (acfg->aot_opts.static_link)
7433                 acfg->aot_opts.autoreg = TRUE;
7434
7435         //acfg->aot_opts.print_skipped_methods = TRUE;
7436
7437 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7438         if (acfg->aot_opts.full_aot) {
7439                 printf ("--aot=full is not supported on this platform.\n");
7440                 return 1;
7441         }
7442 #endif
7443
7444         if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
7445                 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
7446                 exit (1);
7447         }
7448
7449         if (acfg->aot_opts.static_link)
7450                 acfg->aot_opts.asm_writer = TRUE;
7451
7452         if (acfg->aot_opts.soft_debug) {
7453                 MonoDebugOptions *opt = mini_get_debug_options ();
7454
7455                 opt->mdb_optimizations = TRUE;
7456                 opt->gen_seq_points = TRUE;
7457
7458                 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
7459                         fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
7460                         return 1;
7461                 }
7462                 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
7463         }
7464
7465         if (mono_use_llvm) {
7466                 acfg->llvm = TRUE;
7467                 acfg->aot_opts.asm_writer = TRUE;
7468                 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
7469
7470                 if (acfg->aot_opts.soft_debug) {
7471                         fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
7472                         exit (1);
7473                 }
7474         }
7475
7476         if (acfg->aot_opts.full_aot)
7477                 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
7478
7479         load_profile_files (acfg);
7480
7481         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
7482 #ifdef MONO_ARCH_GSHARED_SUPPORTED
7483         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
7484 #endif
7485         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
7486
7487         acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
7488
7489         arch_init (acfg);
7490
7491         acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
7492         acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
7493         acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
7494
7495         /* Get rid of characters which cannot occur in symbols */
7496         for (p = acfg->got_symbol_base; *p; ++p) {
7497                 if (!(isalnum (*p) || *p == '_'))
7498                         *p = '_';
7499         }
7500         for (p = acfg->plt_symbol; *p; ++p) {
7501                 if (!(isalnum (*p) || *p == '_'))
7502                         *p = '_';
7503         }
7504         for (p = acfg->assembly_name_sym; *p; ++p) {
7505                 if (!(isalnum (*p) || *p == '_'))
7506                         *p = '_';
7507         }
7508
7509         acfg->method_index = 1;
7510
7511         collect_methods (acfg);
7512
7513         acfg->cfgs_size = acfg->methods->len + 32;
7514         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
7515
7516         /* PLT offset 0 is reserved for the PLT trampoline */
7517         acfg->plt_offset = 1;
7518
7519 #ifdef ENABLE_LLVM
7520         if (acfg->llvm) {
7521                 llvm_acfg = acfg;
7522                 mono_llvm_create_aot_module (acfg->got_symbol_base);
7523         }
7524 #endif
7525
7526         /* GOT offset 0 is reserved for the address of the current assembly */
7527         {
7528                 MonoJumpInfo *ji;
7529
7530                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7531                 ji->type = MONO_PATCH_INFO_IMAGE;
7532                 ji->data.image = acfg->image;
7533
7534                 get_got_offset (acfg, ji);
7535
7536                 /* Slot 1 is reserved for the mscorlib got addr */
7537                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7538                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
7539                 get_got_offset (acfg, ji);
7540
7541                 /* This is very common */
7542                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7543                 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
7544                 get_got_offset (acfg, ji);
7545         }
7546
7547         TV_GETTIME (atv);
7548
7549         compile_methods (acfg);
7550
7551         TV_GETTIME (btv);
7552
7553         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7554
7555         TV_GETTIME (atv);
7556
7557 #ifdef ENABLE_LLVM
7558         if (acfg->llvm) {
7559                 if (acfg->aot_opts.asm_only) {
7560                         if (acfg->aot_opts.outfile)
7561                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7562                         else
7563                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7564                 } else {
7565                         acfg->tmpfname = g_strdup ("temp.s");
7566                 }
7567
7568                 emit_llvm_file (acfg);
7569         }
7570 #endif
7571
7572         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7573                 if (acfg->aot_opts.outfile)
7574                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7575                 else
7576                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7577
7578                 /* 
7579                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
7580                  * it might be in another file system so the rename () won't work.
7581                  */
7582                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7583
7584                 acfg->fp = fopen (tmp_outfile_name, "w");
7585                 if (!acfg->fp) {
7586                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7587                         return 1;
7588                 }
7589
7590                 acfg->w = img_writer_create (acfg->fp, TRUE);
7591                 acfg->use_bin_writer = TRUE;
7592         } else {
7593                 if (acfg->llvm) {
7594                         /* Append to the .s file created by llvm */
7595                         /* FIXME: Use multiple files instead */
7596                         acfg->fp = fopen (acfg->tmpfname, "a+");
7597                 } else {
7598                         if (acfg->aot_opts.asm_only) {
7599                                 if (acfg->aot_opts.outfile)
7600                                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7601                                 else
7602                                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7603                                 acfg->fp = fopen (acfg->tmpfname, "w+");
7604                         } else {
7605                                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7606                                 acfg->fp = fdopen (i, "w+");
7607                         }
7608                         if (acfg->fp == 0) {
7609                                 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
7610                                 return 1;
7611                         }
7612                 }
7613                 acfg->w = img_writer_create (acfg->fp, FALSE);
7614                 
7615                 tmp_outfile_name = NULL;
7616                 outfile_name = NULL;
7617         }
7618
7619         acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7620
7621         /* Compute symbols for methods */
7622         for (i = 0; i < acfg->nmethods; ++i) {
7623                 if (acfg->cfgs [i]) {
7624                         MonoCompile *cfg = acfg->cfgs [i];
7625                         int method_index = get_method_index (acfg, cfg->orig_method);
7626
7627                         if (COMPILE_LLVM (cfg))
7628                                 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7629                         else
7630                                 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7631                 }
7632         }
7633
7634         if (!acfg->aot_opts.nodebug)
7635                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7636
7637         img_writer_emit_start (acfg->w);
7638
7639         if (acfg->dwarf)
7640                 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7641
7642         if (acfg->thumb_mixed) {
7643                 char symbol [256];
7644                 /*
7645                  * This global symbol marks the end of THUMB code, and the beginning of ARM
7646                  * code generated by our JIT.
7647                  */
7648                 sprintf (symbol, "thumb_end");
7649                 emit_section_change (acfg, ".text", 0);
7650                 emit_label (acfg, symbol);
7651                 emit_zero_bytes (acfg, 16);
7652
7653                 fprintf (acfg->fp, ".arm\n");
7654         }
7655
7656         emit_code (acfg);
7657
7658         emit_info (acfg);
7659
7660         emit_extra_methods (acfg);
7661
7662         emit_trampolines (acfg);
7663
7664         emit_class_name_table (acfg);
7665
7666         emit_got_info (acfg);
7667
7668         emit_exception_info (acfg);
7669
7670         emit_unwind_info (acfg);
7671
7672         emit_class_info (acfg);
7673
7674         emit_plt (acfg);
7675
7676         emit_image_table (acfg);
7677
7678         emit_got (acfg);
7679
7680         emit_file_info (acfg);
7681
7682         emit_blob (acfg);
7683
7684         emit_globals (acfg);
7685
7686         emit_autoreg (acfg);
7687
7688         if (acfg->dwarf) {
7689                 emit_dwarf_info (acfg);
7690                 mono_dwarf_writer_close (acfg->dwarf);
7691         }
7692
7693         emit_mem_end (acfg);
7694
7695         if (acfg->need_pt_gnu_stack) {
7696                 /* This is required so the .so doesn't have an executable stack */
7697                 /* The bin writer already emits this */
7698                 if (!acfg->use_bin_writer)
7699                         fprintf (acfg->fp, "\n.section  .note.GNU-stack,\"\",@progbits\n");
7700         }
7701
7702         TV_GETTIME (btv);
7703
7704         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7705
7706         if (acfg->llvm)
7707                 g_assert (acfg->got_offset <= acfg->final_got_size);
7708
7709         printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
7710
7711         TV_GETTIME (atv);
7712         res = img_writer_emit_writeout (acfg->w);
7713         if (res != 0) {
7714                 acfg_free (acfg);
7715                 return res;
7716         }
7717         if (acfg->use_bin_writer) {
7718                 int err = rename (tmp_outfile_name, outfile_name);
7719
7720                 if (err) {
7721                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7722                         return 1;
7723                 }
7724         } else {
7725                 res = compile_asm (acfg);
7726                 if (res != 0) {
7727                         acfg_free (acfg);
7728                         return res;
7729                 }
7730         }
7731         TV_GETTIME (btv);
7732         acfg->stats.link_time = TV_ELAPSED (atv, btv);
7733
7734         printf ("Compiled %d out of %d methods (%d%%)\n", acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100);
7735         if (acfg->stats.genericcount)
7736                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7737         if (acfg->stats.abscount)
7738                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7739         if (acfg->stats.lmfcount)
7740                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7741         if (acfg->stats.ocount)
7742                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7743         if (acfg->llvm)
7744                 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7745         printf ("Methods without GOT slots: %d (%d%%)\n", acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100);
7746         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7747
7748         if (acfg->aot_opts.stats) {
7749                 int i;
7750
7751                 printf ("GOT slot distribution:\n");
7752                 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7753                         if (acfg->stats.got_slot_types [i])
7754                                 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
7755         }
7756
7757         printf ("JIT time: %d ms, Generation time: %d ms, Assembly+Link time: %d ms.\n", acfg->stats.jit_time / 1000, acfg->stats.gen_time / 1000, acfg->stats.link_time / 1000);
7758
7759         acfg_free (acfg);
7760         
7761         return 0;
7762 }
7763
7764 #else
7765
7766 /* AOT disabled */
7767
7768 void*
7769 mono_aot_readonly_field_override (MonoClassField *field)
7770 {
7771         return NULL;
7772 }
7773
7774 int
7775 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7776 {
7777         return 0;
7778 }
7779
7780 #endif