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