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