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