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