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