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