[runtime] Fix a problem introduced by 522663cdfad5860ffbb84b2827b9d0156c4ed623.
[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                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2670
2671                         g_assert (info);
2672                         encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2673                         break;
2674                 }
2675                 case MONO_WRAPPER_LDFLD_REMOTE:
2676                 case MONO_WRAPPER_STFLD_REMOTE:
2677                         break;
2678                 case MONO_WRAPPER_ALLOC: {
2679                         AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2680
2681                         /* The GC name is saved once in MonoAotFileInfo */
2682                         g_assert (info->alloc_type != -1);
2683                         encode_value (info->alloc_type, p, &p);
2684                         break;
2685                 }
2686                 case MONO_WRAPPER_WRITE_BARRIER:
2687                         break;
2688                 case MONO_WRAPPER_STELEMREF: {
2689                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2690
2691                         g_assert (info);
2692                         encode_value (info->subtype, p, &p);
2693                         if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2694                                 encode_value (info->d.virtual_stelemref.kind, p, &p);
2695                         break;
2696                 }
2697                 case MONO_WRAPPER_UNKNOWN: {
2698                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2699
2700                         g_assert (info);
2701                         encode_value (info->subtype, p, &p);
2702                         if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2703                                 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2704                                 encode_klass_ref (acfg, method->klass, p, &p);
2705                         else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2706                                 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2707                         else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2708                                 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2709                         break;
2710                 }
2711                 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2712                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2713
2714                         g_assert (info);
2715                         encode_value (info->subtype, p, &p);
2716                         if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2717                                 strcpy ((char*)p, method->name);
2718                                 p += strlen (method->name) + 1;
2719                         } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2720                                 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2721                         } else {
2722                                 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2723                                 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2724                         }
2725                         break;
2726                 }
2727                 case MONO_WRAPPER_SYNCHRONIZED: {
2728                         MonoMethod *m;
2729
2730                         m = mono_marshal_method_from_wrapper (method);
2731                         g_assert (m);
2732                         g_assert (m != method);
2733                         encode_method_ref (acfg, m, p, &p);
2734                         break;
2735                 }
2736                 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2737                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2738
2739                         g_assert (info);
2740                         encode_value (info->subtype, p, &p);
2741
2742                         if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2743                                 encode_value (info->d.element_addr.rank, p, &p);
2744                                 encode_value (info->d.element_addr.elem_size, p, &p);
2745                         } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2746                                 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2747                         } else {
2748                                 g_assert_not_reached ();
2749                         }
2750                         break;
2751                 }
2752                 case MONO_WRAPPER_CASTCLASS: {
2753                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2754
2755                         g_assert (info);
2756                         encode_value (info->subtype, p, &p);
2757                         break;
2758                 }
2759                 case MONO_WRAPPER_RUNTIME_INVOKE: {
2760                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2761
2762                         g_assert (info);
2763                         encode_value (info->subtype, p, &p);
2764                         if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2765                                 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2766                         else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2767                                 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2768                         break;
2769                 }
2770                 case MONO_WRAPPER_DELEGATE_INVOKE:
2771                 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2772                 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2773                         if (method->is_inflated) {
2774                                 /* These wrappers are identified by their class */
2775                                 encode_value (1, p, &p);
2776                                 encode_klass_ref (acfg, method->klass, p, &p);
2777                         } else {
2778                                 MonoMethodSignature *sig = mono_method_signature (method);
2779                                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2780
2781                                 encode_value (0, p, &p);
2782                                 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2783                                         encode_value (info ? info->subtype : 0, p, &p);
2784                                 encode_signature (acfg, sig, p, &p);
2785                         }
2786                         break;
2787                 }
2788                 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2789                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2790
2791                         g_assert (info);
2792                         encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2793                         encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2794                         break;
2795                 }
2796                 default:
2797                         g_assert_not_reached ();
2798                 }
2799         } else if (mono_method_signature (method)->is_inflated) {
2800                 /* 
2801                  * This is a generic method, find the original token which referenced it and
2802                  * encode that.
2803                  * Obtain the token from information recorded by the JIT.
2804                  */
2805                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2806                 if (ji) {
2807                         image_index = get_image_index (acfg, ji->image);
2808                         g_assert (image_index < MAX_IMAGE_INDEX);
2809                         token = ji->token;
2810
2811                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2812                         encode_value (image_index, p, &p);
2813                         encode_value (token, p, &p);
2814                 } else {
2815                         MonoMethod *declaring;
2816                         MonoGenericContext *context = mono_method_get_context (method);
2817
2818                         g_assert (method->is_inflated);
2819                         declaring = ((MonoMethodInflated*)method)->declaring;
2820
2821                         /*
2822                          * This might be a non-generic method of a generic instance, which 
2823                          * doesn't have a token since the reference is generated by the JIT 
2824                          * like Nullable:Box/Unbox, or by generic sharing.
2825                          */
2826                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2827                         /* Encode the klass */
2828                         encode_klass_ref (acfg, method->klass, p, &p);
2829                         /* Encode the method */
2830                         image_index = get_image_index (acfg, method->klass->image);
2831                         g_assert (image_index < MAX_IMAGE_INDEX);
2832                         g_assert (declaring->token);
2833                         token = declaring->token;
2834                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2835                         encode_value (image_index, p, &p);
2836                         encode_value (token, p, &p);
2837                         encode_generic_context (acfg, context, p, &p);
2838                 }
2839         } else if (token == 0) {
2840                 /* This might be a method of a constructed type like int[,].Set */
2841                 /* Obtain the token from information recorded by the JIT */
2842                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2843                 if (ji) {
2844                         image_index = get_image_index (acfg, ji->image);
2845                         g_assert (image_index < MAX_IMAGE_INDEX);
2846                         token = ji->token;
2847
2848                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2849                         encode_value (image_index, p, &p);
2850                         encode_value (token, p, &p);
2851                 } else {
2852                         /* Array methods */
2853                         g_assert (method->klass->rank);
2854
2855                         /* Encode directly */
2856                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2857                         encode_klass_ref (acfg, method->klass, p, &p);
2858                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2859                                 encode_value (0, p, &p);
2860                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2861                                 encode_value (1, p, &p);
2862                         else if (!strcmp (method->name, "Get"))
2863                                 encode_value (2, p, &p);
2864                         else if (!strcmp (method->name, "Address"))
2865                                 encode_value (3, p, &p);
2866                         else if (!strcmp (method->name, "Set"))
2867                                 encode_value (4, p, &p);
2868                         else
2869                                 g_assert_not_reached ();
2870                 }
2871         } else {
2872                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2873
2874                 if (image_index >= MONO_AOT_METHODREF_MIN) {
2875                         encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2876                         encode_value (image_index, p, &p);
2877                         encode_value (mono_metadata_token_index (token), p, &p);
2878                 } else {
2879                         encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2880                 }
2881         }
2882         *endbuf = p;
2883 }
2884
2885 static gint
2886 compare_patches (gconstpointer a, gconstpointer b)
2887 {
2888         int i, j;
2889
2890         i = (*(MonoJumpInfo**)a)->ip.i;
2891         j = (*(MonoJumpInfo**)b)->ip.i;
2892
2893         if (i < j)
2894                 return -1;
2895         else
2896                 if (i > j)
2897                         return 1;
2898         else
2899                 return 0;
2900 }
2901
2902 static G_GNUC_UNUSED char*
2903 patch_to_string (MonoJumpInfo *patch_info)
2904 {
2905         GString *str;
2906
2907         str = g_string_new ("");
2908
2909         g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2910
2911         switch (patch_info->type) {
2912         case MONO_PATCH_INFO_VTABLE:
2913                 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2914                 break;
2915         default:
2916                 break;
2917         }
2918         g_string_append_printf (str, ")");
2919         return g_string_free (str, FALSE);
2920 }
2921
2922 /*
2923  * is_plt_patch:
2924  *
2925  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
2926  * PLT entry.
2927  */
2928 static inline gboolean
2929 is_plt_patch (MonoJumpInfo *patch_info)
2930 {
2931         switch (patch_info->type) {
2932         case MONO_PATCH_INFO_METHOD:
2933         case MONO_PATCH_INFO_INTERNAL_METHOD:
2934         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2935         case MONO_PATCH_INFO_ICALL_ADDR:
2936         case MONO_PATCH_INFO_CLASS_INIT:
2937         case MONO_PATCH_INFO_RGCTX_FETCH:
2938         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2939         case MONO_PATCH_INFO_MONITOR_ENTER:
2940         case MONO_PATCH_INFO_MONITOR_EXIT:
2941         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2942                 return TRUE;
2943         default:
2944                 return FALSE;
2945         }
2946 }
2947
2948 /*
2949  * get_plt_symbol:
2950  *
2951  *   Return the symbol identifying the plt entry PLT_OFFSET.
2952  */
2953 static char*
2954 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2955 {
2956 #ifdef TARGET_MACH
2957         /* 
2958          * The Apple linker reorganizes object files, so it doesn't like branches to local
2959          * labels, since those have no relocations.
2960          */
2961         return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2962 #else
2963         return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2964 #endif
2965 }
2966
2967 /*
2968  * get_plt_entry:
2969  *
2970  *   Return a PLT entry which belongs to the method identified by PATCH_INFO.
2971  */
2972 static MonoPltEntry*
2973 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2974 {
2975         MonoPltEntry *res;
2976
2977         if (!is_plt_patch (patch_info))
2978                 return NULL;
2979
2980         if (!acfg->patch_to_plt_entry [patch_info->type])
2981                 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
2982         res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
2983
2984         // FIXME: This breaks the calculation of final_got_size         
2985         if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2986                 /* 
2987                  * Allocate a separate PLT slot for each such patch, since some plt
2988                  * entries will refer to the method itself, and some will refer to the
2989                  * wrapper.
2990                  */
2991                 res = NULL;
2992         }
2993
2994         if (!res) {
2995                 MonoJumpInfo *new_ji;
2996
2997                 g_assert (!acfg->final_got_size);
2998
2999                 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3000
3001                 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3002                 res->plt_offset = acfg->plt_offset;
3003                 res->ji = new_ji;
3004                 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3005                 if (acfg->aot_opts.write_symbols)
3006                         res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3007                 if (res->debug_sym)
3008                         res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3009                 else
3010                         res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3011
3012                 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3013
3014                 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3015
3016                 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3017                 //mono_print_ji (patch_info); printf ("\n");
3018                 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3019
3020                 acfg->plt_offset ++;
3021         }
3022
3023         return res;
3024 }
3025
3026 /**
3027  * get_got_offset:
3028  *
3029  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
3030  * JI could be found if it exists, otherwise allocates a new one.
3031  */
3032 static guint32
3033 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
3034 {
3035         guint32 got_offset;
3036
3037         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
3038         if (got_offset)
3039                 return got_offset - 1;
3040
3041         got_offset = acfg->got_offset;
3042         acfg->got_offset ++;
3043
3044         if (acfg->final_got_size)
3045                 g_assert (got_offset < acfg->final_got_size);
3046
3047         acfg->stats.got_slots ++;
3048         acfg->stats.got_slot_types [ji->type] ++;
3049
3050         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3051         g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3052         g_ptr_array_add (acfg->got_patches, ji);
3053
3054         return got_offset;
3055 }
3056
3057 /* Add a method to the list of methods which need to be emitted */
3058 static void
3059 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3060 {
3061         g_assert (method);
3062         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3063                 g_ptr_array_add (acfg->methods, method);
3064                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3065                 acfg->nmethods = acfg->methods->len + 1;
3066         }
3067
3068         if (method->wrapper_type || extra)
3069                 g_ptr_array_add (acfg->extra_methods, method);
3070 }
3071
3072 static guint32
3073 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3074 {
3075         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3076         
3077         g_assert (index);
3078
3079         return index - 1;
3080 }
3081
3082 static int
3083 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3084 {
3085         int index;
3086
3087         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3088         if (index)
3089                 return index - 1;
3090
3091         index = acfg->method_index;
3092         add_method_with_index (acfg, method, index, extra);
3093
3094         g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3095
3096         g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3097
3098         acfg->method_index ++;
3099
3100         return index;
3101 }
3102
3103 static int
3104 add_method (MonoAotCompile *acfg, MonoMethod *method)
3105 {
3106         return add_method_full (acfg, method, FALSE, 0);
3107 }
3108
3109 static void
3110 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3111 {
3112         if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3113                 method = mini_get_shared_method (method);
3114
3115         if (acfg->aot_opts.log_generics)
3116                 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3117
3118         add_method_full (acfg, method, TRUE, depth);
3119 }
3120
3121 static void
3122 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3123 {
3124         add_extra_method_with_depth (acfg, method, 0);
3125 }
3126
3127 static void
3128 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3129 {
3130         MonoAotCompile *acfg = user_data;
3131         MonoJitICallInfo *callinfo = value;
3132         MonoMethod *wrapper;
3133         char *name;
3134
3135         if (!callinfo->sig)
3136                 return;
3137
3138         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3139         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3140         g_free (name);
3141
3142         add_method (acfg, wrapper);
3143 }
3144
3145 static MonoMethod*
3146 get_runtime_invoke_sig (MonoMethodSignature *sig)
3147 {
3148         MonoMethodBuilder *mb;
3149         MonoMethod *m;
3150
3151         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3152         m = mono_mb_create_method (mb, sig, 16);
3153         return mono_marshal_get_runtime_invoke (m, FALSE);
3154 }
3155
3156 static gboolean
3157 can_marshal_struct (MonoClass *klass)
3158 {
3159         MonoClassField *field;
3160         gboolean can_marshal = TRUE;
3161         gpointer iter = NULL;
3162         MonoMarshalType *info;
3163         int i;
3164
3165         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3166                 return FALSE;
3167
3168         info = mono_marshal_load_type_info (klass);
3169
3170         /* Only allow a few field types to avoid asserts in the marshalling code */
3171         while ((field = mono_class_get_fields (klass, &iter))) {
3172                 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3173                         continue;
3174
3175                 switch (field->type->type) {
3176                 case MONO_TYPE_I4:
3177                 case MONO_TYPE_U4:
3178                 case MONO_TYPE_I1:
3179                 case MONO_TYPE_U1:
3180                 case MONO_TYPE_BOOLEAN:
3181                 case MONO_TYPE_I2:
3182                 case MONO_TYPE_U2:
3183                 case MONO_TYPE_CHAR:
3184                 case MONO_TYPE_I8:
3185                 case MONO_TYPE_U8:
3186                 case MONO_TYPE_I:
3187                 case MONO_TYPE_U:
3188                 case MONO_TYPE_PTR:
3189                 case MONO_TYPE_R4:
3190                 case MONO_TYPE_R8:
3191                 case MONO_TYPE_STRING:
3192                         break;
3193                 case MONO_TYPE_VALUETYPE:
3194                         if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3195                                 can_marshal = FALSE;
3196                         break;
3197                 case MONO_TYPE_SZARRAY: {
3198                         gboolean has_mspec = FALSE;
3199
3200                         if (info) {
3201                                 for (i = 0; i < info->num_fields; ++i) {
3202                                         if (info->fields [i].field == field && info->fields [i].mspec)
3203                                                 has_mspec = TRUE;
3204                                 }
3205                         }
3206                         if (!has_mspec)
3207                                 can_marshal = FALSE;
3208                         break;
3209                 }
3210                 default:
3211                         can_marshal = FALSE;
3212                         break;
3213                 }
3214         }
3215
3216         /* Special cases */
3217         /* Its hard to compute whenever these can be marshalled or not */
3218         if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3219                 return TRUE;
3220
3221         return can_marshal;
3222 }
3223
3224 static void
3225 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3226 {
3227         /* Create a vtype instantiation */
3228         MonoGenericContext shared_context;
3229         MonoType **args;
3230         MonoGenericInst *inst;
3231         MonoGenericContainer *container;
3232         MonoClass **constraints;
3233         int i;
3234
3235         memset (ctx, 0, sizeof (MonoGenericContext));
3236
3237         if (method->klass->generic_container) {
3238                 shared_context = method->klass->generic_container->context;
3239                 inst = shared_context.class_inst;
3240
3241                 args = g_new0 (MonoType*, inst->type_argc);
3242                 for (i = 0; i < inst->type_argc; ++i) {
3243                         args [i] = &mono_defaults.int_class->byval_arg;
3244                 }
3245                 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3246         }
3247         if (method->is_generic) {
3248                 container = mono_method_get_generic_container (method);
3249                 shared_context = container->context;
3250                 inst = shared_context.method_inst;
3251
3252                 args = g_new0 (MonoType*, inst->type_argc);
3253                 for (i = 0; i < container->type_argc; ++i) {
3254                         MonoGenericParamInfo *info = &container->type_params [i].info;
3255                         gboolean ref_only = FALSE;
3256
3257                         if (info && info->constraints) {
3258                                 constraints = info->constraints;
3259
3260                                 while (*constraints) {
3261                                         MonoClass *cklass = *constraints;
3262                                         if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3263                                                 /* Inflaring the method with our vtype would not be valid */
3264                                                 ref_only = TRUE;
3265                                         constraints ++;
3266                                 }
3267                         }
3268
3269                         if (ref_only)
3270                                 args [i] = &mono_defaults.object_class->byval_arg;
3271                         else
3272                                 args [i] = &mono_defaults.int_class->byval_arg;
3273                 }
3274                 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3275         }
3276 }
3277
3278 static void
3279 add_wrappers (MonoAotCompile *acfg)
3280 {
3281         MonoMethod *method, *m;
3282         int i, j;
3283         MonoMethodSignature *sig, *csig;
3284         guint32 token;
3285
3286         /* 
3287          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3288          * so there is only one wrapper of a given type, or inlining their contents into their
3289          * callers.
3290          */
3291         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3292                 MonoMethod *method;
3293                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3294                 gboolean skip = FALSE;
3295
3296                 method = mono_get_method (acfg->image, token, NULL);
3297
3298                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3299                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3300                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3301                         skip = TRUE;
3302
3303                 /* Skip methods which can not be handled by get_runtime_invoke () */
3304                 sig = mono_method_signature (method);
3305                 if (!sig)
3306                         continue;
3307                 if ((sig->ret->type == MONO_TYPE_PTR) ||
3308                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3309                         skip = TRUE;
3310                 if (mono_class_is_open_constructed_type (sig->ret))
3311                         skip = TRUE;
3312
3313                 for (j = 0; j < sig->param_count; j++) {
3314                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3315                                 skip = TRUE;
3316                         if (mono_class_is_open_constructed_type (sig->params [j]))
3317                                 skip = TRUE;
3318                 }
3319
3320 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3321                 if (!mono_class_is_contextbound (method->klass)) {
3322                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3323                         gboolean has_nullable = FALSE;
3324
3325                         for (j = 0; j < sig->param_count; j++) {
3326                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3327                                         has_nullable = TRUE;
3328                         }
3329
3330                         if (info && !has_nullable) {
3331                                 /* Supported by the dynamic runtime-invoke wrapper */
3332                                 skip = TRUE;
3333                                 g_free (info);
3334                         }
3335                 }
3336 #endif
3337
3338                 if (!skip) {
3339                         //printf ("%s\n", mono_method_full_name (method, TRUE));
3340                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3341                 }
3342         }
3343
3344         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3345                 MonoMethodDesc *desc;
3346                 MonoMethod *orig_method;
3347                 int nallocators;
3348
3349                 /* Runtime invoke wrappers */
3350
3351                 /* void runtime-invoke () [.cctor] */
3352                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3353                 csig->ret = &mono_defaults.void_class->byval_arg;
3354                 add_method (acfg, get_runtime_invoke_sig (csig));
3355
3356                 /* void runtime-invoke () [Finalize] */
3357                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3358                 csig->hasthis = 1;
3359                 csig->ret = &mono_defaults.void_class->byval_arg;
3360                 add_method (acfg, get_runtime_invoke_sig (csig));
3361
3362                 /* void runtime-invoke (string) [exception ctor] */
3363                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3364                 csig->hasthis = 1;
3365                 csig->ret = &mono_defaults.void_class->byval_arg;
3366                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3367                 add_method (acfg, get_runtime_invoke_sig (csig));
3368
3369                 /* void runtime-invoke (string, string) [exception ctor] */
3370                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3371                 csig->hasthis = 1;
3372                 csig->ret = &mono_defaults.void_class->byval_arg;
3373                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3374                 csig->params [1] = &mono_defaults.string_class->byval_arg;
3375                 add_method (acfg, get_runtime_invoke_sig (csig));
3376
3377                 /* string runtime-invoke () [Exception.ToString ()] */
3378                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3379                 csig->hasthis = 1;
3380                 csig->ret = &mono_defaults.string_class->byval_arg;
3381                 add_method (acfg, get_runtime_invoke_sig (csig));
3382
3383                 /* void runtime-invoke (string, Exception) [exception ctor] */
3384                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3385                 csig->hasthis = 1;
3386                 csig->ret = &mono_defaults.void_class->byval_arg;
3387                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3388                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3389                 add_method (acfg, get_runtime_invoke_sig (csig));
3390
3391                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3392                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3393                 csig->hasthis = 1;
3394                 csig->ret = &(mono_class_from_name (
3395                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3396                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3397                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3398                 add_method (acfg, get_runtime_invoke_sig (csig));
3399
3400                 /* runtime-invoke used by finalizers */
3401                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3402
3403                 /* This is used by mono_runtime_capture_context () */
3404                 method = mono_get_context_capture_method ();
3405                 if (method)
3406                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3407
3408 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3409                 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3410 #endif
3411
3412                 /* stelemref */
3413                 add_method (acfg, mono_marshal_get_stelemref ());
3414
3415                 if (MONO_ARCH_HAVE_TLS_GET) {
3416                         /* Managed Allocators */
3417                         nallocators = mono_gc_get_managed_allocator_types ();
3418                         for (i = 0; i < nallocators; ++i) {
3419                                 m = mono_gc_get_managed_allocator_by_type (i);
3420                                 if (m)
3421                                         add_method (acfg, m);
3422                         }
3423
3424                         /* Monitor Enter/Exit */
3425                         desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3426                         orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3427                         /* This is a v4 method */
3428                         if (orig_method) {
3429                                 method = mono_monitor_get_fast_path (orig_method);
3430                                 if (method)
3431                                         add_method (acfg, method);
3432                         }
3433                         mono_method_desc_free (desc);
3434
3435                         desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3436                         orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3437                         g_assert (orig_method);
3438                         mono_method_desc_free (desc);
3439                         method = mono_monitor_get_fast_path (orig_method);
3440                         if (method)
3441                                 add_method (acfg, method);
3442                 }
3443
3444                 /* Stelemref wrappers */
3445                 {
3446                         MonoMethod **wrappers;
3447                         int nwrappers;
3448
3449                         wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3450                         for (i = 0; i < nwrappers; ++i)
3451                                 add_method (acfg, wrappers [i]);
3452                         g_free (wrappers);
3453                 }
3454
3455                 /* castclass_with_check wrapper */
3456                 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3457                 /* isinst_with_check wrapper */
3458                 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3459
3460 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3461                 {
3462                         MonoMethodDesc *desc;
3463                         MonoMethod *m;
3464
3465                         desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3466                         m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3467                         mono_method_desc_free (desc);
3468                         if (m) {
3469                                 m = mono_monitor_get_fast_path (m);
3470                                 if (m)
3471                                         add_method (acfg, m);
3472                         }
3473                 }
3474 #endif
3475
3476                 /* JIT icall wrappers */
3477                 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3478                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3479         }
3480
3481         /* 
3482          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3483          * we use the original method instead at runtime.
3484          * Since full-aot doesn't support remoting, this is not a problem.
3485          */
3486 #if 0
3487         /* remoting-invoke wrappers */
3488         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3489                 MonoMethodSignature *sig;
3490                 
3491                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3492                 method = mono_get_method (acfg->image, token, NULL);
3493
3494                 sig = mono_method_signature (method);
3495
3496                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3497                         m = mono_marshal_get_remoting_invoke_with_check (method);
3498
3499                         add_method (acfg, m);
3500                 }
3501         }
3502 #endif
3503
3504         /* delegate-invoke wrappers */
3505         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3506                 MonoClass *klass;
3507                 MonoCustomAttrInfo *cattr;
3508                 
3509                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3510                 klass = mono_class_get (acfg->image, token);
3511
3512                 if (!klass) {
3513                         mono_loader_clear_error ();
3514                         continue;
3515                 }
3516
3517                 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3518                         continue;
3519
3520                 if (!klass->generic_container) {
3521                         method = mono_get_delegate_invoke (klass);
3522
3523                         m = mono_marshal_get_delegate_invoke (method, NULL);
3524
3525                         add_method (acfg, m);
3526
3527                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3528                         if (method)
3529                                 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3530
3531                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3532                         if (method)
3533                                 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3534
3535                         cattr = mono_custom_attrs_from_class (klass);
3536
3537                         if (cattr) {
3538                                 int j;
3539
3540                                 for (j = 0; j < cattr->num_attrs; ++j)
3541                                         if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3542                                                 break;
3543                                 if (j < cattr->num_attrs)
3544                                         add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3545                         }
3546                 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3547                         MonoGenericContext ctx;
3548                         MonoMethod *inst, *gshared;
3549
3550                         /*
3551                          * Emit gsharedvt versions of the generic delegate-invoke wrappers
3552                          */
3553                         /* Invoke */
3554                         method = mono_get_delegate_invoke (klass);
3555                         create_gsharedvt_inst (acfg, method, &ctx);
3556
3557                         inst = mono_class_inflate_generic_method (method, &ctx);
3558
3559                         m = mono_marshal_get_delegate_invoke (inst, NULL);
3560                         g_assert (m->is_inflated);
3561
3562                         gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3563                         add_extra_method (acfg, gshared);
3564
3565                         /* begin-invoke */
3566                         method = mono_get_delegate_begin_invoke (klass);
3567                         create_gsharedvt_inst (acfg, method, &ctx);
3568
3569                         inst = mono_class_inflate_generic_method (method, &ctx);
3570
3571                         m = mono_marshal_get_delegate_begin_invoke (inst);
3572                         g_assert (m->is_inflated);
3573
3574                         gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3575                         add_extra_method (acfg, gshared);
3576
3577                         /* end-invoke */
3578                         method = mono_get_delegate_end_invoke (klass);
3579                         create_gsharedvt_inst (acfg, method, &ctx);
3580
3581                         inst = mono_class_inflate_generic_method (method, &ctx);
3582
3583                         m = mono_marshal_get_delegate_end_invoke (inst);
3584                         g_assert (m->is_inflated);
3585
3586                         gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3587                         add_extra_method (acfg, gshared);
3588
3589                 }
3590         }
3591
3592         /* array access wrappers */
3593         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3594                 MonoClass *klass;
3595                 
3596                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3597                 klass = mono_class_get (acfg->image, token);
3598
3599                 if (!klass) {
3600                         mono_loader_clear_error ();
3601                         continue;
3602                 }
3603
3604                 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3605                         MonoMethod *m, *wrapper;
3606
3607                         /* Add runtime-invoke wrappers too */
3608
3609                         m = mono_class_get_method_from_name (klass, "Get", -1);
3610                         g_assert (m);
3611                         wrapper = mono_marshal_get_array_accessor_wrapper (m);
3612                         add_extra_method (acfg, wrapper);
3613                         add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3614
3615                         m = mono_class_get_method_from_name (klass, "Set", -1);
3616                         g_assert (m);
3617                         wrapper = mono_marshal_get_array_accessor_wrapper (m);
3618                         add_extra_method (acfg, wrapper);
3619                         add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3620                 }
3621         }
3622
3623         /* Synchronized wrappers */
3624         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3625                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3626                 method = mono_get_method (acfg->image, token, NULL);
3627
3628                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3629                         if (method->is_generic) {
3630                                 // FIXME:
3631                         } else if (method->klass->generic_container) {
3632                                 MonoGenericContext ctx;
3633                                 MonoMethod *inst, *gshared, *m;
3634
3635                                 /*
3636                                  * Create a generic wrapper for a generic instance, and AOT that.
3637                                  */
3638                                 create_gsharedvt_inst (acfg, method, &ctx);
3639                                 inst = mono_class_inflate_generic_method (method, &ctx);        
3640                                 m = mono_marshal_get_synchronized_wrapper (inst);
3641                                 g_assert (m->is_inflated);
3642                                 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3643                                 add_method (acfg, gshared);
3644                         } else {
3645                                 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3646                         }
3647                 }
3648         }
3649
3650         /* pinvoke wrappers */
3651         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3652                 MonoMethod *method;
3653                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3654
3655                 method = mono_get_method (acfg->image, token, NULL);
3656
3657                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3658                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3659                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3660                 }
3661         }
3662  
3663         /* native-to-managed wrappers */
3664         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3665                 MonoMethod *method;
3666                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3667                 MonoCustomAttrInfo *cattr;
3668                 int j;
3669
3670                 method = mono_get_method (acfg->image, token, NULL);
3671
3672                 /* 
3673                  * Only generate native-to-managed wrappers for methods which have an
3674                  * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3675                  * name to avoid defining a new assembly to contain it.
3676                  */
3677                 cattr = mono_custom_attrs_from_method (method);
3678
3679                 if (cattr) {
3680                         for (j = 0; j < cattr->num_attrs; ++j)
3681                                 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3682                                         break;
3683                         if (j < cattr->num_attrs) {
3684                                 MonoCustomAttrEntry *e = &cattr->attrs [j];
3685                                 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3686                                 const char *p = (const char*)e->data;
3687                                 const char *named;
3688                                 int slen, num_named, named_type, data_type;
3689                                 char *n;
3690                                 MonoType *t;
3691                                 MonoClass *klass;
3692                                 char *export_name = NULL;
3693                                 MonoMethod *wrapper;
3694
3695                                 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3696                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3697                                         g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks", 
3698                                                 mono_method_full_name (method, TRUE));
3699                                         exit (1);
3700                                 }
3701
3702                                 g_assert (sig->param_count == 1);
3703                                 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3704
3705                                 /* 
3706                                  * Decode the cattr manually since we can't create objects
3707                                  * during aot compilation.
3708                                  */
3709                                         
3710                                 /* Skip prolog */
3711                                 p += 2;
3712
3713                                 /* From load_cattr_value () in reflection.c */
3714                                 slen = mono_metadata_decode_value (p, &p);
3715                                 n = g_memdup (p, slen + 1);
3716                                 n [slen] = 0;
3717                                 t = mono_reflection_type_from_name (n, acfg->image);
3718                                 g_assert (t);
3719                                 g_free (n);
3720
3721                                 klass = mono_class_from_mono_type (t);
3722                                 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3723
3724                                 p += slen;
3725
3726                                 num_named = read16 (p);
3727                                 p += 2;
3728
3729                                 g_assert (num_named < 2);
3730                                 if (num_named == 1) {
3731                                         int name_len;
3732                                         char *name;
3733                                         MonoType *prop_type;
3734
3735                                         /* parse ExportSymbol attribute */
3736                                         named = p;
3737                                         named_type = *named;
3738                                         named += 1;
3739                                         data_type = *named;
3740                                         named += 1;
3741
3742                                         name_len = mono_metadata_decode_blob_size (named, &named);
3743                                         name = g_malloc (name_len + 1);
3744                                         memcpy (name, named, name_len);
3745                                         name [name_len] = 0;
3746                                         named += name_len;
3747
3748                                         g_assert (named_type == 0x54);
3749                                         g_assert (!strcmp (name, "ExportSymbol"));
3750
3751                                         prop_type = &mono_defaults.string_class->byval_arg;
3752
3753                                         /* load_cattr_value (), string case */
3754                                         g_assert (*named != (char)0xff);
3755                                         slen = mono_metadata_decode_value (named, &named);
3756                                         export_name = g_malloc (slen + 1);
3757                                         memcpy (export_name, named, slen);
3758                                         export_name [slen] = 0;
3759                                         named += slen;
3760                                 }
3761
3762                                 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3763                                 add_method (acfg, wrapper);
3764                                 if (export_name)
3765                                         g_hash_table_insert (acfg->export_names, wrapper, export_name);
3766                         }
3767                 }
3768
3769                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3770                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3771                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3772                 }
3773         }
3774
3775         /* StructureToPtr/PtrToStructure wrappers */
3776         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3777                 MonoClass *klass;
3778                 
3779                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3780                 klass = mono_class_get (acfg->image, token);
3781
3782                 if (!klass) {
3783                         mono_loader_clear_error ();
3784                         continue;
3785                 }
3786
3787                 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3788                         !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3789                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3790                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3791                 }
3792         }
3793 }
3794
3795 static gboolean
3796 has_type_vars (MonoClass *klass)
3797 {
3798         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3799                 return TRUE;
3800         if (klass->rank)
3801                 return has_type_vars (klass->element_class);
3802         if (klass->generic_class) {
3803                 MonoGenericContext *context = &klass->generic_class->context;
3804                 if (context->class_inst) {
3805                         int i;
3806
3807                         for (i = 0; i < context->class_inst->type_argc; ++i)
3808                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3809                                         return TRUE;
3810                 }
3811         }
3812         if (klass->generic_container)
3813                 return TRUE;
3814         return FALSE;
3815 }
3816
3817 static gboolean
3818 is_vt_inst (MonoGenericInst *inst)
3819 {
3820         int i;
3821
3822         for (i = 0; i < inst->type_argc; ++i) {
3823                 MonoType *t = inst->type_argv [i];
3824                 if (t->type == MONO_TYPE_VALUETYPE)
3825                         return TRUE;
3826         }
3827         return FALSE;
3828 }
3829
3830 static gboolean
3831 method_has_type_vars (MonoMethod *method)
3832 {
3833         if (has_type_vars (method->klass))
3834                 return TRUE;
3835
3836         if (method->is_inflated) {
3837                 MonoGenericContext *context = mono_method_get_context (method);
3838                 if (context->method_inst) {
3839                         int i;
3840
3841                         for (i = 0; i < context->method_inst->type_argc; ++i)
3842                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3843                                         return TRUE;
3844                 }
3845         }
3846         return FALSE;
3847 }
3848
3849 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3850
3851 static void
3852 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3853 {
3854         /* This might lead to a huge code blowup so only do it if neccesary */
3855         if (!acfg->aot_opts.full_aot && !force)
3856                 return;
3857
3858         add_generic_class_with_depth (acfg, klass, 0, ref);
3859 }
3860
3861 static gboolean
3862 check_type_depth (MonoType *t, int depth)
3863 {
3864         int i;
3865
3866         if (depth > 8)
3867                 return TRUE;
3868
3869         switch (t->type) {
3870         case MONO_TYPE_GENERICINST: {
3871                 MonoGenericClass *gklass = t->data.generic_class;
3872                 MonoGenericInst *ginst = gklass->context.class_inst;
3873
3874                 if (ginst) {
3875                         for (i = 0; i < ginst->type_argc; ++i) {
3876                                 if (check_type_depth (ginst->type_argv [i], depth + 1))
3877                                         return TRUE;
3878                         }
3879                 }
3880                 break;
3881         }
3882         default:
3883                 break;
3884         }
3885
3886         return FALSE;
3887 }
3888
3889 static void
3890 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3891
3892 /*
3893  * add_generic_class:
3894  *
3895  *   Add all methods of a generic class.
3896  */
3897 static void
3898 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3899 {
3900         MonoMethod *method;
3901         MonoClassField *field;
3902         gpointer iter;
3903         gboolean use_gsharedvt = FALSE;
3904
3905         if (!acfg->ginst_hash)
3906                 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3907
3908         mono_class_init (klass);
3909
3910         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3911                 return;
3912
3913         if (has_type_vars (klass))
3914                 return;
3915
3916         if (!klass->generic_class && !klass->rank)
3917                 return;
3918
3919         if (klass->exception_type)
3920                 return;
3921
3922         if (!acfg->ginst_hash)
3923                 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3924
3925         if (g_hash_table_lookup (acfg->ginst_hash, klass))
3926                 return;
3927
3928         if (check_type_depth (&klass->byval_arg, 0))
3929                 return;
3930
3931         if (acfg->aot_opts.log_generics)
3932                 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3933
3934         g_hash_table_insert (acfg->ginst_hash, klass, klass);
3935
3936         /*
3937          * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3938          * Enable this only for some classes since gsharedvt might not support all methods.
3939          */
3940         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) &&
3941                 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
3942                 use_gsharedvt = TRUE;
3943
3944         iter = NULL;
3945         while ((method = mono_class_get_methods (klass, &iter))) {
3946                 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3947                         /*
3948                          * This is partial sharing, and we can't handle it yet
3949                          */
3950                         continue;
3951                 }
3952                 
3953                 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
3954                         /* Already added */
3955                         add_types_from_method_header (acfg, method);
3956                         continue;
3957                 }
3958
3959                 if (method->is_generic)
3960                         /* FIXME: */
3961                         continue;
3962
3963                 /*
3964                  * FIXME: Instances which are referenced by these methods are not added,
3965                  * for example Array.Resize<int> for List<int>.Add ().
3966                  */
3967                 add_extra_method_with_depth (acfg, method, depth + 1);
3968         }
3969
3970         iter = NULL;
3971         while ((field = mono_class_get_fields (klass, &iter))) {
3972                 if (field->type->type == MONO_TYPE_GENERICINST)
3973                         add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3974         }
3975
3976         if (klass->delegate) {
3977                 method = mono_get_delegate_invoke (klass);
3978
3979                 method = mono_marshal_get_delegate_invoke (method, NULL);
3980
3981                 if (acfg->aot_opts.log_generics)
3982                         printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3983
3984                 add_method (acfg, method);
3985         }
3986
3987         /* Add superclasses */
3988         if (klass->parent)
3989                 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3990
3991         /* 
3992          * For ICollection<T>, add instances of the helper methods
3993          * in Array, since a T[] could be cast to ICollection<T>.
3994          */
3995         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3996                 (!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"))) {
3997                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3998                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3999                 gpointer iter;
4000                 char *name_prefix;
4001
4002                 if (!strcmp (klass->name, "IEnumerator`1"))
4003                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4004                 else
4005                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4006
4007                 /* Add the T[]/InternalEnumerator class */
4008                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4009                         MonoClass *nclass;
4010
4011                         iter = NULL;
4012                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4013                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4014                                         break;
4015                         }
4016                         g_assert (nclass);
4017                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4018                         add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4019                 }
4020
4021                 iter = NULL;
4022                 while ((method = mono_class_get_methods (array_class, &iter))) {
4023                         if (strstr (method->name, name_prefix)) {
4024                                 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4025
4026                                 add_extra_method_with_depth (acfg, m, depth);
4027                         }
4028                 }
4029
4030                 g_free (name_prefix);
4031         }
4032
4033         /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4034         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4035                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4036                 MonoClass *icomparable, *gcomparer;
4037                 MonoGenericContext ctx;
4038                 MonoType *args [16];
4039
4040                 memset (&ctx, 0, sizeof (ctx));
4041
4042                 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4043                 g_assert (icomparable);
4044                 args [0] = &tclass->byval_arg;
4045                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4046
4047                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4048                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4049                         g_assert (gcomparer);
4050                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4051                 }
4052         }
4053
4054         /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4055         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4056                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4057                 MonoClass *iface, *gcomparer;
4058                 MonoGenericContext ctx;
4059                 MonoType *args [16];
4060
4061                 memset (&ctx, 0, sizeof (ctx));
4062
4063                 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4064                 g_assert (iface);
4065                 args [0] = &tclass->byval_arg;
4066                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4067
4068                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4069                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4070                         g_assert (gcomparer);
4071                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4072                 }
4073         }
4074 }
4075
4076 static void
4077 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4078 {
4079         int i;
4080         MonoGenericContext ctx;
4081         MonoType *args [16];
4082
4083         if (acfg->aot_opts.no_instances)
4084                 return;
4085
4086         memset (&ctx, 0, sizeof (ctx));
4087
4088         for (i = 0; i < ninsts; ++i) {
4089                 args [0] = insts [i];
4090                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4091                 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4092         }
4093 }
4094
4095 static void
4096 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4097 {
4098         MonoMethodHeader *header;
4099         MonoMethodSignature *sig;
4100         int j, depth;
4101
4102         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4103
4104         sig = mono_method_signature (method);
4105
4106         if (sig) {
4107                 for (j = 0; j < sig->param_count; ++j)
4108                         if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4109                                 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4110         }
4111
4112         header = mono_method_get_header (method);
4113
4114         if (header) {
4115                 for (j = 0; j < header->num_locals; ++j)
4116                         if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4117                                 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4118         } else {
4119                 mono_loader_clear_error ();
4120         }
4121 }
4122
4123 /*
4124  * add_generic_instances:
4125  *
4126  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
4127  */
4128 static void
4129 add_generic_instances (MonoAotCompile *acfg)
4130 {
4131         int i;
4132         guint32 token;
4133         MonoMethod *method;
4134         MonoGenericContext *context;
4135
4136         if (acfg->aot_opts.no_instances)
4137                 return;
4138
4139         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4140                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4141                 method = mono_get_method (acfg->image, token, NULL);
4142
4143                 if (!method)
4144                         continue;
4145
4146                 if (method->klass->image != acfg->image)
4147                         continue;
4148
4149                 context = mono_method_get_context (method);
4150
4151                 if (context && ((context->class_inst && context->class_inst->is_open)))
4152                         continue;
4153
4154                 /*
4155                  * For open methods, create an instantiation which can be passed to the JIT.
4156                  * FIXME: Handle class_inst as well.
4157                  */
4158                 if (context && context->method_inst && context->method_inst->is_open) {
4159                         MonoGenericContext shared_context;
4160                         MonoGenericInst *inst;
4161                         MonoType **type_argv;
4162                         int i;
4163                         MonoMethod *declaring_method;
4164                         gboolean supported = TRUE;
4165
4166                         /* Check that the context doesn't contain open constructed types */
4167                         if (context->class_inst) {
4168                                 inst = context->class_inst;
4169                                 for (i = 0; i < inst->type_argc; ++i) {
4170                                         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)
4171                                                 continue;
4172                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4173                                                 supported = FALSE;
4174                                 }
4175                         }
4176                         if (context->method_inst) {
4177                                 inst = context->method_inst;
4178                                 for (i = 0; i < inst->type_argc; ++i) {
4179                                         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)
4180                                                 continue;
4181                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4182                                                 supported = FALSE;
4183                                 }
4184                         }
4185
4186                         if (!supported)
4187                                 continue;
4188
4189                         memset (&shared_context, 0, sizeof (MonoGenericContext));
4190
4191                         inst = context->class_inst;
4192                         if (inst) {
4193                                 type_argv = g_new0 (MonoType*, inst->type_argc);
4194                                 for (i = 0; i < inst->type_argc; ++i) {
4195                                         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)
4196                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
4197                                         else
4198                                                 type_argv [i] = inst->type_argv [i];
4199                                 }
4200                                 
4201                                 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4202                                 g_free (type_argv);
4203                         }
4204
4205                         inst = context->method_inst;
4206                         if (inst) {
4207                                 type_argv = g_new0 (MonoType*, inst->type_argc);
4208                                 for (i = 0; i < inst->type_argc; ++i) {
4209                                         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)
4210                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
4211                                         else
4212                                                 type_argv [i] = inst->type_argv [i];
4213                                 }
4214
4215                                 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4216                                 g_free (type_argv);
4217                         }
4218
4219                         if (method->is_generic || method->klass->generic_container)
4220                                 declaring_method = method;
4221                         else
4222                                 declaring_method = mono_method_get_declaring_generic_method (method);
4223
4224                         method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4225                 }
4226
4227                 /* 
4228                  * If the method is fully sharable, it was already added in place of its
4229                  * generic definition.
4230                  */
4231                 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4232                         continue;
4233
4234                 /*
4235                  * FIXME: Partially shared methods are not shared here, so we end up with
4236                  * many identical methods.
4237                  */
4238                 add_extra_method (acfg, method);
4239         }
4240
4241         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4242                 MonoClass *klass;
4243
4244                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4245
4246                 klass = mono_class_get (acfg->image, token);
4247                 if (!klass || klass->rank) {
4248                         mono_loader_clear_error ();
4249                         continue;
4250                 }
4251
4252                 add_generic_class (acfg, klass, FALSE, "typespec");
4253         }
4254
4255         /* Add types of args/locals */
4256         for (i = 0; i < acfg->methods->len; ++i) {
4257                 method = g_ptr_array_index (acfg->methods, i);
4258                 add_types_from_method_header (acfg, method);
4259         }
4260
4261         if (acfg->image == mono_defaults.corlib) {
4262                 MonoClass *klass;
4263                 MonoType *insts [256];
4264                 int ninsts = 0;
4265
4266                 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4267                 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4268                 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4269                 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4270                 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4271                 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4272                 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4273                 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4274                 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4275                 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4276                 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4277                 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4278
4279                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4280                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4281                 if (klass)
4282                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4283                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4284                 if (klass)
4285                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4286
4287                 /* Add instances of the array generic interfaces for primitive types */
4288                 /* This will add instances of the InternalArray_ helper methods in Array too */
4289                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4290                 if (klass)
4291                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4292                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4293                 if (klass)
4294                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4295                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4296                 if (klass)
4297                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4298
4299                 /* 
4300                  * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4301                  * used for all instances of GetGenericValueImpl by the AOT runtime.
4302                  */
4303                 {
4304                         MonoGenericContext ctx;
4305                         MonoType *args [16];
4306                         MonoMethod *get_method;
4307                         MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4308
4309                         get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4310
4311                         if (get_method) {
4312                                 memset (&ctx, 0, sizeof (ctx));
4313                                 args [0] = &mono_defaults.object_class->byval_arg;
4314                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4315                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4316                         }
4317                 }
4318
4319                 /* Same for CompareExchange<T>/Exchange<T> */
4320                 {
4321                         MonoGenericContext ctx;
4322                         MonoType *args [16];
4323                         MonoMethod *m;
4324                         MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4325                         gpointer iter = NULL;
4326
4327                         while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4328                                 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4329                                         memset (&ctx, 0, sizeof (ctx));
4330                                         args [0] = &mono_defaults.object_class->byval_arg;
4331                                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4332                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4333                                 }
4334                         }
4335                 }
4336
4337                 /* Same for Volatile.Read/Write<T> */
4338                 {
4339                         MonoGenericContext ctx;
4340                         MonoType *args [16];
4341                         MonoMethod *m;
4342                         MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4343                         gpointer iter = NULL;
4344
4345                         if (volatile_klass) {
4346                                 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4347                                         if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4348                                                 memset (&ctx, 0, sizeof (ctx));
4349                                                 args [0] = &mono_defaults.object_class->byval_arg;
4350                                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4351                                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4352                                         }
4353                                 }
4354                         }
4355                 }
4356         }
4357 }
4358
4359 /*
4360  * is_direct_callable:
4361  *
4362  *   Return whenever the method identified by JI is directly callable without 
4363  * going through the PLT.
4364  */
4365 static gboolean
4366 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4367 {
4368         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4369                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4370                 if (callee_cfg) {
4371                         gboolean direct_callable = TRUE;
4372
4373                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4374                                 direct_callable = FALSE;
4375                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4376                                 // FIXME: Maybe call the wrapper directly ?
4377                                 direct_callable = FALSE;
4378
4379                         if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4380                                 /* Disable this so all calls go through load_method (), see the
4381                                  * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4382                                  * mono_debugger_agent_init ().
4383                                  */
4384                                 direct_callable = FALSE;
4385                         }
4386
4387                         if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4388                                 /* sgen does some initialization when the allocator method is created */
4389                                 direct_callable = FALSE;
4390
4391                         if (direct_callable)
4392                                 return TRUE;
4393                 }
4394         } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4395                 if (acfg->aot_opts.direct_pinvoke)
4396                         return TRUE;
4397         } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4398                 if (acfg->aot_opts.direct_icalls)
4399                         return TRUE;
4400                 return FALSE;
4401         }
4402
4403         return FALSE;
4404 }
4405
4406 #ifdef MONO_ARCH_AOT_SUPPORTED
4407 static const char *
4408 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4409 {
4410         MonoImage *image = method->klass->image;
4411         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4412         MonoTableInfo *tables = image->tables;
4413         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4414         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4415         guint32 im_cols [MONO_IMPLMAP_SIZE];
4416         char *import;
4417
4418         import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4419         if (import != NULL)
4420                 return import;
4421
4422         if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4423                 return NULL;
4424
4425         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4426
4427         if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4428                 return NULL;
4429
4430         import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4431
4432         g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4433         
4434         return import;
4435 }
4436 #endif
4437
4438 static gint
4439 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4440 {
4441         if (a->native_offset == b->native_offset)
4442                 return a->il_offset - b->il_offset;
4443         else
4444                 return a->native_offset - b->native_offset;
4445 }
4446
4447 /*
4448  * compute_line_numbers:
4449  *
4450  * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4451  * entry.
4452  */
4453 static MonoDebugSourceLocation**
4454 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4455 {
4456         MonoDebugMethodInfo *minfo;
4457         MonoDebugLineNumberEntry *ln_array;
4458         MonoDebugSourceLocation *loc;
4459         int i, prev_line, prev_il_offset;
4460         int *native_to_il_offset = NULL;
4461         MonoDebugSourceLocation **res;
4462         gboolean first;
4463
4464         minfo = mono_debug_lookup_method (method);
4465         if (!minfo)
4466                 return NULL;
4467         // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4468         if (debug_info->code_size != code_size)
4469                 return NULL;
4470
4471         g_assert (code_size);
4472
4473         /* Compute the native->IL offset mapping */
4474
4475         ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4476         memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4477
4478         qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4479
4480         native_to_il_offset = g_new0 (int, code_size + 1);
4481
4482         for (i = 0; i < debug_info->num_line_numbers; ++i) {
4483                 int j;
4484                 MonoDebugLineNumberEntry *lne = &ln_array [i];
4485
4486                 if (i == 0) {
4487                         for (j = 0; j < lne->native_offset; ++j)
4488                                 native_to_il_offset [j] = -1;
4489                 }
4490
4491                 if (i < debug_info->num_line_numbers - 1) {
4492                         MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4493
4494                         for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4495                                 native_to_il_offset [j] = lne->il_offset;
4496                 } else {
4497                         for (j = lne->native_offset; j < code_size; ++j)
4498                                 native_to_il_offset [j] = lne->il_offset;
4499                 }
4500         }
4501         g_free (ln_array);
4502
4503         /* Compute the native->line number mapping */
4504         res = g_new0 (MonoDebugSourceLocation*, code_size);
4505         prev_il_offset = -1;
4506         prev_line = -1;
4507         first = TRUE;
4508         for (i = 0; i < code_size; ++i) {
4509                 int il_offset = native_to_il_offset [i];
4510
4511                 if (il_offset == -1 || il_offset == prev_il_offset)
4512                         continue;
4513                 prev_il_offset = il_offset;
4514                 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4515                 if (!(loc && loc->source_file))
4516                         continue;
4517                 if (loc->row == prev_line) {
4518                         mono_debug_symfile_free_location (loc);
4519                         continue;
4520                 }
4521                 prev_line = loc->row;
4522                 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4523                 if (first)
4524                         /* This will cover the prolog too */
4525                         res [0] = loc;
4526                 else
4527                         res [i] = loc;
4528                 first = FALSE;
4529         }
4530         return res;
4531 }
4532
4533 static int
4534 get_file_index (MonoAotCompile *acfg, const char *source_file)
4535 {
4536         int findex;
4537
4538         // FIXME: Free these
4539         if (!acfg->dwarf_ln_filenames)
4540                 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4541         findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4542         if (!findex) {
4543                 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4544                 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4545                 emit_unset_mode (acfg);
4546                 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4547         }
4548         return findex;
4549 }
4550
4551 #ifdef TARGET_ARM64
4552 #define INST_LEN 4
4553 #else
4554 #define INST_LEN 1
4555 #endif
4556
4557 /*
4558  * emit_and_reloc_code:
4559  *
4560  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4561  * is true, calls are made through the GOT too. This is used for emitting trampolines
4562  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4563  * since trampolines are needed to make PTL work.
4564  */
4565 static void
4566 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4567 {
4568         int i, pindex, start_index, method_index;
4569         GPtrArray *patches;
4570         MonoJumpInfo *patch_info;
4571         MonoMethodHeader *header;
4572         MonoDebugSourceLocation **locs = NULL;
4573         gboolean skip;
4574 #ifdef MONO_ARCH_AOT_SUPPORTED
4575         gboolean direct_call, external_call;
4576         guint32 got_slot;
4577         const char *direct_call_target = 0;
4578         const char *direct_pinvoke;
4579 #endif
4580
4581         if (method) {
4582                 header = mono_method_get_header (method);
4583
4584                 method_index = get_method_index (acfg, method);
4585         }
4586
4587         if (acfg->gas_line_numbers && method && debug_info) {
4588                 locs = compute_line_numbers (method, code_len, debug_info);
4589                 if (!locs) {
4590                         int findex = get_file_index (acfg, "<unknown>");
4591                         emit_unset_mode (acfg);
4592                         fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4593                 }
4594         }
4595
4596         /* Collect and sort relocations */
4597         patches = g_ptr_array_new ();
4598         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4599                 g_ptr_array_add (patches, patch_info);
4600         g_ptr_array_sort (patches, compare_patches);
4601
4602         start_index = 0;
4603         for (i = 0; i < code_len; i += INST_LEN) {
4604                 patch_info = NULL;
4605                 for (pindex = start_index; pindex < patches->len; ++pindex) {
4606                         patch_info = g_ptr_array_index (patches, pindex);
4607                         if (patch_info->ip.i >= i)
4608                                 break;
4609                 }
4610
4611                 if (locs && locs [i]) {
4612                         MonoDebugSourceLocation *loc = locs [i];
4613                         int findex;
4614
4615                         findex = get_file_index (acfg, loc->source_file);
4616                         emit_unset_mode (acfg);
4617                         fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4618                         mono_debug_symfile_free_location (loc);
4619                 }
4620
4621                 skip = FALSE;
4622 #ifdef MONO_ARCH_AOT_SUPPORTED
4623                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4624                         start_index = pindex;
4625
4626                         switch (patch_info->type) {
4627                         case MONO_PATCH_INFO_NONE:
4628                                 break;
4629                         case MONO_PATCH_INFO_GOT_OFFSET: {
4630                                 int code_size;
4631  
4632                                 arch_emit_got_offset (acfg, code + i, &code_size);
4633                                 i += code_size - INST_LEN;
4634                                 skip = TRUE;
4635                                 patch_info->type = MONO_PATCH_INFO_NONE;
4636                                 break;
4637                         }
4638                         case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4639                                 int code_size, index;
4640                                 char *selector = (void*)patch_info->data.target;
4641
4642                                 if (!acfg->objc_selector_to_index)
4643                                         acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4644                                 if (!acfg->objc_selectors)
4645                                         acfg->objc_selectors = g_ptr_array_new ();
4646                                 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4647                                 if (index)
4648                                         index --;
4649                                 else {
4650                                         index = acfg->objc_selector_index;
4651                                         g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4652                                         g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4653                                         acfg->objc_selector_index ++;
4654                                 }
4655
4656                                 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4657                                 i += code_size - INST_LEN;
4658                                 skip = TRUE;
4659                                 patch_info->type = MONO_PATCH_INFO_NONE;
4660                                 break;
4661                         }
4662                         default: {
4663                                 /*
4664                                  * If this patch is a call, try emitting a direct call instead of
4665                                  * through a PLT entry. This is possible if the called method is in
4666                                  * the same assembly and requires no initialization.
4667                                  */
4668                                 direct_call = FALSE;
4669                                 external_call = FALSE;
4670                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4671                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4672                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4673                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4674                                                 direct_call = TRUE;
4675                                                 direct_call_target = callee_cfg->asm_symbol;
4676                                                 patch_info->type = MONO_PATCH_INFO_NONE;
4677                                                 acfg->stats.direct_calls ++;
4678                                         }
4679
4680                                         acfg->stats.all_calls ++;
4681                                 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4682                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4683                                                 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4684                                                         direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4685                                                 else
4686                                                         direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4687                                                 if (direct_pinvoke) {
4688                                                         direct_call = TRUE;
4689                                                         g_assert (strlen (direct_pinvoke) < 1000);
4690                                                         direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4691                                                 }
4692                                         }
4693                                 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4694                                         const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4695                                         if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4696                                                 /* Call to a C function implementing a jit icall */
4697                                                 direct_call = TRUE;
4698                                                 external_call = TRUE;
4699                                                 g_assert (strlen (sym) < 1000);
4700                                                 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4701                                         }
4702                                 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4703                                         MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4704                                         const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4705                                         if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4706                                                 /* Call to a jit icall without a wrapper */
4707                                                 direct_call = TRUE;
4708                                                 external_call = TRUE;
4709                                                 g_assert (strlen (sym) < 1000);
4710                                                 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4711                                         }
4712                                 }
4713
4714                                 if (direct_call) {
4715                                         patch_info->type = MONO_PATCH_INFO_NONE;
4716                                         acfg->stats.direct_calls ++;
4717                                 }
4718
4719                                 if (!got_only && !direct_call) {
4720                                         MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4721                                         if (plt_entry) {
4722                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4723                                                 direct_call = TRUE;
4724                                                 direct_call_target = plt_entry->symbol;
4725                 
4726                                                 /* Nullify the patch */
4727                                                 patch_info->type = MONO_PATCH_INFO_NONE;
4728                                                 plt_entry->jit_used = TRUE;
4729                                         }
4730                                 }
4731
4732                                 if (direct_call) {
4733                                         int call_size;
4734
4735                                         arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4736                                         i += call_size - INST_LEN;
4737                                 } else {
4738                                         int code_size;
4739
4740                                         got_slot = get_got_offset (acfg, patch_info);
4741
4742                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4743                                         i += code_size - INST_LEN;
4744                                 }
4745                                 skip = TRUE;
4746                         }
4747                         }
4748                 }
4749 #endif /* MONO_ARCH_AOT_SUPPORTED */
4750
4751                 if (!skip) {
4752                         /* Find next patch */
4753                         patch_info = NULL;
4754                         for (pindex = start_index; pindex < patches->len; ++pindex) {
4755                                 patch_info = g_ptr_array_index (patches, pindex);
4756                                 if (patch_info->ip.i >= i)
4757                                         break;
4758                         }
4759
4760                         /* Try to emit multiple bytes at once */
4761                         if (pindex < patches->len && patch_info->ip.i > i) {
4762                                 int limit;
4763
4764                                 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4765                                         if (locs && locs [limit])
4766                                                 break;
4767                                 }
4768
4769                                 emit_code_bytes (acfg, code + i, limit - i);
4770                                 i = limit - INST_LEN;
4771                         } else {
4772                                 emit_code_bytes (acfg, code + i, INST_LEN);
4773                         }
4774                 }
4775         }
4776
4777         g_free (locs);
4778 }
4779
4780 /*
4781  * sanitize_symbol:
4782  *
4783  *   Return a modified version of S which only includes characters permissible in symbols.
4784  */
4785 static char*
4786 sanitize_symbol (MonoAotCompile *acfg, char *s)
4787 {
4788         gboolean process = FALSE;
4789         int i, len;
4790         GString *gs;
4791         char *res;
4792
4793         if (!s)
4794                 return s;
4795
4796         len = strlen (s);
4797         for (i = 0; i < len; ++i)
4798                 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4799                         process = TRUE;
4800         if (!process)
4801                 return s;
4802
4803         gs = g_string_sized_new (len);
4804         for (i = 0; i < len; ++i) {
4805                 guint8 c = s [i];
4806                 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4807                         g_string_append_c (gs, c);
4808                 } else if (c > 0x7f) {
4809                         /* multi-byte utf8 */
4810                         g_string_append_printf (gs, "_0x%x", c);
4811                         i ++;
4812                         c = s [i];
4813                         while (c >> 6 == 0x2) {
4814                                 g_string_append_printf (gs, "%x", c);
4815                                 i ++;
4816                                 c = s [i];
4817                         }
4818                         g_string_append_printf (gs, "_");
4819                         i --;
4820                 } else {
4821                         g_string_append_c (gs, '_');
4822                 }
4823         }
4824
4825         res = mono_mempool_strdup (acfg->mempool, gs->str);
4826         g_string_free (gs, TRUE);
4827         return res;
4828 }
4829
4830 static char*
4831 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4832 {
4833         char *name1, *name2, *cached;
4834         int i, j, len, count;
4835
4836 #ifdef TARGET_MACH
4837         // This is so that we don't accidentally create a local symbol (which starts with 'L')
4838         if (!prefix || !*prefix)
4839                 prefix = "_";
4840 #endif
4841
4842         name1 = mono_method_full_name (method, TRUE);
4843         len = strlen (name1);
4844         name2 = malloc (strlen (prefix) + len + 16);
4845         memcpy (name2, prefix, strlen (prefix));
4846         j = strlen (prefix);
4847         for (i = 0; i < len; ++i) {
4848                 if (isalnum (name1 [i])) {
4849                         name2 [j ++] = name1 [i];
4850                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4851                         i += 2;
4852                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4853                         name2 [j ++] = '_';
4854                         i++;
4855                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4856                 } else
4857                         name2 [j ++] = '_';
4858         }
4859         name2 [j] = '\0';
4860
4861         g_free (name1);
4862
4863         count = 0;
4864         while (g_hash_table_lookup (cache, name2)) {
4865                 sprintf (name2 + j, "_%d", count);
4866                 count ++;
4867         }
4868
4869         cached = g_strdup (name2);
4870         g_hash_table_insert (cache, cached, cached);
4871
4872         return name2;
4873 }
4874
4875 static void
4876 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4877 {
4878         MonoMethod *method;
4879         int method_index;
4880         guint8 *code;
4881         char *debug_sym = NULL;
4882         char *symbol = NULL;
4883         int func_alignment = AOT_FUNC_ALIGNMENT;
4884         MonoMethodHeader *header;
4885         char *export_name;
4886
4887         method = cfg->orig_method;
4888         code = cfg->native_code;
4889         header = cfg->header;
4890
4891         method_index = get_method_index (acfg, method);
4892         symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4893
4894
4895         /* Make the labels local */
4896         emit_section_change (acfg, ".text", 0);
4897         emit_alignment (acfg, func_alignment);
4898         
4899         if (acfg->global_symbols && acfg->need_no_dead_strip)
4900                 fprintf (acfg->fp, "    .no_dead_strip %s\n", cfg->asm_symbol);
4901         
4902         emit_label (acfg, cfg->asm_symbol);
4903
4904         if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4905                 /* 
4906                  * Write a C style symbol for every method, this has two uses:
4907                  * - it works on platforms where the dwarf debugging info is not
4908                  *   yet supported.
4909                  * - it allows the setting of breakpoints of aot-ed methods.
4910                  */
4911                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4912
4913                 if (acfg->need_no_dead_strip)
4914                         fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
4915                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4916                 emit_label (acfg, debug_sym);
4917         }
4918
4919         export_name = g_hash_table_lookup (acfg->export_names, method);
4920         if (export_name) {
4921                 /* Emit a global symbol for the method */
4922                 emit_global_inner (acfg, export_name, TRUE);
4923                 emit_label (acfg, export_name);
4924         }
4925
4926         if (cfg->verbose_level > 0)
4927                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4928
4929         acfg->stats.code_size += cfg->code_len;
4930
4931         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4932
4933         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 ()));
4934
4935         emit_line (acfg);
4936
4937         if (acfg->aot_opts.write_symbols) {
4938                 emit_symbol_size (acfg, debug_sym, ".");
4939                 g_free (debug_sym);
4940         }
4941
4942         emit_label (acfg, symbol);
4943         g_free (symbol);
4944 }
4945
4946 /**
4947  * encode_patch:
4948  *
4949  *  Encode PATCH_INFO into its disk representation.
4950  */
4951 static void
4952 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4953 {
4954         guint8 *p = buf;
4955
4956         switch (patch_info->type) {
4957         case MONO_PATCH_INFO_NONE:
4958                 break;
4959         case MONO_PATCH_INFO_IMAGE:
4960                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4961                 break;
4962         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4963         case MONO_PATCH_INFO_JIT_TLS_ID:
4964         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4965         case MONO_PATCH_INFO_CASTCLASS_CACHE:
4966                 break;
4967         case MONO_PATCH_INFO_METHOD_REL:
4968                 encode_value ((gint)patch_info->data.offset, p, &p);
4969                 break;
4970         case MONO_PATCH_INFO_SWITCH: {
4971                 gpointer *table = (gpointer *)patch_info->data.table->table;
4972                 int k;
4973
4974                 encode_value (patch_info->data.table->table_size, p, &p);
4975                 for (k = 0; k < patch_info->data.table->table_size; k++)
4976                         encode_value ((int)(gssize)table [k], p, &p);
4977                 break;
4978         }
4979         case MONO_PATCH_INFO_METHODCONST:
4980         case MONO_PATCH_INFO_METHOD:
4981         case MONO_PATCH_INFO_METHOD_JUMP:
4982         case MONO_PATCH_INFO_ICALL_ADDR:
4983         case MONO_PATCH_INFO_METHOD_RGCTX:
4984         case MONO_PATCH_INFO_METHOD_CODE_SLOT:
4985                 encode_method_ref (acfg, patch_info->data.method, p, &p);
4986                 break;
4987         case MONO_PATCH_INFO_INTERNAL_METHOD:
4988         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4989                 guint32 len = strlen (patch_info->data.name);
4990
4991                 encode_value (len, p, &p);
4992
4993                 memcpy (p, patch_info->data.name, len);
4994                 p += len;
4995                 *p++ = '\0';
4996                 break;
4997         }
4998         case MONO_PATCH_INFO_LDSTR: {
4999                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5000                 guint32 token = patch_info->data.token->token;
5001                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5002                 encode_value (image_index, p, &p);
5003                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5004                 break;
5005         }
5006         case MONO_PATCH_INFO_RVA:
5007         case MONO_PATCH_INFO_DECLSEC:
5008         case MONO_PATCH_INFO_LDTOKEN:
5009         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5010                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5011                 encode_value (patch_info->data.token->token, p, &p);
5012                 encode_value (patch_info->data.token->has_context, p, &p);
5013                 if (patch_info->data.token->has_context)
5014                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5015                 break;
5016         case MONO_PATCH_INFO_EXC_NAME: {
5017                 MonoClass *ex_class;
5018
5019                 ex_class =
5020                         mono_class_from_name (mono_defaults.exception_class->image,
5021                                                                   "System", patch_info->data.target);
5022                 g_assert (ex_class);
5023                 encode_klass_ref (acfg, ex_class, p, &p);
5024                 break;
5025         }
5026         case MONO_PATCH_INFO_R4:
5027                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5028                 break;
5029         case MONO_PATCH_INFO_R8:
5030                 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5031                 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5032                 break;
5033         case MONO_PATCH_INFO_VTABLE:
5034         case MONO_PATCH_INFO_CLASS:
5035         case MONO_PATCH_INFO_IID:
5036         case MONO_PATCH_INFO_ADJUSTED_IID:
5037         case MONO_PATCH_INFO_CLASS_INIT:
5038                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5039                 break;
5040         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5041                 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5042                 if (patch_info->data.del_tramp->method) {
5043                         encode_value (1, p, &p);
5044                         encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5045                 } else {
5046                         encode_value (0, p, &p);
5047                 }
5048                 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5049                 break;
5050         case MONO_PATCH_INFO_FIELD:
5051         case MONO_PATCH_INFO_SFLDA:
5052                 encode_field_info (acfg, patch_info->data.field, p, &p);
5053                 break;
5054         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5055                 break;
5056         case MONO_PATCH_INFO_RGCTX_FETCH: {
5057                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5058                 guint32 offset;
5059                 guint8 *buf2, *p2;
5060
5061                 /* 
5062                  * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5063                  * reference the same method, so encode the method only once.
5064                  */
5065                 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5066                 if (!offset) {
5067                         buf2 = g_malloc (1024);
5068                         p2 = buf2;
5069
5070                         encode_method_ref (acfg, entry->method, p2, &p2);
5071                         g_assert (p2 - buf2 < 1024);
5072
5073                         offset = add_to_blob (acfg, buf2, p2 - buf2);
5074                         g_free (buf2);
5075
5076                         g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5077                 } else {
5078                         offset --;
5079                 }
5080
5081                 encode_value (offset, p, &p);
5082                 g_assert ((int)entry->info_type < 256);
5083                 g_assert (entry->data->type < 256);
5084                 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5085                 encode_patch (acfg, entry->data, p, &p);
5086                 break;
5087         }
5088         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5089         case MONO_PATCH_INFO_MONITOR_ENTER:
5090         case MONO_PATCH_INFO_MONITOR_EXIT:
5091         case MONO_PATCH_INFO_SEQ_POINT_INFO:
5092                 break;
5093         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5094                 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5095                 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5096                 break;
5097         case MONO_PATCH_INFO_SIGNATURE:
5098                 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5099                 break;
5100         case MONO_PATCH_INFO_TLS_OFFSET:
5101                 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5102                 break;
5103         case MONO_PATCH_INFO_GSHAREDVT_CALL:
5104                 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5105                 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5106                 break;
5107         case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5108                 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5109                 int i;
5110
5111                 encode_method_ref (acfg, info->method, p, &p);
5112                 encode_value (info->num_entries, p, &p);
5113                 for (i = 0; i < info->num_entries; ++i) {
5114                         MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5115
5116                         encode_value (template->info_type, p, &p);
5117                         switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5118                         case MONO_PATCH_INFO_CLASS:
5119                                 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5120                                 break;
5121                         case MONO_PATCH_INFO_FIELD:
5122                                 encode_field_info (acfg, template->data, p, &p);
5123                                 break;
5124                         default:
5125                                 g_assert_not_reached ();
5126                                 break;
5127                         }
5128                 }
5129                 break;
5130         }
5131         default:
5132                 g_warning ("unable to handle jump info %d", patch_info->type);
5133                 g_assert_not_reached ();
5134         }
5135
5136         *endbuf = p;
5137 }
5138
5139 static void
5140 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5141 {
5142         guint8 *p = buf;
5143         guint32 pindex, offset;
5144         MonoJumpInfo *patch_info;
5145
5146         encode_value (n_patches, p, &p);
5147
5148         for (pindex = 0; pindex < patches->len; ++pindex) {
5149                 patch_info = g_ptr_array_index (patches, pindex);
5150
5151                 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5152                         /* Nothing to do */
5153                         continue;
5154
5155                 offset = get_got_offset (acfg, patch_info);
5156                 encode_value (offset, p, &p);
5157         }
5158
5159         *endbuf = p;
5160 }
5161
5162 static void
5163 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5164 {
5165         MonoMethod *method;
5166         GList *l;
5167         int pindex, buf_size, n_patches;
5168         GPtrArray *patches;
5169         MonoJumpInfo *patch_info;
5170         MonoMethodHeader *header;
5171         guint32 method_index;
5172         guint8 *p, *buf;
5173         guint32 first_got_offset;
5174
5175         method = cfg->orig_method;
5176         header = mono_method_get_header (method);
5177
5178         method_index = get_method_index (acfg, method);
5179
5180         /* Sort relocations */
5181         patches = g_ptr_array_new ();
5182         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5183                 g_ptr_array_add (patches, patch_info);
5184         g_ptr_array_sort (patches, compare_patches);
5185
5186         first_got_offset = acfg->cfgs [method_index]->got_offset;
5187
5188         /**********************/
5189         /* Encode method info */
5190         /**********************/
5191
5192         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5193         p = buf = g_malloc (buf_size);
5194
5195         if (mono_class_get_cctor (method->klass))
5196                 encode_klass_ref (acfg, method->klass, p, &p);
5197         else
5198                 /* Not needed when loading the method */
5199                 encode_value (0, p, &p);
5200
5201         /* String table */
5202         if (cfg->opt & MONO_OPT_SHARED) {
5203                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5204                 for (l = cfg->ldstr_list; l; l = l->next) {
5205                         encode_value ((long)l->data, p, &p);
5206                 }
5207         }
5208         else
5209                 /* Used only in shared mode */
5210                 g_assert (!cfg->ldstr_list);
5211
5212         n_patches = 0;
5213         for (pindex = 0; pindex < patches->len; ++pindex) {
5214                 patch_info = g_ptr_array_index (patches, pindex);
5215                 
5216                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5217                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
5218                         patch_info->type = MONO_PATCH_INFO_NONE;
5219                         /* Nothing to do */
5220                         continue;
5221                 }
5222
5223                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5224                         /* Stored in a GOT slot initialized at module load time */
5225                         patch_info->type = MONO_PATCH_INFO_NONE;
5226                         continue;
5227                 }
5228
5229                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5230                         /* Stored in a GOT slot initialized at module load time */
5231                         patch_info->type = MONO_PATCH_INFO_NONE;
5232                         continue;
5233                 }
5234
5235                 if (is_plt_patch (patch_info)) {
5236                         /* Calls are made through the PLT */
5237                         patch_info->type = MONO_PATCH_INFO_NONE;
5238                         continue;
5239                 }
5240
5241                 n_patches ++;
5242         }
5243
5244         if (n_patches)
5245                 g_assert (cfg->has_got_slots);
5246
5247         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5248
5249         acfg->stats.info_size += p - buf;
5250
5251         g_assert (p - buf < buf_size);
5252
5253         cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5254         g_free (buf);
5255 }
5256
5257 static guint32
5258 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5259 {
5260         guint32 cache_index;
5261         guint32 offset;
5262
5263         /* Reuse the unwind module to canonize and store unwind info entries */
5264         cache_index = mono_cache_unwind_info (encoded, encoded_len);
5265
5266         /* Use +/- 1 to distinguish 0s from missing entries */
5267         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5268         if (offset)
5269                 return offset - 1;
5270         else {
5271                 guint8 buf [16];
5272                 guint8 *p;
5273
5274                 /* 
5275                  * It would be easier to use assembler symbols, but the caller needs an
5276                  * offset now.
5277                  */
5278                 offset = acfg->unwind_info_offset;
5279                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5280                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5281
5282                 p = buf;
5283                 encode_value (encoded_len, p, &p);
5284
5285                 acfg->unwind_info_offset += encoded_len + (p - buf);
5286                 return offset;
5287         }
5288 }
5289
5290 static void
5291 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5292 {
5293         MonoMethod *method;
5294         int i, k, buf_size, method_index;
5295         guint32 debug_info_size;
5296         guint8 *code;
5297         MonoMethodHeader *header;
5298         guint8 *p, *buf, *debug_info;
5299         MonoJitInfo *jinfo = cfg->jit_info;
5300         guint32 flags;
5301         gboolean use_unwind_ops = FALSE;
5302         MonoSeqPointInfo *seq_points;
5303
5304         method = cfg->orig_method;
5305         code = cfg->native_code;
5306         header = cfg->header;
5307
5308         method_index = get_method_index (acfg, method);
5309
5310         if (!acfg->aot_opts.nodebug) {
5311                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5312         } else {
5313                 debug_info = NULL;
5314                 debug_info_size = 0;
5315         }
5316
5317         seq_points = cfg->seq_point_info;
5318
5319         buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 128) : 0) + cfg->gc_map_size;
5320         p = buf = g_malloc (buf_size);
5321
5322         use_unwind_ops = cfg->unwind_ops != NULL;
5323
5324         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);
5325
5326         encode_value (flags, p, &p);
5327
5328         if (use_unwind_ops) {
5329                 guint32 encoded_len;
5330                 guint8 *encoded;
5331                 guint32 unwind_desc;
5332
5333                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5334
5335                 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5336                 g_assert (unwind_desc < 0xffff);
5337                 if (cfg->has_unwind_info_for_epilog) {
5338                         /*
5339                          * The lower 16 bits identify the unwind descriptor, the upper 16 bits contain the offset of
5340                          * the start of the epilog from the end of the method.
5341                          */
5342                         g_assert (cfg->code_size - cfg->epilog_begin < 0xffff);
5343                         encode_value (((cfg->code_size - cfg->epilog_begin) << 16) | unwind_desc, p, &p);
5344                         g_free (encoded);
5345                 } else {
5346                         encode_value (unwind_desc, p, &p);
5347                 }
5348         } else {
5349                 encode_value (jinfo->unwind_info, p, &p);
5350         }
5351
5352         /*Encode the number of holes before the number of clauses to make decoding easier*/
5353         if (jinfo->has_try_block_holes) {
5354                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5355                 encode_value (table->num_holes, p, &p);
5356         }
5357
5358         /* Exception table */
5359         if (cfg->compile_llvm) {
5360                 /*
5361                  * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5362                  * since the information is only available to llc. Instead, we let llc save the data
5363                  * into the LSDA, and read it from there at runtime.
5364                  */
5365                 /* The assembly might be CIL stripped so emit the data ourselves */
5366                 if (header->num_clauses)
5367                         encode_value (header->num_clauses, p, &p);
5368
5369                 for (k = 0; k < header->num_clauses; ++k) {
5370                         MonoExceptionClause *clause;
5371
5372                         clause = &header->clauses [k];
5373
5374                         encode_value (clause->flags, p, &p);
5375                         if (clause->data.catch_class) {
5376                                 encode_value (1, p, &p);
5377                                 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5378                         } else {
5379                                 encode_value (0, p, &p);
5380                         }
5381
5382                         /* Emit a list of nesting clauses */
5383                         for (i = 0; i < header->num_clauses; ++i) {
5384                                 gint32 cindex1 = k;
5385                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5386                                 gint32 cindex2 = i;
5387                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5388
5389                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5390                                         encode_value (i, p, &p);
5391                         }
5392                         encode_value (-1, p, &p);
5393                 }
5394         } else {
5395                 if (jinfo->num_clauses)
5396                         encode_value (jinfo->num_clauses, p, &p);
5397
5398                 for (k = 0; k < jinfo->num_clauses; ++k) {
5399                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5400
5401                         encode_value (ei->flags, p, &p);
5402                         encode_value (ei->exvar_offset, p, &p);
5403
5404                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5405                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5406                         else {
5407                                 if (ei->data.catch_class) {
5408                                         guint8 *buf2, *p2;
5409                                         int len;
5410
5411                                         buf2 = g_malloc (4096);
5412                                         p2 = buf2;
5413                                         encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5414                                         len = p2 - buf2;
5415                                         g_assert (len < 4096);
5416                                         encode_value (len, p, &p);
5417                                         memcpy (p, buf2, len);
5418                                         p += p2 - buf2;
5419                                         g_free (buf2);
5420                                 } else {
5421                                         encode_value (0, p, &p);
5422                                 }
5423                         }
5424
5425                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5426                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5427                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5428                 }
5429         }
5430
5431         if (jinfo->has_try_block_holes) {
5432                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5433                 for (i = 0; i < table->num_holes; ++i) {
5434                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5435                         encode_value (hole->clause, p, &p);
5436                         encode_value (hole->length, p, &p);
5437                         encode_value (hole->offset, p, &p);
5438                 }
5439         }
5440
5441         if (jinfo->has_arch_eh_info) {
5442                 MonoArchEHJitInfo *eh_info;
5443
5444                 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5445                 encode_value (eh_info->stack_size, p, &p);
5446         }
5447
5448         if (jinfo->has_generic_jit_info) {
5449                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5450                 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5451                 guint8 *p1;
5452                 guint8 *buf2, *p2;
5453                 int len;
5454
5455                 p1 = p;
5456                 encode_value (gi->nlocs, p, &p);
5457                 if (gi->nlocs) {
5458                         for (i = 0; i < gi->nlocs; ++i) {
5459                                 MonoDwarfLocListEntry *entry = &gi->locations [i];
5460
5461                                 encode_value (entry->is_reg ? 1 : 0, p, &p);
5462                                 encode_value (entry->reg, p, &p);
5463                                 if (!entry->is_reg)
5464                                         encode_value (entry->offset, p, &p);
5465                                 if (i == 0)
5466                                         g_assert (entry->from == 0);
5467                                 else
5468                                         encode_value (entry->from, p, &p);
5469                                 encode_value (entry->to, p, &p);
5470                         }
5471                 } else {
5472                         if (!cfg->compile_llvm) {
5473                                 encode_value (gi->has_this ? 1 : 0, p, &p);
5474                                 encode_value (gi->this_reg, p, &p);
5475                                 encode_value (gi->this_offset, p, &p);
5476                         }
5477                 }
5478
5479                 /* 
5480                  * Need to encode jinfo->method too, since it is not equal to 'method'
5481                  * when using generic sharing.
5482                  */
5483                 buf2 = g_malloc (4096);
5484                 p2 = buf2;
5485                 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5486                 len = p2 - buf2;
5487                 g_assert (len < 4096);
5488                 encode_value (len, p, &p);
5489                 memcpy (p, buf2, len);
5490                 p += p2 - buf2;
5491                 g_free (buf2);
5492
5493                 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5494                         MonoMethodInflated *inflated;
5495                         MonoGenericContext *context;
5496                         MonoGenericInst *inst;
5497
5498                         g_assert (jinfo->d.method->is_inflated);
5499                         inflated = (MonoMethodInflated*)jinfo->d.method;
5500                         context = &inflated->context;
5501
5502                         encode_value (1, p, &p);
5503                         if (context->class_inst) {
5504                                 inst = context->class_inst;
5505
5506                                 encode_value (inst->type_argc, p, &p);
5507                                 for (i = 0; i < inst->type_argc; ++i)
5508                                         encode_value (gsctx->var_is_vt [i], p, &p);
5509                         } else {
5510                                 encode_value (0, p, &p);
5511                         }
5512                         if (context->method_inst) {
5513                                 inst = context->method_inst;
5514
5515                                 encode_value (inst->type_argc, p, &p);
5516                                 for (i = 0; i < inst->type_argc; ++i)
5517                                         encode_value (gsctx->mvar_is_vt [i], p, &p);
5518                         } else {
5519                                 encode_value (0, p, &p);
5520                         }
5521                 } else {
5522                         encode_value (0, p, &p);
5523                 }
5524         }
5525
5526         if (seq_points) {
5527                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5528
5529                 encode_value (seq_points->len, p, &p);
5530                 last_il_offset = last_native_offset = 0;
5531                 for (i = 0; i < seq_points->len; ++i) {
5532                         SeqPoint *sp = &seq_points->seq_points [i];
5533                         il_offset = sp->il_offset;
5534                         native_offset = sp->native_offset;
5535                         encode_value (il_offset - last_il_offset, p, &p);
5536                         encode_value (native_offset - last_native_offset, p, &p);
5537                         last_il_offset = il_offset;
5538                         last_native_offset = native_offset;
5539
5540                         encode_value (sp->flags, p, &p);
5541                         encode_value (sp->next_len, p, &p);
5542                         for (j = 0; j < sp->next_len; ++j)
5543                                 encode_value (sp->next [j], p, &p);
5544                 }
5545         }
5546                 
5547         g_assert (debug_info_size < buf_size);
5548
5549         encode_value (debug_info_size, p, &p);
5550         if (debug_info_size) {
5551                 memcpy (p, debug_info, debug_info_size);
5552                 p += debug_info_size;
5553                 g_free (debug_info);
5554         }
5555
5556         /* GC Map */
5557         if (cfg->gc_map) {
5558                 encode_value (cfg->gc_map_size, p, &p);
5559                 /* The GC map requires 4 bytes of alignment */
5560                 while ((gsize)p % 4)
5561                         p ++;
5562                 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5563                 p += cfg->gc_map_size;
5564         }
5565
5566         acfg->stats.ex_info_size += p - buf;
5567
5568         g_assert (p - buf < buf_size);
5569
5570         /* Emit info */
5571         /* The GC Map requires 4 byte alignment */
5572         cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5573         g_free (buf);
5574 }
5575
5576 static guint32
5577 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5578 {
5579         MonoClass *klass = mono_class_get (acfg->image, token);
5580         guint8 *p, *buf;
5581         int i, buf_size, res;
5582         gboolean no_special_static, cant_encode;
5583         gpointer iter = NULL;
5584
5585         if (!klass) {
5586                 mono_loader_clear_error ();
5587
5588                 buf_size = 16;
5589
5590                 p = buf = g_malloc (buf_size);
5591
5592                 /* Mark as unusable */
5593                 encode_value (-1, p, &p);
5594
5595                 res = add_to_blob (acfg, buf, p - buf);
5596                 g_free (buf);
5597
5598                 return res;
5599         }
5600                 
5601         buf_size = 10240 + (klass->vtable_size * 16);
5602         p = buf = g_malloc (buf_size);
5603
5604         g_assert (klass);
5605
5606         mono_class_init (klass);
5607
5608         mono_class_get_nested_types (klass, &iter);
5609         g_assert (klass->nested_classes_inited);
5610
5611         mono_class_setup_vtable (klass);
5612
5613         /* 
5614          * Emit all the information which is required for creating vtables so
5615          * the runtime does not need to create the MonoMethod structures which
5616          * take up a lot of space.
5617          */
5618
5619         no_special_static = !mono_class_has_special_static_fields (klass);
5620
5621         /* Check whenever we have enough info to encode the vtable */
5622         cant_encode = FALSE;
5623         for (i = 0; i < klass->vtable_size; ++i) {
5624                 MonoMethod *cm = klass->vtable [i];
5625
5626                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5627                         cant_encode = TRUE;
5628         }
5629
5630         mono_class_has_finalizer (klass);
5631
5632         if (klass->generic_container || cant_encode) {
5633                 encode_value (-1, p, &p);
5634         } else {
5635                 encode_value (klass->vtable_size, p, &p);
5636                 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);
5637                 if (klass->has_cctor)
5638                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5639                 if (klass->has_finalize)
5640                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5641  
5642                 encode_value (klass->instance_size, p, &p);
5643                 encode_value (mono_class_data_size (klass), p, &p);
5644                 encode_value (klass->packing_size, p, &p);
5645                 encode_value (klass->min_align, p, &p);
5646
5647                 for (i = 0; i < klass->vtable_size; ++i) {
5648                         MonoMethod *cm = klass->vtable [i];
5649
5650                         if (cm)
5651                                 encode_method_ref (acfg, cm, p, &p);
5652                         else
5653                                 encode_value (0, p, &p);
5654                 }
5655         }
5656
5657         acfg->stats.class_info_size += p - buf;
5658
5659         g_assert (p - buf < buf_size);
5660         res = add_to_blob (acfg, buf, p - buf);
5661         g_free (buf);
5662
5663         return res;
5664 }
5665
5666 static char*
5667 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5668 {
5669         char *debug_sym = NULL;
5670         char *s;
5671
5672         switch (ji->type) {
5673         case MONO_PATCH_INFO_METHOD:
5674                 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5675                 break;
5676         case MONO_PATCH_INFO_INTERNAL_METHOD:
5677                 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5678                 break;
5679         case MONO_PATCH_INFO_CLASS_INIT:
5680                 s = mono_type_get_name (&ji->data.klass->byval_arg);
5681                 debug_sym = g_strdup_printf ("plt__class_init_%s", s);
5682                 g_free (s);
5683                 break;
5684         case MONO_PATCH_INFO_RGCTX_FETCH:
5685                 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5686                 break;
5687         case MONO_PATCH_INFO_ICALL_ADDR: {
5688                 char *s = get_debug_sym (ji->data.method, "", cache);
5689                 
5690                 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5691                 g_free (s);
5692                 break;
5693         }
5694         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5695                 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5696                 break;
5697         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5698                 debug_sym = g_strdup_printf ("plt__generic_class_init");
5699                 break;
5700         default:
5701                 break;
5702         }
5703
5704         return sanitize_symbol (acfg, debug_sym);
5705 }
5706
5707 /*
5708  * Calls made from AOTed code are routed through a table of jumps similar to the
5709  * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5710  * control to the AOT runtime through a trampoline.
5711  */
5712 static void
5713 emit_plt (MonoAotCompile *acfg)
5714 {
5715         char symbol [128];
5716         int i;
5717
5718         emit_line (acfg);
5719         sprintf (symbol, "plt");
5720
5721         emit_section_change (acfg, ".text", 0);
5722         emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5723         emit_label (acfg, symbol);
5724         emit_label (acfg, acfg->plt_symbol);
5725
5726         for (i = 0; i < acfg->plt_offset; ++i) {
5727                 char *debug_sym = NULL;
5728                 MonoPltEntry *plt_entry = NULL;
5729                 MonoJumpInfo *ji;
5730
5731                 if (i == 0)
5732                         /* 
5733                          * The first plt entry is unused.
5734                          */
5735                         continue;
5736
5737                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5738                 ji = plt_entry->ji;
5739
5740                 if (acfg->llvm) {
5741                         /*
5742                          * If the target is directly callable, alias the plt symbol to point to
5743                          * the method code.
5744                          * FIXME: Use this to simplify emit_and_reloc_code ().
5745                          * FIXME: Avoid the got slot.
5746                          * FIXME: Add support to the binary writer.
5747                          */
5748                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5749                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5750
5751                                 if (callee_cfg) {
5752                                         if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5753                                                 /* LLVM calls the PLT entries using bl, so emit a stub */
5754                                                 emit_set_thumb_mode (acfg);
5755                                                 fprintf (acfg->fp, "\n.thumb_func\n");
5756                                                 emit_label (acfg, plt_entry->llvm_symbol);
5757                                                 fprintf (acfg->fp, "bx pc\n");
5758                                                 fprintf (acfg->fp, "nop\n");
5759                                                 emit_set_arm_mode (acfg);
5760                                                 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5761                                         } else {
5762                                                 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5763                                         }
5764                                         continue;
5765                                 }
5766                         }
5767                 }
5768
5769                 debug_sym = plt_entry->debug_sym;
5770
5771                 if (acfg->thumb_mixed && !plt_entry->jit_used)
5772                         /* Emit only a thumb version */
5773                         continue;
5774
5775                 if (acfg->llvm && !acfg->thumb_mixed)
5776                         emit_label (acfg, plt_entry->llvm_symbol);
5777
5778                 if (debug_sym) {
5779                         if (acfg->need_no_dead_strip) {
5780                                 emit_unset_mode (acfg);
5781                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
5782                         }
5783                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5784                         emit_label (acfg, debug_sym);
5785                 }
5786
5787                 emit_label (acfg, plt_entry->symbol);
5788
5789                 arch_emit_plt_entry (acfg, i);
5790
5791                 if (debug_sym)
5792                         emit_symbol_size (acfg, debug_sym, ".");
5793         }
5794
5795         if (acfg->thumb_mixed) {
5796                 /* Make sure the ARM symbols don't alias the thumb ones */
5797                 emit_zero_bytes (acfg, 16);
5798
5799                 /* 
5800                  * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5801                  * code.
5802                  */
5803                 for (i = 0; i < acfg->plt_offset; ++i) {
5804                         char *debug_sym = NULL;
5805                         MonoPltEntry *plt_entry = NULL;
5806                         MonoJumpInfo *ji;
5807
5808                         if (i == 0)
5809                                 continue;
5810
5811                         plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5812                         ji = plt_entry->ji;
5813
5814                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5815                                 continue;
5816
5817                         /* Skip plt entries not actually called by LLVM code */
5818                         if (!plt_entry->llvm_used)
5819                                 continue;
5820
5821                         if (acfg->aot_opts.write_symbols) {
5822                                 if (plt_entry->debug_sym)
5823                                         debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5824                         }
5825
5826                         if (debug_sym) {
5827 #if defined(TARGET_MACH)
5828                                 fprintf (acfg->fp, "    .thumb_func %s\n", debug_sym);
5829                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
5830 #endif
5831                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5832                                 emit_label (acfg, debug_sym);
5833                         }
5834                         fprintf (acfg->fp, "\n.thumb_func\n");
5835
5836                         emit_label (acfg, plt_entry->llvm_symbol);
5837
5838                         arch_emit_llvm_plt_entry (acfg, i);
5839
5840                         if (debug_sym) {
5841                                 emit_symbol_size (acfg, debug_sym, ".");
5842                                 g_free (debug_sym);
5843                         }
5844                 }
5845         }
5846
5847         emit_symbol_size (acfg, acfg->plt_symbol, ".");
5848
5849         sprintf (symbol, "plt_end");
5850         emit_label (acfg, symbol);
5851 }
5852
5853 /*
5854  * emit_trampoline_full:
5855  *
5856  *   If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5857  * create_jit_info_for_trampoline ().
5858  */
5859 static G_GNUC_UNUSED void
5860 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5861 {
5862         char start_symbol [256];
5863         char end_symbol [256];
5864         char symbol [256];
5865         guint32 buf_size, info_offset;
5866         MonoJumpInfo *patch_info;
5867         guint8 *buf, *p;
5868         GPtrArray *patches;
5869         char *name;
5870         guint8 *code;
5871         guint32 code_size;
5872         MonoJumpInfo *ji;
5873         GSList *unwind_ops;
5874
5875         g_assert (info);
5876
5877         name = info->name;
5878         code = info->code;
5879         code_size = info->code_size;
5880         ji = info->ji;
5881         unwind_ops = info->unwind_ops;
5882
5883 #ifdef __native_client_codegen__
5884         mono_nacl_fix_patches (code, ji);
5885 #endif
5886
5887         /* Emit code */
5888
5889         sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5890
5891         emit_section_change (acfg, ".text", 0);
5892         emit_global (acfg, start_symbol, TRUE);
5893         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5894         emit_label (acfg, start_symbol);
5895
5896         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5897         emit_label (acfg, symbol);
5898
5899         /* 
5900          * The code should access everything through the GOT, so we pass
5901          * TRUE here.
5902          */
5903         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5904
5905         emit_symbol_size (acfg, start_symbol, ".");
5906
5907         if (emit_tinfo) {
5908                 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5909                 emit_label (acfg, end_symbol);
5910         }
5911
5912         /* Emit info */
5913
5914         /* Sort relocations */
5915         patches = g_ptr_array_new ();
5916         for (patch_info = ji; patch_info; patch_info = patch_info->next)
5917                 if (patch_info->type != MONO_PATCH_INFO_NONE)
5918                         g_ptr_array_add (patches, patch_info);
5919         g_ptr_array_sort (patches, compare_patches);
5920
5921         buf_size = patches->len * 128 + 128;
5922         buf = g_malloc (buf_size);
5923         p = buf;
5924
5925         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5926         g_assert (p - buf < buf_size);
5927
5928         sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5929
5930         info_offset = add_to_blob (acfg, buf, p - buf);
5931
5932         emit_section_change (acfg, RODATA_SECT, 0);
5933         emit_global (acfg, symbol, FALSE);
5934         emit_label (acfg, symbol);
5935
5936         emit_int32 (acfg, info_offset);
5937
5938         if (emit_tinfo) {
5939                 guint8 *encoded;
5940                 guint32 encoded_len;
5941                 guint32 uw_offset;
5942
5943                 /*
5944                  * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5945                  */
5946                 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5947                 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5948                 g_free (encoded);
5949
5950                 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5951                 emit_int32 (acfg, uw_offset);
5952         }
5953
5954         /* Emit debug info */
5955         if (unwind_ops) {
5956                 char symbol2 [256];
5957
5958                 sprintf (symbol, "%s", name);
5959                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5960
5961                 if (acfg->dwarf)
5962                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5963         }
5964 }
5965
5966 static G_GNUC_UNUSED void
5967 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5968 {
5969         emit_trampoline_full (acfg, got_offset, info, FALSE);
5970 }
5971
5972 static void
5973 emit_trampolines (MonoAotCompile *acfg)
5974 {
5975         char symbol [256];
5976         char end_symbol [256];
5977         int i, tramp_got_offset;
5978         MonoAotTrampoline ntype;
5979 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5980         int tramp_type;
5981 #endif
5982
5983         if (!acfg->aot_opts.full_aot)
5984                 return;
5985         
5986         g_assert (acfg->image->assembly);
5987
5988         /* Currently, we emit most trampolines into the mscorlib AOT image. */
5989         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5990 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5991                 MonoTrampInfo *info;
5992
5993                 /*
5994                  * Emit the generic trampolines.
5995                  *
5996                  * We could save some code by treating the generic trampolines as a wrapper
5997                  * method, but that approach has its own complexities, so we choose the simpler
5998                  * method.
5999                  */
6000                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6001                         /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6002 #ifdef DISABLE_REMOTING
6003                         if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6004                                 continue;
6005 #endif
6006 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6007                         if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6008                                 continue;
6009 #endif
6010                         mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6011                         emit_trampoline (acfg, acfg->got_offset, info);
6012                 }
6013
6014                 mono_arch_get_nullified_class_init_trampoline (&info);
6015                 emit_trampoline (acfg, acfg->got_offset, info);
6016 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6017                 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
6018                 emit_trampoline (acfg, acfg->got_offset, info);
6019                 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6020                 emit_trampoline (acfg, acfg->got_offset, info);
6021 #endif
6022
6023                 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6024                 emit_trampoline (acfg, acfg->got_offset, info);
6025
6026                 /* Emit the exception related code pieces */
6027                 mono_arch_get_restore_context (&info, TRUE);
6028                 emit_trampoline (acfg, acfg->got_offset, info);
6029                 mono_arch_get_call_filter (&info, TRUE);
6030                 emit_trampoline (acfg, acfg->got_offset, info);
6031                 mono_arch_get_throw_exception (&info, TRUE);
6032                 emit_trampoline (acfg, acfg->got_offset, info);
6033                 mono_arch_get_rethrow_exception (&info, TRUE);
6034                 emit_trampoline (acfg, acfg->got_offset, info);
6035                 mono_arch_get_throw_corlib_exception (&info, TRUE);
6036                 emit_trampoline (acfg, acfg->got_offset, info);
6037
6038 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6039                 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6040                 if (info) {
6041                         emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6042
6043                         /* Create a separate out trampoline for more information in stack traces */
6044                         info->name = g_strdup ("gsharedvt_out_trampoline");
6045                         emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6046                 }
6047 #endif
6048
6049 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6050                 {
6051                         GSList *l = mono_arch_get_trampolines (TRUE);
6052
6053                         while (l) {
6054                                 MonoTrampInfo *info = l->data;
6055
6056                                 emit_trampoline (acfg, acfg->got_offset, info);
6057                                 l = l->next;
6058                         }
6059                 }
6060 #endif
6061
6062                 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6063                         int offset;
6064
6065                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6066                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6067                         emit_trampoline (acfg, acfg->got_offset, info);
6068
6069                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6070                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6071                         emit_trampoline (acfg, acfg->got_offset, info);
6072                 }
6073
6074 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6075                 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6076                 emit_trampoline (acfg, acfg->got_offset, info);
6077 #endif
6078
6079                 {
6080                         GSList *l;
6081
6082                         /* delegate_invoke_impl trampolines */
6083                         l = mono_arch_get_delegate_invoke_impls ();
6084                         while (l) {
6085                                 MonoTrampInfo *info = l->data;
6086
6087                                 emit_trampoline (acfg, acfg->got_offset, info);
6088                                 l = l->next;
6089                         }
6090                 }
6091
6092 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6093
6094                 /* Emit trampolines which are numerous */
6095
6096                 /*
6097                  * These include the following:
6098                  * - specific trampolines
6099                  * - static rgctx invoke trampolines
6100                  * - imt thunks
6101                  * These trampolines have the same code, they are parameterized by GOT 
6102                  * slots. 
6103                  * They are defined in this file, in the arch_... routines instead of
6104                  * in tramp-<ARCH>.c, since it is easier to do it this way.
6105                  */
6106
6107                 /*
6108                  * When running in aot-only mode, we can't create specific trampolines at 
6109                  * runtime, so we create a few, and save them in the AOT file. 
6110                  * Normal trampolines embed their argument as a literal inside the 
6111                  * trampoline code, we can't do that here, so instead we embed an offset
6112                  * which needs to be added to the trampoline address to get the address of
6113                  * the GOT slot which contains the argument value.
6114                  * The generated trampolines jump to the generic trampolines using another
6115                  * GOT slot, which will be setup by the AOT loader to point to the 
6116                  * generic trampoline code of the given type.
6117                  */
6118
6119                 /*
6120                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6121                  * each class).
6122                  */
6123
6124                 emit_section_change (acfg, ".text", 0);
6125
6126                 tramp_got_offset = acfg->got_offset;
6127
6128                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6129                         switch (ntype) {
6130                         case MONO_AOT_TRAMP_SPECIFIC:
6131                                 sprintf (symbol, "specific_trampolines");
6132                                 break;
6133                         case MONO_AOT_TRAMP_STATIC_RGCTX:
6134                                 sprintf (symbol, "static_rgctx_trampolines");
6135                                 break;
6136                         case MONO_AOT_TRAMP_IMT_THUNK:
6137                                 sprintf (symbol, "imt_thunks");
6138                                 break;
6139                         case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6140                                 sprintf (symbol, "gsharedvt_arg_trampolines");
6141                                 break;
6142                         default:
6143                                 g_assert_not_reached ();
6144                         }
6145
6146                         sprintf (end_symbol, "%s_e", symbol);
6147
6148                         if (acfg->aot_opts.write_symbols)
6149                                 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6150
6151                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6152                         emit_label (acfg, symbol);
6153
6154                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6155
6156                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6157                                 int tramp_size = 0;
6158
6159                                 switch (ntype) {
6160                                 case MONO_AOT_TRAMP_SPECIFIC:
6161                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6162                                         tramp_got_offset += 2;
6163                                 break;
6164                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
6165                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
6166                                         tramp_got_offset += 2;
6167                                         break;
6168                                 case MONO_AOT_TRAMP_IMT_THUNK:
6169                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6170                                         tramp_got_offset += 1;
6171                                         break;
6172                                 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6173                                         arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);                               
6174                                         tramp_got_offset += 2;
6175                                         break;
6176                                 default:
6177                                         g_assert_not_reached ();
6178                                 }
6179 #ifdef __native_client_codegen__
6180                                 /* align to avoid 32-byte boundary crossings */
6181                                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6182 #endif
6183
6184                                 if (!acfg->trampoline_size [ntype]) {
6185                                         g_assert (tramp_size);
6186                                         acfg->trampoline_size [ntype] = tramp_size;
6187                                 }
6188                         }
6189
6190                         emit_label (acfg, end_symbol);
6191                         emit_int32 (acfg, 0);
6192                 }
6193
6194                 arch_emit_specific_trampoline_pages (acfg);
6195
6196                 /* Reserve some entries at the end of the GOT for our use */
6197                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6198         }
6199
6200         acfg->got_offset += acfg->num_trampoline_got_entries;
6201 }
6202
6203 static gboolean
6204 str_begins_with (const char *str1, const char *str2)
6205 {
6206         int len = strlen (str2);
6207         return strncmp (str1, str2, len) == 0;
6208 }
6209
6210 void*
6211 mono_aot_readonly_field_override (MonoClassField *field)
6212 {
6213         ReadOnlyValue *rdv;
6214         for (rdv = readonly_values; rdv; rdv = rdv->next) {
6215                 char *p = rdv->name;
6216                 int len;
6217                 len = strlen (field->parent->name_space);
6218                 if (strncmp (p, field->parent->name_space, len))
6219                         continue;
6220                 p += len;
6221                 if (*p++ != '.')
6222                         continue;
6223                 len = strlen (field->parent->name);
6224                 if (strncmp (p, field->parent->name, len))
6225                         continue;
6226                 p += len;
6227                 if (*p++ != '.')
6228                         continue;
6229                 if (strcmp (p, field->name))
6230                         continue;
6231                 switch (rdv->type) {
6232                 case MONO_TYPE_I1:
6233                         return &rdv->value.i1;
6234                 case MONO_TYPE_I2:
6235                         return &rdv->value.i2;
6236                 case MONO_TYPE_I4:
6237                         return &rdv->value.i4;
6238                 default:
6239                         break;
6240                 }
6241         }
6242         return NULL;
6243 }
6244
6245 static void
6246 add_readonly_value (MonoAotOptions *opts, const char *val)
6247 {
6248         ReadOnlyValue *rdv;
6249         const char *fval;
6250         const char *tval;
6251         /* the format of val is:
6252          * namespace.typename.fieldname=type/value
6253          * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6254          */
6255         fval = strrchr (val, '/');
6256         if (!fval) {
6257                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6258                 exit (1);
6259         }
6260         tval = strrchr (val, '=');
6261         if (!tval) {
6262                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6263                 exit (1);
6264         }
6265         rdv = g_new0 (ReadOnlyValue, 1);
6266         rdv->name = g_malloc0 (tval - val + 1);
6267         memcpy (rdv->name, val, tval - val);
6268         tval++;
6269         fval++;
6270         if (strncmp (tval, "i1", 2) == 0) {
6271                 rdv->value.i1 = atoi (fval);
6272                 rdv->type = MONO_TYPE_I1;
6273         } else if (strncmp (tval, "i2", 2) == 0) {
6274                 rdv->value.i2 = atoi (fval);
6275                 rdv->type = MONO_TYPE_I2;
6276         } else if (strncmp (tval, "i4", 2) == 0) {
6277                 rdv->value.i4 = atoi (fval);
6278                 rdv->type = MONO_TYPE_I4;
6279         } else {
6280                 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6281                 exit (1);
6282         }
6283         rdv->next = readonly_values;
6284         readonly_values = rdv;
6285 }
6286
6287 static void
6288 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6289 {
6290         gchar **args, **ptr;
6291
6292         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6293         for (ptr = args; ptr && *ptr; ptr ++) {
6294                 const char *arg = *ptr;
6295
6296                 if (str_begins_with (arg, "outfile=")) {
6297                         opts->outfile = g_strdup (arg + strlen ("outfile="));
6298                 } else if (str_begins_with (arg, "save-temps")) {
6299                         opts->save_temps = TRUE;
6300                 } else if (str_begins_with (arg, "keep-temps")) {
6301                         opts->save_temps = TRUE;
6302                 } else if (str_begins_with (arg, "write-symbols")) {
6303                         opts->write_symbols = TRUE;
6304                 } else if (str_begins_with (arg, "no-write-symbols")) {
6305                         opts->write_symbols = FALSE;
6306                 } else if (str_begins_with (arg, "metadata-only")) {
6307                         opts->metadata_only = TRUE;
6308                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6309                         opts->bind_to_runtime_version = TRUE;
6310                 } else if (str_begins_with (arg, "full")) {
6311                         opts->full_aot = TRUE;
6312                 } else if (str_begins_with (arg, "threads=")) {
6313                         opts->nthreads = atoi (arg + strlen ("threads="));
6314                 } else if (str_begins_with (arg, "static")) {
6315                         opts->static_link = TRUE;
6316                         opts->no_dlsym = TRUE;
6317                 } else if (str_begins_with (arg, "asmonly")) {
6318                         opts->asm_only = TRUE;
6319                 } else if (str_begins_with (arg, "asmwriter")) {
6320                         opts->asm_writer = TRUE;
6321                 } else if (str_begins_with (arg, "nodebug")) {
6322                         opts->nodebug = TRUE;
6323                 } else if (str_begins_with (arg, "dwarfdebug")) {
6324                         opts->dwarf_debug = TRUE;
6325                 } else if (str_begins_with (arg, "nopagetrampolines")) {
6326                         opts->use_trampolines_page = FALSE;
6327                 } else if (str_begins_with (arg, "ntrampolines=")) {
6328                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6329                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6330                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6331                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6332                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6333                 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6334                         opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6335                 } else if (str_begins_with (arg, "autoreg")) {
6336                         opts->autoreg = TRUE;
6337                 } else if (str_begins_with (arg, "tool-prefix=")) {
6338                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6339                 } else if (str_begins_with (arg, "soft-debug")) {
6340                         opts->soft_debug = TRUE;
6341                 } else if (str_begins_with (arg, "direct-pinvoke")) {
6342                         opts->direct_pinvoke = TRUE;
6343                 } else if (str_begins_with (arg, "direct-icalls")) {
6344                         opts->direct_icalls = TRUE;
6345 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6346                 } else if (str_begins_with (arg, "iphone-abi")) {
6347                         // older full-aot users did depend on this.
6348 #endif
6349                 } else if (str_begins_with (arg, "no-direct-calls")) {
6350                         opts->no_direct_calls = TRUE;
6351                 } else if (str_begins_with (arg, "print-skipped")) {
6352                         opts->print_skipped_methods = TRUE;
6353                 } else if (str_begins_with (arg, "stats")) {
6354                         opts->stats = TRUE;
6355                 } else if (str_begins_with (arg, "no-instances")) {
6356                         opts->no_instances = TRUE;
6357                 } else if (str_begins_with (arg, "log-generics")) {
6358                         opts->log_generics = TRUE;
6359                 } else if (str_begins_with (arg, "log-instances=")) {
6360                         opts->log_instances = TRUE;
6361                         opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6362                 } else if (str_begins_with (arg, "log-instances")) {
6363                         opts->log_instances = TRUE;
6364                 } else if (str_begins_with (arg, "mtriple=")) {
6365                         opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6366                 } else if (str_begins_with (arg, "llvm-path=")) {
6367                         opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6368                 } else if (str_begins_with (arg, "readonly-value=")) {
6369                         add_readonly_value (opts, arg + strlen ("readonly-value="));
6370                 } else if (str_begins_with (arg, "info")) {
6371                         printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6372                         exit (0);
6373                 } else if (str_begins_with (arg, "gc-maps")) {
6374                         mini_gc_enable_gc_maps_for_aot ();
6375                 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6376                         printf ("Supported options for --aot:\n");
6377                         printf ("    outfile=\n");
6378                         printf ("    save-temps\n");
6379                         printf ("    keep-temps\n");
6380                         printf ("    write-symbols\n");
6381                         printf ("    metadata-only\n");
6382                         printf ("    bind-to-runtime-version\n");
6383                         printf ("    full\n");
6384                         printf ("    threads=\n");
6385                         printf ("    static\n");
6386                         printf ("    asmonly\n");
6387                         printf ("    asmwriter\n");
6388                         printf ("    nodebug\n");
6389                         printf ("    dwarfdebug\n");
6390                         printf ("    ntrampolines=\n");
6391                         printf ("    nrgctx-trampolines=\n");
6392                         printf ("    nimt-trampolines=\n");
6393                         printf ("    ngsharedvt-trampolines=\n");
6394                         printf ("    autoreg\n");
6395                         printf ("    tool-prefix=\n");
6396                         printf ("    readonly-value=\n");
6397                         printf ("    soft-debug\n");
6398                         printf ("    gc-maps\n");
6399                         printf ("    print-skipped\n");
6400                         printf ("    no-instances\n");
6401                         printf ("    stats\n");
6402                         printf ("    info\n");
6403                         printf ("    help/?\n");
6404                         exit (0);
6405                 } else {
6406                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6407                         exit (1);
6408                 }
6409         }
6410
6411         if (opts->use_trampolines_page) {
6412                 opts->ntrampolines = 0;
6413                 opts->nrgctx_trampolines = 0;
6414                 opts->nimt_trampolines = 0;
6415                 opts->ngsharedvt_arg_trampolines = 0;
6416         }
6417         g_strfreev (args);
6418 }
6419
6420 static void
6421 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6422 {
6423         MonoMethod *method = (MonoMethod*)key;
6424         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6425         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6426         MonoAotCompile *acfg = user_data;
6427
6428         new_ji->image = ji->image;
6429         new_ji->token = ji->token;
6430         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6431 }
6432
6433 static gboolean
6434 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6435 {
6436         if (klass->type_token)
6437                 return TRUE;
6438         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6439                 return TRUE;
6440         if (klass->rank)
6441                 return can_encode_class (acfg, klass->element_class);
6442         return FALSE;
6443 }
6444
6445 static gboolean
6446 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6447 {
6448                 if (method->wrapper_type) {
6449                         switch (method->wrapper_type) {
6450                         case MONO_WRAPPER_NONE:
6451                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6452                         case MONO_WRAPPER_XDOMAIN_INVOKE:
6453                         case MONO_WRAPPER_STFLD:
6454                         case MONO_WRAPPER_LDFLD:
6455                         case MONO_WRAPPER_LDFLDA:
6456                         case MONO_WRAPPER_LDFLD_REMOTE:
6457                         case MONO_WRAPPER_STFLD_REMOTE:
6458                         case MONO_WRAPPER_STELEMREF:
6459                         case MONO_WRAPPER_ISINST:
6460                         case MONO_WRAPPER_PROXY_ISINST:
6461                         case MONO_WRAPPER_ALLOC:
6462                         case MONO_WRAPPER_REMOTING_INVOKE:
6463                         case MONO_WRAPPER_UNKNOWN:
6464                         case MONO_WRAPPER_WRITE_BARRIER:
6465                         case MONO_WRAPPER_DELEGATE_INVOKE:
6466                         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6467                         case MONO_WRAPPER_DELEGATE_END_INVOKE:
6468                         case MONO_WRAPPER_SYNCHRONIZED:
6469                                 break;
6470                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
6471                         case MONO_WRAPPER_CASTCLASS: {
6472                                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6473
6474                                 if (info)
6475                                         return TRUE;
6476                                 else
6477                                         return FALSE;
6478                                 break;
6479                         }
6480                         default:
6481                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6482                                 return FALSE;
6483                         }
6484                 } else {
6485                         if (!method->token) {
6486                                 /* The method is part of a constructed type like Int[,].Set (). */
6487                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6488                                         if (method->klass->rank)
6489                                                 return TRUE;
6490                                         return FALSE;
6491                                 }
6492                         }
6493                 }
6494                 return TRUE;
6495 }
6496
6497 static gboolean
6498 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6499 {
6500         switch (patch_info->type) {
6501         case MONO_PATCH_INFO_METHOD:
6502         case MONO_PATCH_INFO_METHODCONST:
6503         case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6504                 MonoMethod *method = patch_info->data.method;
6505
6506                 return can_encode_method (acfg, method);
6507         }
6508         case MONO_PATCH_INFO_VTABLE:
6509         case MONO_PATCH_INFO_CLASS_INIT:
6510         case MONO_PATCH_INFO_CLASS:
6511         case MONO_PATCH_INFO_IID:
6512         case MONO_PATCH_INFO_ADJUSTED_IID:
6513                 if (!can_encode_class (acfg, patch_info->data.klass)) {
6514                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6515                         return FALSE;
6516                 }
6517                 break;
6518         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6519                 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6520                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6521                         return FALSE;
6522                 }
6523                 break;
6524         }
6525         case MONO_PATCH_INFO_RGCTX_FETCH: {
6526                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6527
6528                 if (!can_encode_method (acfg, entry->method))
6529                         return FALSE;
6530                 if (!can_encode_patch (acfg, entry->data))
6531                         return FALSE;
6532                 break;
6533         }
6534         default:
6535                 break;
6536         }
6537
6538         return TRUE;
6539 }
6540
6541 /*
6542  * compile_method:
6543  *
6544  *   AOT compile a given method.
6545  * This function might be called by multiple threads, so it must be thread-safe.
6546  */
6547 static void
6548 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6549 {
6550         MonoCompile *cfg;
6551         MonoJumpInfo *patch_info;
6552         gboolean skip;
6553         int index, depth;
6554         MonoMethod *wrapped;
6555
6556         if (acfg->aot_opts.metadata_only)
6557                 return;
6558
6559         mono_acfg_lock (acfg);
6560         index = get_method_index (acfg, method);
6561         mono_acfg_unlock (acfg);
6562
6563         /* fixme: maybe we can also precompile wrapper methods */
6564         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6565                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6566                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6567                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6568                 return;
6569         }
6570
6571         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6572                 return;
6573
6574         wrapped = mono_marshal_method_from_wrapper (method);
6575         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6576                 // FIXME: The wrapper should be generic too, but it is not
6577                 return;
6578
6579         if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6580                 return;
6581
6582         InterlockedIncrement (&acfg->stats.mcount);
6583
6584 #if 0
6585         if (method->is_generic || method->klass->generic_container) {
6586                 InterlockedIncrement (&acfg->stats.genericcount);
6587                 return;
6588         }
6589 #endif
6590
6591         //acfg->aot_opts.print_skipped_methods = TRUE;
6592
6593         /*
6594          * Since these methods are the only ones which are compiled with
6595          * AOT support, and they are not used by runtime startup/shutdown code,
6596          * the runtime will not see AOT methods during AOT compilation,so it
6597          * does not need to support them by creating a fake GOT etc.
6598          */
6599         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);
6600         mono_loader_clear_error ();
6601
6602         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6603                 if (acfg->aot_opts.print_skipped_methods)
6604                         printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6605                 InterlockedIncrement (&acfg->stats.genericcount);
6606                 return;
6607         }
6608         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6609                 if (acfg->aot_opts.print_skipped_methods)
6610                         printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6611                 /* Let the exception happen at runtime */
6612                 return;
6613         }
6614
6615         if (cfg->disable_aot) {
6616                 if (acfg->aot_opts.print_skipped_methods)
6617                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6618                 InterlockedIncrement (&acfg->stats.ocount);
6619                 mono_destroy_compile (cfg);
6620                 return;
6621         }
6622         cfg->method_index = index;
6623
6624         /* Nullify patches which need no aot processing */
6625         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6626                 switch (patch_info->type) {
6627                 case MONO_PATCH_INFO_LABEL:
6628                 case MONO_PATCH_INFO_BB:
6629                         patch_info->type = MONO_PATCH_INFO_NONE;
6630                         break;
6631                 default:
6632                         break;
6633                 }
6634         }
6635
6636         /* Collect method->token associations from the cfg */
6637         mono_acfg_lock (acfg);
6638         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6639         mono_acfg_unlock (acfg);
6640
6641         /*
6642          * Check for absolute addresses.
6643          */
6644         skip = FALSE;
6645         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6646                 switch (patch_info->type) {
6647                 case MONO_PATCH_INFO_ABS:
6648                         /* unable to handle this */
6649                         skip = TRUE;    
6650                         break;
6651                 default:
6652                         break;
6653                 }
6654         }
6655
6656         if (skip) {
6657                 if (acfg->aot_opts.print_skipped_methods)
6658                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6659                 InterlockedIncrement (&acfg->stats.abscount);
6660                 mono_destroy_compile (cfg);
6661                 return;
6662         }
6663
6664         /* Lock for the rest of the code */
6665         mono_acfg_lock (acfg);
6666
6667         /*
6668          * Check for methods/klasses we can't encode.
6669          */
6670         skip = FALSE;
6671         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6672                 if (!can_encode_patch (acfg, patch_info))
6673                         skip = TRUE;
6674         }
6675
6676         if (skip) {
6677                 if (acfg->aot_opts.print_skipped_methods)
6678                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6679                 acfg->stats.ocount++;
6680                 mono_destroy_compile (cfg);
6681                 mono_acfg_unlock (acfg);
6682                 return;
6683         }
6684
6685         if (method->is_inflated && acfg->aot_opts.log_instances) {
6686                 if (acfg->instances_logfile)
6687                         fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6688                 else
6689                         printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6690         }
6691
6692         /* Adds generic instances referenced by this method */
6693         /* 
6694          * The depth is used to avoid infinite loops when generic virtual recursion is 
6695          * encountered.
6696          */
6697         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6698         if (!acfg->aot_opts.no_instances && depth < 32) {
6699                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6700                         switch (patch_info->type) {
6701                         case MONO_PATCH_INFO_METHOD: {
6702                                 MonoMethod *m = patch_info->data.method;
6703                                 if (m->is_inflated) {
6704                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
6705                                                   mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6706                                                 !method_has_type_vars (m)) {
6707                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6708                                                         if (acfg->aot_opts.full_aot)
6709                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6710                                                 } else {
6711                                                         add_extra_method_with_depth (acfg, m, depth + 1);
6712                                                         add_types_from_method_header (acfg, m);
6713                                                 }
6714                                         }
6715                                         add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6716                                 }
6717                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6718                                         add_extra_method_with_depth (acfg, m, depth + 1);
6719                                 break;
6720                         }
6721                         case MONO_PATCH_INFO_VTABLE: {
6722                                 MonoClass *klass = patch_info->data.klass;
6723
6724                                 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6725                                         add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6726                                 break;
6727                         }
6728                         case MONO_PATCH_INFO_SFLDA: {
6729                                 MonoClass *klass = patch_info->data.field->parent;
6730
6731                                 /* The .cctor needs to run at runtime. */
6732                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6733                                         add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6734                                 break;
6735                         }
6736                         default:
6737                                 break;
6738                         }
6739                 }
6740         }
6741
6742         /* Determine whenever the method has GOT slots */
6743         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6744                 switch (patch_info->type) {
6745                 case MONO_PATCH_INFO_GOT_OFFSET:
6746                 case MONO_PATCH_INFO_NONE:
6747                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6748                         break;
6749                 case MONO_PATCH_INFO_IMAGE:
6750                         /* The assembly is stored in GOT slot 0 */
6751                         if (patch_info->data.image != acfg->image)
6752                                 cfg->has_got_slots = TRUE;
6753                         break;
6754                 default:
6755                         if (!is_plt_patch (patch_info))
6756                                 cfg->has_got_slots = TRUE;
6757                         break;
6758                 }
6759         }
6760
6761         if (!cfg->has_got_slots)
6762                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6763
6764         /* 
6765          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6766          */
6767         /* Make a copy of the patch info which is in the mempool */
6768         {
6769                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6770
6771                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6772                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6773
6774                         if (!patches)
6775                                 patches = new_patch_info;
6776                         else
6777                                 patches_end->next = new_patch_info;
6778                         patches_end = new_patch_info;
6779                 }
6780                 cfg->patch_info = patches;
6781         }
6782         /* Make a copy of the unwind info */
6783         {
6784                 GSList *l, *unwind_ops;
6785                 MonoUnwindOp *op;
6786
6787                 unwind_ops = NULL;
6788                 for (l = cfg->unwind_ops; l; l = l->next) {
6789                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6790                         memcpy (op, l->data, sizeof (MonoUnwindOp));
6791                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6792                 }
6793                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6794         }
6795         /* Make a copy of the argument/local info */
6796         {
6797                 MonoInst **args, **locals;
6798                 MonoMethodSignature *sig;
6799                 MonoMethodHeader *header;
6800                 int i;
6801                 
6802                 sig = mono_method_signature (method);
6803                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6804                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6805                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6806                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6807                 }
6808                 cfg->args = args;
6809
6810                 header = mono_method_get_header (method);
6811                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6812                 for (i = 0; i < header->num_locals; ++i) {
6813                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6814                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6815                 }
6816                 cfg->locals = locals;
6817         }
6818
6819         /* Free some fields used by cfg to conserve memory */
6820         mono_mempool_destroy (cfg->mempool);
6821         cfg->mempool = NULL;
6822         g_free (cfg->varinfo);
6823         cfg->varinfo = NULL;
6824         g_free (cfg->vars);
6825         cfg->vars = NULL;
6826         if (cfg->rs) {
6827                 mono_regstate_free (cfg->rs);
6828                 cfg->rs = NULL;
6829         }
6830
6831         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
6832
6833         while (index >= acfg->cfgs_size) {
6834                 MonoCompile **new_cfgs;
6835                 int new_size;
6836
6837                 new_size = acfg->cfgs_size * 2;
6838                 new_cfgs = g_new0 (MonoCompile*, new_size);
6839                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6840                 g_free (acfg->cfgs);
6841                 acfg->cfgs = new_cfgs;
6842                 acfg->cfgs_size = new_size;
6843         }
6844         acfg->cfgs [index] = cfg;
6845
6846         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6847
6848         /*
6849         if (cfg->orig_method->wrapper_type)
6850                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6851         */
6852
6853         mono_acfg_unlock (acfg);
6854
6855         InterlockedIncrement (&acfg->stats.ccount);
6856 }
6857  
6858 static void
6859 compile_thread_main (gpointer *user_data)
6860 {
6861         MonoDomain *domain = user_data [0];
6862         MonoAotCompile *acfg = user_data [1];
6863         GPtrArray *methods = user_data [2];
6864         int i;
6865
6866         mono_thread_attach (domain);
6867
6868         for (i = 0; i < methods->len; ++i)
6869                 compile_method (acfg, g_ptr_array_index (methods, i));
6870 }
6871
6872 static void
6873 load_profile_files (MonoAotCompile *acfg)
6874 {
6875         FILE *infile;
6876         char *tmp;
6877         int file_index, res, method_index, i;
6878         char ver [256];
6879         guint32 token;
6880         GList *unordered, *l;
6881         gboolean found;
6882
6883         file_index = 0;
6884         while (TRUE) {
6885                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6886
6887                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6888                         g_free (tmp);
6889                         break;
6890                 }
6891
6892                 infile = fopen (tmp, "r");
6893                 g_assert (infile);
6894
6895                 printf ("Using profile data file '%s'\n", tmp);
6896                 g_free (tmp);
6897
6898                 file_index ++;
6899
6900                 res = fscanf (infile, "%32s\n", ver);
6901                 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6902                         printf ("Profile file has wrong version or invalid.\n");
6903                         fclose (infile);
6904                         continue;
6905                 }
6906
6907                 while (TRUE) {
6908                         char name [1024];
6909                         MonoMethodDesc *desc;
6910                         MonoMethod *method;
6911
6912                         if (fgets (name, 1023, infile) == NULL)
6913                                 break;
6914
6915                         /* Kill the newline */
6916                         if (strlen (name) > 0)
6917                                 name [strlen (name) - 1] = '\0';
6918
6919                         desc = mono_method_desc_new (name, TRUE);
6920
6921                         method = mono_method_desc_search_in_image (desc, acfg->image);
6922
6923                         if (method && mono_method_get_token (method)) {
6924                                 token = mono_method_get_token (method);
6925                                 method_index = mono_metadata_token_index (token) - 1;
6926
6927                                 found = FALSE;
6928                                 for (i = 0; i < acfg->method_order->len; ++i) {
6929                                         if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6930                                                 found = TRUE;
6931                                                 break;
6932                                         }
6933                                 }
6934                                 if (!found)
6935                                         g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6936                         } else {
6937                                 //printf ("No method found matching '%s'.\n", name);
6938                         }
6939                 }
6940                 fclose (infile);
6941         }
6942
6943         /* Add missing methods */
6944         unordered = NULL;
6945         for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6946                 found = FALSE;
6947                 for (i = 0; i < acfg->method_order->len; ++i) {
6948                         if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6949                                 found = TRUE;
6950                                 break;
6951                         }
6952                 }
6953                 if (!found)
6954                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6955         }
6956         unordered = g_list_reverse (unordered);
6957         for (l = unordered; l; l = l->next)
6958                 g_ptr_array_add (acfg->method_order, l->data);
6959 }
6960  
6961 /* Used by the LLVM backend */
6962 guint32
6963 mono_aot_get_got_offset (MonoJumpInfo *ji)
6964 {
6965         return get_got_offset (llvm_acfg, ji);
6966 }
6967
6968 char*
6969 mono_aot_get_method_name (MonoCompile *cfg)
6970 {
6971         if (llvm_acfg->aot_opts.static_link)
6972                 /* Include the assembly name too to avoid duplicate symbol errors */
6973                 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6974         else
6975                 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6976 }
6977
6978 char*
6979 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6980 {
6981         MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6982         MonoPltEntry *plt_entry;
6983
6984         ji->type = type;
6985         ji->data.target = data;
6986
6987         if (!can_encode_patch (llvm_acfg, ji))
6988                 return NULL;
6989
6990         plt_entry = get_plt_entry (llvm_acfg, ji);
6991         plt_entry->llvm_used = TRUE;
6992
6993 #if defined(TARGET_MACH)
6994         return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6995 #else
6996         return g_strdup_printf (plt_entry->llvm_symbol);
6997 #endif
6998 }
6999
7000 int
7001 mono_aot_get_method_index (MonoMethod *method)
7002 {
7003         g_assert (llvm_acfg);
7004         return get_method_index (llvm_acfg, method);
7005 }
7006
7007 MonoJumpInfo*
7008 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7009 {
7010         MonoJumpInfo *res;
7011
7012         mono_acfg_lock (llvm_acfg);
7013         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7014         mono_acfg_unlock (llvm_acfg);
7015
7016         return res;
7017 }
7018
7019 #ifdef ENABLE_LLVM
7020
7021 /*
7022  * emit_llvm_file:
7023  *
7024  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7025  * tools.
7026  */
7027 static void
7028 emit_llvm_file (MonoAotCompile *acfg)
7029 {
7030         char *command, *opts, *tempbc;
7031         int i;
7032         MonoJumpInfo *patch_info;
7033
7034         /*
7035          * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
7036          * to it.
7037          */
7038
7039         /* Compute the final size of the got */
7040         for (i = 0; i < acfg->nmethods; ++i) {
7041                 if (acfg->cfgs [i]) {
7042                         for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
7043                                 if (patch_info->type != MONO_PATCH_INFO_NONE) {
7044                                         if (!is_plt_patch (patch_info))
7045                                                 get_got_offset (acfg, patch_info);
7046                                         else
7047                                                 get_plt_entry (acfg, patch_info);
7048                                 }
7049                         }
7050                 }
7051         }
7052
7053         acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
7054
7055         if (acfg->aot_opts.full_aot) {
7056                 int ntype;
7057
7058                 /* 
7059                  * Need to add the got entries used by the trampolines.
7060                  * This is only a conservative approximation.
7061                  */
7062                 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
7063                         /* For the generic + rgctx trampolines */
7064                         acfg->final_got_size += 400;
7065                         /* For the specific trampolines */
7066                         for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
7067                                 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
7068                 }
7069         }
7070
7071
7072         tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7073         mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
7074         g_free (tempbc);
7075
7076         /*
7077          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7078          * a lot of time, and doesn't seem to save much space.
7079          * The following optimizations cannot be enabled:
7080          * - 'tailcallelim'
7081          * - 'jump-threading' changes our blockaddress references to int constants.
7082          * - 'basiccg' fails because it contains:
7083          * if (CS && !isa<IntrinsicInst>(II)) {
7084          * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7085          * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7086          * The opt list below was produced by taking the output of:
7087          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7088          * then removing tailcallelim + the global opts.
7089          * strip-dead-prototypes deletes unused intrinsics definitions.
7090          */
7091         opts = g_strdup ("-instcombine -simplifycfg");
7092         //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");
7093         /* The dse pass is disabled because of #13734 and #17616 */
7094         /*
7095          * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7096          * // If we have no DataLayout information around, then the size of the store
7097          *  // is inferrable from the pointee type.  If they are the same type, then
7098          * // we know that the store is safe.
7099          * if (AA.getDataLayout() == 0 &&
7100          * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7101          * return OverwriteComplete;
7102          * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7103          */
7104         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");
7105 #if 1
7106         command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7107         printf ("Executing opt: %s\n", command);
7108         if (system (command) != 0) {
7109                 exit (1);
7110         }
7111 #endif
7112         g_free (opts);
7113
7114         if (!acfg->llc_args)
7115                 acfg->llc_args = g_string_new ("");
7116
7117         /* Verbose asm slows down llc greatly */
7118         g_string_append (acfg->llc_args, " -asm-verbose=false");
7119
7120         if (acfg->aot_opts.mtriple)
7121                 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7122
7123 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7124         /* ios requires PIC code now */
7125         g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7126 #else
7127         if (llvm_acfg->aot_opts.static_link)
7128                 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7129         else
7130                 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7131 #endif
7132         unlink (acfg->tmpfname);
7133
7134         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);
7135
7136         printf ("Executing llc: %s\n", command);
7137
7138         if (system (command) != 0) {
7139                 exit (1);
7140         }
7141 }
7142 #endif
7143
7144 static void
7145 emit_code (MonoAotCompile *acfg)
7146 {
7147         int oindex, i, prev_index;
7148         char symbol [256];
7149
7150 #if defined(TARGET_POWERPC64)
7151         sprintf (symbol, ".Lgot_addr");
7152         emit_section_change (acfg, ".text", 0);
7153         emit_alignment (acfg, 8);
7154         emit_label (acfg, symbol);
7155         emit_pointer (acfg, acfg->got_symbol);
7156 #endif
7157
7158         /* 
7159          * This global symbol is used to compute the address of each method using the
7160          * code_offsets array. It is also used to compute the memory ranges occupied by
7161          * AOT code, so it must be equal to the address of the first emitted method.
7162          */
7163         emit_section_change (acfg, ".text", 0);
7164         emit_alignment (acfg, 8);
7165         if (acfg->llvm) {
7166                 for (i = 0; i < acfg->nmethods; ++i) {
7167                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7168                                 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7169                                 break;
7170                         }
7171                 }
7172         }
7173         if (!acfg->methods_symbol) {
7174                 sprintf (symbol, "methods");
7175                 emit_label (acfg, symbol);
7176                 acfg->methods_symbol = g_strdup (symbol);
7177         }
7178
7179         /* 
7180          * Emit some padding so the local symbol for the first method doesn't have the
7181          * same address as 'methods'.
7182          */
7183 #if defined(__default_codegen__)
7184         emit_zero_bytes (acfg, 16);
7185 #elif defined(__native_client_codegen__)
7186         {
7187                 const int kPaddingSize = 16;
7188                 guint8 pad_buffer[kPaddingSize];
7189                 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7190                 emit_bytes (acfg, pad_buffer, kPaddingSize);
7191         }
7192 #endif
7193
7194         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7195                 MonoCompile *cfg;
7196                 MonoMethod *method;
7197
7198                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7199
7200                 cfg = acfg->cfgs [i];
7201
7202                 if (!cfg)
7203                         continue;
7204
7205                 method = cfg->orig_method;
7206
7207                 /* Emit unbox trampoline */
7208                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7209                         sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7210
7211                         emit_section_change (acfg, ".text", 0);
7212 #ifdef __native_client_codegen__
7213                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7214 #endif
7215
7216                         if (acfg->thumb_mixed && cfg->compile_llvm) {
7217                                 emit_set_thumb_mode (acfg);
7218                                 fprintf (acfg->fp, "\n.thumb_func\n");
7219                         }
7220
7221                         emit_label (acfg, symbol);
7222
7223                         arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7224
7225                         if (acfg->thumb_mixed && cfg->compile_llvm) {
7226                                 emit_set_arm_mode (acfg);
7227                         }
7228                 }
7229
7230                 if (cfg->compile_llvm)
7231                         acfg->stats.llvm_count ++;
7232                 else
7233                         emit_method_code (acfg, cfg);
7234         }
7235
7236         sprintf (symbol, "methods_end");
7237         emit_section_change (acfg, ".text", 0);
7238         emit_alignment (acfg, 8);
7239         emit_label (acfg, symbol);
7240         /* To distinguish it from the next symbol */
7241         emit_int32 (acfg, 0);
7242
7243         /* 
7244          * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7245          * from optimizing them away, since it doesn't see that code_offsets references them.
7246          * JITted methods don't need this since they are referenced using assembler local
7247          * symbols.
7248          * FIXME: This is why write-symbols doesn't work on OSX ?
7249          */
7250         if (acfg->llvm && acfg->need_no_dead_strip) {
7251                 fprintf (acfg->fp, "\n");
7252                 for (i = 0; i < acfg->nmethods; ++i) {
7253                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7254                                 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7255                 }
7256         }
7257
7258         if (acfg->direct_method_addresses) {
7259                 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7260
7261                 /*
7262                  * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7263                  * This is PIE code, and the linker can update it if needed.
7264                  */
7265                 sprintf (symbol, "method_addresses");
7266                 emit_section_change (acfg, ".text", 1);
7267                 emit_alignment (acfg, 8);
7268                 emit_label (acfg, symbol);
7269                 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7270                 emit_unset_mode (acfg);
7271                 if (acfg->need_no_dead_strip)
7272                         fprintf (acfg->fp, "    .no_dead_strip %s\n", symbol);
7273
7274                 for (i = 0; i < acfg->nmethods; ++i) {
7275 #ifdef MONO_ARCH_AOT_SUPPORTED
7276                         int call_size;
7277
7278                         if (acfg->cfgs [i])
7279                                 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7280                         else
7281                                 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7282 #endif
7283                 }
7284
7285                 sprintf (symbol, "method_addresses_end");
7286                 emit_label (acfg, symbol);
7287
7288                 /* Empty */
7289                 sprintf (symbol, "code_offsets");
7290                 emit_section_change (acfg, RODATA_SECT, 1);
7291                 emit_alignment (acfg, 8);
7292                 emit_label (acfg, symbol);
7293                 emit_int32 (acfg, 0);
7294         } else {
7295                 sprintf (symbol, "code_offsets");
7296                 emit_section_change (acfg, RODATA_SECT, 1);
7297                 emit_alignment (acfg, 8);
7298                 emit_label (acfg, symbol);
7299
7300                 acfg->stats.offsets_size += acfg->nmethods * 4;
7301
7302                 for (i = 0; i < acfg->nmethods; ++i) {
7303                         if (acfg->cfgs [i]) {
7304                                 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7305                         } else {
7306                                 emit_int32 (acfg, 0xffffffff);
7307                         }
7308                 }
7309         }
7310         emit_line (acfg);
7311
7312         /* Emit a sorted table mapping methods to their unbox trampolines */
7313         sprintf (symbol, "unbox_trampolines");
7314         if (acfg->direct_method_addresses)
7315                 emit_section_change (acfg, ".text", 0);
7316         else
7317                 emit_section_change (acfg, RODATA_SECT, 0);
7318         emit_alignment (acfg, 8);
7319         emit_label (acfg, symbol);
7320
7321         prev_index = -1;
7322         for (i = 0; i < acfg->nmethods; ++i) {
7323                 MonoCompile *cfg;
7324                 MonoMethod *method;
7325                 int index;
7326
7327                 cfg = acfg->cfgs [i];
7328                 if (!cfg)
7329                         continue;
7330
7331                 method = cfg->orig_method;
7332
7333                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7334 #ifdef MONO_ARCH_AOT_SUPPORTED
7335                         int call_size;
7336 #endif
7337
7338                         index = get_method_index (acfg, method);
7339                         sprintf (symbol, "ut_%d", index);
7340
7341                         emit_int32 (acfg, index);
7342                         if (acfg->direct_method_addresses) {
7343 #ifdef MONO_ARCH_AOT_SUPPORTED
7344                                 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7345 #endif
7346                         } else {
7347                                 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7348                         }
7349                         /* Make sure the table is sorted by index */
7350                         g_assert (index > prev_index);
7351                         prev_index = index;
7352                 }
7353         }
7354         sprintf (symbol, "unbox_trampolines_end");
7355         emit_label (acfg, symbol);
7356         emit_int32 (acfg, 0);
7357 }
7358
7359 static void
7360 emit_info (MonoAotCompile *acfg)
7361 {
7362         int oindex, i;
7363         char symbol [256];
7364         gint32 *offsets;
7365
7366         offsets = g_new0 (gint32, acfg->nmethods);
7367
7368         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7369                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7370
7371                 if (acfg->cfgs [i]) {
7372                         emit_method_info (acfg, acfg->cfgs [i]);
7373                         offsets [i] = acfg->cfgs [i]->method_info_offset;
7374                 } else {
7375                         offsets [i] = 0;
7376                 }
7377         }
7378
7379         sprintf (symbol, "method_info_offsets");
7380         emit_section_change (acfg, RODATA_SECT, 1);
7381         emit_alignment (acfg, 8);
7382         emit_label (acfg, symbol);
7383
7384         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7385
7386         g_free (offsets);
7387 }
7388
7389 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7390
7391 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7392 #define mix(a,b,c) { \
7393         a -= c;  a ^= rot(c, 4);  c += b; \
7394         b -= a;  b ^= rot(a, 6);  a += c; \
7395         c -= b;  c ^= rot(b, 8);  b += a; \
7396         a -= c;  a ^= rot(c,16);  c += b; \
7397         b -= a;  b ^= rot(a,19);  a += c; \
7398         c -= b;  c ^= rot(b, 4);  b += a; \
7399 }
7400 #define final(a,b,c) { \
7401         c ^= b; c -= rot(b,14); \
7402         a ^= c; a -= rot(c,11); \
7403         b ^= a; b -= rot(a,25); \
7404         c ^= b; c -= rot(b,16); \
7405         a ^= c; a -= rot(c,4);  \
7406         b ^= a; b -= rot(a,14); \
7407         c ^= b; c -= rot(b,24); \
7408 }
7409
7410 static guint
7411 mono_aot_type_hash (MonoType *t1)
7412 {
7413         guint hash = t1->type;
7414
7415         hash |= t1->byref << 6; /* do not collide with t1->type values */
7416         switch (t1->type) {
7417         case MONO_TYPE_VALUETYPE:
7418         case MONO_TYPE_CLASS:
7419         case MONO_TYPE_SZARRAY:
7420                 /* check if the distribution is good enough */
7421                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7422         case MONO_TYPE_PTR:
7423                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7424         case MONO_TYPE_ARRAY:
7425                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7426         case MONO_TYPE_GENERICINST:
7427                 return ((hash << 5) - hash) ^ 0;
7428         default:
7429                 return hash;
7430         }
7431 }
7432
7433 /*
7434  * mono_aot_method_hash:
7435  *
7436  *   Return a hash code for methods which only depends on metadata.
7437  */
7438 guint32
7439 mono_aot_method_hash (MonoMethod *method)
7440 {
7441         MonoMethodSignature *sig;
7442         MonoClass *klass;
7443         int i, hindex;
7444         int hashes_count;
7445         guint32 *hashes_start, *hashes;
7446         guint32 a, b, c;
7447         MonoGenericInst *ginst = NULL;
7448
7449         /* Similar to the hash in mono_method_get_imt_slot () */
7450
7451         sig = mono_method_signature (method);
7452
7453         if (method->is_inflated)
7454                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7455
7456         hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7457         hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7458         hashes = hashes_start;
7459
7460         /* Some wrappers are assigned to random classes */
7461         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7462                 klass = method->klass;
7463         else
7464                 klass = mono_defaults.object_class;
7465
7466         if (!method->wrapper_type) {
7467                 char *full_name = mono_type_full_name (&klass->byval_arg);
7468
7469                 hashes [0] = mono_metadata_str_hash (full_name);
7470                 hashes [1] = 0;
7471                 g_free (full_name);
7472         } else {
7473                 hashes [0] = mono_metadata_str_hash (klass->name);
7474                 hashes [1] = mono_metadata_str_hash (klass->name_space);
7475         }
7476         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7477                 /* The method name includes a stringified pointer */
7478                 hashes [2] = 0;
7479         else
7480                 hashes [2] = mono_metadata_str_hash (method->name);
7481         hashes [3] = method->wrapper_type;
7482         hashes [4] = mono_aot_type_hash (sig->ret);
7483         hindex = 5;
7484         for (i = 0; i < sig->param_count; i++) {
7485                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7486         }
7487         if (ginst) {
7488                 for (i = 0; i < ginst->type_argc; ++i)
7489                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7490         }               
7491         g_assert (hindex == hashes_count);
7492
7493         /* Setup internal state */
7494         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7495
7496         /* Handle most of the hashes */
7497         while (hashes_count > 3) {
7498                 a += hashes [0];
7499                 b += hashes [1];
7500                 c += hashes [2];
7501                 mix (a,b,c);
7502                 hashes_count -= 3;
7503                 hashes += 3;
7504         }
7505
7506         /* Handle the last 3 hashes (all the case statements fall through) */
7507         switch (hashes_count) { 
7508         case 3 : c += hashes [2];
7509         case 2 : b += hashes [1];
7510         case 1 : a += hashes [0];
7511                 final (a,b,c);
7512         case 0: /* nothing left to add */
7513                 break;
7514         }
7515         
7516         free (hashes_start);
7517         
7518         return c;
7519 }
7520 #undef rot
7521 #undef mix
7522 #undef final
7523
7524 /*
7525  * mono_aot_get_array_helper_from_wrapper;
7526  *
7527  * Get the helper method in Array called by an array wrapper method.
7528  */
7529 MonoMethod*
7530 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7531 {
7532         MonoMethod *m;
7533         const char *prefix;
7534         MonoGenericContext ctx;
7535         MonoType *args [16];
7536         char *mname, *iname, *s, *s2, *helper_name = NULL;
7537
7538         prefix = "System.Collections.Generic";
7539         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7540         s2 = strstr (s, "`1.");
7541         g_assert (s2);
7542         s2 [0] = '\0';
7543         iname = s;
7544         mname = s2 + 3;
7545
7546         //printf ("X: %s %s\n", iname, mname);
7547
7548         if (!strcmp (iname, "IList"))
7549                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7550         else
7551                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7552         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7553         g_assert (m);
7554         g_free (helper_name);
7555         g_free (s);
7556
7557         if (m->is_generic) {
7558                 memset (&ctx, 0, sizeof (ctx));
7559                 args [0] = &method->klass->element_class->byval_arg;
7560                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7561                 m = mono_class_inflate_generic_method (m, &ctx);
7562         }
7563
7564         return m;
7565 }
7566
7567 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7568
7569 typedef struct HashEntry {
7570     guint32 key, value, index;
7571         struct HashEntry *next;
7572 } HashEntry;
7573
7574 /*
7575  * emit_extra_methods:
7576  *
7577  * Emit methods which are not in the METHOD table, like wrappers.
7578  */
7579 static void
7580 emit_extra_methods (MonoAotCompile *acfg)
7581 {
7582         int i, table_size, buf_size;
7583         char symbol [256];
7584         guint8 *p, *buf;
7585         guint32 *info_offsets;
7586         guint32 hash;
7587         GPtrArray *table;
7588         HashEntry *entry, *new_entry;
7589         int nmethods, max_chain_length;
7590         int *chain_lengths;
7591
7592         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7593
7594         /* Emit method info */
7595         nmethods = 0;
7596         for (i = 0; i < acfg->extra_methods->len; ++i) {
7597                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7598                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7599
7600                 if (!cfg)
7601                         continue;
7602
7603                 buf_size = 10240;
7604                 p = buf = g_malloc (buf_size);
7605
7606                 nmethods ++;
7607
7608                 method = cfg->method_to_register;
7609
7610                 encode_method_ref (acfg, method, p, &p);
7611
7612                 g_assert ((p - buf) < buf_size);
7613
7614                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7615                 g_free (buf);
7616         }
7617
7618         /*
7619          * Construct a chained hash table for mapping indexes in extra_method_info to
7620          * method indexes.
7621          */
7622         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7623         table = g_ptr_array_sized_new (table_size);
7624         for (i = 0; i < table_size; ++i)
7625                 g_ptr_array_add (table, NULL);
7626         chain_lengths = g_new0 (int, table_size);
7627         max_chain_length = 0;
7628         for (i = 0; i < acfg->extra_methods->len; ++i) {
7629                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7630                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7631                 guint32 key, value;
7632
7633                 if (!cfg)
7634                         continue;
7635
7636                 key = info_offsets [i];
7637                 value = get_method_index (acfg, method);
7638
7639                 hash = mono_aot_method_hash (method) % table_size;
7640                 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7641
7642                 chain_lengths [hash] ++;
7643                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7644
7645                 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7646                 new_entry->key = key;
7647                 new_entry->value = value;
7648
7649                 entry = g_ptr_array_index (table, hash);
7650                 if (entry == NULL) {
7651                         new_entry->index = hash;
7652                         g_ptr_array_index (table, hash) = new_entry;
7653                 } else {
7654                         while (entry->next)
7655                                 entry = entry->next;
7656                         
7657                         entry->next = new_entry;
7658                         new_entry->index = table->len;
7659                         g_ptr_array_add (table, new_entry);
7660                 }
7661         }
7662
7663         //printf ("MAX: %d\n", max_chain_length);
7664
7665         /* Emit the table */
7666         sprintf (symbol, "extra_method_table");
7667         emit_section_change (acfg, RODATA_SECT, 0);
7668         emit_alignment (acfg, 8);
7669         emit_label (acfg, symbol);
7670
7671         emit_int32 (acfg, table_size);
7672         for (i = 0; i < table->len; ++i) {
7673                 HashEntry *entry = g_ptr_array_index (table, i);
7674
7675                 if (entry == NULL) {
7676                         emit_int32 (acfg, 0);
7677                         emit_int32 (acfg, 0);
7678                         emit_int32 (acfg, 0);
7679                 } else {
7680                         //g_assert (entry->key > 0);
7681                         emit_int32 (acfg, entry->key);
7682                         emit_int32 (acfg, entry->value);
7683                         if (entry->next)
7684                                 emit_int32 (acfg, entry->next->index);
7685                         else
7686                                 emit_int32 (acfg, 0);
7687                 }
7688         }
7689
7690         /* 
7691          * Emit a table reverse mapping method indexes to their index in extra_method_info.
7692          * This is used by mono_aot_find_jit_info ().
7693          */
7694         sprintf (symbol, "extra_method_info_offsets");
7695         emit_section_change (acfg, RODATA_SECT, 0);
7696         emit_alignment (acfg, 8);
7697         emit_label (acfg, symbol);
7698
7699         emit_int32 (acfg, acfg->extra_methods->len);
7700         for (i = 0; i < acfg->extra_methods->len; ++i) {
7701                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7702
7703                 emit_int32 (acfg, get_method_index (acfg, method));
7704                 emit_int32 (acfg, info_offsets [i]);
7705         }
7706 }       
7707
7708 static void
7709 emit_exception_info (MonoAotCompile *acfg)
7710 {
7711         int i;
7712         char symbol [256];
7713         gint32 *offsets;
7714
7715         offsets = g_new0 (gint32, acfg->nmethods);
7716         for (i = 0; i < acfg->nmethods; ++i) {
7717                 if (acfg->cfgs [i]) {
7718                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
7719                         offsets [i] = acfg->cfgs [i]->ex_info_offset;
7720                 } else {
7721                         offsets [i] = 0;
7722                 }
7723         }
7724
7725         sprintf (symbol, "ex_info_offsets");
7726         emit_section_change (acfg, RODATA_SECT, 1);
7727         emit_alignment (acfg, 8);
7728         emit_label (acfg, symbol);
7729
7730         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7731         g_free (offsets);
7732 }
7733
7734 static void
7735 emit_unwind_info (MonoAotCompile *acfg)
7736 {
7737         int i;
7738         char symbol [128];
7739
7740         /* 
7741          * The unwind info contains a lot of duplicates so we emit each unique
7742          * entry once, and only store the offset from the start of the table in the
7743          * exception info.
7744          */
7745
7746         sprintf (symbol, "unwind_info");
7747         emit_section_change (acfg, RODATA_SECT, 1);
7748         emit_alignment (acfg, 8);
7749         emit_label (acfg, symbol);
7750
7751         for (i = 0; i < acfg->unwind_ops->len; ++i) {
7752                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7753                 guint8 *unwind_info;
7754                 guint32 unwind_info_len;
7755                 guint8 buf [16];
7756                 guint8 *p;
7757
7758                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7759
7760                 p = buf;
7761                 encode_value (unwind_info_len, p, &p);
7762                 emit_bytes (acfg, buf, p - buf);
7763                 emit_bytes (acfg, unwind_info, unwind_info_len);
7764
7765                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7766         }
7767 }
7768
7769 static void
7770 emit_class_info (MonoAotCompile *acfg)
7771 {
7772         int i;
7773         char symbol [256];
7774         gint32 *offsets;
7775
7776         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7777         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7778                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7779
7780         sprintf (symbol, "class_info_offsets");
7781         emit_section_change (acfg, RODATA_SECT, 1);
7782         emit_alignment (acfg, 8);
7783         emit_label (acfg, symbol);
7784
7785         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7786         g_free (offsets);
7787 }
7788
7789 typedef struct ClassNameTableEntry {
7790         guint32 token, index;
7791         struct ClassNameTableEntry *next;
7792 } ClassNameTableEntry;
7793
7794 static void
7795 emit_class_name_table (MonoAotCompile *acfg)
7796 {
7797         int i, table_size;
7798         guint32 token, hash;
7799         MonoClass *klass;
7800         GPtrArray *table;
7801         char *full_name;
7802         char symbol [256];
7803         ClassNameTableEntry *entry, *new_entry;
7804
7805         /*
7806          * Construct a chained hash table for mapping class names to typedef tokens.
7807          */
7808         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7809         table = g_ptr_array_sized_new (table_size);
7810         for (i = 0; i < table_size; ++i)
7811                 g_ptr_array_add (table, NULL);
7812         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7813                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7814                 klass = mono_class_get (acfg->image, token);
7815                 if (!klass) {
7816                         mono_loader_clear_error ();
7817                         continue;
7818                 }
7819                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7820                 hash = mono_metadata_str_hash (full_name) % table_size;
7821                 g_free (full_name);
7822
7823                 /* FIXME: Allocate from the mempool */
7824                 new_entry = g_new0 (ClassNameTableEntry, 1);
7825                 new_entry->token = token;
7826
7827                 entry = g_ptr_array_index (table, hash);
7828                 if (entry == NULL) {
7829                         new_entry->index = hash;
7830                         g_ptr_array_index (table, hash) = new_entry;
7831                 } else {
7832                         while (entry->next)
7833                                 entry = entry->next;
7834                         
7835                         entry->next = new_entry;
7836                         new_entry->index = table->len;
7837                         g_ptr_array_add (table, new_entry);
7838                 }
7839         }
7840
7841         /* Emit the table */
7842         sprintf (symbol, "class_name_table");
7843         emit_section_change (acfg, RODATA_SECT, 0);
7844         emit_alignment (acfg, 8);
7845         emit_label (acfg, symbol);
7846
7847         /* FIXME: Optimize memory usage */
7848         g_assert (table_size < 65000);
7849         emit_int16 (acfg, table_size);
7850         g_assert (table->len < 65000);
7851         for (i = 0; i < table->len; ++i) {
7852                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7853
7854                 if (entry == NULL) {
7855                         emit_int16 (acfg, 0);
7856                         emit_int16 (acfg, 0);
7857                 } else {
7858                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
7859                         if (entry->next)
7860                                 emit_int16 (acfg, entry->next->index);
7861                         else
7862                                 emit_int16 (acfg, 0);
7863                 }
7864         }
7865 }
7866
7867 static void
7868 emit_image_table (MonoAotCompile *acfg)
7869 {
7870         int i;
7871         char symbol [256];
7872
7873         /*
7874          * The image table is small but referenced in a lot of places.
7875          * So we emit it at once, and reference its elements by an index.
7876          */
7877
7878         sprintf (symbol, "image_table");
7879         emit_section_change (acfg, RODATA_SECT, 1);
7880         emit_alignment (acfg, 8);
7881         emit_label (acfg, symbol);
7882
7883         emit_int32 (acfg, acfg->image_table->len);
7884         for (i = 0; i < acfg->image_table->len; i++) {
7885                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7886                 MonoAssemblyName *aname = &image->assembly->aname;
7887
7888                 /* FIXME: Support multi-module assemblies */
7889                 g_assert (image->assembly->image == image);
7890
7891                 emit_string (acfg, image->assembly_name);
7892                 emit_string (acfg, image->guid);
7893                 emit_string (acfg, aname->culture ? aname->culture : "");
7894                 emit_string (acfg, (const char*)aname->public_key_token);
7895
7896                 emit_alignment (acfg, 8);
7897                 emit_int32 (acfg, aname->flags);
7898                 emit_int32 (acfg, aname->major);
7899                 emit_int32 (acfg, aname->minor);
7900                 emit_int32 (acfg, aname->build);
7901                 emit_int32 (acfg, aname->revision);
7902         }
7903 }
7904
7905 static void
7906 emit_got_info (MonoAotCompile *acfg)
7907 {
7908         char symbol [256];
7909         int i, first_plt_got_patch, buf_size;
7910         guint8 *p, *buf;
7911         guint32 *got_info_offsets;
7912
7913         /* Add the patches needed by the PLT to the GOT */
7914         acfg->plt_got_offset_base = acfg->got_offset;
7915         first_plt_got_patch = acfg->got_patches->len;
7916         for (i = 1; i < acfg->plt_offset; ++i) {
7917                 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7918
7919                 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7920
7921                 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7922         }
7923
7924         acfg->got_offset += acfg->plt_offset;
7925
7926         /**
7927          * FIXME: 
7928          * - optimize offsets table.
7929          * - reduce number of exported symbols.
7930          * - emit info for a klass only once.
7931          * - determine when a method uses a GOT slot which is guaranteed to be already 
7932          *   initialized.
7933          * - clean up and document the code.
7934          * - use String.Empty in class libs.
7935          */
7936
7937         /* Encode info required to decode shared GOT entries */
7938         buf_size = acfg->got_patches->len * 128;
7939         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7940         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7941         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7942         /* Unused */
7943         if (acfg->plt_offset)
7944                 acfg->plt_got_info_offsets [0] = 0;
7945         for (i = 0; i < acfg->got_patches->len; ++i) {
7946                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7947                 guint8 *p2;
7948
7949                 p = buf;
7950
7951                 encode_value (ji->type, p, &p);
7952                 p2 = p;
7953                 encode_patch (acfg, ji, p, &p);
7954                 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7955                 g_assert (p - buf <= buf_size);
7956                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7957
7958                 if (i >= first_plt_got_patch)
7959                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7960                 acfg->stats.got_info_size += p - buf;
7961         }
7962
7963         /* Emit got_info_offsets table */
7964         sprintf (symbol, "got_info_offsets");
7965         emit_section_change (acfg, RODATA_SECT, 1);
7966         emit_alignment (acfg, 8);
7967         emit_label (acfg, symbol);
7968
7969         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7970         acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7971 }
7972
7973 static void
7974 emit_got (MonoAotCompile *acfg)
7975 {
7976         char symbol [256];
7977
7978         if (!acfg->llvm) {
7979                 /* Don't make GOT global so accesses to it don't need relocations */
7980                 sprintf (symbol, "%s", acfg->got_symbol);
7981                 emit_section_change (acfg, ".bss", 0);
7982                 emit_alignment (acfg, 8);
7983                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7984                 emit_label (acfg, symbol);
7985                 if (acfg->got_offset > 0)
7986                         emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7987
7988                 sprintf (symbol, "got_end");
7989                 emit_label (acfg, symbol);
7990         }
7991 }
7992
7993 typedef struct GlobalsTableEntry {
7994         guint32 value, index;
7995         struct GlobalsTableEntry *next;
7996 } GlobalsTableEntry;
7997
7998 static void
7999 emit_globals (MonoAotCompile *acfg)
8000 {
8001         int i, table_size;
8002         guint32 hash;
8003         GPtrArray *table;
8004         char symbol [256];
8005         GlobalsTableEntry *entry, *new_entry;
8006
8007         if (!acfg->aot_opts.static_link)
8008                 return;
8009
8010         /* 
8011          * When static linking, we emit a table containing our globals.
8012          */
8013
8014         /*
8015          * Construct a chained hash table for mapping global names to their index in
8016          * the globals table.
8017          */
8018         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8019         table = g_ptr_array_sized_new (table_size);
8020         for (i = 0; i < table_size; ++i)
8021                 g_ptr_array_add (table, NULL);
8022         for (i = 0; i < acfg->globals->len; ++i) {
8023                 char *name = g_ptr_array_index (acfg->globals, i);
8024
8025                 hash = mono_metadata_str_hash (name) % table_size;
8026
8027                 /* FIXME: Allocate from the mempool */
8028                 new_entry = g_new0 (GlobalsTableEntry, 1);
8029                 new_entry->value = i;
8030
8031                 entry = g_ptr_array_index (table, hash);
8032                 if (entry == NULL) {
8033                         new_entry->index = hash;
8034                         g_ptr_array_index (table, hash) = new_entry;
8035                 } else {
8036                         while (entry->next)
8037                                 entry = entry->next;
8038                         
8039                         entry->next = new_entry;
8040                         new_entry->index = table->len;
8041                         g_ptr_array_add (table, new_entry);
8042                 }
8043         }
8044
8045         /* Emit the table */
8046         sprintf (symbol, ".Lglobals_hash");
8047         emit_section_change (acfg, RODATA_SECT, 0);
8048         emit_alignment (acfg, 8);
8049         emit_label (acfg, symbol);
8050
8051         /* FIXME: Optimize memory usage */
8052         g_assert (table_size < 65000);
8053         emit_int16 (acfg, table_size);
8054         for (i = 0; i < table->len; ++i) {
8055                 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8056
8057                 if (entry == NULL) {
8058                         emit_int16 (acfg, 0);
8059                         emit_int16 (acfg, 0);
8060                 } else {
8061                         emit_int16 (acfg, entry->value + 1);
8062                         if (entry->next)
8063                                 emit_int16 (acfg, entry->next->index);
8064                         else
8065                                 emit_int16 (acfg, 0);
8066                 }
8067         }
8068
8069         /* Emit the names */
8070         for (i = 0; i < acfg->globals->len; ++i) {
8071                 char *name = g_ptr_array_index (acfg->globals, i);
8072
8073                 sprintf (symbol, "name_%d", i);
8074                 emit_section_change (acfg, RODATA_SECT, 1);
8075 #ifdef TARGET_MACH
8076                 emit_alignment (acfg, 4);
8077 #endif
8078                 emit_label (acfg, symbol);
8079                 emit_string (acfg, name);
8080         }
8081
8082         /* Emit the globals table */
8083         sprintf (symbol, "globals");
8084         emit_section_change (acfg, ".data", 0);
8085         /* This is not a global, since it is accessed by the init function */
8086         emit_alignment (acfg, 8);
8087         emit_label (acfg, symbol);
8088
8089         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8090         emit_pointer (acfg, symbol);
8091
8092         for (i = 0; i < acfg->globals->len; ++i) {
8093                 char *name = g_ptr_array_index (acfg->globals, i);
8094
8095                 sprintf (symbol, "name_%d", i);
8096                 emit_pointer (acfg, symbol);
8097
8098                 sprintf (symbol, "%s", name);
8099                 emit_pointer (acfg, symbol);
8100         }
8101         /* Null terminate the table */
8102         emit_int32 (acfg, 0);
8103         emit_int32 (acfg, 0);
8104 }
8105
8106 static void
8107 emit_autoreg (MonoAotCompile *acfg)
8108 {
8109         char *symbol;
8110
8111         /*
8112          * Emit a function into the .ctor section which will be called by the ELF
8113          * loader to register this module with the runtime.
8114          */
8115         if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8116                 return;
8117
8118         symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8119
8120         arch_emit_autoreg (acfg, symbol);
8121
8122         g_free (symbol);
8123 }       
8124
8125 static void
8126 emit_mem_end (MonoAotCompile *acfg)
8127 {
8128         char symbol [128];
8129
8130         sprintf (symbol, "mem_end");
8131         emit_section_change (acfg, ".text", 1);
8132         emit_alignment (acfg, 8);
8133         emit_label (acfg, symbol);
8134 }
8135
8136 /*
8137  * Emit a structure containing all the information not stored elsewhere.
8138  */
8139 static void
8140 emit_file_info (MonoAotCompile *acfg)
8141 {
8142         char symbol [256];
8143         int i;
8144         int gc_name_offset;
8145         const char *gc_name;
8146         char *build_info;
8147
8148         emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8149
8150         if (acfg->aot_opts.bind_to_runtime_version) {
8151                 build_info = mono_get_runtime_build_info ();
8152                 emit_string_symbol (acfg, "runtime_version", build_info);
8153                 g_free (build_info);
8154         } else {
8155                 emit_string_symbol (acfg, "runtime_version", "");
8156         }
8157
8158         /* Emit a string holding the assembly name */
8159         emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8160
8161         /*
8162          * The managed allocators are GC specific, so can't use an AOT image created by one GC
8163          * in another.
8164          */
8165         gc_name = mono_gc_get_gc_name ();
8166         gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8167
8168         sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8169         emit_section_change (acfg, ".data", 0);
8170         emit_alignment (acfg, 8);
8171         emit_label (acfg, symbol);
8172         if (!acfg->aot_opts.static_link)
8173                 emit_global (acfg, symbol, FALSE);
8174
8175         /* The data emitted here must match MonoAotFileInfo. */
8176
8177         emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8178         emit_int32 (acfg, 0);
8179
8180         /* 
8181          * We emit pointers to our data structures instead of emitting global symbols which
8182          * point to them, to reduce the number of globals, and because using globals leads to
8183          * various problems (i.e. arm/thumb).
8184          */
8185         emit_pointer (acfg, acfg->got_symbol);
8186         emit_pointer (acfg, acfg->methods_symbol);
8187         if (acfg->llvm) {
8188                 /*
8189                  * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8190                  */
8191                 emit_pointer (acfg, "mono_eh_frame");
8192         } else {
8193                 emit_pointer (acfg, NULL);
8194         }
8195         emit_pointer (acfg, "blob");
8196         emit_pointer (acfg, "class_name_table");
8197         emit_pointer (acfg, "class_info_offsets");
8198         emit_pointer (acfg, "method_info_offsets");
8199         emit_pointer (acfg, "ex_info_offsets");
8200         emit_pointer (acfg, "code_offsets");
8201         if (acfg->direct_method_addresses)
8202                 emit_pointer (acfg, "method_addresses");
8203         else
8204                 emit_pointer (acfg, NULL);
8205         emit_pointer (acfg, "extra_method_info_offsets");
8206         emit_pointer (acfg, "extra_method_table");
8207         emit_pointer (acfg, "got_info_offsets");
8208         emit_pointer (acfg, "methods_end");
8209         emit_pointer (acfg, "unwind_info");
8210         emit_pointer (acfg, "mem_end");
8211         emit_pointer (acfg, "image_table");
8212         emit_pointer (acfg, "plt");
8213         emit_pointer (acfg, "plt_end");
8214         emit_pointer (acfg, "assembly_guid");
8215         emit_pointer (acfg, "runtime_version");
8216         if (acfg->num_trampoline_got_entries) {
8217                 emit_pointer (acfg, "specific_trampolines");
8218                 emit_pointer (acfg, "static_rgctx_trampolines");
8219                 emit_pointer (acfg, "imt_thunks");
8220                 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8221         } else {
8222                 emit_pointer (acfg, NULL);
8223                 emit_pointer (acfg, NULL);
8224                 emit_pointer (acfg, NULL);
8225                 emit_pointer (acfg, NULL);
8226         }
8227         if (acfg->thumb_mixed) {
8228                 emit_pointer (acfg, "thumb_end");
8229         } else {
8230                 emit_pointer (acfg, NULL);
8231         }
8232         if (acfg->aot_opts.static_link) {
8233                 emit_pointer (acfg, "globals");
8234         } else {
8235                 emit_pointer (acfg, NULL);
8236         }
8237         emit_pointer (acfg, "assembly_name");
8238         emit_pointer (acfg, "unbox_trampolines");
8239         emit_pointer (acfg, "unbox_trampolines_end");
8240
8241         emit_int32 (acfg, acfg->plt_got_offset_base);
8242         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8243         emit_int32 (acfg, acfg->plt_offset);
8244         emit_int32 (acfg, acfg->nmethods);
8245         emit_int32 (acfg, acfg->flags);
8246         emit_int32 (acfg, acfg->opts);
8247         emit_int32 (acfg, acfg->simd_opts);
8248         emit_int32 (acfg, gc_name_offset);
8249
8250         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8251                 emit_int32 (acfg, acfg->num_trampolines [i]);
8252         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8253                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8254         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8255                 emit_int32 (acfg, acfg->trampoline_size [i]);
8256         emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8257
8258 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8259         {
8260                 MonoType t;
8261                 int align = 0;
8262
8263                 memset (&t, 0, sizeof (MonoType));
8264                 t.type = MONO_TYPE_R8;
8265                 mono_type_size (&t, &align);
8266                 emit_int32 (acfg, align);
8267
8268                 memset (&t, 0, sizeof (MonoType));
8269                 t.type = MONO_TYPE_I8;
8270                 mono_type_size (&t, &align);
8271
8272                 emit_int32 (acfg, align);
8273         }
8274 #else
8275         emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8276         emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8277 #endif
8278         emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8279         emit_int32 (acfg, acfg->tramp_page_size);
8280         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8281                 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8282
8283         if (acfg->aot_opts.static_link) {
8284                 char *p;
8285
8286                 /* 
8287                  * Emit a global symbol which can be passed by an embedding app to
8288                  * mono_aot_register_module (). The symbol points to a pointer to the the file info
8289                  * structure.
8290                  */
8291                 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8292
8293                 /* Get rid of characters which cannot occur in symbols */
8294                 p = symbol;
8295                 for (p = symbol; *p; ++p) {
8296                         if (!(isalnum (*p) || *p == '_'))
8297                                 *p = '_';
8298                 }
8299                 acfg->static_linking_symbol = g_strdup (symbol);
8300                 emit_global_inner (acfg, symbol, FALSE);
8301                 emit_alignment (acfg, sizeof (gpointer));
8302                 emit_label (acfg, symbol);
8303                 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8304         }
8305 }
8306
8307 static void
8308 emit_blob (MonoAotCompile *acfg)
8309 {
8310         char symbol [128];
8311
8312         sprintf (symbol, "blob");
8313         emit_section_change (acfg, RODATA_SECT, 1);
8314         emit_alignment (acfg, 8);
8315         emit_label (acfg, symbol);
8316
8317         emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8318 }
8319
8320 static void
8321 emit_objc_selectors (MonoAotCompile *acfg)
8322 {
8323         int i;
8324
8325         if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8326                 return;
8327
8328         /*
8329          * From
8330          * cat > foo.m << EOF
8331          * void *ret ()
8332          * {
8333          * return @selector(print:);
8334          * }
8335          * EOF
8336          */
8337
8338         img_writer_emit_unset_mode (acfg->w);
8339         g_assert (acfg->fp);
8340         fprintf (acfg->fp, ".section    __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8341         fprintf (acfg->fp, ".align      3\n");
8342         for (i = 0; i < acfg->objc_selectors->len; ++i) {
8343                 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8344                 fprintf (acfg->fp, ".long       L_OBJC_METH_VAR_NAME_%d\n", i);
8345         }
8346         fprintf (acfg->fp, ".section    __TEXT,__cstring,cstring_literals\n");
8347         for (i = 0; i < acfg->objc_selectors->len; ++i) {
8348                 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8349                 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8350         }
8351
8352         fprintf (acfg->fp, ".section    __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8353         fprintf (acfg->fp, ".align      3\n");
8354         fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8355         fprintf (acfg->fp, ".long       0\n");
8356         fprintf (acfg->fp, ".long       16\n");
8357 }
8358
8359 static void
8360 emit_dwarf_info (MonoAotCompile *acfg)
8361 {
8362 #ifdef EMIT_DWARF_INFO
8363         int i;
8364         char symbol2 [128];
8365
8366         /* DIEs for methods */
8367         for (i = 0; i < acfg->nmethods; ++i) {
8368                 MonoCompile *cfg = acfg->cfgs [i];
8369
8370                 if (!cfg)
8371                         continue;
8372
8373                 // FIXME: LLVM doesn't define .Lme_...
8374                 if (cfg->compile_llvm)
8375                         continue;
8376
8377                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8378
8379                 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 ()));
8380         }
8381 #endif
8382 }
8383
8384 static void
8385 collect_methods (MonoAotCompile *acfg)
8386 {
8387         int mindex, i;
8388         MonoImage *image = acfg->image;
8389
8390         /* Collect methods */
8391         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8392                 MonoMethod *method;
8393                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8394
8395                 method = mono_get_method (acfg->image, token, NULL);
8396
8397                 if (!method) {
8398                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8399                         printf ("Run with MONO_LOG_LEVEL=debug for more information.\n");
8400                         exit (1);
8401                 }
8402                         
8403                 /* Load all methods eagerly to skip the slower lazy loading code */
8404                 mono_class_setup_methods (method->klass);
8405
8406                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8407                         /* Compile the wrapper instead */
8408                         /* We do this here instead of add_wrappers () because it is easy to do it here */
8409                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8410                         method = wrapper;
8411                 }
8412
8413                 /* FIXME: Some mscorlib methods don't have debug info */
8414                 /*
8415                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8416                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8417                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8418                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8419                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8420                                 if (!mono_debug_lookup_method (method)) {
8421                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8422                                         exit (1);
8423                                 }
8424                         }
8425                 }
8426                 */
8427
8428                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8429                 add_method_with_index (acfg, method, i, FALSE);
8430                 acfg->method_index ++;
8431         }
8432
8433         /* gsharedvt methods */
8434         for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8435                 MonoMethod *method;
8436                 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8437
8438                 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8439                         continue;
8440
8441                 method = mono_get_method (acfg->image, token, NULL);
8442                 if (!method)
8443                         continue;
8444                 /*
8445                 if (strcmp (method->name, "gshared2"))
8446                         continue;
8447                 */
8448                 /*
8449                 if (!strstr (method->klass->image->name, "mini"))
8450                         continue;
8451                 */
8452                 if (method->is_generic || method->klass->generic_container) {
8453                         MonoMethod *gshared;
8454
8455                         gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8456                         add_extra_method (acfg, gshared);
8457                 }
8458         }
8459
8460         add_generic_instances (acfg);
8461
8462         if (acfg->aot_opts.full_aot)
8463                 add_wrappers (acfg);
8464 }
8465
8466 static void
8467 compile_methods (MonoAotCompile *acfg)
8468 {
8469         int i, methods_len;
8470
8471         if (acfg->aot_opts.nthreads > 0) {
8472                 GPtrArray *frag;
8473                 int len, j;
8474                 GPtrArray *threads;
8475                 HANDLE handle;
8476                 gpointer *user_data;
8477                 MonoMethod **methods;
8478
8479                 methods_len = acfg->methods->len;
8480
8481                 len = acfg->methods->len / acfg->aot_opts.nthreads;
8482                 g_assert (len > 0);
8483                 /* 
8484                  * Partition the list of methods into fragments, and hand it to threads to
8485                  * process.
8486                  */
8487                 threads = g_ptr_array_new ();
8488                 /* Make a copy since acfg->methods is modified by compile_method () */
8489                 methods = g_new0 (MonoMethod*, methods_len);
8490                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8491                 for (i = 0; i < methods_len; ++i)
8492                         methods [i] = g_ptr_array_index (acfg->methods, i);
8493                 i = 0;
8494                 while (i < methods_len) {
8495                         frag = g_ptr_array_new ();
8496                         for (j = 0; j < len; ++j) {
8497                                 if (i < methods_len) {
8498                                         g_ptr_array_add (frag, methods [i]);
8499                                         i ++;
8500                                 }
8501                         }
8502
8503                         user_data = g_new0 (gpointer, 3);
8504                         user_data [0] = mono_domain_get ();
8505                         user_data [1] = acfg;
8506                         user_data [2] = frag;
8507                         
8508                         handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8509                         g_ptr_array_add (threads, handle);
8510                 }
8511                 g_free (methods);
8512
8513                 for (i = 0; i < threads->len; ++i) {
8514                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8515                 }
8516         } else {
8517                 methods_len = 0;
8518         }
8519
8520         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8521         for (i = methods_len; i < acfg->methods->len; ++i) {
8522                 /* This can new methods to acfg->methods */
8523                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8524         }
8525 }
8526
8527 static int
8528 compile_asm (MonoAotCompile *acfg)
8529 {
8530         char *command, *objfile;
8531         char *outfile_name, *tmp_outfile_name;
8532         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8533
8534 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8535 #define AS_OPTIONS "--64"
8536 #elif defined(TARGET_POWERPC64)
8537 #define AS_OPTIONS "-a64 -mppc64"
8538 #define LD_OPTIONS "-m elf64ppc"
8539 #elif defined(sparc) && SIZEOF_VOID_P == 8
8540 #define AS_OPTIONS "-xarch=v9"
8541 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8542 #define AS_OPTIONS "-arch i386"
8543 #else
8544 #define AS_OPTIONS ""
8545 #endif
8546
8547 #ifdef __native_client_codegen__
8548 #if defined(TARGET_AMD64)
8549 #define AS_NAME "nacl64-as"
8550 #else
8551 #define AS_NAME "nacl-as"
8552 #endif
8553 #elif defined(TARGET_OSX)
8554 #define AS_NAME "clang -c -x assembler"
8555 #else
8556 #define AS_NAME "as"
8557 #endif
8558
8559 #ifndef LD_OPTIONS
8560 #define LD_OPTIONS ""
8561 #endif
8562
8563 #if defined(sparc)
8564 #define LD_NAME "ld -shared -G"
8565 #elif defined(__ppc__) && defined(TARGET_MACH)
8566 #define LD_NAME "gcc -dynamiclib"
8567 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8568 #define LD_NAME "clang --shared"
8569 #elif defined(HOST_WIN32)
8570 #define LD_NAME "gcc -shared --dll"
8571 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8572 #define LD_NAME "clang -m32 -dynamiclib"
8573 #endif
8574
8575         if (acfg->aot_opts.asm_only) {
8576                 printf ("Output file: '%s'.\n", acfg->tmpfname);
8577                 if (acfg->aot_opts.static_link)
8578                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8579                 return 0;
8580         }
8581
8582         if (acfg->aot_opts.static_link) {
8583                 if (acfg->aot_opts.outfile)
8584                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8585                 else
8586                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
8587         } else {
8588                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8589         }
8590         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);
8591         printf ("Executing the native assembler: %s\n", command);
8592         if (system (command) != 0) {
8593                 g_free (command);
8594                 g_free (objfile);
8595                 return 1;
8596         }
8597
8598         g_free (command);
8599
8600         if (acfg->aot_opts.static_link) {
8601                 printf ("Output file: '%s'.\n", objfile);
8602                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8603                 g_free (objfile);
8604                 return 0;
8605         }
8606
8607         if (acfg->aot_opts.outfile)
8608                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8609         else
8610                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8611
8612         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8613
8614 #ifdef LD_NAME
8615         command = g_strdup_printf ("%s -o %s %s.o", LD_NAME, tmp_outfile_name, acfg->tmpfname);
8616 #else
8617         command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8618 #endif
8619         printf ("Executing the native linker: %s\n", command);
8620         if (system (command) != 0) {
8621                 g_free (tmp_outfile_name);
8622                 g_free (outfile_name);
8623                 g_free (command);
8624                 g_free (objfile);
8625                 return 1;
8626         }
8627
8628         g_free (command);
8629
8630         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8631         printf ("Stripping the binary: %s\n", com);
8632         system (com);
8633         g_free (com);*/
8634
8635 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8636         /* 
8637          * gas generates 'mapping symbols' each time code and data is mixed, which 
8638          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8639          */
8640         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8641         printf ("Stripping the binary: %s\n", command);
8642         if (system (command) != 0) {
8643                 g_free (tmp_outfile_name);
8644                 g_free (outfile_name);
8645                 g_free (command);
8646                 g_free (objfile);
8647                 return 1;
8648         }
8649 #endif
8650
8651         rename (tmp_outfile_name, outfile_name);
8652
8653 #if defined(TARGET_MACH)
8654         command = g_strdup_printf ("dsymutil %s", outfile_name);
8655         printf ("Executing dsymutil: %s\n", command);
8656         if (system (command) != 0) {
8657                 return 1;
8658         }
8659 #endif
8660
8661         if (!acfg->aot_opts.save_temps)
8662                 unlink (objfile);
8663
8664         g_free (tmp_outfile_name);
8665         g_free (outfile_name);
8666         g_free (objfile);
8667
8668         if (acfg->aot_opts.save_temps)
8669                 printf ("Retained input file.\n");
8670         else
8671                 unlink (acfg->tmpfname);
8672
8673         return 0;
8674 }
8675
8676 static MonoAotCompile*
8677 acfg_create (MonoAssembly *ass, guint32 opts)
8678 {
8679         MonoImage *image = ass->image;
8680         MonoAotCompile *acfg;
8681         int i;
8682
8683         acfg = g_new0 (MonoAotCompile, 1);
8684         acfg->methods = g_ptr_array_new ();
8685         acfg->method_indexes = g_hash_table_new (NULL, NULL);
8686         acfg->method_depth = g_hash_table_new (NULL, NULL);
8687         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8688         acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8689         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8690         acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8691         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8692                 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8693         acfg->got_patches = g_ptr_array_new ();
8694         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8695         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8696         acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8697         acfg->image_hash = g_hash_table_new (NULL, NULL);
8698         acfg->image_table = g_ptr_array_new ();
8699         acfg->globals = g_ptr_array_new ();
8700         acfg->image = image;
8701         acfg->opts = opts;
8702         /* TODO: Write out set of SIMD instructions used, rather than just those available */
8703         acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8704         acfg->mempool = mono_mempool_new ();
8705         acfg->extra_methods = g_ptr_array_new ();
8706         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8707         acfg->unwind_ops = g_ptr_array_new ();
8708         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8709         acfg->method_order = g_ptr_array_new ();
8710         acfg->export_names = g_hash_table_new (NULL, NULL);
8711         acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8712         acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8713         acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8714         mono_mutex_init_recursive (&acfg->mutex);
8715
8716         return acfg;
8717 }
8718
8719 static void
8720 acfg_free (MonoAotCompile *acfg)
8721 {
8722         int i;
8723
8724         img_writer_destroy (acfg->w);
8725         for (i = 0; i < acfg->nmethods; ++i)
8726                 if (acfg->cfgs [i])
8727                         g_free (acfg->cfgs [i]);
8728         g_free (acfg->cfgs);
8729         g_free (acfg->static_linking_symbol);
8730         g_free (acfg->got_symbol);
8731         g_free (acfg->plt_symbol);
8732         g_ptr_array_free (acfg->methods, TRUE);
8733         g_ptr_array_free (acfg->got_patches, TRUE);
8734         g_ptr_array_free (acfg->image_table, TRUE);
8735         g_ptr_array_free (acfg->globals, TRUE);
8736         g_ptr_array_free (acfg->unwind_ops, TRUE);
8737         g_hash_table_destroy (acfg->method_indexes);
8738         g_hash_table_destroy (acfg->method_depth);
8739         g_hash_table_destroy (acfg->plt_offset_to_entry);
8740         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8741                 if (acfg->patch_to_plt_entry [i])
8742                         g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8743         }
8744         g_free (acfg->patch_to_plt_entry);
8745         g_hash_table_destroy (acfg->patch_to_got_offset);
8746         g_hash_table_destroy (acfg->method_to_cfg);
8747         g_hash_table_destroy (acfg->token_info_hash);
8748         g_hash_table_destroy (acfg->method_to_pinvoke_import);
8749         g_hash_table_destroy (acfg->image_hash);
8750         g_hash_table_destroy (acfg->unwind_info_offsets);
8751         g_hash_table_destroy (acfg->method_label_hash);
8752         g_hash_table_destroy (acfg->export_names);
8753         g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8754         g_hash_table_destroy (acfg->klass_blob_hash);
8755         g_hash_table_destroy (acfg->method_blob_hash);
8756         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8757                 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8758         g_free (acfg->patch_to_got_offset_by_type);
8759         mono_mempool_destroy (acfg->mempool);
8760         g_free (acfg);
8761 }
8762
8763 int
8764 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8765 {
8766         MonoImage *image = ass->image;
8767         int i, res, all_sizes;
8768         MonoAotCompile *acfg;
8769         char *outfile_name, *tmp_outfile_name, *p;
8770         char llvm_stats_msg [256];
8771         TV_DECLARE (atv);
8772         TV_DECLARE (btv);
8773
8774 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8775         if (opts & MONO_OPT_GSHAREDVT) {
8776                 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8777                 exit (1);
8778         }
8779 #endif
8780
8781         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8782
8783         acfg = acfg_create (ass, opts);
8784
8785         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8786         acfg->aot_opts.write_symbols = TRUE;
8787         acfg->aot_opts.ntrampolines = 1024;
8788         acfg->aot_opts.nrgctx_trampolines = 1024;
8789         acfg->aot_opts.nimt_trampolines = 128;
8790         acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8791         acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8792         acfg->aot_opts.llvm_path = g_strdup ("");
8793 #ifdef MONOTOUCH
8794         acfg->aot_opts.use_trampolines_page = TRUE;
8795 #endif
8796
8797         mono_aot_parse_options (aot_options, &acfg->aot_opts);
8798
8799         if (acfg->aot_opts.static_link)
8800                 acfg->aot_opts.autoreg = TRUE;
8801
8802         //acfg->aot_opts.print_skipped_methods = TRUE;
8803
8804 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8805         if (acfg->aot_opts.full_aot) {
8806                 printf ("--aot=full is not supported on this platform.\n");
8807                 return 1;
8808         }
8809 #endif
8810
8811         if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8812                 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8813                 exit (1);
8814         }
8815
8816         if (acfg->aot_opts.static_link)
8817                 acfg->aot_opts.asm_writer = TRUE;
8818
8819         if (acfg->aot_opts.soft_debug) {
8820                 MonoDebugOptions *opt = mini_get_debug_options ();
8821
8822                 opt->mdb_optimizations = TRUE;
8823                 opt->gen_seq_points = TRUE;
8824
8825                 if (!mono_debug_enabled ()) {
8826                         fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8827                         return 1;
8828                 }
8829                 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8830         }
8831
8832         if (mono_use_llvm) {
8833                 acfg->llvm = TRUE;
8834                 acfg->aot_opts.asm_writer = TRUE;
8835                 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8836
8837                 if (acfg->aot_opts.soft_debug) {
8838                         fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8839                         exit (1);
8840                 }
8841         }
8842
8843         if (acfg->aot_opts.full_aot)
8844                 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8845
8846         if (acfg->aot_opts.instances_logfile_path) {
8847                 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
8848                 if (!acfg->instances_logfile) {
8849                         fprintf (stderr, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
8850                         exit (1);
8851                 }
8852         }
8853
8854         load_profile_files (acfg);
8855
8856         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8857 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8858         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8859 #endif
8860         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8861 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8862         if (acfg->opts & MONO_OPT_GSHAREDVT)
8863                 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8864 #endif
8865
8866         acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8867
8868         arch_init (acfg);
8869
8870         acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8871         acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8872         acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8873
8874         /* Get rid of characters which cannot occur in symbols */
8875         for (p = acfg->got_symbol_base; *p; ++p) {
8876                 if (!(isalnum (*p) || *p == '_'))
8877                         *p = '_';
8878         }
8879         for (p = acfg->plt_symbol; *p; ++p) {
8880                 if (!(isalnum (*p) || *p == '_'))
8881                         *p = '_';
8882         }
8883         for (p = acfg->assembly_name_sym; *p; ++p) {
8884                 if (!(isalnum (*p) || *p == '_'))
8885                         *p = '_';
8886         }
8887
8888         acfg->method_index = 1;
8889
8890         // FIXME:
8891         /*
8892         if (acfg->aot_opts.full_aot)
8893                 mono_set_partial_sharing_supported (TRUE);
8894         */
8895
8896         collect_methods (acfg);
8897
8898         acfg->cfgs_size = acfg->methods->len + 32;
8899         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8900
8901         /* PLT offset 0 is reserved for the PLT trampoline */
8902         acfg->plt_offset = 1;
8903
8904 #ifdef ENABLE_LLVM
8905         if (acfg->llvm) {
8906                 llvm_acfg = acfg;
8907                 mono_llvm_create_aot_module (acfg->got_symbol_base);
8908         }
8909 #endif
8910
8911         /* GOT offset 0 is reserved for the address of the current assembly */
8912         {
8913                 MonoJumpInfo *ji;
8914
8915                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8916                 ji->type = MONO_PATCH_INFO_IMAGE;
8917                 ji->data.image = acfg->image;
8918
8919                 get_got_offset (acfg, ji);
8920
8921                 /* Slot 1 is reserved for the mscorlib got addr */
8922                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8923                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8924                 get_got_offset (acfg, ji);
8925
8926                 /* This is very common */
8927                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8928                 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8929                 get_got_offset (acfg, ji);
8930
8931                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8932                 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8933                 get_got_offset (acfg, ji);
8934         }
8935
8936         TV_GETTIME (atv);
8937
8938         compile_methods (acfg);
8939
8940         TV_GETTIME (btv);
8941
8942         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8943
8944         TV_GETTIME (atv);
8945
8946 #ifdef ENABLE_LLVM
8947         if (acfg->llvm) {
8948                 if (acfg->aot_opts.asm_only) {
8949                         if (acfg->aot_opts.outfile) {
8950                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8951                                 acfg->tmpbasename = g_strdup (acfg->tmpfname);
8952                         } else {
8953                                 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
8954                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8955                         }
8956                 } else {
8957                         acfg->tmpbasename = g_strdup_printf ("%s", "temp");
8958                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8959                 }
8960
8961                 emit_llvm_file (acfg);
8962         }
8963 #endif
8964
8965         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8966                 if (acfg->aot_opts.outfile)
8967                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8968                 else
8969                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8970
8971                 /* 
8972                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
8973                  * it might be in another file system so the rename () won't work.
8974                  */
8975                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8976
8977                 acfg->fp = fopen (tmp_outfile_name, "w");
8978                 if (!acfg->fp) {
8979                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8980                         return 1;
8981                 }
8982
8983                 acfg->w = img_writer_create (acfg->fp, TRUE);
8984                 acfg->use_bin_writer = TRUE;
8985         } else {
8986                 if (acfg->llvm) {
8987                         /* Append to the .s file created by llvm */
8988                         /* FIXME: Use multiple files instead */
8989                         acfg->fp = fopen (acfg->tmpfname, "a+");
8990                 } else {
8991                         if (acfg->aot_opts.asm_only) {
8992                                 if (acfg->aot_opts.outfile)
8993                                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8994                                 else
8995                                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8996                                 acfg->fp = fopen (acfg->tmpfname, "w+");
8997                         } else {
8998                                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8999                                 acfg->fp = fdopen (i, "w+");
9000                         }
9001                 }
9002                 if (acfg->fp == 0) {
9003                         fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9004                         return 1;
9005                 }
9006                 acfg->w = img_writer_create (acfg->fp, FALSE);
9007                 
9008                 tmp_outfile_name = NULL;
9009                 outfile_name = NULL;
9010         }
9011
9012         acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9013
9014         /* Compute symbols for methods */
9015         for (i = 0; i < acfg->nmethods; ++i) {
9016                 if (acfg->cfgs [i]) {
9017                         MonoCompile *cfg = acfg->cfgs [i];
9018                         int method_index = get_method_index (acfg, cfg->orig_method);
9019
9020                         if (COMPILE_LLVM (cfg))
9021                                 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9022                         else if (acfg->global_symbols)
9023                                 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
9024                         else
9025                                 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9026                 }
9027         }
9028
9029         if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9030                 /*
9031                  * CLANG supports GAS .file/.loc directives, so emit line number information this way
9032                  * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9033                  * .byte directives.
9034                  */
9035                 //acfg->gas_line_numbers = TRUE;
9036         }
9037
9038         if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9039                 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9040                         fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
9041                         return 1;
9042                 }
9043                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9044         }
9045
9046         img_writer_emit_start (acfg->w);
9047
9048         if (acfg->dwarf)
9049                 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9050
9051         if (acfg->thumb_mixed) {
9052                 char symbol [256];
9053                 /*
9054                  * This global symbol marks the end of THUMB code, and the beginning of ARM
9055                  * code generated by our JIT.
9056                  */
9057                 sprintf (symbol, "thumb_end");
9058                 emit_section_change (acfg, ".text", 0);
9059                 emit_alignment (acfg, 8);
9060                 emit_label (acfg, symbol);
9061                 emit_zero_bytes (acfg, 16);
9062
9063                 fprintf (acfg->fp, ".arm\n");
9064         }
9065
9066         emit_code (acfg);
9067
9068         emit_info (acfg);
9069
9070         emit_extra_methods (acfg);
9071
9072         emit_trampolines (acfg);
9073
9074         emit_class_name_table (acfg);
9075
9076         emit_got_info (acfg);
9077
9078         emit_exception_info (acfg);
9079
9080         emit_unwind_info (acfg);
9081
9082         emit_class_info (acfg);
9083
9084         emit_plt (acfg);
9085
9086         emit_image_table (acfg);
9087
9088         emit_got (acfg);
9089
9090         emit_file_info (acfg);
9091
9092         emit_blob (acfg);
9093
9094         emit_objc_selectors (acfg);
9095
9096         emit_globals (acfg);
9097
9098         emit_autoreg (acfg);
9099
9100         if (acfg->dwarf) {
9101                 emit_dwarf_info (acfg);
9102                 mono_dwarf_writer_close (acfg->dwarf);
9103         }
9104
9105         emit_mem_end (acfg);
9106
9107         if (acfg->need_pt_gnu_stack) {
9108                 /* This is required so the .so doesn't have an executable stack */
9109                 /* The bin writer already emits this */
9110                 if (!acfg->use_bin_writer)
9111                         fprintf (acfg->fp, "\n.section  .note.GNU-stack,\"\",@progbits\n");
9112         }
9113
9114         TV_GETTIME (btv);
9115
9116         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9117
9118         if (acfg->llvm)
9119                 g_assert (acfg->got_offset <= acfg->final_got_size);
9120
9121         if (acfg->llvm)
9122                 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9123         else
9124                 strcpy (llvm_stats_msg, "");
9125
9126         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;
9127
9128         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",
9129                         acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9130                         acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9131                         acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9132                         acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9133                         acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9134                         acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9135                         acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9136                         acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9137                         (int)(acfg->got_offset * sizeof (gpointer)));
9138         printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n", 
9139                         acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9140                         llvm_stats_msg,
9141                         acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9142                         acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9143         if (acfg->stats.genericcount)
9144                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9145         if (acfg->stats.abscount)
9146                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9147         if (acfg->stats.lmfcount)
9148                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9149         if (acfg->stats.ocount)
9150                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9151
9152         TV_GETTIME (atv);
9153         res = img_writer_emit_writeout (acfg->w);
9154         if (res != 0) {
9155                 acfg_free (acfg);
9156                 return res;
9157         }
9158         if (acfg->use_bin_writer) {
9159                 int err = rename (tmp_outfile_name, outfile_name);
9160
9161                 if (err) {
9162                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9163                         return 1;
9164                 }
9165         } else {
9166                 res = compile_asm (acfg);
9167                 if (res != 0) {
9168                         acfg_free (acfg);
9169                         return res;
9170                 }
9171         }
9172         TV_GETTIME (btv);
9173         acfg->stats.link_time = TV_ELAPSED (atv, btv);
9174
9175         if (acfg->aot_opts.stats) {
9176                 int i;
9177
9178                 printf ("GOT slot distribution:\n");
9179                 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9180                         if (acfg->stats.got_slot_types [i])
9181                                 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9182         }
9183
9184         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);
9185
9186         acfg_free (acfg);
9187         
9188         return 0;
9189 }
9190
9191 #else
9192
9193 /* AOT disabled */
9194
9195 void*
9196 mono_aot_readonly_field_override (MonoClassField *field)
9197 {
9198         return NULL;
9199 }
9200
9201 int
9202 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9203 {
9204         return 0;
9205 }
9206
9207 #endif