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