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