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