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