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