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