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