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