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