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