[docs] Enable documentation for mini.
[mono.git] / mono / mini / aot-compiler.c
1 /**
2  * \file
3  * mono Ahead of Time compiler
4  *
5  * Author:
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *   Zoltan Varga (vargaz@gmail.com)
8  *   Johan Lorensson (lateralusx.github@gmail.com)
9  *
10  * (C) 2002 Ximian, Inc.
11  * Copyright 2003-2011 Novell, Inc 
12  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14  */
15
16 #include "config.h"
17 #include <sys/types.h>
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #ifdef HAVE_STDINT_H
22 #include <stdint.h>
23 #endif
24 #include <fcntl.h>
25 #include <ctype.h>
26 #include <string.h>
27 #ifndef HOST_WIN32
28 #include <sys/time.h>
29 #else
30 #include <winsock2.h>
31 #include <windows.h>
32 #endif
33
34 #include <errno.h>
35 #include <sys/stat.h>
36
37 #include <mono/metadata/abi-details.h>
38 #include <mono/metadata/tabledefs.h>
39 #include <mono/metadata/class.h>
40 #include <mono/metadata/object.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/appdomain.h>
43 #include <mono/metadata/debug-helpers.h>
44 #include <mono/metadata/assembly.h>
45 #include <mono/metadata/metadata-internals.h>
46 #include <mono/metadata/reflection-internals.h>
47 #include <mono/metadata/marshal.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/mempool-internals.h>
50 #include <mono/metadata/mono-endian.h>
51 #include <mono/metadata/threads-types.h>
52 #include <mono/utils/mono-logger-internals.h>
53 #include <mono/utils/mono-compiler.h>
54 #include <mono/utils/mono-time.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/mono-rand.h>
57 #include <mono/utils/json.h>
58 #include <mono/utils/mono-threads-coop.h>
59 #include <mono/profiler/mono-profiler-aot.h>
60 #include <mono/utils/w32api.h>
61
62 #include "aot-compiler.h"
63 #include "seq-points.h"
64 #include "image-writer.h"
65 #include "dwarfwriter.h"
66 #include "mini-gc.h"
67 #include "mini-llvm.h"
68
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
70
71 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
72 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
73 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
74 #define TARGET_X86_64_WIN32_MSVC
75 #endif
76
77 #if defined(TARGET_X86_64_WIN32_MSVC)
78 #define TARGET_WIN32_MSVC
79 #endif
80
81 #if defined(__linux__) || defined(__native_client_codegen__)
82 #define RODATA_SECT ".rodata"
83 #elif defined(TARGET_MACH)
84 #define RODATA_SECT ".section __TEXT, __const"
85 #elif defined(TARGET_WIN32_MSVC)
86 #define RODATA_SECT ".rdata"
87 #else
88 #define RODATA_SECT ".text"
89 #endif
90
91 #define TV_DECLARE(name) gint64 name
92 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
93 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
94
95 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
96 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
97 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
98
99 typedef struct {
100         char *name;
101         MonoImage *image;
102 } ImageProfileData;
103
104 typedef struct ClassProfileData ClassProfileData;
105
106 typedef struct {
107         int argc;
108         ClassProfileData **argv;
109         MonoGenericInst *inst;
110 } GInstProfileData;
111
112 struct ClassProfileData {
113         ImageProfileData *image;
114         char *ns, *name;
115         GInstProfileData *inst;
116         MonoClass *klass;
117 };
118
119 typedef struct {
120         ClassProfileData *klass;
121         int id;
122         char *name;
123         int param_count;
124         char *signature;
125         GInstProfileData *inst;
126         MonoMethod *method;
127 } MethodProfileData;
128
129 typedef struct {
130         GHashTable *images, *classes, *ginsts, *methods;
131 } ProfileData;
132
133 /* predefined values for static readonly fields without needed to run the .cctor */
134 typedef struct _ReadOnlyValue ReadOnlyValue;
135 struct _ReadOnlyValue {
136         ReadOnlyValue *next;
137         char *name;
138         int type; /* to be used later for typechecking to prevent user errors */
139         union {
140                 guint8 i1;
141                 guint16 i2;
142                 guint32 i4;
143                 guint64 i8;
144                 gpointer ptr;
145         } value;
146 };
147 static ReadOnlyValue *readonly_values;
148
149 typedef struct MonoAotOptions {
150         char *outfile;
151         char *llvm_outfile;
152         char *data_outfile;
153         GList *profile_files;
154         gboolean save_temps;
155         gboolean write_symbols;
156         gboolean metadata_only;
157         gboolean bind_to_runtime_version;
158         MonoAotMode mode;
159         gboolean no_dlsym;
160         gboolean static_link;
161         gboolean asm_only;
162         gboolean asm_writer;
163         gboolean nodebug;
164         gboolean dwarf_debug;
165         gboolean soft_debug;
166         gboolean log_generics;
167         gboolean log_instances;
168         gboolean gen_msym_dir;
169         char *gen_msym_dir_path;
170         gboolean direct_pinvoke;
171         gboolean direct_icalls;
172         gboolean no_direct_calls;
173         gboolean use_trampolines_page;
174         gboolean no_instances;
175         gboolean gnu_asm;
176         gboolean llvm;
177         gboolean llvm_only;
178         int nthreads;
179         int ntrampolines;
180         int nrgctx_trampolines;
181         int nimt_trampolines;
182         int ngsharedvt_arg_trampolines;
183         int nrgctx_fetch_trampolines;
184         gboolean print_skipped_methods;
185         gboolean stats;
186         gboolean verbose;
187         char *tool_prefix;
188         char *ld_flags;
189         char *mtriple;
190         char *llvm_path;
191         char *temp_path;
192         char *instances_logfile_path;
193         char *logfile;
194         gboolean dump_json;
195         gboolean profile_only;
196 } MonoAotOptions;
197
198 typedef enum {
199         METHOD_CAT_NORMAL,
200         METHOD_CAT_GSHAREDVT,
201         METHOD_CAT_INST,
202         METHOD_CAT_WRAPPER,
203         METHOD_CAT_NUM
204 } MethodCategory;
205
206 typedef struct MonoAotStats {
207         int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
208         gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
209         int methods_without_got_slots, direct_calls, all_calls, llvm_count;
210         int got_slots, offsets_size;
211         int method_categories [METHOD_CAT_NUM];
212         int got_slot_types [MONO_PATCH_INFO_NUM];
213         int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
214         int jit_time, gen_time, link_time;
215 } MonoAotStats;
216
217 typedef struct GotInfo {
218         GHashTable *patch_to_got_offset;
219         GHashTable **patch_to_got_offset_by_type;
220         GPtrArray *got_patches;
221 } GotInfo;
222
223 typedef struct MonoAotCompile {
224         MonoImage *image;
225         GPtrArray *methods;
226         GHashTable *method_indexes;
227         GHashTable *method_depth;
228         MonoCompile **cfgs;
229         int cfgs_size;
230         GHashTable **patch_to_plt_entry;
231         GHashTable *plt_offset_to_entry;
232         //GHashTable *patch_to_got_offset;
233         //GHashTable **patch_to_got_offset_by_type;
234         //GPtrArray *got_patches;
235         GotInfo got_info, llvm_got_info;
236         GHashTable *image_hash;
237         GHashTable *method_to_cfg;
238         GHashTable *token_info_hash;
239         GHashTable *method_to_pinvoke_import;
240         GPtrArray *extra_methods;
241         GPtrArray *image_table;
242         GPtrArray *globals;
243         GPtrArray *method_order;
244         GHashTable *export_names;
245         /* Maps MonoClass* -> blob offset */
246         GHashTable *klass_blob_hash;
247         /* Maps MonoMethod* -> blob offset */
248         GHashTable *method_blob_hash;
249         GHashTable *gsharedvt_in_signatures;
250         GHashTable *gsharedvt_out_signatures;
251         guint32 *plt_got_info_offsets;
252         guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
253         /* Number of GOT entries reserved for trampolines */
254         guint32 num_trampoline_got_entries;
255         guint32 tramp_page_size;
256
257         guint32 table_offsets [MONO_AOT_TABLE_NUM];
258         guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
259         guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
260         guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
261         guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
262
263         MonoAotOptions aot_opts;
264         guint32 nmethods;
265         guint32 opts;
266         guint32 simd_opts;
267         MonoMemPool *mempool;
268         MonoAotStats stats;
269         int method_index;
270         char *static_linking_symbol;
271         mono_mutex_t mutex;
272         gboolean gas_line_numbers;
273         /* Whenever to emit an object file directly from llc */
274         gboolean llvm_owriter;
275         gboolean llvm_owriter_supported;
276         MonoImageWriter *w;
277         MonoDwarfWriter *dwarf;
278         FILE *fp;
279         char *tmpbasename;
280         char *tmpfname;
281         char *llvm_sfile;
282         char *llvm_ofile;
283         GSList *cie_program;
284         GHashTable *unwind_info_offsets;
285         GPtrArray *unwind_ops;
286         guint32 unwind_info_offset;
287         char *global_prefix;
288         char *got_symbol;
289         char *llvm_got_symbol;
290         char *plt_symbol;
291         char *llvm_eh_frame_symbol;
292         GHashTable *method_label_hash;
293         const char *temp_prefix;
294         const char *user_symbol_prefix;
295         const char *llvm_label_prefix;
296         const char *inst_directive;
297         int align_pad_value;
298         guint32 label_generator;
299         gboolean llvm;
300         gboolean has_jitted_code;
301         MonoAotFileFlags flags;
302         MonoDynamicStream blob;
303         gboolean blob_closed;
304         GHashTable *typespec_classes;
305         GString *llc_args;
306         GString *as_args;
307         char *assembly_name_sym;
308         GHashTable *plt_entry_debug_sym_cache;
309         gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
310         GHashTable *ginst_hash;
311         GHashTable *dwarf_ln_filenames;
312         gboolean global_symbols;
313         int objc_selector_index, objc_selector_index_2;
314         GPtrArray *objc_selectors;
315         GHashTable *objc_selector_to_index;
316         GList *profile_data;
317         GHashTable *profile_methods;
318         FILE *logfile;
319         FILE *instances_logfile;
320         FILE *data_outfile;
321         int datafile_offset;
322         int gc_name_offset;
323 } MonoAotCompile;
324
325 typedef struct {
326         int plt_offset;
327         char *symbol, *llvm_symbol, *debug_sym;
328         MonoJumpInfo *ji;
329         gboolean jit_used, llvm_used;
330 } MonoPltEntry;
331
332 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
333 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
334
335 /* This points to the current acfg in LLVM mode */
336 static MonoAotCompile *llvm_acfg;
337
338 #ifdef HAVE_ARRAY_ELEM_INIT
339 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
340 #define MSGSTRFIELD1(line) str##line
341 static const struct msgstr_t {
342 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
343 #include "patch-info.h"
344 #undef PATCH_INFO
345 } opstr = {
346 #define PATCH_INFO(a,b) b,
347 #include "patch-info.h"
348 #undef PATCH_INFO
349 };
350 static const gint16 opidx [] = {
351 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
352 #include "patch-info.h"
353 #undef PATCH_INFO
354 };
355
356 static G_GNUC_UNUSED const char*
357 get_patch_name (int info)
358 {
359         return (const char*)&opstr + opidx [info];
360 }
361
362 #else
363 #define PATCH_INFO(a,b) b,
364 static const char* const
365 patch_types [MONO_PATCH_INFO_NUM + 1] = {
366 #include "patch-info.h"
367         NULL
368 };
369
370 static G_GNUC_UNUSED const char*
371 get_patch_name (int info)
372 {
373         return patch_types [info];
374 }
375
376 #endif
377
378 static guint32
379 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
380
381 static char*
382 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
383
384 static void
385 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out);
386
387 static void
388 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
389
390 static void
391 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
392 {
393         FILE *output;
394         va_list args;
395
396         if (acfg->logfile)
397                 output = acfg->logfile;
398         else
399                 output = stdout;
400
401         va_start (args, format);
402         vfprintf (output, format, args);
403         va_end (args);
404 }
405
406 static void
407 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
408 {
409         FILE *output;
410         va_list args;
411
412         if (acfg->logfile)
413                 output = acfg->logfile;
414         else
415                 output = stderr;
416
417         va_start (args, format);
418         vfprintf (output, format, args);
419         va_end (args);
420 }
421
422 static void
423 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
424 {
425         FILE *output;
426         va_list args;
427
428         if (mono_error_ok (error))
429                 return;
430
431         if (acfg->logfile)
432                 output = acfg->logfile;
433         else
434                 output = stderr;
435
436         va_start (args, format);
437         vfprintf (output, format, args);
438         va_end (args);
439         mono_error_cleanup (error);
440
441         g_error ("FullAOT cannot continue if there are loader errors");
442 }
443
444 /* Wrappers around the image writer functions */
445
446 #define MAX_SYMBOL_SIZE 256
447
448 static inline const char *
449 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
450 {
451         gsize needed_size = length;
452
453         g_assert (NULL != symbol);
454         g_assert (NULL != mangled_symbol);
455         g_assert (0 != length);
456
457 #if defined(TARGET_WIN32) && defined(TARGET_X86)
458         if (symbol && '_' != symbol [0]) {
459                 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
460         } else {
461                 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
462         }
463 #else
464         needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
465 #endif
466
467         g_assert (0 <= needed_size && needed_size < length);
468         return mangled_symbol;
469 }
470
471 static inline char *
472 mangle_symbol_alloc (const char * symbol)
473 {
474         g_assert (NULL != symbol);
475
476 #if defined(TARGET_WIN32) && defined(TARGET_X86)
477         if (symbol && '_' != symbol [0]) {
478                 return g_strdup_printf ("_%s", symbol);
479         }
480         else {
481                 return g_strdup_printf ("%s", symbol);
482         }
483 #else
484         return g_strdup_printf ("%s", symbol);
485 #endif
486 }
487
488 static inline void
489 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
490 {
491         mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
492 }
493
494 #if defined(TARGET_WIN32) && defined(TARGET_X86)
495
496 static inline void
497 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
498 {
499         const char * mangled_symbol_name = name;
500         char * mangled_symbol_name_alloc = NULL;
501
502         if (TRUE == func) {
503                 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
504                 mangled_symbol_name = mangled_symbol_name_alloc;
505         }
506
507         if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
508                 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
509         }
510         mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
511
512         if (NULL != mangled_symbol_name_alloc) {
513                 g_free (mangled_symbol_name_alloc);
514         }
515 }
516
517 #else
518
519 static inline void
520 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
521
522         mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
523 }
524
525 #endif
526
527 static inline void
528 emit_label (MonoAotCompile *acfg, const char *name) 
529
530         mono_img_writer_emit_label (acfg->w, name); 
531 }
532
533 static inline void
534 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
535
536         mono_img_writer_emit_bytes (acfg->w, buf, size); 
537 }
538
539 static inline void
540 emit_string (MonoAotCompile *acfg, const char *value) 
541
542         mono_img_writer_emit_string (acfg->w, value); 
543 }
544
545 static inline void
546 emit_line (MonoAotCompile *acfg) 
547
548         mono_img_writer_emit_line (acfg->w); 
549 }
550
551 static inline void
552 emit_alignment (MonoAotCompile *acfg, int size)
553
554         mono_img_writer_emit_alignment (acfg->w, size);
555 }
556
557 static inline void
558 emit_alignment_code (MonoAotCompile *acfg, int size)
559 {
560         if (acfg->align_pad_value)
561                 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
562         else
563                 mono_img_writer_emit_alignment (acfg->w, size);
564 }
565
566 static inline void
567 emit_padding (MonoAotCompile *acfg, int size)
568 {
569         int i;
570         guint8 buf [16];
571
572         if (acfg->align_pad_value) {
573                 for (i = 0; i < 16; ++i)
574                         buf [i] = acfg->align_pad_value;
575         } else {
576                 memset (buf, 0, sizeof (buf));
577         }
578
579         for (i = 0; i < size; i += 16) {
580                 if (size - i < 16)
581                         emit_bytes (acfg, buf, size - i);
582                 else
583                         emit_bytes (acfg, buf, 16);
584         }
585 }
586
587 static inline void
588 emit_pointer (MonoAotCompile *acfg, const char *target) 
589
590         mono_img_writer_emit_pointer (acfg->w, target); 
591 }
592
593 static inline void
594 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target) 
595
596         if (prefix [0] != '\0') {
597                 char *s = g_strdup_printf ("%s%s", prefix, target);
598                 mono_img_writer_emit_pointer (acfg->w, s);
599                 g_free (s);
600         } else {
601                 mono_img_writer_emit_pointer (acfg->w, target);
602         }
603 }
604
605 static inline void
606 emit_int16 (MonoAotCompile *acfg, int value) 
607
608         mono_img_writer_emit_int16 (acfg->w, value); 
609 }
610
611 static inline void
612 emit_int32 (MonoAotCompile *acfg, int value) 
613
614         mono_img_writer_emit_int32 (acfg->w, value); 
615 }
616
617 static inline void
618 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
619
620         mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
621 }
622
623 static inline void
624 emit_zero_bytes (MonoAotCompile *acfg, int num) 
625
626         mono_img_writer_emit_zero_bytes (acfg->w, num); 
627 }
628
629 static inline void
630 emit_byte (MonoAotCompile *acfg, guint8 val) 
631
632         mono_img_writer_emit_byte (acfg->w, val); 
633 }
634
635 #if defined(TARGET_WIN32) && defined(TARGET_X86)
636
637 static G_GNUC_UNUSED void
638 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
639 {
640         const char * mangled_symbol_name = name;
641         char * mangled_symbol_name_alloc = NULL;
642
643         mangled_symbol_name_alloc = mangle_symbol_alloc (name);
644         mangled_symbol_name = mangled_symbol_name_alloc;
645         
646         if (0 != g_strcasecmp (name, mangled_symbol_name)) {
647                 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
648         }
649         mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
650
651         if (NULL != mangled_symbol_name_alloc) {
652                 g_free (mangled_symbol_name_alloc);
653         }
654 }
655
656 #else
657
658 static G_GNUC_UNUSED void
659 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
660 {
661         mono_img_writer_emit_global (acfg->w, name, func);
662 }
663
664 #endif
665
666 static inline gboolean
667 link_shared_library (MonoAotCompile *acfg)
668 {
669         return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
670 }
671
672 static inline gboolean
673 add_to_global_symbol_table (MonoAotCompile *acfg)
674 {
675 #ifdef TARGET_WIN32_MSVC
676         return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
677 #else
678         return acfg->aot_opts.no_dlsym;
679 #endif
680 }
681
682 static void
683 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
684 {
685         if (add_to_global_symbol_table (acfg))
686                 g_ptr_array_add (acfg->globals, g_strdup (name));
687
688         if (acfg->aot_opts.no_dlsym) {
689                 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
690         } else {
691                 emit_global_inner (acfg, name, func);
692         }
693 }
694
695 static void
696 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
697 {
698         mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
699 }
700
701 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
702 static void
703 emit_info_symbol (MonoAotCompile *acfg, const char *name)
704 {
705         char symbol [MAX_SYMBOL_SIZE];
706
707         if (acfg->llvm) {
708                 emit_label (acfg, name);
709                 /* LLVM generated code references this */
710                 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
711                 emit_label (acfg, symbol);
712                 emit_global_inner (acfg, symbol, FALSE);
713         } else {
714                 emit_label (acfg, name);
715         }
716 }
717
718 static void
719 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
720 {
721         if (acfg->llvm) {
722                 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
723                 return;
724         }
725
726         mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
727 #ifdef TARGET_MACH
728         /* On apple, all symbols need to be aligned to avoid warnings from ld */
729         emit_alignment (acfg, 4);
730 #endif
731         mono_img_writer_emit_label (acfg->w, name);
732         mono_img_writer_emit_string (acfg->w, value);
733 }
734
735 static G_GNUC_UNUSED void
736 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
737 {
738         do {
739                 guint8 b = value & 0x7f;
740                 value >>= 7;
741                 if (value != 0) /* more bytes to come */
742                         b |= 0x80;
743                 emit_byte (acfg, b);
744         } while (value);
745 }
746
747 static G_GNUC_UNUSED void
748 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
749 {
750         gboolean more = 1;
751         gboolean negative = (value < 0);
752         guint32 size = 64;
753         guint8 byte;
754
755         while (more) {
756                 byte = value & 0x7f;
757                 value >>= 7;
758                 /* the following is unnecessary if the
759                  * implementation of >>= uses an arithmetic rather
760                  * than logical shift for a signed left operand
761                  */
762                 if (negative)
763                         /* sign extend */
764                         value |= - ((gint64)1 <<(size - 7));
765                 /* sign bit of byte is second high order bit (0x40) */
766                 if ((value == 0 && !(byte & 0x40)) ||
767                         (value == -1 && (byte & 0x40)))
768                         more = 0;
769                 else
770                         byte |= 0x80;
771                 emit_byte (acfg, byte);
772         }
773 }
774
775 static G_GNUC_UNUSED void
776 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
777 {
778         guint8 *p = buf;
779
780         do {
781                 guint8 b = value & 0x7f;
782                 value >>= 7;
783                 if (value != 0) /* more bytes to come */
784                         b |= 0x80;
785                 *p ++ = b;
786         } while (value);
787
788         *endbuf = p;
789 }
790
791 static G_GNUC_UNUSED void
792 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
793 {
794         gboolean more = 1;
795         gboolean negative = (value < 0);
796         guint32 size = 32;
797         guint8 byte;
798         guint8 *p = buf;
799
800         while (more) {
801                 byte = value & 0x7f;
802                 value >>= 7;
803                 /* the following is unnecessary if the
804                  * implementation of >>= uses an arithmetic rather
805                  * than logical shift for a signed left operand
806                  */
807                 if (negative)
808                         /* sign extend */
809                         value |= - (1 <<(size - 7));
810                 /* sign bit of byte is second high order bit (0x40) */
811                 if ((value == 0 && !(byte & 0x40)) ||
812                         (value == -1 && (byte & 0x40)))
813                         more = 0;
814                 else
815                         byte |= 0x80;
816                 *p ++= byte;
817         }
818
819         *endbuf = p;
820 }
821
822 static void
823 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
824 {
825         // FIXME: Big-endian
826         buf [0] = (val >> 0) & 0xff;
827         buf [1] = (val >> 8) & 0xff;
828         buf [2] = (val >> 16) & 0xff;
829         buf [3] = (val >> 24) & 0xff;
830
831         *endbuf = buf + 4;
832 }
833
834 static void
835 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
836 {
837         buf [0] = (val >> 0) & 0xff;
838         buf [1] = (val >> 8) & 0xff;
839
840         *endbuf = buf + 2;
841 }
842
843 static void
844 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
845 {
846         int len = strlen (s);
847
848         memcpy (buf, s, len + 1);
849         *endbuf = buf + len + 1;
850 }
851
852 static void
853 emit_unset_mode (MonoAotCompile *acfg)
854 {
855         mono_img_writer_emit_unset_mode (acfg->w);
856 }
857
858 static G_GNUC_UNUSED void
859 emit_set_thumb_mode (MonoAotCompile *acfg)
860 {
861         emit_unset_mode (acfg);
862         fprintf (acfg->fp, ".code 16\n");
863 }
864
865 static G_GNUC_UNUSED void
866 emit_set_arm_mode (MonoAotCompile *acfg)
867 {
868         emit_unset_mode (acfg);
869         fprintf (acfg->fp, ".code 32\n");
870 }
871
872 static inline void
873 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
874 {
875 #ifdef TARGET_ARM64
876         int i;
877
878         g_assert (size % 4 == 0);
879         emit_unset_mode (acfg);
880         for (i = 0; i < size; i += 4)
881                 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
882 #else
883         emit_bytes (acfg, buf, size);
884 #endif
885 }
886
887 /* ARCHITECTURE SPECIFIC CODE */
888
889 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
890 #define EMIT_DWARF_INFO 1
891 #endif
892
893 #ifdef TARGET_WIN32_MSVC
894 #undef EMIT_DWARF_INFO
895 #endif
896
897 #if defined(TARGET_ARM)
898 #define AOT_FUNC_ALIGNMENT 4
899 #else
900 #define AOT_FUNC_ALIGNMENT 16
901 #endif
902  
903 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
904 #define PPC_LD_OP "ld"
905 #define PPC_LDX_OP "ldx"
906 #else
907 #define PPC_LD_OP "lwz"
908 #define PPC_LDX_OP "lwzx"
909 #endif
910
911 #ifdef TARGET_X86_64_WIN32_MSVC
912 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
913 #elif TARGET_AMD64
914 #define AOT_TARGET_STR "AMD64"
915 #endif
916
917 #ifdef TARGET_ARM
918 #ifdef TARGET_MACH
919 #define AOT_TARGET_STR "ARM (MACH)"
920 #else
921 #define AOT_TARGET_STR "ARM (!MACH)"
922 #endif
923 #endif
924
925 #ifdef TARGET_ARM64
926 #ifdef TARGET_MACH
927 #define AOT_TARGET_STR "ARM64 (MACH)"
928 #else
929 #define AOT_TARGET_STR "ARM64 (!MACH)"
930 #endif
931 #endif
932
933 #ifdef TARGET_POWERPC64
934 #ifdef __mono_ilp32__
935 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
936 #else
937 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
938 #endif
939 #else
940 #ifdef TARGET_POWERPC
941 #ifdef __mono_ilp32__
942 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
943 #else
944 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
945 #endif
946 #endif
947 #endif
948
949 #ifdef TARGET_X86
950 #ifdef TARGET_WIN32
951 #define AOT_TARGET_STR "X86 (WIN32)"
952 #elif defined(__native_client_codegen__)
953 #define AOT_TARGET_STR "X86 (native client codegen)"
954 #else
955 #define AOT_TARGET_STR "X86 (!native client codegen)"
956 #endif
957 #endif
958
959 #ifndef AOT_TARGET_STR
960 #define AOT_TARGET_STR ""
961 #endif
962
963 static void
964 arch_init (MonoAotCompile *acfg)
965 {
966         acfg->llc_args = g_string_new ("");
967         acfg->as_args = g_string_new ("");
968         acfg->llvm_owriter_supported = TRUE;
969
970         /*
971          * The prefix LLVM likes to put in front of symbol names on darwin.
972          * The mach-os specs require this for globals, but LLVM puts them in front of all
973          * symbols. We need to handle this, since we need to refer to LLVM generated
974          * symbols.
975          */
976         acfg->llvm_label_prefix = "";
977         acfg->user_symbol_prefix = "";
978
979 #if defined(TARGET_X86)
980         g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
981 #endif
982
983 #if defined(TARGET_AMD64)
984         g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
985         /* NOP */
986         acfg->align_pad_value = 0x90;
987 #endif
988
989 #ifdef TARGET_ARM
990         if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
991                 g_string_append (acfg->llc_args, "-mattr=+v6");
992         } else {
993 #if defined(ARM_FPU_VFP_HARD)
994                 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
995                 g_string_append (acfg->as_args, " -mfpu=vfp3");
996 #elif defined(ARM_FPU_VFP)
997                 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
998                 g_string_append (acfg->as_args, " -mfpu=vfp3");
999 #else
1000                 g_string_append (acfg->llc_args, " -soft-float");
1001 #endif
1002         }
1003         if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1004                 acfg->thumb_mixed = TRUE;
1005
1006         if (acfg->aot_opts.mtriple)
1007                 mono_arch_set_target (acfg->aot_opts.mtriple);
1008 #endif
1009
1010 #ifdef TARGET_ARM64
1011         acfg->inst_directive = ".inst";
1012         if (acfg->aot_opts.mtriple)
1013                 mono_arch_set_target (acfg->aot_opts.mtriple);
1014 #endif
1015
1016 #ifdef TARGET_MACH
1017         acfg->user_symbol_prefix = "_";
1018         acfg->llvm_label_prefix = "_";
1019         acfg->inst_directive = ".word";
1020         acfg->need_no_dead_strip = TRUE;
1021         acfg->aot_opts.gnu_asm = TRUE;
1022 #endif
1023
1024 #if defined(__linux__) && !defined(TARGET_ARM)
1025         acfg->need_pt_gnu_stack = TRUE;
1026 #endif
1027
1028 #ifdef MONOTOUCH
1029         acfg->global_symbols = TRUE;
1030 #endif
1031
1032 #ifdef TARGET_ANDROID
1033         acfg->llvm_owriter_supported = FALSE;
1034 #endif
1035 }
1036
1037 #ifdef TARGET_ARM64
1038
1039
1040 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1041 static void
1042 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1043 {
1044         int offset;
1045
1046         g_assert (acfg->fp);
1047         emit_unset_mode (acfg);
1048         /* r16==ip0 */
1049         offset = (int)(got_slot * sizeof (gpointer));
1050 #ifdef TARGET_MACH
1051         /* clang's integrated assembler */
1052         fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1053         fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1054         fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1055 #else
1056         /* Linux GAS */
1057         fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1058         fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1059         fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1060 #endif
1061 }
1062
1063 static void
1064 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1065 {
1066         int reg;
1067
1068         g_assert (acfg->fp);
1069         emit_unset_mode (acfg);
1070
1071         /* ldr rt, target */
1072         reg = arm_get_ldr_lit_reg (code);
1073
1074         fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1075         fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1076         fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1077
1078         *code_size = 12;
1079 }
1080
1081 static void
1082 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1083 {
1084         g_assert (acfg->fp);
1085         emit_unset_mode (acfg);
1086         if (ji && ji->relocation == MONO_R_ARM64_B) {
1087                 fprintf (acfg->fp, "b %s\n", target);
1088         } else {
1089                 if (ji)
1090                         g_assert (ji->relocation == MONO_R_ARM64_BL);
1091                 fprintf (acfg->fp, "bl %s\n", target);
1092         }
1093         *call_size = 4;
1094 }
1095
1096 static void
1097 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1098 {
1099         int reg;
1100
1101         /* ldr rt, target */
1102         reg = arm_get_ldr_lit_reg (code);
1103         arm64_emit_load_got_slot (acfg, reg, got_slot);
1104         *code_size = 12;
1105 }
1106
1107 static void
1108 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1109 {
1110         arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1111         fprintf (acfg->fp, "br x16\n");
1112         /* Used by mono_aot_get_plt_info_offset () */
1113         fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1114 }
1115
1116 static void
1117 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1118 {
1119         guint8 buf [256];
1120         guint8 *code;
1121         int imm;
1122
1123         /* The common code */
1124         code = buf;
1125         imm = pagesize;
1126         /* The trampoline address is in IP0 */
1127         arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1128         arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1129         /* Compute the data slot address */
1130         arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1131         /* Trampoline argument */
1132         arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1133         /* Address */
1134         arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1135         arm_brx (code, ARMREG_IP0);
1136
1137         /* Emit it */
1138         emit_code_bytes (acfg, buf, code - buf);
1139
1140         *size = code - buf;
1141 }
1142
1143 static void
1144 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1145 {
1146         guint8 buf [256];
1147         guint8 *code;
1148         int i, count;
1149
1150         count = (pagesize - common_tramp_size) / specific_tramp_size;
1151         for (i = 0; i < count; ++i) {
1152                 code = buf;
1153                 arm_adrx (code, ARMREG_IP0, code);
1154                 /* Branch to the generic code */
1155                 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1156                 /* This has to be 2 pointers long */
1157                 arm_nop (code);
1158                 arm_nop (code);
1159                 g_assert (code - buf == specific_tramp_size);
1160                 emit_code_bytes (acfg, buf, code - buf);
1161         }
1162 }
1163
1164 static void
1165 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1166 {
1167         guint8 buf [128];
1168         guint8 *code;
1169         guint8 *labels [16];
1170         int common_tramp_size;
1171         int specific_tramp_size = 2 * 8;
1172         int imm, pagesize;
1173         char symbol [128];
1174
1175         if (!acfg->aot_opts.use_trampolines_page)
1176                 return;
1177
1178 #ifdef TARGET_MACH
1179         /* Have to match the target pagesize */
1180         pagesize = 16384;
1181 #else
1182         pagesize = mono_pagesize ();
1183 #endif
1184         acfg->tramp_page_size = pagesize;
1185
1186         /* The specific trampolines */
1187         sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1188         emit_alignment (acfg, pagesize);
1189         emit_global (acfg, symbol, TRUE);
1190         emit_label (acfg, symbol);
1191
1192         /* The common code */
1193         arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1194         acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1195
1196         arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1197
1198         /* The rgctx trampolines */
1199         /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1200         sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1201         emit_alignment (acfg, pagesize);
1202         emit_global (acfg, symbol, TRUE);
1203         emit_label (acfg, symbol);
1204
1205         /* The common code */
1206         arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1207         acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1208
1209         arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1210
1211         /* The gsharedvt arg trampolines */
1212         /* These are the same as the specific trampolines */
1213         sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1214         emit_alignment (acfg, pagesize);
1215         emit_global (acfg, symbol, TRUE);
1216         emit_label (acfg, symbol);
1217
1218         arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1219         acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1220
1221         arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1222
1223         /* The IMT trampolines */
1224         sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1225         emit_alignment (acfg, pagesize);
1226         emit_global (acfg, symbol, TRUE);
1227         emit_label (acfg, symbol);
1228
1229         code = buf;
1230         imm = pagesize;
1231         /* The trampoline address is in IP0 */
1232         arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1233         arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1234         /* Compute the data slot address */
1235         arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1236         /* Trampoline argument */
1237         arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1238
1239         /* Same as arch_emit_imt_trampoline () */
1240         labels [0] = code;
1241         arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1242         arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1243         labels [1] = code;
1244         arm_bcc (code, ARMCOND_EQ, 0);
1245
1246         /* End-of-loop check */
1247         labels [2] = code;
1248         arm_cbzx (code, ARMREG_IP0, 0);
1249
1250         /* Loop footer */
1251         arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1252         arm_b (code, labels [0]);
1253
1254         /* Match */
1255         mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1256         /* Load vtable slot addr */
1257         arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1258         /* Load vtable slot */
1259         arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1260         arm_brx (code, ARMREG_IP0);
1261
1262         /* No match */
1263         mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1264         /* Load fail addr */
1265         arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1266         arm_brx (code, ARMREG_IP0);
1267
1268         emit_code_bytes (acfg, buf, code - buf);
1269
1270         common_tramp_size = code - buf;
1271         acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1272
1273         arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1274 }
1275
1276 static void
1277 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1278 {
1279         /* Load argument from second GOT slot */
1280         arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1281         /* Load generic trampoline address from first GOT slot */
1282         arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1283         fprintf (acfg->fp, "br x16\n");
1284         *tramp_size = 7 * 4;
1285 }
1286
1287 static void
1288 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1289 {
1290         emit_unset_mode (acfg);
1291         fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1292         fprintf (acfg->fp, "b %s\n", call_target);
1293 }
1294
1295 static void
1296 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1297 {
1298         /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1299
1300         /* Load argument from first GOT slot */
1301         arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1302         /* Load generic trampoline address from second GOT slot */
1303         arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1304         fprintf (acfg->fp, "br x16\n");
1305         *tramp_size = 7 * 4;
1306 }
1307
1308 static void
1309 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1310 {
1311         guint8 buf [128];
1312         guint8 *code, *labels [16];
1313
1314         /* Load parameter from GOT slot into ip1 */
1315         arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1316
1317         code = buf;
1318         labels [0] = code;
1319         arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1320         arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1321         labels [1] = code;
1322         arm_bcc (code, ARMCOND_EQ, 0);
1323
1324         /* End-of-loop check */
1325         labels [2] = code;
1326         arm_cbzx (code, ARMREG_IP0, 0);
1327
1328         /* Loop footer */
1329         arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1330         arm_b (code, labels [0]);
1331
1332         /* Match */
1333         mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1334         /* Load vtable slot addr */
1335         arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1336         /* Load vtable slot */
1337         arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1338         arm_brx (code, ARMREG_IP0);
1339
1340         /* No match */
1341         mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1342         /* Load fail addr */
1343         arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1344         arm_brx (code, ARMREG_IP0);
1345
1346         emit_code_bytes (acfg, buf, code - buf);
1347
1348         *tramp_size = code - buf + (3 * 4);
1349 }
1350
1351 static void
1352 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1353 {
1354         /* Similar to the specific trampolines, but the address is in the second slot */
1355         /* Load argument from first GOT slot */
1356         arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1357         /* Load generic trampoline address from second GOT slot */
1358         arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1359         fprintf (acfg->fp, "br x16\n");
1360         *tramp_size = 7 * 4;
1361 }
1362
1363
1364 #endif
1365
1366 #ifdef MONO_ARCH_AOT_SUPPORTED
1367 /*
1368  * arch_emit_direct_call:
1369  *
1370  *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1371  * calling code.
1372  */
1373 static void
1374 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1375 {
1376 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1377         /* Need to make sure this is exactly 5 bytes long */
1378         emit_unset_mode (acfg);
1379         fprintf (acfg->fp, "call %s\n", target);
1380         *call_size = 5;
1381 #elif defined(TARGET_ARM)
1382         emit_unset_mode (acfg);
1383         if (thumb)
1384                 fprintf (acfg->fp, "blx %s\n", target);
1385         else
1386                 fprintf (acfg->fp, "bl %s\n", target);
1387         *call_size = 4;
1388 #elif defined(TARGET_ARM64)
1389         arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1390 #elif defined(TARGET_POWERPC)
1391         emit_unset_mode (acfg);
1392         fprintf (acfg->fp, "bl %s\n", target);
1393         *call_size = 4;
1394 #else
1395         g_assert_not_reached ();
1396 #endif
1397 }
1398 #endif
1399
1400 /*
1401  * PPC32 design:
1402  * - we use an approach similar to the x86 abi: reserve a register (r30) to hold 
1403  *   the GOT pointer.
1404  * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1405  *   in in the 2. slot of every GOT, and require every method to place the GOT
1406  *   address in r30, even when it doesn't access the GOT otherwise. This way,
1407  *   the trampolines can compute the mscorlib GOT address by loading 4(r30).
1408  */
1409
1410 /*
1411  * PPC64 design:
1412  * PPC64 uses function descriptors which greatly complicate all code, since
1413  * these are used very inconsistently in the runtime. Some functions like 
1414  * mono_compile_method () return ftn descriptors, while others like the
1415  * trampoline creation functions do not.
1416  * We assume that all GOT slots contain function descriptors, and create 
1417  * descriptors in aot-runtime.c when needed.
1418  * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1419  * from function descriptors, we could do the same, but it would require 
1420  * rewriting all the ppc/aot code to handle function descriptors properly.
1421  * So instead, we use the same approach as on PPC32.
1422  * This is a horrible mess, but fixing it would probably lead to an even bigger
1423  * one.
1424  */
1425
1426 /*
1427  * X86 design:
1428  * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1429  */
1430
1431 #ifdef MONO_ARCH_AOT_SUPPORTED
1432 /*
1433  * arch_emit_got_offset:
1434  *
1435  *   The memory pointed to by CODE should hold native code for computing the GOT
1436  * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1437  * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1438  */
1439 static void
1440 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1441 {
1442 #if defined(TARGET_POWERPC64)
1443         emit_unset_mode (acfg);
1444         /* 
1445          * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1446          * unsupported relocations. So we store the got address into the .Lgot_addr
1447          * symbol which is in the text segment, compute its address, and load it.
1448          */
1449         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1450         fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1451         fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1452         fprintf (acfg->fp, "add 30, 30, 0\n");
1453         fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1454         acfg->label_generator ++;
1455         *code_size = 16;
1456 #elif defined(TARGET_POWERPC)
1457         emit_unset_mode (acfg);
1458         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1459         fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1460         fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1461         acfg->label_generator ++;
1462         *code_size = 8;
1463 #else
1464         guint32 offset = mono_arch_get_patch_offset (code);
1465         emit_bytes (acfg, code, offset);
1466         emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1467
1468         *code_size = offset + 4;
1469 #endif
1470 }
1471
1472 /*
1473  * arch_emit_got_access:
1474  *
1475  *   The memory pointed to by CODE should hold native code for loading a GOT
1476  * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1477  * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1478  */
1479 static void
1480 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1481 {
1482 #ifdef TARGET_AMD64
1483         /* mov reg, got+offset(%rip) */
1484         if (acfg->llvm) {
1485                 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1486                 int dreg;
1487                 int rex_r;
1488
1489                 /* Decode reg, see amd64_mov_reg_membase () */
1490                 rex_r = code [0] & AMD64_REX_R;
1491                 g_assert (code [0] == 0x49 + rex_r);
1492                 g_assert (code [1] == 0x8b);
1493                 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1494
1495                 emit_unset_mode (acfg);
1496                 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1497                 *code_size = 7;
1498         } else {
1499                 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1500                 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1501                 *code_size = mono_arch_get_patch_offset (code) + 4;
1502         }
1503 #elif defined(TARGET_X86)
1504         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1505         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1506         *code_size = mono_arch_get_patch_offset (code) + 4;
1507 #elif defined(TARGET_ARM)
1508         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1509         emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1510         *code_size = mono_arch_get_patch_offset (code) + 4;
1511 #elif defined(TARGET_ARM64)
1512         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1513         arm64_emit_got_access (acfg, code, got_slot, code_size);
1514 #elif defined(TARGET_POWERPC)
1515         {
1516                 guint8 buf [32];
1517
1518                 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1519                 code = buf;
1520                 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1521                 g_assert (code - buf == 8);
1522                 emit_bytes (acfg, buf, code - buf);
1523                 *code_size = code - buf;
1524         }
1525 #else
1526         g_assert_not_reached ();
1527 #endif
1528 }
1529
1530 #endif
1531
1532 #ifdef MONO_ARCH_AOT_SUPPORTED
1533 /*
1534  * arch_emit_objc_selector_ref:
1535  *
1536  *   Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1537  */
1538 static void
1539 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1540 {
1541 #if defined(TARGET_ARM)
1542         char symbol1 [MAX_SYMBOL_SIZE];
1543         char symbol2 [MAX_SYMBOL_SIZE];
1544         int lindex = acfg->objc_selector_index_2 ++;
1545
1546         /* Emit ldr.imm/b */
1547         emit_bytes (acfg, code, 8);
1548
1549         sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1550         sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1551
1552         emit_label (acfg, symbol1);
1553         mono_img_writer_emit_unset_mode (acfg->w);
1554         fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1555
1556         *code_size = 12;
1557 #elif defined(TARGET_ARM64)
1558         arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1559 #else
1560         g_assert_not_reached ();
1561 #endif
1562 }
1563 #endif
1564
1565 /*
1566  * arch_emit_plt_entry:
1567  *
1568  *   Emit code for the PLT entry.
1569  * The plt entry should look like this:
1570  * <indirect jump to GOT_SYMBOL + OFFSET>
1571  * <INFO_OFFSET embedded into the instruction stream>
1572  */
1573 static void
1574 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1575 {
1576 #if defined(TARGET_X86)
1577                 /* jmp *<offset>(%ebx) */
1578                 emit_byte (acfg, 0xff);
1579                 emit_byte (acfg, 0xa3);
1580                 emit_int32 (acfg, offset);
1581                 /* Used by mono_aot_get_plt_info_offset */
1582                 emit_int32 (acfg, info_offset);
1583 #elif defined(TARGET_AMD64)
1584                 emit_unset_mode (acfg);
1585                 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1586                 /* Used by mono_aot_get_plt_info_offset */
1587                 emit_int32 (acfg, info_offset);
1588                 acfg->stats.plt_size += 10;
1589 #elif defined(TARGET_ARM)
1590                 guint8 buf [256];
1591                 guint8 *code;
1592
1593                 code = buf;
1594                 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1595                 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1596                 emit_bytes (acfg, buf, code - buf);
1597                 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1598                 /* Used by mono_aot_get_plt_info_offset */
1599                 emit_int32 (acfg, info_offset);
1600 #elif defined(TARGET_ARM64)
1601                 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1602 #elif defined(TARGET_POWERPC)
1603                 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1604                 emit_unset_mode (acfg);
1605                 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1606                 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1607                 fprintf (acfg->fp, "add 11, 11, 30\n");
1608                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1609 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1610                 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1611                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1612 #endif
1613                 fprintf (acfg->fp, "mtctr 11\n");
1614                 fprintf (acfg->fp, "bctr\n");
1615                 emit_int32 (acfg, info_offset);
1616 #else
1617                 g_assert_not_reached ();
1618 #endif
1619 }
1620
1621 /*
1622  * arch_emit_llvm_plt_entry:
1623  *
1624  *   Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1625  * This is only needed on arm to handle thumb interop.
1626  */
1627 static void
1628 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1629 {
1630 #if defined(TARGET_ARM)
1631         /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1632         /* The caller already transitioned to thumb */
1633         /* The code below should be 12 bytes long */
1634         /* clang has trouble encoding these instructions, so emit the binary */
1635 #if 0
1636         fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1637         /* thumb can't encode ld pc, [pc, ip] */
1638         fprintf (acfg->fp, "add ip, pc, ip\n");
1639         fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1640         fprintf (acfg->fp, "bx ip\n");
1641 #endif
1642         emit_set_thumb_mode (acfg);
1643         fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1644         fprintf (acfg->fp, ".2byte 0x44fc\n");
1645         fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1646         fprintf (acfg->fp, ".2byte 0x4760\n");
1647         emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1648         emit_int32 (acfg, info_offset);
1649         emit_unset_mode (acfg);
1650         emit_set_arm_mode (acfg);
1651 #else
1652         g_assert_not_reached ();
1653 #endif
1654 }
1655
1656 /* Save unwind_info in the module and emit the offset to the information at symbol */
1657 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1658 {
1659         guint32 uw_offset, encoded_len;
1660         guint8 *encoded;
1661
1662         emit_section_change (acfg, RODATA_SECT, 0);
1663         emit_global (acfg, symbol, FALSE);
1664         emit_label (acfg, symbol);
1665
1666         encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1667         uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1668         g_free (encoded);
1669         emit_int32 (acfg, uw_offset);
1670 }
1671
1672 /*
1673  * arch_emit_specific_trampoline_pages:
1674  *
1675  * Emits a page full of trampolines: each trampoline uses its own address to
1676  * lookup both the generic trampoline code and the data argument.
1677  * This page can be remapped in process multiple times so we can get an
1678  * unlimited number of trampolines.
1679  * Specifically this implementation uses the following trick: two memory pages
1680  * are allocated, with the first containing the data and the second containing the trampolines.
1681  * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1682  * implementation does all the lifting.
1683  * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1684  * on the arm 32 bit system.
1685  */
1686 static void
1687 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1688 {
1689 #if defined(TARGET_ARM)
1690         guint8 buf [128];
1691         guint8 *code;
1692         guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1693         int i;
1694         int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1695         GSList *unwind_ops = NULL;
1696 #define COMMON_TRAMP_SIZE 16
1697         int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1698         int imm8, rot_amount;
1699         char symbol [128];
1700
1701         if (!acfg->aot_opts.use_trampolines_page)
1702                 return;
1703
1704         acfg->tramp_page_size = pagesize;
1705
1706         sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1707         emit_alignment (acfg, pagesize);
1708         emit_global (acfg, symbol, TRUE);
1709         emit_label (acfg, symbol);
1710
1711         /* emit the generic code first, the trampoline address + 8 is in the lr register */
1712         code = buf;
1713         imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1714         ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1715         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1716         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1717         ARM_NOP (code);
1718         g_assert (code - buf == COMMON_TRAMP_SIZE);
1719
1720         /* Emit it */
1721         emit_bytes (acfg, buf, code - buf);
1722
1723         for (i = 0; i < count; ++i) {
1724                 code = buf;
1725                 ARM_PUSH (code, 0x5fff);
1726                 ARM_BL (code, 0);
1727                 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1728                 g_assert (code - buf == 8);
1729                 emit_bytes (acfg, buf, code - buf);
1730         }
1731
1732         /* now the rgctx trampolines: each specific trampolines puts in the ip register
1733          * the instruction pointer address, so the generic trampoline at the start of the page
1734          * subtracts 4096 to get to the data page and loads the values
1735          * We again fit the generic trampiline in 16 bytes.
1736          */
1737         sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1738         emit_global (acfg, symbol, TRUE);
1739         emit_label (acfg, symbol);
1740         code = buf;
1741         imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1742         ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1743         ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1744         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1745         ARM_NOP (code);
1746         g_assert (code - buf == COMMON_TRAMP_SIZE);
1747
1748         /* Emit it */
1749         emit_bytes (acfg, buf, code - buf);
1750
1751         for (i = 0; i < count; ++i) {
1752                 code = buf;
1753                 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1754                 ARM_B (code, 0);
1755                 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1756                 g_assert (code - buf == 8);
1757                 emit_bytes (acfg, buf, code - buf);
1758         }
1759
1760         /*
1761          * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1762          */
1763         sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1764         emit_global (acfg, symbol, TRUE);
1765         emit_label (acfg, symbol);
1766         code = buf;
1767         ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1768         imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1769         ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1770         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1771         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1772         g_assert (code - buf == COMMON_TRAMP_SIZE);
1773         /* Emit it */
1774         emit_bytes (acfg, buf, code - buf);
1775
1776         for (i = 0; i < count; ++i) {
1777                 code = buf;
1778                 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1779                 ARM_B (code, 0);
1780                 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1781                 g_assert (code - buf == 8);
1782                 emit_bytes (acfg, buf, code - buf);
1783         }
1784
1785         /* now the imt trampolines: each specific trampolines puts in the ip register
1786          * the instruction pointer address, so the generic trampoline at the start of the page
1787          * subtracts 4096 to get to the data page and loads the values
1788          */
1789 #define IMT_TRAMP_SIZE 72
1790         sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1791         emit_global (acfg, symbol, TRUE);
1792         emit_label (acfg, symbol);
1793         code = buf;
1794         /* Need at least two free registers, plus a slot for storing the pc */
1795         ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1796
1797         imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1798         ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1799         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1800
1801         /* The IMT method is in v5, r0 has the imt array address */
1802
1803         loop_start = code;
1804         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1805         ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1806         imt_found_check = code;
1807         ARM_B_COND (code, ARMCOND_EQ, 0);
1808
1809         /* End-of-loop check */
1810         ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1811         loop_end_check = code;
1812         ARM_B_COND (code, ARMCOND_EQ, 0);
1813
1814         /* Loop footer */
1815         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1816         loop_branch_back = code;
1817         ARM_B (code, 0);
1818         arm_patch (loop_branch_back, loop_start);
1819
1820         /* Match */
1821         arm_patch (imt_found_check, code);
1822         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1823         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1824         /* Save it to the third stack slot */
1825         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1826         /* Restore the registers and branch */
1827         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1828
1829         /* No match */
1830         arm_patch (loop_end_check, code);
1831         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1832         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1833         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1834         ARM_NOP (code);
1835
1836         /* Emit it */
1837         g_assert (code - buf == IMT_TRAMP_SIZE);
1838         emit_bytes (acfg, buf, code - buf);
1839
1840         for (i = 0; i < count; ++i) {
1841                 code = buf;
1842                 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1843                 ARM_B (code, 0);
1844                 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1845                 g_assert (code - buf == 8);
1846                 emit_bytes (acfg, buf, code - buf);
1847         }
1848
1849         acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1850         acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1851         acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1852         acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1853
1854         /* Unwind info for specifc trampolines */
1855         sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1856         /* We unwind to the original caller, from the stack, since lr is clobbered */
1857         mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1858         mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1859         save_unwind_info (acfg, symbol, unwind_ops);
1860         mono_free_unwind_info (unwind_ops);
1861
1862         sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1863         mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1864         mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1865         save_unwind_info (acfg, symbol, unwind_ops);
1866         mono_free_unwind_info (unwind_ops);
1867
1868         /* Unwind info for rgctx trampolines */
1869         sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1870         mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1871         save_unwind_info (acfg, symbol, unwind_ops);
1872
1873         sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1874         save_unwind_info (acfg, symbol, unwind_ops);
1875         mono_free_unwind_info (unwind_ops);
1876
1877         /* Unwind info for gsharedvt trampolines */
1878         sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1879         mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1880         mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1881         save_unwind_info (acfg, symbol, unwind_ops);
1882         mono_free_unwind_info (unwind_ops);
1883
1884         sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1885         mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1886         save_unwind_info (acfg, symbol, unwind_ops);
1887         mono_free_unwind_info (unwind_ops);
1888
1889         /* Unwind info for imt trampolines */
1890         sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1891         mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1892         mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1893         save_unwind_info (acfg, symbol, unwind_ops);
1894         mono_free_unwind_info (unwind_ops);
1895
1896         sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1897         mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1898         save_unwind_info (acfg, symbol, unwind_ops);
1899         mono_free_unwind_info (unwind_ops);
1900 #elif defined(TARGET_ARM64)
1901         arm64_emit_specific_trampoline_pages (acfg);
1902 #endif
1903 }
1904
1905 /*
1906  * arch_emit_specific_trampoline:
1907  *
1908  *   Emit code for a specific trampoline. OFFSET is the offset of the first of
1909  * two GOT slots which contain the generic trampoline address and the trampoline
1910  * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1911  */
1912 static void
1913 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1914 {
1915         /*
1916          * The trampolines created here are variations of the specific 
1917          * trampolines created in mono_arch_create_specific_trampoline (). The 
1918          * differences are:
1919          * - the generic trampoline address is taken from a got slot.
1920          * - the offset of the got slot where the trampoline argument is stored
1921          *   is embedded in the instruction stream, and the generic trampoline
1922          *   can load the argument by loading the offset, adding it to the
1923          *   address of the trampoline to get the address of the got slot, and
1924          *   loading the argument from there.
1925          * - all the trampolines should be of the same length.
1926          */
1927 #if defined(TARGET_AMD64)
1928         /* This should be exactly 8 bytes long */
1929         *tramp_size = 8;
1930         /* call *<offset>(%rip) */
1931         if (acfg->llvm) {
1932                 emit_unset_mode (acfg);
1933                 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1934                 emit_zero_bytes (acfg, 2);
1935         } else {
1936                 emit_byte (acfg, '\x41');
1937                 emit_byte (acfg, '\xff');
1938                 emit_byte (acfg, '\x15');
1939                 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1940                 emit_zero_bytes (acfg, 1);
1941         }
1942 #elif defined(TARGET_ARM)
1943         guint8 buf [128];
1944         guint8 *code;
1945
1946         /* This should be exactly 20 bytes long */
1947         *tramp_size = 20;
1948         code = buf;
1949         ARM_PUSH (code, 0x5fff);
1950         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1951         /* Load the value from the GOT */
1952         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1953         /* Branch to it */
1954         ARM_BLX_REG (code, ARMREG_R1);
1955
1956         g_assert (code - buf == 16);
1957
1958         /* Emit it */
1959         emit_bytes (acfg, buf, code - buf);
1960         /* 
1961          * Only one offset is needed, since the second one would be equal to the
1962          * first one.
1963          */
1964         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1965         //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1966 #elif defined(TARGET_ARM64)
1967         arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1968 #elif defined(TARGET_POWERPC)
1969         guint8 buf [128];
1970         guint8 *code;
1971
1972         *tramp_size = 4;
1973         code = buf;
1974
1975         /*
1976          * PPC has no ip relative addressing, so we need to compute the address
1977          * of the mscorlib got. That is slow and complex, so instead, we store it
1978          * in the second got slot of every aot image. The caller already computed
1979          * the address of its got and placed it into r30.
1980          */
1981         emit_unset_mode (acfg);
1982         /* Load mscorlib got address */
1983         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1984         /* Load generic trampoline address */
1985         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1986         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1987         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1988 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1989         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1990 #endif
1991         fprintf (acfg->fp, "mtctr 11\n");
1992         /* Load trampoline argument */
1993         /* On ppc, we pass it normally to the generic trampoline */
1994         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1995         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1996         fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1997         /* Branch to generic trampoline */
1998         fprintf (acfg->fp, "bctr\n");
1999
2000 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2001         *tramp_size = 10 * 4;
2002 #else
2003         *tramp_size = 9 * 4;
2004 #endif
2005 #elif defined(TARGET_X86)
2006         guint8 buf [128];
2007         guint8 *code;
2008
2009         /* Similar to the PPC code above */
2010
2011         /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2012
2013         code = buf;
2014         /* Load mscorlib got address */
2015         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2016         /* Push trampoline argument */
2017         x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2018         /* Load generic trampoline address */
2019         x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2020         /* Branch to generic trampoline */
2021         x86_jump_reg (code, X86_ECX);
2022
2023         emit_bytes (acfg, buf, code - buf);
2024
2025         *tramp_size = 17;
2026         g_assert (code - buf == *tramp_size);
2027 #else
2028         g_assert_not_reached ();
2029 #endif
2030 }
2031
2032 /*
2033  * arch_emit_unbox_trampoline:
2034  *
2035  *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
2036  * CALL_TARGET is the symbol pointing to the native code of METHOD.
2037  */
2038 static void
2039 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2040 {
2041 #if defined(TARGET_AMD64)
2042         guint8 buf [32];
2043         guint8 *code;
2044         int this_reg;
2045
2046         this_reg = mono_arch_get_this_arg_reg (NULL);
2047         code = buf;
2048         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2049
2050         emit_bytes (acfg, buf, code - buf);
2051         /* jump <method> */
2052         if (acfg->llvm) {
2053                 emit_unset_mode (acfg);
2054                 fprintf (acfg->fp, "jmp %s\n", call_target);
2055         } else {
2056                 emit_byte (acfg, '\xe9');
2057                 emit_symbol_diff (acfg, call_target, ".", -4);
2058         }
2059 #elif defined(TARGET_X86)
2060         guint8 buf [32];
2061         guint8 *code;
2062         int this_pos = 4;
2063
2064         code = buf;
2065
2066         x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2067
2068         emit_bytes (acfg, buf, code - buf);
2069
2070         /* jump <method> */
2071         emit_byte (acfg, '\xe9');
2072         emit_symbol_diff (acfg, call_target, ".", -4);
2073 #elif defined(TARGET_ARM)
2074         guint8 buf [128];
2075         guint8 *code;
2076
2077         if (acfg->thumb_mixed && cfg->compile_llvm) {
2078                 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2079                 fprintf (acfg->fp, "b %s\n", call_target);
2080                 fprintf (acfg->fp, ".arm\n");
2081                 fprintf (acfg->fp, ".align 2\n");
2082                 return;
2083         }
2084
2085         code = buf;
2086
2087         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2088
2089         emit_bytes (acfg, buf, code - buf);
2090         /* jump to method */
2091         if (acfg->thumb_mixed && cfg->compile_llvm)
2092                 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2093         else
2094                 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2095 #elif defined(TARGET_ARM64)
2096         arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2097 #elif defined(TARGET_POWERPC)
2098         int this_pos = 3;
2099
2100         fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2101         fprintf (acfg->fp, "\n\tb %s\n", call_target);
2102 #else
2103         g_assert_not_reached ();
2104 #endif
2105 }
2106
2107 /*
2108  * arch_emit_static_rgctx_trampoline:
2109  *
2110  *   Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2111  * two GOT slots which contain the rgctx argument, and the method to jump to.
2112  * TRAMP_SIZE is set to the size of the emitted trampoline.
2113  * These kinds of trampolines cannot be enumerated statically, since there could
2114  * be one trampoline per method instantiation, so we emit the same code for all
2115  * trampolines, and parameterize them using two GOT slots.
2116  */
2117 static void
2118 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2119 {
2120 #if defined(TARGET_AMD64)
2121         /* This should be exactly 13 bytes long */
2122         *tramp_size = 13;
2123
2124         if (acfg->llvm) {
2125                 emit_unset_mode (acfg);
2126                 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2127                 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2128         } else {
2129                 /* mov <OFFSET>(%rip), %r10 */
2130                 emit_byte (acfg, '\x4d');
2131                 emit_byte (acfg, '\x8b');
2132                 emit_byte (acfg, '\x15');
2133                 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2134
2135                 /* jmp *<offset>(%rip) */
2136                 emit_byte (acfg, '\xff');
2137                 emit_byte (acfg, '\x25');
2138                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2139         }
2140 #elif defined(TARGET_ARM)
2141         guint8 buf [128];
2142         guint8 *code;
2143
2144         /* This should be exactly 24 bytes long */
2145         *tramp_size = 24;
2146         code = buf;
2147         /* Load rgctx value */
2148         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2149         ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2150         /* Load branch addr + branch */
2151         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2152         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2153
2154         g_assert (code - buf == 16);
2155
2156         /* Emit it */
2157         emit_bytes (acfg, buf, code - buf);
2158         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2159         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2160 #elif defined(TARGET_ARM64)
2161         arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2162 #elif defined(TARGET_POWERPC)
2163         guint8 buf [128];
2164         guint8 *code;
2165
2166         *tramp_size = 4;
2167         code = buf;
2168
2169         /*
2170          * PPC has no ip relative addressing, so we need to compute the address
2171          * of the mscorlib got. That is slow and complex, so instead, we store it
2172          * in the second got slot of every aot image. The caller already computed
2173          * the address of its got and placed it into r30.
2174          */
2175         emit_unset_mode (acfg);
2176         /* Load mscorlib got address */
2177         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2178         /* Load rgctx */
2179         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2180         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2181         fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2182         /* Load target address */
2183         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2184         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2185         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2186 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2187         fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2188         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2189 #endif
2190         fprintf (acfg->fp, "mtctr 11\n");
2191         /* Branch to the target address */
2192         fprintf (acfg->fp, "bctr\n");
2193
2194 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2195         *tramp_size = 11 * 4;
2196 #else
2197         *tramp_size = 9 * 4;
2198 #endif
2199
2200 #elif defined(TARGET_X86)
2201         guint8 buf [128];
2202         guint8 *code;
2203
2204         /* Similar to the PPC code above */
2205
2206         g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2207
2208         code = buf;
2209         /* Load mscorlib got address */
2210         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2211         /* Load arg */
2212         x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2213         /* Branch to the target address */
2214         x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2215
2216         emit_bytes (acfg, buf, code - buf);
2217
2218         *tramp_size = 15;
2219         g_assert (code - buf == *tramp_size);
2220 #else
2221         g_assert_not_reached ();
2222 #endif
2223 }       
2224
2225 /*
2226  * arch_emit_imt_trampoline:
2227  *
2228  *   Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2229  * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2230  * key is the IMT key, and ptr holds the address of a memory location holding
2231  * the address to branch to if the IMT arg matches the key. The array is 
2232  * terminated by a pair whose key is NULL, and whose ptr is the address of the 
2233  * fail_tramp.
2234  * TRAMP_SIZE is set to the size of the emitted trampoline.
2235  */
2236 static void
2237 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2238 {
2239 #if defined(TARGET_AMD64)
2240         guint8 *buf, *code;
2241         guint8 *labels [16];
2242         guint8 mov_buf[3];
2243         guint8 *mov_buf_ptr = mov_buf;
2244
2245         const int kSizeOfMove = 7;
2246
2247         code = buf = (guint8 *)g_malloc (256);
2248
2249         /* FIXME: Optimize this, i.e. use binary search etc. */
2250         /* Maybe move the body into a separate function (slower, but much smaller) */
2251
2252         /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2253
2254         if (acfg->llvm) {
2255                 emit_unset_mode (acfg);
2256                 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2257         }
2258
2259         labels [0] = code;
2260         amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2261         labels [1] = code;
2262         amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2263
2264         /* Check key */
2265         amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2266         labels [2] = code;
2267         amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2268
2269         /* Loop footer */
2270         amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2271         amd64_jump_code (code, labels [0]);
2272
2273         /* Match */
2274         mono_amd64_patch (labels [2], code);
2275         amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2276         amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2277
2278         /* No match */
2279         mono_amd64_patch (labels [1], code);
2280         /* Load fail tramp */
2281         amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2282         /* Check if there is a fail tramp */
2283         amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2284         labels [3] = code;
2285         amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2286         /* Jump to fail tramp */
2287         amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2288
2289         /* Fail */
2290         mono_amd64_patch (labels [3], code);
2291         x86_breakpoint (code);
2292
2293         if (!acfg->llvm) {
2294                 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2295                 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2296                 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2297                 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2298                 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2299                 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2300         }
2301         emit_bytes (acfg, buf, code - buf);
2302
2303         *tramp_size = code - buf + kSizeOfMove;
2304
2305         g_free (buf);
2306
2307 #elif defined(TARGET_X86)
2308         guint8 *buf, *code;
2309         guint8 *labels [16];
2310
2311         code = buf = g_malloc (256);
2312
2313         /* Allocate a temporary stack slot */
2314         x86_push_reg (code, X86_EAX);
2315         /* Save EAX */
2316         x86_push_reg (code, X86_EAX);
2317
2318         /* Load mscorlib got address */
2319         x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2320         /* Load arg */
2321         x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2322
2323         labels [0] = code;
2324         x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2325         labels [1] = code;
2326         x86_branch8 (code, X86_CC_Z, FALSE, 0);
2327
2328         /* Check key */
2329         x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2330         labels [2] = code;
2331         x86_branch8 (code, X86_CC_Z, FALSE, 0);
2332
2333         /* Loop footer */
2334         x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2335         x86_jump_code (code, labels [0]);
2336
2337         /* Match */
2338         mono_x86_patch (labels [2], code);
2339         x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2340         x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2341         /* Save the target address to the temporary stack location */
2342         x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2343         /* Restore EAX */
2344         x86_pop_reg (code, X86_EAX);
2345         /* Jump to the target address */
2346         x86_ret (code);
2347
2348         /* No match */
2349         mono_x86_patch (labels [1], code);
2350         /* Load fail tramp */
2351         x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2352         x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2353         labels [3] = code;
2354         x86_branch8 (code, X86_CC_Z, FALSE, 0);
2355         /* Jump to fail tramp */
2356         x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2357         x86_pop_reg (code, X86_EAX);
2358         x86_ret (code);
2359
2360         /* Fail */
2361         mono_x86_patch (labels [3], code);
2362         x86_breakpoint (code);
2363
2364         emit_bytes (acfg, buf, code - buf);
2365         
2366         *tramp_size = code - buf;
2367
2368         g_free (buf);
2369
2370 #elif defined(TARGET_ARM)
2371         guint8 buf [128];
2372         guint8 *code, *code2, *labels [16];
2373
2374         code = buf;
2375
2376         /* The IMT method is in v5 */
2377
2378         /* Need at least two free registers, plus a slot for storing the pc */
2379         ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2380         labels [0] = code;
2381         /* Load the parameter from the GOT */
2382         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2383         ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2384
2385         labels [1] = code;
2386         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2387         ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2388         labels [2] = code;
2389         ARM_B_COND (code, ARMCOND_EQ, 0);
2390
2391         /* End-of-loop check */
2392         ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2393         labels [3] = code;
2394         ARM_B_COND (code, ARMCOND_EQ, 0);
2395
2396         /* Loop footer */
2397         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2398         labels [4] = code;
2399         ARM_B (code, 0);
2400         arm_patch (labels [4], labels [1]);
2401
2402         /* Match */
2403         arm_patch (labels [2], code);
2404         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2405         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2406         /* Save it to the third stack slot */
2407         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2408         /* Restore the registers and branch */
2409         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2410
2411         /* No match */
2412         arm_patch (labels [3], code);
2413         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2414         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2415         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2416
2417         /* Fixup offset */
2418         code2 = labels [0];
2419         ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2420
2421         emit_bytes (acfg, buf, code - buf);
2422         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2423
2424         *tramp_size = code - buf + 4;
2425 #elif defined(TARGET_ARM64)
2426         arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2427 #elif defined(TARGET_POWERPC)
2428         guint8 buf [128];
2429         guint8 *code, *labels [16];
2430
2431         code = buf;
2432
2433         /* Load the mscorlib got address */
2434         ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2435         /* Load the parameter from the GOT */
2436         ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2437         ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2438
2439         /* Load and check key */
2440         labels [1] = code;
2441         ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2442         ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2443         labels [2] = code;
2444         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2445
2446         /* End-of-loop check */
2447         ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2448         labels [3] = code;
2449         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2450
2451         /* Loop footer */
2452         ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2453         labels [4] = code;
2454         ppc_b (code, 0);
2455         mono_ppc_patch (labels [4], labels [1]);
2456
2457         /* Match */
2458         mono_ppc_patch (labels [2], code);
2459         ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2460         /* r12 now contains the value of the vtable slot */
2461         /* this is not a function descriptor on ppc64 */
2462         ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2463         ppc_mtctr (code, ppc_r12);
2464         ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2465
2466         /* Fail */
2467         mono_ppc_patch (labels [3], code);
2468         /* FIXME: */
2469         ppc_break (code);
2470
2471         *tramp_size = code - buf;
2472
2473         emit_bytes (acfg, buf, code - buf);
2474 #else
2475         g_assert_not_reached ();
2476 #endif
2477 }
2478
2479
2480 #if defined (TARGET_AMD64)
2481
2482 static void
2483 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2484 {
2485
2486         g_assert (acfg->fp);
2487         emit_unset_mode (acfg);
2488
2489         fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2490 }
2491
2492 #endif
2493
2494
2495 /*
2496  * arch_emit_gsharedvt_arg_trampoline:
2497  *
2498  *   Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2499  * two GOT slots which contain the argument, and the code to jump to.
2500  * TRAMP_SIZE is set to the size of the emitted trampoline.
2501  * These kinds of trampolines cannot be enumerated statically, since there could
2502  * be one trampoline per method instantiation, so we emit the same code for all
2503  * trampolines, and parameterize them using two GOT slots.
2504  */
2505 static void
2506 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2507 {
2508 #if defined(TARGET_X86)
2509         guint8 buf [128];
2510         guint8 *code;
2511
2512         /* Similar to the PPC code above */
2513
2514         g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2515
2516         code = buf;
2517         /* Load mscorlib got address */
2518         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2519         /* Load arg */
2520         x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2521         /* Branch to the target address */
2522         x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2523
2524         emit_bytes (acfg, buf, code - buf);
2525
2526         *tramp_size = 15;
2527         g_assert (code - buf == *tramp_size);
2528 #elif defined(TARGET_ARM)
2529         guint8 buf [128];
2530         guint8 *code;
2531
2532         /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2533         /* Similar to arch_emit_specific_trampoline () */
2534         *tramp_size = 24;
2535         code = buf;
2536         ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2537         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2538         /* Load the arg value from the GOT */
2539         ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2540         /* Load the addr from the GOT */
2541         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2542         /* Branch to it */
2543         ARM_BX (code, ARMREG_R1);
2544
2545         g_assert (code - buf == 20);
2546
2547         /* Emit it */
2548         emit_bytes (acfg, buf, code - buf);
2549         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2550 #elif defined(TARGET_ARM64)
2551         arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2552 #elif defined (TARGET_AMD64)
2553
2554         amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2555         amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2556         g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2557         fprintf (acfg->fp, "jmp *%%r11\n");
2558
2559         *tramp_size = 0x11;
2560 #else
2561         g_assert_not_reached ();
2562 #endif
2563 }       
2564
2565 /* END OF ARCH SPECIFIC CODE */
2566
2567 static guint32
2568 mono_get_field_token (MonoClassField *field) 
2569 {
2570         MonoClass *klass = field->parent;
2571         int i;
2572
2573         int fcount = mono_class_get_field_count (klass);
2574         for (i = 0; i < fcount; ++i) {
2575                 if (field == &klass->fields [i])
2576                         return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2577         }
2578
2579         g_assert_not_reached ();
2580         return 0;
2581 }
2582
2583 static inline void
2584 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2585 {
2586         guint8 *p = buf;
2587
2588         //printf ("ENCODE: %d 0x%x.\n", value, value);
2589
2590         /* 
2591          * Same encoding as the one used in the metadata, extended to handle values
2592          * greater than 0x1fffffff.
2593          */
2594         if ((value >= 0) && (value <= 127))
2595                 *p++ = value;
2596         else if ((value >= 0) && (value <= 16383)) {
2597                 p [0] = 0x80 | (value >> 8);
2598                 p [1] = value & 0xff;
2599                 p += 2;
2600         } else if ((value >= 0) && (value <= 0x1fffffff)) {
2601                 p [0] = (value >> 24) | 0xc0;
2602                 p [1] = (value >> 16) & 0xff;
2603                 p [2] = (value >> 8) & 0xff;
2604                 p [3] = value & 0xff;
2605                 p += 4;
2606         }
2607         else {
2608                 p [0] = 0xff;
2609                 p [1] = (value >> 24) & 0xff;
2610                 p [2] = (value >> 16) & 0xff;
2611                 p [3] = (value >> 8) & 0xff;
2612                 p [4] = value & 0xff;
2613                 p += 5;
2614         }
2615         if (endbuf)
2616                 *endbuf = p;
2617 }
2618
2619 static void
2620 stream_init (MonoDynamicStream *sh)
2621 {
2622         sh->index = 0;
2623         sh->alloc_size = 4096;
2624         sh->data = (char *)g_malloc (4096);
2625
2626         /* So offsets are > 0 */
2627         sh->data [0] = 0;
2628         sh->index ++;
2629 }
2630
2631 static void
2632 make_room_in_stream (MonoDynamicStream *stream, int size)
2633 {
2634         if (size <= stream->alloc_size)
2635                 return;
2636         
2637         while (stream->alloc_size <= size) {
2638                 if (stream->alloc_size < 4096)
2639                         stream->alloc_size = 4096;
2640                 else
2641                         stream->alloc_size *= 2;
2642         }
2643         
2644         stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2645 }
2646
2647 static guint32
2648 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2649 {
2650         guint32 idx;
2651         
2652         make_room_in_stream (stream, stream->index + len);
2653         memcpy (stream->data + stream->index, data, len);
2654         idx = stream->index;
2655         stream->index += len;
2656         return idx;
2657 }
2658
2659 /*
2660  * add_to_blob:
2661  *
2662  *   Add data to the binary blob inside the aot image. Returns the offset inside the
2663  * blob where the data was stored.
2664  */
2665 static guint32
2666 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2667 {
2668         g_assert (!acfg->blob_closed);
2669
2670         if (acfg->blob.alloc_size == 0)
2671                 stream_init (&acfg->blob);
2672
2673         return add_stream_data (&acfg->blob, (char*)data, data_len);
2674 }
2675
2676 static guint32
2677 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2678 {
2679         char buf [4] = {0};
2680         guint32 count;
2681
2682         if (acfg->blob.alloc_size == 0)
2683                 stream_init (&acfg->blob);
2684
2685         count = acfg->blob.index % align;
2686
2687         /* we assume the stream data will be aligned */
2688         if (count)
2689                 add_stream_data (&acfg->blob, buf, 4 - count);
2690
2691         return add_stream_data (&acfg->blob, (char*)data, data_len);
2692 }
2693
2694 /* Emit a table of data into the aot image */
2695 static void
2696 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2697 {
2698         if (acfg->data_outfile) {
2699                 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2700                 fwrite (data,1, size, acfg->data_outfile);
2701                 acfg->datafile_offset += size;
2702                 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2703                 int align = 8 - size % 8;
2704                 acfg->datafile_offset += align;
2705                 guint8 align_buf [16];
2706                 memset (&align_buf, 0, sizeof (align_buf));
2707                 fwrite (align_buf, align, 1, acfg->data_outfile);
2708         } else if (acfg->llvm) {
2709                 mono_llvm_emit_aot_data (symbol, data, size);
2710         } else {
2711                 emit_section_change (acfg, RODATA_SECT, 0);
2712                 emit_alignment (acfg, 8);
2713                 emit_label (acfg, symbol);
2714                 emit_bytes (acfg, data, size);
2715         }
2716 }
2717
2718 /*
2719  * emit_offset_table:
2720  *
2721  *   Emit a table of increasing offsets in a compact form using differential encoding.
2722  * There is an index entry for each GROUP_SIZE number of entries. The greater the
2723  * group size, the more compact the table becomes, but the slower it becomes to compute
2724  * a given entry. Returns the size of the table.
2725  */
2726 static guint32
2727 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2728 {
2729         gint32 current_offset;
2730         int i, buf_size, ngroups, index_entry_size;
2731         guint8 *p, *buf;
2732         guint8 *data_p, *data_buf;
2733         guint32 *index_offsets;
2734
2735         ngroups = (noffsets + (group_size - 1)) / group_size;
2736
2737         index_offsets = g_new0 (guint32, ngroups);
2738
2739         buf_size = noffsets * 4;
2740         p = buf = (guint8 *)g_malloc0 (buf_size);
2741
2742         current_offset = 0;
2743         for (i = 0; i < noffsets; ++i) {
2744                 //printf ("D: %d -> %d\n", i, offsets [i]);
2745                 if ((i % group_size) == 0) {
2746                         index_offsets [i / group_size] = p - buf;
2747                         /* Emit the full value for these entries */
2748                         encode_value (offsets [i], p, &p);
2749                 } else {
2750                         /* The offsets are allowed to be non-increasing */
2751                         //g_assert (offsets [i] >= current_offset);
2752                         encode_value (offsets [i] - current_offset, p, &p);
2753                 }
2754                 current_offset = offsets [i];
2755         }
2756         data_buf = buf;
2757         data_p = p;
2758
2759         if (ngroups && index_offsets [ngroups - 1] < 65000)
2760                 index_entry_size = 2;
2761         else
2762                 index_entry_size = 4;
2763
2764         buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2765         p = buf = (guint8 *)g_malloc0 (buf_size);
2766
2767         /* Emit the header */
2768         encode_int (noffsets, p, &p);
2769         encode_int (group_size, p, &p);
2770         encode_int (ngroups, p, &p);
2771         encode_int (index_entry_size, p, &p);
2772
2773         /* Emit the index */
2774         for (i = 0; i < ngroups; ++i) {
2775                 if (index_entry_size == 2)
2776                         encode_int16 (index_offsets [i], p, &p);
2777                 else
2778                         encode_int (index_offsets [i], p, &p);
2779         }
2780         /* Emit the data */
2781         memcpy (p, data_buf, data_p - data_buf);
2782         p += data_p - data_buf;
2783
2784         g_assert (p - buf <= buf_size);
2785
2786         emit_aot_data (acfg, table, symbol, buf, p - buf);
2787
2788         g_free (buf);
2789         g_free (data_buf);
2790
2791     return (int)(p - buf);
2792 }
2793
2794 static guint32
2795 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2796 {
2797         guint32 index;
2798
2799         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2800         if (index)
2801                 return index - 1;
2802         else {
2803                 index = g_hash_table_size (cfg->image_hash);
2804                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2805                 g_ptr_array_add (cfg->image_table, image);
2806                 return index;
2807         }
2808 }
2809
2810 static guint32
2811 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2812 {
2813         int i;
2814         int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2815
2816         /* FIXME: Search referenced images as well */
2817         if (!acfg->typespec_classes) {
2818                 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2819                 for (i = 0; i < len; i++) {
2820                         MonoError error;
2821                         int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2822                         MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2823                         if (!is_ok (&error)) {
2824                                 mono_error_cleanup (&error);
2825                                 continue;
2826                         }
2827                         g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2828                 }
2829         }
2830         return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2831 }
2832
2833 static void
2834 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2835
2836 static void
2837 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2838
2839 static void
2840 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2841
2842 static void
2843 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2844
2845 static void
2846 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2847 {
2848         guint8 *p = buf;
2849
2850         /*
2851          * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2852          * information.
2853          */
2854
2855         if (mono_class_is_ginst (klass)) {
2856                 guint32 token;
2857                 g_assert (klass->type_token);
2858
2859                 /* Find a typespec for a class if possible */
2860                 token = find_typespec_for_class (acfg, klass);
2861                 if (token) {
2862                         encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2863                         encode_value (token, p, &p);
2864                 } else {
2865                         MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2866                         MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2867                         static int count = 0;
2868                         guint8 *p1 = p;
2869
2870                         encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2871                         encode_klass_ref (acfg, gclass, p, &p);
2872                         encode_ginst (acfg, inst, p, &p);
2873
2874                         count += p - p1;
2875                 }
2876         } else if (klass->type_token) {
2877                 int iindex = get_image_index (acfg, klass->image);
2878
2879                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2880                 if (iindex == 0) {
2881                         encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2882                         encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2883                 } else {
2884                         encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2885                         encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2886                         encode_value (get_image_index (acfg, klass->image), p, &p);
2887                 }
2888         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2889                 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2890                 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2891
2892                 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2893
2894                 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2895                 if (par->gshared_constraint) {
2896                         MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2897                         encode_type (acfg, par->gshared_constraint, p, &p);
2898                         encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2899                 } else {
2900                         encode_value (klass->byval_arg.type, p, &p);
2901                         encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2902
2903                         encode_value (container->is_anonymous ? 0 : 1, p, &p);
2904
2905                         if (!container->is_anonymous) {
2906                                 encode_value (container->is_method, p, &p);
2907                                 if (container->is_method)
2908                                         encode_method_ref (acfg, container->owner.method, p, &p);
2909                                 else
2910                                         encode_klass_ref (acfg, container->owner.klass, p, &p);
2911                         }
2912                 }
2913         } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2914                 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2915                 encode_type (acfg, &klass->byval_arg, p, &p);
2916         } else {
2917                 /* Array class */
2918                 g_assert (klass->rank > 0);
2919                 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2920                 encode_value (klass->rank, p, &p);
2921                 encode_klass_ref (acfg, klass->element_class, p, &p);
2922         }
2923         *endbuf = p;
2924 }
2925
2926 /*
2927  * encode_klass_ref:
2928  *
2929  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
2930  * standard metadata encoding.
2931  */
2932 static void
2933 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2934 {
2935         gboolean shared = FALSE;
2936
2937         /* 
2938          * The encoding of generic instances is large so emit them only once.
2939          */
2940         if (mono_class_is_ginst (klass)) {
2941                 guint32 token;
2942                 g_assert (klass->type_token);
2943
2944                 /* Find a typespec for a class if possible */
2945                 token = find_typespec_for_class (acfg, klass);
2946                 if (!token)
2947                         shared = TRUE;
2948         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2949                 shared = TRUE;
2950         }
2951
2952         if (shared) {
2953                 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2954                 guint8 *buf2, *p;
2955
2956                 if (!offset) {
2957                         buf2 = (guint8 *)g_malloc (1024);
2958                         p = buf2;
2959
2960                         encode_klass_ref_inner (acfg, klass, p, &p);
2961                         g_assert (p - buf2 < 1024);
2962
2963                         offset = add_to_blob (acfg, buf2, p - buf2);
2964                         g_free (buf2);
2965
2966                         g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2967                 } else {
2968                         offset --;
2969                 }
2970
2971                 p = buf;
2972                 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2973                 encode_value (offset, p, &p);
2974                 *endbuf = p;
2975                 return;
2976         }
2977
2978         encode_klass_ref_inner (acfg, klass, buf, endbuf);
2979 }
2980
2981 static void
2982 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2983 {
2984         guint32 token = mono_get_field_token (field);
2985         guint8 *p = buf;
2986
2987         encode_klass_ref (cfg, field->parent, p, &p);
2988         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2989         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2990         *endbuf = p;
2991 }
2992
2993 static void
2994 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2995 {
2996         guint8 *p = buf;
2997         int i;
2998
2999         encode_value (inst->type_argc, p, &p);
3000         for (i = 0; i < inst->type_argc; ++i)
3001                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3002         *endbuf = p;
3003 }
3004
3005 static void
3006 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3007 {
3008         guint8 *p = buf;
3009         MonoGenericInst *inst;
3010
3011         inst = context->class_inst;
3012         if (inst) {
3013                 g_assert (inst->type_argc);
3014                 encode_ginst (acfg, inst, p, &p);
3015         } else {
3016                 encode_value (0, p, &p);
3017         }
3018         inst = context->method_inst;
3019         if (inst) {
3020                 g_assert (inst->type_argc);
3021                 encode_ginst (acfg, inst, p, &p);
3022         } else {
3023                 encode_value (0, p, &p);
3024         }
3025         *endbuf = p;
3026 }
3027
3028 static void
3029 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3030 {
3031         guint8 *p = buf;
3032
3033         g_assert (t->num_mods == 0);
3034         /* t->attrs can be ignored */
3035         //g_assert (t->attrs == 0);
3036
3037         if (t->pinned) {
3038                 *p = MONO_TYPE_PINNED;
3039                 ++p;
3040         }
3041         if (t->byref) {
3042                 *p = MONO_TYPE_BYREF;
3043                 ++p;
3044         }
3045
3046         *p = t->type;
3047         p ++;
3048
3049         switch (t->type) {
3050         case MONO_TYPE_VOID:
3051         case MONO_TYPE_BOOLEAN:
3052         case MONO_TYPE_CHAR:
3053         case MONO_TYPE_I1:
3054         case MONO_TYPE_U1:
3055         case MONO_TYPE_I2:
3056         case MONO_TYPE_U2:
3057         case MONO_TYPE_I4:
3058         case MONO_TYPE_U4:
3059         case MONO_TYPE_I8:
3060         case MONO_TYPE_U8:
3061         case MONO_TYPE_R4:
3062         case MONO_TYPE_R8:
3063         case MONO_TYPE_I:
3064         case MONO_TYPE_U:
3065         case MONO_TYPE_STRING:
3066         case MONO_TYPE_OBJECT:
3067         case MONO_TYPE_TYPEDBYREF:
3068                 break;
3069         case MONO_TYPE_VALUETYPE:
3070         case MONO_TYPE_CLASS:
3071                 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3072                 break;
3073         case MONO_TYPE_SZARRAY:
3074                 encode_klass_ref (acfg, t->data.klass, p, &p);
3075                 break;
3076         case MONO_TYPE_PTR:
3077                 encode_type (acfg, t->data.type, p, &p);
3078                 break;
3079         case MONO_TYPE_GENERICINST: {
3080                 MonoClass *gclass = t->data.generic_class->container_class;
3081                 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3082
3083                 encode_klass_ref (acfg, gclass, p, &p);
3084                 encode_ginst (acfg, inst, p, &p);
3085                 break;
3086         }
3087         case MONO_TYPE_ARRAY: {
3088                 MonoArrayType *array = t->data.array;
3089                 int i;
3090
3091                 encode_klass_ref (acfg, array->eklass, p, &p);
3092                 encode_value (array->rank, p, &p);
3093                 encode_value (array->numsizes, p, &p);
3094                 for (i = 0; i < array->numsizes; ++i)
3095                         encode_value (array->sizes [i], p, &p);
3096                 encode_value (array->numlobounds, p, &p);
3097                 for (i = 0; i < array->numlobounds; ++i)
3098                         encode_value (array->lobounds [i], p, &p);
3099                 break;
3100         }
3101         case MONO_TYPE_VAR:
3102         case MONO_TYPE_MVAR:
3103                 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3104                 break;
3105         default:
3106                 g_assert_not_reached ();
3107         }
3108
3109         *endbuf = p;
3110 }
3111
3112 static void
3113 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3114 {
3115         guint8 *p = buf;
3116         guint32 flags = 0;
3117         int i;
3118
3119         /* Similar to the metadata encoding */
3120         if (sig->generic_param_count)
3121                 flags |= 0x10;
3122         if (sig->hasthis)
3123                 flags |= 0x20;
3124         if (sig->explicit_this)
3125                 flags |= 0x40;
3126         flags |= (sig->call_convention & 0x0F);
3127
3128         *p = flags;
3129         ++p;
3130         if (sig->generic_param_count)
3131                 encode_value (sig->generic_param_count, p, &p);
3132         encode_value (sig->param_count, p, &p);
3133
3134         encode_type (acfg, sig->ret, p, &p);
3135         for (i = 0; i < sig->param_count; ++i) {
3136                 if (sig->sentinelpos == i) {
3137                         *p = MONO_TYPE_SENTINEL;
3138                         ++p;
3139                 }
3140                 encode_type (acfg, sig->params [i], p, &p);
3141         }
3142
3143         *endbuf = p;
3144 }
3145
3146 #define MAX_IMAGE_INDEX 250
3147
3148 static void
3149 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3150 {
3151         guint32 image_index = get_image_index (acfg, method->klass->image);
3152         guint32 token = method->token;
3153         MonoJumpInfoToken *ji;
3154         guint8 *p = buf;
3155
3156         /*
3157          * The encoding for most methods is as follows:
3158          * - image index encoded as a leb128
3159          * - token index encoded as a leb128
3160          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3161          * types of method encodings.
3162          */
3163
3164         /* Mark methods which can't use aot trampolines because they need the further 
3165          * processing in mono_magic_trampoline () which requires a MonoMethod*.
3166          */
3167         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3168                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3169                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3170
3171         if (method->wrapper_type) {
3172                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3173
3174                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3175
3176                 encode_value (method->wrapper_type, p, &p);
3177
3178                 switch (method->wrapper_type) {
3179                 case MONO_WRAPPER_REMOTING_INVOKE:
3180                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3181                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3182                         MonoMethod *m;
3183
3184                         m = mono_marshal_method_from_wrapper (method);
3185                         g_assert (m);
3186                         encode_method_ref (acfg, m, p, &p);
3187                         break;
3188                 }
3189                 case MONO_WRAPPER_PROXY_ISINST:
3190                 case MONO_WRAPPER_LDFLD:
3191                 case MONO_WRAPPER_LDFLDA:
3192                 case MONO_WRAPPER_STFLD: {
3193                         g_assert (info);
3194                         encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3195                         break;
3196                 }
3197                 case MONO_WRAPPER_ALLOC: {
3198                         /* The GC name is saved once in MonoAotFileInfo */
3199                         g_assert (info->d.alloc.alloc_type != -1);
3200                         encode_value (info->d.alloc.alloc_type, p, &p);
3201                         break;
3202                 }
3203                 case MONO_WRAPPER_WRITE_BARRIER: {
3204                         g_assert (info);
3205                         break;
3206                 }
3207                 case MONO_WRAPPER_STELEMREF: {
3208                         g_assert (info);
3209                         encode_value (info->subtype, p, &p);
3210                         if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3211                                 encode_value (info->d.virtual_stelemref.kind, p, &p);
3212                         break;
3213                 }
3214                 case MONO_WRAPPER_UNKNOWN: {
3215                         g_assert (info);
3216                         encode_value (info->subtype, p, &p);
3217                         if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3218                                 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3219                                 encode_klass_ref (acfg, method->klass, p, &p);
3220                         else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3221                                 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3222                         else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3223                                 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3224                         else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3225                                 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3226                         else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3227                                 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3228                         break;
3229                 }
3230                 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3231                         g_assert (info);
3232                         encode_value (info->subtype, p, &p);
3233                         if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3234                                 strcpy ((char*)p, method->name);
3235                                 p += strlen (method->name) + 1;
3236                         } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3237                                 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3238                         } else {
3239                                 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3240                                 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3241                         }
3242                         break;
3243                 }
3244                 case MONO_WRAPPER_SYNCHRONIZED: {
3245                         MonoMethod *m;
3246
3247                         m = mono_marshal_method_from_wrapper (method);
3248                         g_assert (m);
3249                         g_assert (m != method);
3250                         encode_method_ref (acfg, m, p, &p);
3251                         break;
3252                 }
3253                 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3254                         g_assert (info);
3255                         encode_value (info->subtype, p, &p);
3256
3257                         if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3258                                 encode_value (info->d.element_addr.rank, p, &p);
3259                                 encode_value (info->d.element_addr.elem_size, p, &p);
3260                         } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3261                                 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3262                         } else {
3263                                 g_assert_not_reached ();
3264                         }
3265                         break;
3266                 }
3267                 case MONO_WRAPPER_CASTCLASS: {
3268                         g_assert (info);
3269                         encode_value (info->subtype, p, &p);
3270                         break;
3271                 }
3272                 case MONO_WRAPPER_RUNTIME_INVOKE: {
3273                         g_assert (info);
3274                         encode_value (info->subtype, p, &p);
3275                         if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3276                                 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3277                         else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3278                                 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3279                         break;
3280                 }
3281                 case MONO_WRAPPER_DELEGATE_INVOKE:
3282                 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3283                 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3284                         if (method->is_inflated) {
3285                                 /* These wrappers are identified by their class */
3286                                 encode_value (1, p, &p);
3287                                 encode_klass_ref (acfg, method->klass, p, &p);
3288                         } else {
3289                                 MonoMethodSignature *sig = mono_method_signature (method);
3290                                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3291
3292                                 encode_value (0, p, &p);
3293                                 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3294                                         encode_value (info ? info->subtype : 0, p, &p);
3295                                 encode_signature (acfg, sig, p, &p);
3296                         }
3297                         break;
3298                 }
3299                 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3300                         g_assert (info);
3301                         encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3302                         encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3303                         break;
3304                 }
3305                 default:
3306                         g_assert_not_reached ();
3307                 }
3308         } else if (mono_method_signature (method)->is_inflated) {
3309                 /* 
3310                  * This is a generic method, find the original token which referenced it and
3311                  * encode that.
3312                  * Obtain the token from information recorded by the JIT.
3313                  */
3314                 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3315                 if (ji) {
3316                         image_index = get_image_index (acfg, ji->image);
3317                         g_assert (image_index < MAX_IMAGE_INDEX);
3318                         token = ji->token;
3319
3320                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3321                         encode_value (image_index, p, &p);
3322                         encode_value (token, p, &p);
3323                 } else {
3324                         MonoMethod *declaring;
3325                         MonoGenericContext *context = mono_method_get_context (method);
3326
3327                         g_assert (method->is_inflated);
3328                         declaring = ((MonoMethodInflated*)method)->declaring;
3329
3330                         /*
3331                          * This might be a non-generic method of a generic instance, which 
3332                          * doesn't have a token since the reference is generated by the JIT 
3333                          * like Nullable:Box/Unbox, or by generic sharing.
3334                          */
3335                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3336                         /* Encode the klass */
3337                         encode_klass_ref (acfg, method->klass, p, &p);
3338                         /* Encode the method */
3339                         image_index = get_image_index (acfg, method->klass->image);
3340                         g_assert (image_index < MAX_IMAGE_INDEX);
3341                         g_assert (declaring->token);
3342                         token = declaring->token;
3343                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3344                         encode_value (image_index, p, &p);
3345                         encode_value (token, p, &p);
3346                         encode_generic_context (acfg, context, p, &p);
3347                 }
3348         } else if (token == 0) {
3349                 /* This might be a method of a constructed type like int[,].Set */
3350                 /* Obtain the token from information recorded by the JIT */
3351                 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3352                 if (ji) {
3353                         image_index = get_image_index (acfg, ji->image);
3354                         g_assert (image_index < MAX_IMAGE_INDEX);
3355                         token = ji->token;
3356
3357                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3358                         encode_value (image_index, p, &p);
3359                         encode_value (token, p, &p);
3360                 } else {
3361                         /* Array methods */
3362                         g_assert (method->klass->rank);
3363
3364                         /* Encode directly */
3365                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3366                         encode_klass_ref (acfg, method->klass, p, &p);
3367                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3368                                 encode_value (0, p, &p);
3369                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3370                                 encode_value (1, p, &p);
3371                         else if (!strcmp (method->name, "Get"))
3372                                 encode_value (2, p, &p);
3373                         else if (!strcmp (method->name, "Address"))
3374                                 encode_value (3, p, &p);
3375                         else if (!strcmp (method->name, "Set"))
3376                                 encode_value (4, p, &p);
3377                         else
3378                                 g_assert_not_reached ();
3379                 }
3380         } else {
3381                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3382
3383                 if (image_index >= MONO_AOT_METHODREF_MIN) {
3384                         encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3385                         encode_value (image_index, p, &p);
3386                         encode_value (mono_metadata_token_index (token), p, &p);
3387                 } else {
3388                         encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3389                 }
3390         }
3391         *endbuf = p;
3392 }
3393
3394 static gint
3395 compare_patches (gconstpointer a, gconstpointer b)
3396 {
3397         int i, j;
3398
3399         i = (*(MonoJumpInfo**)a)->ip.i;
3400         j = (*(MonoJumpInfo**)b)->ip.i;
3401
3402         if (i < j)
3403                 return -1;
3404         else
3405                 if (i > j)
3406                         return 1;
3407         else
3408                 return 0;
3409 }
3410
3411 static G_GNUC_UNUSED char*
3412 patch_to_string (MonoJumpInfo *patch_info)
3413 {
3414         GString *str;
3415
3416         str = g_string_new ("");
3417
3418         g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3419
3420         switch (patch_info->type) {
3421         case MONO_PATCH_INFO_VTABLE:
3422                 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3423                 break;
3424         default:
3425                 break;
3426         }
3427         g_string_append_printf (str, ")");
3428         return g_string_free (str, FALSE);
3429 }
3430
3431 /*
3432  * is_plt_patch:
3433  *
3434  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
3435  * PLT entry.
3436  */
3437 static inline gboolean
3438 is_plt_patch (MonoJumpInfo *patch_info)
3439 {
3440         switch (patch_info->type) {
3441         case MONO_PATCH_INFO_METHOD:
3442         case MONO_PATCH_INFO_INTERNAL_METHOD:
3443         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3444         case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3445         case MONO_PATCH_INFO_RGCTX_FETCH:
3446                 return TRUE;
3447         default:
3448                 return FALSE;
3449         }
3450 }
3451
3452 /*
3453  * get_plt_symbol:
3454  *
3455  *   Return the symbol identifying the plt entry PLT_OFFSET.
3456  */
3457 static char*
3458 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3459 {
3460 #ifdef TARGET_MACH
3461         /* 
3462          * The Apple linker reorganizes object files, so it doesn't like branches to local
3463          * labels, since those have no relocations.
3464          */
3465         return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3466 #else
3467         return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3468 #endif
3469 }
3470
3471 /*
3472  * get_plt_entry:
3473  *
3474  *   Return a PLT entry which belongs to the method identified by PATCH_INFO.
3475  */
3476 static MonoPltEntry*
3477 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3478 {
3479         MonoPltEntry *res;
3480         gboolean synchronized = FALSE;
3481         static int synchronized_symbol_idx;
3482
3483         if (!is_plt_patch (patch_info))
3484                 return NULL;
3485
3486         if (!acfg->patch_to_plt_entry [patch_info->type])
3487                 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3488         res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3489
3490         if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3491                 /* 
3492                  * Allocate a separate PLT slot for each such patch, since some plt
3493                  * entries will refer to the method itself, and some will refer to the
3494                  * wrapper.
3495                  */
3496                 res = NULL;
3497                 synchronized = TRUE;
3498         }
3499
3500         if (!res) {
3501                 MonoJumpInfo *new_ji;
3502
3503                 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3504
3505                 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3506                 res->plt_offset = acfg->plt_offset;
3507                 res->ji = new_ji;
3508                 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3509                 if (acfg->aot_opts.write_symbols)
3510                         res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3511                 if (synchronized) {
3512                         /* Avoid duplicate symbols because we don't cache */
3513                         res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3514                         if (res->debug_sym)
3515                                 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3516                         synchronized_symbol_idx ++;
3517                 }
3518                 if (res->debug_sym)
3519                         res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3520                 else
3521                         res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3522
3523                 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3524
3525                 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3526
3527                 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3528                 //mono_print_ji (patch_info); printf ("\n");
3529                 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3530
3531                 acfg->plt_offset ++;
3532         }
3533
3534         return res;
3535 }
3536
3537 /**
3538  * get_got_offset:
3539  *
3540  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
3541  * JI could be found if it exists, otherwise allocates a new one.
3542  */
3543 static guint32
3544 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3545 {
3546         guint32 got_offset;
3547         GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3548
3549         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3550         if (got_offset)
3551                 return got_offset - 1;
3552
3553         if (llvm) {
3554                 got_offset = acfg->llvm_got_offset;
3555                 acfg->llvm_got_offset ++;
3556         } else {
3557                 got_offset = acfg->got_offset;
3558                 acfg->got_offset ++;
3559         }
3560
3561         acfg->stats.got_slots ++;
3562         acfg->stats.got_slot_types [ji->type] ++;
3563
3564         g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3565         g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3566         g_ptr_array_add (info->got_patches, ji);
3567
3568         return got_offset;
3569 }
3570
3571 /* Add a method to the list of methods which need to be emitted */
3572 static void
3573 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3574 {
3575         g_assert (method);
3576         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3577                 g_ptr_array_add (acfg->methods, method);
3578                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3579                 acfg->nmethods = acfg->methods->len + 1;
3580         }
3581
3582         if (method->wrapper_type || extra)
3583                 g_ptr_array_add (acfg->extra_methods, method);
3584 }
3585
3586 static gboolean
3587 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3588 {
3589         /* One instantiation with valuetypes is generated for each async method */
3590         if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3591                 return TRUE;
3592         else
3593                 return FALSE;
3594 }
3595
3596 static guint32
3597 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3598 {
3599         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3600         
3601         g_assert (index);
3602
3603         return index - 1;
3604 }
3605
3606 static int
3607 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3608 {
3609         int index;
3610
3611         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3612         if (index)
3613                 return index - 1;
3614
3615         index = acfg->method_index;
3616         add_method_with_index (acfg, method, index, extra);
3617
3618         g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3619
3620         g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3621
3622         acfg->method_index ++;
3623
3624         return index;
3625 }
3626
3627 static int
3628 add_method (MonoAotCompile *acfg, MonoMethod *method)
3629 {
3630         return add_method_full (acfg, method, FALSE, 0);
3631 }
3632
3633 static void
3634 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3635 {
3636         if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3637                 method = mini_get_shared_method (method);
3638         else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3639                 /* Use the gsharedvt version */
3640                 method = mini_get_shared_method_full (method, TRUE, TRUE);
3641
3642         if (acfg->aot_opts.log_generics)
3643                 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3644
3645         add_method_full (acfg, method, TRUE, depth);
3646 }
3647
3648 static void
3649 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3650 {
3651         add_extra_method_with_depth (acfg, method, 0);
3652 }
3653
3654 static void
3655 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3656 {
3657         MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3658         MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3659         MonoMethod *wrapper;
3660         char *name;
3661
3662         if (!callinfo->sig)
3663                 return;
3664
3665         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3666         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3667         g_free (name);
3668
3669         add_method (acfg, wrapper);
3670 }
3671
3672 static MonoMethod*
3673 get_runtime_invoke_sig (MonoMethodSignature *sig)
3674 {
3675         MonoMethodBuilder *mb;
3676         MonoMethod *m;
3677
3678         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3679         m = mono_mb_create_method (mb, sig, 16);
3680         MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3681         mono_mb_free (mb);
3682         return invoke;
3683 }
3684
3685 static MonoMethod*
3686 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3687 {
3688         return mono_marshal_get_runtime_invoke (method, virtual_);
3689 }
3690
3691 static gboolean
3692 can_marshal_struct (MonoClass *klass)
3693 {
3694         MonoClassField *field;
3695         gboolean can_marshal = TRUE;
3696         gpointer iter = NULL;
3697         MonoMarshalType *info;
3698         int i;
3699
3700         if (mono_class_is_auto_layout (klass))
3701                 return FALSE;
3702
3703         info = mono_marshal_load_type_info (klass);
3704
3705         /* Only allow a few field types to avoid asserts in the marshalling code */
3706         while ((field = mono_class_get_fields (klass, &iter))) {
3707                 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3708                         continue;
3709
3710                 switch (field->type->type) {
3711                 case MONO_TYPE_I4:
3712                 case MONO_TYPE_U4:
3713                 case MONO_TYPE_I1:
3714                 case MONO_TYPE_U1:
3715                 case MONO_TYPE_BOOLEAN:
3716                 case MONO_TYPE_I2:
3717                 case MONO_TYPE_U2:
3718                 case MONO_TYPE_CHAR:
3719                 case MONO_TYPE_I8:
3720                 case MONO_TYPE_U8:
3721                 case MONO_TYPE_I:
3722                 case MONO_TYPE_U:
3723                 case MONO_TYPE_PTR:
3724                 case MONO_TYPE_R4:
3725                 case MONO_TYPE_R8:
3726                 case MONO_TYPE_STRING:
3727                         break;
3728                 case MONO_TYPE_VALUETYPE:
3729                         if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3730                                 can_marshal = FALSE;
3731                         break;
3732                 case MONO_TYPE_SZARRAY: {
3733                         gboolean has_mspec = FALSE;
3734
3735                         if (info) {
3736                                 for (i = 0; i < info->num_fields; ++i) {
3737                                         if (info->fields [i].field == field && info->fields [i].mspec)
3738                                                 has_mspec = TRUE;
3739                                 }
3740                         }
3741                         if (!has_mspec)
3742                                 can_marshal = FALSE;
3743                         break;
3744                 }
3745                 default:
3746                         can_marshal = FALSE;
3747                         break;
3748                 }
3749         }
3750
3751         /* Special cases */
3752         /* Its hard to compute whenever these can be marshalled or not */
3753         if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3754                 return TRUE;
3755
3756         return can_marshal;
3757 }
3758
3759 static void
3760 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3761 {
3762         /* Create a vtype instantiation */
3763         MonoGenericContext shared_context;
3764         MonoType **args;
3765         MonoGenericInst *inst;
3766         MonoGenericContainer *container;
3767         MonoClass **constraints;
3768         int i;
3769
3770         memset (ctx, 0, sizeof (MonoGenericContext));
3771
3772         if (mono_class_is_gtd (method->klass)) {
3773                 shared_context = mono_class_get_generic_container (method->klass)->context;
3774                 inst = shared_context.class_inst;
3775
3776                 args = g_new0 (MonoType*, inst->type_argc);
3777                 for (i = 0; i < inst->type_argc; ++i) {
3778                         args [i] = &mono_defaults.int_class->byval_arg;
3779                 }
3780                 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3781         }
3782         if (method->is_generic) {
3783                 container = mono_method_get_generic_container (method);
3784                 shared_context = container->context;
3785                 inst = shared_context.method_inst;
3786
3787                 args = g_new0 (MonoType*, inst->type_argc);
3788                 for (i = 0; i < container->type_argc; ++i) {
3789                         MonoGenericParamInfo *info = &container->type_params [i].info;
3790                         gboolean ref_only = FALSE;
3791
3792                         if (info && info->constraints) {
3793                                 constraints = info->constraints;
3794
3795                                 while (*constraints) {
3796                                         MonoClass *cklass = *constraints;
3797                                         if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3798                                                 /* Inflaring the method with our vtype would not be valid */
3799                                                 ref_only = TRUE;
3800                                         constraints ++;
3801                                 }
3802                         }
3803
3804                         if (ref_only)
3805                                 args [i] = &mono_defaults.object_class->byval_arg;
3806                         else
3807                                 args [i] = &mono_defaults.int_class->byval_arg;
3808                 }
3809                 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3810         }
3811 }
3812
3813 static void
3814 add_wrappers (MonoAotCompile *acfg)
3815 {
3816         MonoMethod *method, *m;
3817         int i, j;
3818         MonoMethodSignature *sig, *csig;
3819         guint32 token;
3820
3821         /* 
3822          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3823          * so there is only one wrapper of a given type, or inlining their contents into their
3824          * callers.
3825          */
3826         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3827                 MonoError error;
3828                 MonoMethod *method;
3829                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3830                 gboolean skip = FALSE;
3831
3832                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3833                 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3834
3835                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3836                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3837                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3838                         skip = TRUE;
3839
3840                 /* Skip methods which can not be handled by get_runtime_invoke () */
3841                 sig = mono_method_signature (method);
3842                 if (!sig)
3843                         continue;
3844                 if ((sig->ret->type == MONO_TYPE_PTR) ||
3845                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3846                         skip = TRUE;
3847                 if (mono_class_is_open_constructed_type (sig->ret))
3848                         skip = TRUE;
3849
3850                 for (j = 0; j < sig->param_count; j++) {
3851                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3852                                 skip = TRUE;
3853                         if (mono_class_is_open_constructed_type (sig->params [j]))
3854                                 skip = TRUE;
3855                 }
3856
3857 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3858                 if (!mono_class_is_contextbound (method->klass)) {
3859                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3860                         gboolean has_nullable = FALSE;
3861
3862                         for (j = 0; j < sig->param_count; j++) {
3863                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3864                                         has_nullable = TRUE;
3865                         }
3866
3867                         if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3868                                 /* Supported by the dynamic runtime-invoke wrapper */
3869                                 skip = TRUE;
3870                         }
3871                         if (info)
3872                                 mono_arch_dyn_call_free (info);
3873                 }
3874 #endif
3875
3876                 if (acfg->aot_opts.llvm_only)
3877                         /* Supported by the gsharedvt based runtime-invoke wrapper */
3878                         skip = TRUE;
3879
3880                 if (!skip) {
3881                         //printf ("%s\n", mono_method_full_name (method, TRUE));
3882                         add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3883                 }
3884         }
3885
3886         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3887                 int nallocators;
3888
3889                 /* Runtime invoke wrappers */
3890
3891                 /* void runtime-invoke () [.cctor] */
3892                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3893                 csig->ret = &mono_defaults.void_class->byval_arg;
3894                 add_method (acfg, get_runtime_invoke_sig (csig));
3895
3896                 /* void runtime-invoke () [Finalize] */
3897                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3898                 csig->hasthis = 1;
3899                 csig->ret = &mono_defaults.void_class->byval_arg;
3900                 add_method (acfg, get_runtime_invoke_sig (csig));
3901
3902                 /* void runtime-invoke (string) [exception ctor] */
3903                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3904                 csig->hasthis = 1;
3905                 csig->ret = &mono_defaults.void_class->byval_arg;
3906                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3907                 add_method (acfg, get_runtime_invoke_sig (csig));
3908
3909                 /* void runtime-invoke (string, string) [exception ctor] */
3910                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3911                 csig->hasthis = 1;
3912                 csig->ret = &mono_defaults.void_class->byval_arg;
3913                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3914                 csig->params [1] = &mono_defaults.string_class->byval_arg;
3915                 add_method (acfg, get_runtime_invoke_sig (csig));
3916
3917                 /* string runtime-invoke () [Exception.ToString ()] */
3918                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3919                 csig->hasthis = 1;
3920                 csig->ret = &mono_defaults.string_class->byval_arg;
3921                 add_method (acfg, get_runtime_invoke_sig (csig));
3922
3923                 /* void runtime-invoke (string, Exception) [exception ctor] */
3924                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3925                 csig->hasthis = 1;
3926                 csig->ret = &mono_defaults.void_class->byval_arg;
3927                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3928                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3929                 add_method (acfg, get_runtime_invoke_sig (csig));
3930
3931                 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
3932                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
3933                 csig->hasthis = 1;
3934                 csig->ret = &(mono_class_load_from_name (
3935                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3936                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3937                 csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3938                 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
3939                 add_method (acfg, get_runtime_invoke_sig (csig));
3940
3941                 /* runtime-invoke used by finalizers */
3942                 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3943
3944                 /* This is used by mono_runtime_capture_context () */
3945                 method = mono_get_context_capture_method ();
3946                 if (method)
3947                         add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3948
3949 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3950                 if (!acfg->aot_opts.llvm_only)
3951                         add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3952 #endif
3953
3954                 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3955                 if (acfg->aot_opts.llvm_only) {
3956                         int variants;
3957
3958                         /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3959                         for (variants = 0; variants < 4; ++variants) {
3960                                 for (i = 0; i < 16; ++i) {
3961                                         sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3962                                         add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3963
3964                                         g_free (sig);
3965                                 }
3966                         }
3967                 }
3968
3969                 /* stelemref */
3970                 add_method (acfg, mono_marshal_get_stelemref ());
3971
3972                 /* Managed Allocators */
3973                 nallocators = mono_gc_get_managed_allocator_types ();
3974                 for (i = 0; i < nallocators; ++i) {
3975                         if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3976                                 add_method (acfg, m);
3977                         if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3978                                 add_method (acfg, m);
3979                 }
3980
3981                 /* write barriers */
3982                 if (mono_gc_is_moving ()) {
3983                         add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3984                         add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3985                 }
3986
3987                 /* Stelemref wrappers */
3988                 {
3989                         MonoMethod **wrappers;
3990                         int nwrappers;
3991
3992                         wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3993                         for (i = 0; i < nwrappers; ++i)
3994                                 add_method (acfg, wrappers [i]);
3995                         g_free (wrappers);
3996                 }
3997
3998                 /* castclass_with_check wrapper */
3999                 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4000                 /* isinst_with_check wrapper */
4001                 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4002
4003                 /* JIT icall wrappers */
4004                 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4005                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4006         }
4007
4008         /* 
4009          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4010          * we use the original method instead at runtime.
4011          * Since full-aot doesn't support remoting, this is not a problem.
4012          */
4013 #if 0
4014         /* remoting-invoke wrappers */
4015         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4016                 MonoError error;
4017                 MonoMethodSignature *sig;
4018                 
4019                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4020                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4021                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4022
4023                 sig = mono_method_signature (method);
4024
4025                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4026                         m = mono_marshal_get_remoting_invoke_with_check (method);
4027
4028                         add_method (acfg, m);
4029                 }
4030         }
4031 #endif
4032
4033         /* delegate-invoke wrappers */
4034         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4035                 MonoError error;
4036                 MonoClass *klass;
4037                 MonoCustomAttrInfo *cattr;
4038                 
4039                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4040                 klass = mono_class_get_checked (acfg->image, token, &error);
4041
4042                 if (!klass) {
4043                         mono_error_cleanup (&error);
4044                         continue;
4045                 }
4046
4047                 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4048                         continue;
4049
4050                 if (!mono_class_is_gtd (klass)) {
4051                         method = mono_get_delegate_invoke (klass);
4052
4053                         m = mono_marshal_get_delegate_invoke (method, NULL);
4054
4055                         add_method (acfg, m);
4056
4057                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4058                         if (method)
4059                                 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4060
4061                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4062                         if (method)
4063                                 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4064
4065                         cattr = mono_custom_attrs_from_class_checked (klass, &error);
4066                         if (!is_ok (&error)) {
4067                                 mono_error_cleanup (&error);
4068                                 continue;
4069                         }
4070
4071                         if (cattr) {
4072                                 int j;
4073
4074                                 for (j = 0; j < cattr->num_attrs; ++j)
4075                                         if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4076                                                 break;
4077                                 if (j < cattr->num_attrs) {
4078                                         MonoMethod *invoke;
4079                                         MonoMethod *wrapper;
4080                                         MonoMethod *del_invoke;
4081
4082                                         /* Add wrappers needed by mono_ftnptr_to_delegate () */
4083                                         invoke = mono_get_delegate_invoke (klass);
4084                                         wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4085                                         del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4086                                         add_method (acfg, wrapper);
4087                                         add_method (acfg, del_invoke);
4088                                 }
4089                         }
4090                 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4091                         MonoError error;
4092                         MonoGenericContext ctx;
4093                         MonoMethod *inst, *gshared;
4094
4095                         /*
4096                          * Emit gsharedvt versions of the generic delegate-invoke wrappers
4097                          */
4098                         /* Invoke */
4099                         method = mono_get_delegate_invoke (klass);
4100                         create_gsharedvt_inst (acfg, method, &ctx);
4101
4102                         inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4103                         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4104
4105                         m = mono_marshal_get_delegate_invoke (inst, NULL);
4106                         g_assert (m->is_inflated);
4107
4108                         gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4109                         add_extra_method (acfg, gshared);
4110
4111                         /* begin-invoke */
4112                         method = mono_get_delegate_begin_invoke (klass);
4113                         if (method) {
4114                                 create_gsharedvt_inst (acfg, method, &ctx);
4115
4116                                 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4117                                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4118
4119                                 m = mono_marshal_get_delegate_begin_invoke (inst);
4120                                 g_assert (m->is_inflated);
4121
4122                                 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4123                                 add_extra_method (acfg, gshared);
4124                         }
4125
4126                         /* end-invoke */
4127                         method = mono_get_delegate_end_invoke (klass);
4128                         if (method) {
4129                                 create_gsharedvt_inst (acfg, method, &ctx);
4130
4131                                 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4132                                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4133
4134                                 m = mono_marshal_get_delegate_end_invoke (inst);
4135                                 g_assert (m->is_inflated);
4136
4137                                 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4138                                 add_extra_method (acfg, gshared);
4139                         }
4140                 }
4141         }
4142
4143         /* array access wrappers */
4144         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4145                 MonoError error;
4146                 MonoClass *klass;
4147                 
4148                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4149                 klass = mono_class_get_checked (acfg->image, token, &error);
4150
4151                 if (!klass) {
4152                         mono_error_cleanup (&error);
4153                         continue;
4154                 }
4155
4156                 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4157                         MonoMethod *m, *wrapper;
4158
4159                         /* Add runtime-invoke wrappers too */
4160
4161                         m = mono_class_get_method_from_name (klass, "Get", -1);
4162                         g_assert (m);
4163                         wrapper = mono_marshal_get_array_accessor_wrapper (m);
4164                         add_extra_method (acfg, wrapper);
4165                         if (!acfg->aot_opts.llvm_only)
4166                                 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4167
4168                         m = mono_class_get_method_from_name (klass, "Set", -1);
4169                         g_assert (m);
4170                         wrapper = mono_marshal_get_array_accessor_wrapper (m);
4171                         add_extra_method (acfg, wrapper);
4172                         if (!acfg->aot_opts.llvm_only)
4173                                 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4174                 }
4175         }
4176
4177         /* Synchronized wrappers */
4178         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4179                 MonoError error;
4180                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4181                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4182                 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4183
4184                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4185                         if (method->is_generic) {
4186                                 // FIXME:
4187                         } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4188                                 MonoError error;
4189                                 MonoGenericContext ctx;
4190                                 MonoMethod *inst, *gshared, *m;
4191
4192                                 /*
4193                                  * Create a generic wrapper for a generic instance, and AOT that.
4194                                  */
4195                                 create_gsharedvt_inst (acfg, method, &ctx);
4196                                 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4197                                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4198                                 m = mono_marshal_get_synchronized_wrapper (inst);
4199                                 g_assert (m->is_inflated);
4200                                 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4201                                 add_method (acfg, gshared);
4202                         } else {
4203                                 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4204                         }
4205                 }
4206         }
4207
4208         /* pinvoke wrappers */
4209         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4210                 MonoError error;
4211                 MonoMethod *method;
4212                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4213
4214                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4215                 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4216
4217                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4218                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4219                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4220                 }
4221
4222                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4223                         if (acfg->aot_opts.llvm_only) {
4224                                 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4225                                 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE);
4226                         }
4227                 }
4228         }
4229  
4230         /* native-to-managed wrappers */
4231         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4232                 MonoError error;
4233                 MonoMethod *method;
4234                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4235                 MonoCustomAttrInfo *cattr;
4236                 int j;
4237
4238                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4239                 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4240
4241                 /* 
4242                  * Only generate native-to-managed wrappers for methods which have an
4243                  * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4244                  * name to avoid defining a new assembly to contain it.
4245                  */
4246                 cattr = mono_custom_attrs_from_method_checked (method, &error);
4247                 if (!is_ok (&error)) {
4248                         char *name = mono_method_get_full_name (method);
4249                         report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4250                         g_free (name);
4251                 }
4252
4253                 if (cattr) {
4254                         for (j = 0; j < cattr->num_attrs; ++j)
4255                                 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4256                                         break;
4257                         if (j < cattr->num_attrs) {
4258                                 MonoCustomAttrEntry *e = &cattr->attrs [j];
4259                                 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4260                                 const char *p = (const char*)e->data;
4261                                 const char *named;
4262                                 int slen, num_named, named_type;
4263                                 char *n;
4264                                 MonoType *t;
4265                                 MonoClass *klass;
4266                                 char *export_name = NULL;
4267                                 MonoMethod *wrapper;
4268
4269                                 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4270                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4271                                         g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks", 
4272                                                 mono_method_full_name (method, TRUE));
4273                                         exit (1);
4274                                 }
4275
4276                                 g_assert (sig->param_count == 1);
4277                                 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4278
4279                                 /* 
4280                                  * Decode the cattr manually since we can't create objects
4281                                  * during aot compilation.
4282                                  */
4283                                         
4284                                 /* Skip prolog */
4285                                 p += 2;
4286
4287                                 /* From load_cattr_value () in reflection.c */
4288                                 slen = mono_metadata_decode_value (p, &p);
4289                                 n = (char *)g_memdup (p, slen + 1);
4290                                 n [slen] = 0;
4291                                 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4292                                 g_assert (t);
4293                                 mono_error_assert_ok (&error);
4294                                 g_free (n);
4295
4296                                 klass = mono_class_from_mono_type (t);
4297                                 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4298
4299                                 p += slen;
4300
4301                                 num_named = read16 (p);
4302                                 p += 2;
4303
4304                                 g_assert (num_named < 2);
4305                                 if (num_named == 1) {
4306                                         int name_len;
4307                                         char *name;
4308
4309                                         /* parse ExportSymbol attribute */
4310                                         named = p;
4311                                         named_type = *named;
4312                                         named += 1;
4313                                         /* data_type = *named; */
4314                                         named += 1;
4315
4316                                         name_len = mono_metadata_decode_blob_size (named, &named);
4317                                         name = (char *)g_malloc (name_len + 1);
4318                                         memcpy (name, named, name_len);
4319                                         name [name_len] = 0;
4320                                         named += name_len;
4321
4322                                         g_assert (named_type == 0x54);
4323                                         g_assert (!strcmp (name, "ExportSymbol"));
4324
4325                                         /* load_cattr_value (), string case */
4326                                         g_assert (*named != (char)0xff);
4327                                         slen = mono_metadata_decode_value (named, &named);
4328                                         export_name = (char *)g_malloc (slen + 1);
4329                                         memcpy (export_name, named, slen);
4330                                         export_name [slen] = 0;
4331                                         named += slen;
4332                                 }
4333
4334                                 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, &error);
4335                                 mono_error_assert_ok (&error);
4336
4337                                 add_method (acfg, wrapper);
4338                                 if (export_name)
4339                                         g_hash_table_insert (acfg->export_names, wrapper, export_name);
4340                         }
4341                         g_free (cattr);
4342                 }
4343
4344                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4345                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4346                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4347                 }
4348         }
4349
4350         /* StructureToPtr/PtrToStructure wrappers */
4351         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4352                 MonoError error;
4353                 MonoClass *klass;
4354                 
4355                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4356                 klass = mono_class_get_checked (acfg->image, token, &error);
4357
4358                 if (!klass) {
4359                         mono_error_cleanup (&error);
4360                         continue;
4361                 }
4362
4363                 if (klass->valuetype && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4364                         !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4365                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4366                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4367                 }
4368         }
4369 }
4370
4371 static gboolean
4372 has_type_vars (MonoClass *klass)
4373 {
4374         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4375                 return TRUE;
4376         if (klass->rank)
4377                 return has_type_vars (klass->element_class);
4378         if (mono_class_is_ginst (klass)) {
4379                 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4380                 if (context->class_inst) {
4381                         int i;
4382
4383                         for (i = 0; i < context->class_inst->type_argc; ++i)
4384                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4385                                         return TRUE;
4386                 }
4387         }
4388         if (mono_class_is_gtd (klass))
4389                 return TRUE;
4390         return FALSE;
4391 }
4392
4393 static gboolean
4394 is_vt_inst (MonoGenericInst *inst)
4395 {
4396         int i;
4397
4398         for (i = 0; i < inst->type_argc; ++i) {
4399                 MonoType *t = inst->type_argv [i];
4400                 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4401                         return TRUE;
4402         }
4403         return FALSE;
4404 }
4405
4406 static gboolean
4407 method_has_type_vars (MonoMethod *method)
4408 {
4409         if (has_type_vars (method->klass))
4410                 return TRUE;
4411
4412         if (method->is_inflated) {
4413                 MonoGenericContext *context = mono_method_get_context (method);
4414                 if (context->method_inst) {
4415                         int i;
4416
4417                         for (i = 0; i < context->method_inst->type_argc; ++i)
4418                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4419                                         return TRUE;
4420                 }
4421         }
4422         return FALSE;
4423 }
4424
4425 static
4426 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4427 {
4428         return opts->mode == MONO_AOT_MODE_FULL;
4429 }
4430
4431 static
4432 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4433 {
4434         return opts->mode == MONO_AOT_MODE_HYBRID;
4435 }
4436
4437 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4438
4439 static void
4440 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4441 {
4442         /* This might lead to a huge code blowup so only do it if neccesary */
4443         if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4444                 return;
4445
4446         add_generic_class_with_depth (acfg, klass, 0, ref);
4447 }
4448
4449 static gboolean
4450 check_type_depth (MonoType *t, int depth)
4451 {
4452         int i;
4453
4454         if (depth > 8)
4455                 return TRUE;
4456
4457         switch (t->type) {
4458         case MONO_TYPE_GENERICINST: {
4459                 MonoGenericClass *gklass = t->data.generic_class;
4460                 MonoGenericInst *ginst = gklass->context.class_inst;
4461
4462                 if (ginst) {
4463                         for (i = 0; i < ginst->type_argc; ++i) {
4464                                 if (check_type_depth (ginst->type_argv [i], depth + 1))
4465                                         return TRUE;
4466                         }
4467                 }
4468                 break;
4469         }
4470         default:
4471                 break;
4472         }
4473
4474         return FALSE;
4475 }
4476
4477 static void
4478 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4479
4480 /*
4481  * add_generic_class:
4482  *
4483  *   Add all methods of a generic class.
4484  */
4485 static void
4486 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4487 {
4488         MonoMethod *method;
4489         MonoClassField *field;
4490         gpointer iter;
4491         gboolean use_gsharedvt = FALSE;
4492
4493         if (!acfg->ginst_hash)
4494                 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4495
4496         mono_class_init (klass);
4497
4498         if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4499                 return;
4500
4501         if (has_type_vars (klass))
4502                 return;
4503
4504         if (!mono_class_is_ginst (klass) && !klass->rank)
4505                 return;
4506
4507         if (mono_class_has_failure (klass))
4508                 return;
4509
4510         if (!acfg->ginst_hash)
4511                 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4512
4513         if (g_hash_table_lookup (acfg->ginst_hash, klass))
4514                 return;
4515
4516         if (check_type_depth (&klass->byval_arg, 0))
4517                 return;
4518
4519         if (acfg->aot_opts.log_generics)
4520                 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4521
4522         g_hash_table_insert (acfg->ginst_hash, klass, klass);
4523
4524         /*
4525          * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4526          * Enable this only for some classes since gsharedvt might not support all methods.
4527          */
4528         if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst (mono_class_get_generic_class (klass)->context.class_inst) &&
4529                 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4530                 use_gsharedvt = TRUE;
4531
4532         iter = NULL;
4533         while ((method = mono_class_get_methods (klass, &iter))) {
4534                 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4535                         /*
4536                          * This is partial sharing, and we can't handle it yet
4537                          */
4538                         continue;
4539                 }
4540                 
4541                 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4542                         /* Already added */
4543                         add_types_from_method_header (acfg, method);
4544                         continue;
4545                 }
4546
4547                 if (method->is_generic)
4548                         /* FIXME: */
4549                         continue;
4550
4551                 /*
4552                  * FIXME: Instances which are referenced by these methods are not added,
4553                  * for example Array.Resize<int> for List<int>.Add ().
4554                  */
4555                 add_extra_method_with_depth (acfg, method, depth + 1);
4556         }
4557
4558         iter = NULL;
4559         while ((field = mono_class_get_fields (klass, &iter))) {
4560                 if (field->type->type == MONO_TYPE_GENERICINST)
4561                         add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4562         }
4563
4564         if (klass->delegate) {
4565                 method = mono_get_delegate_invoke (klass);
4566
4567                 method = mono_marshal_get_delegate_invoke (method, NULL);
4568
4569                 if (acfg->aot_opts.log_generics)
4570                         aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4571
4572                 add_method (acfg, method);
4573         }
4574
4575         /* Add superclasses */
4576         if (klass->parent)
4577                 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4578
4579         /* 
4580          * For ICollection<T>, add instances of the helper methods
4581          * in Array, since a T[] could be cast to ICollection<T>.
4582          */
4583         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4584                 (!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"))) {
4585                 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4586                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4587                 gpointer iter;
4588                 char *name_prefix;
4589
4590                 if (!strcmp (klass->name, "IEnumerator`1"))
4591                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4592                 else
4593                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4594
4595                 /* Add the T[]/InternalEnumerator class */
4596                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4597                         MonoError error;
4598                         MonoClass *nclass;
4599
4600                         iter = NULL;
4601                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4602                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4603                                         break;
4604                         }
4605                         g_assert (nclass);
4606                         nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), &error);
4607                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4608                         add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4609                 }
4610
4611                 iter = NULL;
4612                 while ((method = mono_class_get_methods (array_class, &iter))) {
4613                         if (strstr (method->name, name_prefix)) {
4614                                 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4615
4616                                 add_extra_method_with_depth (acfg, m, depth);
4617                         }
4618                 }
4619
4620                 g_free (name_prefix);
4621         }
4622
4623         /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4624         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4625                 MonoError error;
4626                 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4627                 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4628                 MonoGenericContext ctx;
4629                 MonoType *args [16];
4630
4631                 memset (&ctx, 0, sizeof (ctx));
4632
4633                 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4634
4635                 args [0] = &tclass->byval_arg;
4636                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4637
4638                 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4639                 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4640
4641                 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4642                         MonoClass *gcomparer_inst;
4643                         gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4644                         gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4645                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4646
4647                         add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4648                 }
4649         }
4650
4651         /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4652         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4653                 MonoError error;
4654                 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4655                 MonoClass *iface, *gcomparer, *iface_inst;
4656                 MonoGenericContext ctx;
4657                 MonoType *args [16];
4658
4659                 memset (&ctx, 0, sizeof (ctx));
4660
4661                 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4662                 g_assert (iface);
4663                 args [0] = &tclass->byval_arg;
4664                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4665
4666                 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4667                 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4668
4669                 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4670                         MonoClass *gcomparer_inst;
4671                         MonoError error;
4672
4673                         gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4674                         gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4675                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4676                         add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4677                 }
4678         }
4679
4680         /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4681         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4682                 MonoClass *enum_comparer;
4683                 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4684                 MonoGenericContext ctx;
4685                 MonoType *args [16];
4686
4687                 if (mono_class_is_enum (tclass)) {
4688                         MonoClass *enum_comparer_inst;
4689                         MonoError error;
4690
4691                         memset (&ctx, 0, sizeof (ctx));
4692                         args [0] = &tclass->byval_arg;
4693                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4694
4695                         enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4696                         enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4697                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4698                         add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4699                 }
4700         }
4701
4702         /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4703         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4704                 MonoClass *comparer;
4705                 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4706                 MonoGenericContext ctx;
4707                 MonoType *args [16];
4708
4709                 if (mono_class_is_enum (tclass)) {
4710                         MonoClass *comparer_inst;
4711                         MonoError error;
4712
4713                         memset (&ctx, 0, sizeof (ctx));
4714                         args [0] = &tclass->byval_arg;
4715                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4716
4717                         comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4718                         comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4719                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4720                         add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4721                 }
4722         }
4723 }
4724
4725 static void
4726 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4727 {
4728         int i;
4729         MonoGenericContext ctx;
4730         MonoType *args [16];
4731
4732         if (acfg->aot_opts.no_instances)
4733                 return;
4734
4735         memset (&ctx, 0, sizeof (ctx));
4736
4737         for (i = 0; i < ninsts; ++i) {
4738                 MonoError error;
4739                 MonoClass *generic_inst;
4740                 args [0] = insts [i];
4741                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4742                 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4743                 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4744                 add_generic_class (acfg, generic_inst, force, "");
4745         }
4746 }
4747
4748 static void
4749 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4750 {
4751         MonoError error;
4752         MonoMethodHeader *header;
4753         MonoMethodSignature *sig;
4754         int j, depth;
4755
4756         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4757
4758         sig = mono_method_signature (method);
4759
4760         if (sig) {
4761                 for (j = 0; j < sig->param_count; ++j)
4762                         if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4763                                 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4764         }
4765
4766         header = mono_method_get_header_checked (method, &error);
4767
4768         if (header) {
4769                 for (j = 0; j < header->num_locals; ++j)
4770                         if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4771                                 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4772                 mono_metadata_free_mh (header);
4773         } else {
4774                 mono_error_cleanup (&error); /* FIXME report the error */
4775         }
4776
4777 }
4778
4779 /*
4780  * add_generic_instances:
4781  *
4782  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
4783  */
4784 static void
4785 add_generic_instances (MonoAotCompile *acfg)
4786 {
4787         int i;
4788         guint32 token;
4789         MonoMethod *method;
4790         MonoGenericContext *context;
4791
4792         if (acfg->aot_opts.no_instances)
4793                 return;
4794
4795         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4796                 MonoError error;
4797                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4798                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4799
4800                 if (!method) {
4801                         aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4802                         aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4803                         mono_error_cleanup (&error);
4804                         continue;
4805                 }
4806
4807                 if (method->klass->image != acfg->image)
4808                         continue;
4809
4810                 context = mono_method_get_context (method);
4811
4812                 if (context && ((context->class_inst && context->class_inst->is_open)))
4813                         continue;
4814
4815                 /*
4816                  * For open methods, create an instantiation which can be passed to the JIT.
4817                  * FIXME: Handle class_inst as well.
4818                  */
4819                 if (context && context->method_inst && context->method_inst->is_open) {
4820                         MonoError error;
4821                         MonoGenericContext shared_context;
4822                         MonoGenericInst *inst;
4823                         MonoType **type_argv;
4824                         int i;
4825                         MonoMethod *declaring_method;
4826                         gboolean supported = TRUE;
4827
4828                         /* Check that the context doesn't contain open constructed types */
4829                         if (context->class_inst) {
4830                                 inst = context->class_inst;
4831                                 for (i = 0; i < inst->type_argc; ++i) {
4832                                         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)
4833                                                 continue;
4834                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4835                                                 supported = FALSE;
4836                                 }
4837                         }
4838                         if (context->method_inst) {
4839                                 inst = context->method_inst;
4840                                 for (i = 0; i < inst->type_argc; ++i) {
4841                                         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)
4842                                                 continue;
4843                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4844                                                 supported = FALSE;
4845                                 }
4846                         }
4847
4848                         if (!supported)
4849                                 continue;
4850
4851                         memset (&shared_context, 0, sizeof (MonoGenericContext));
4852
4853                         inst = context->class_inst;
4854                         if (inst) {
4855                                 type_argv = g_new0 (MonoType*, inst->type_argc);
4856                                 for (i = 0; i < inst->type_argc; ++i) {
4857                                         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)
4858                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
4859                                         else
4860                                                 type_argv [i] = inst->type_argv [i];
4861                                 }
4862                                 
4863                                 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4864                                 g_free (type_argv);
4865                         }
4866
4867                         inst = context->method_inst;
4868                         if (inst) {
4869                                 type_argv = g_new0 (MonoType*, inst->type_argc);
4870                                 for (i = 0; i < inst->type_argc; ++i) {
4871                                         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)
4872                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
4873                                         else
4874                                                 type_argv [i] = inst->type_argv [i];
4875                                 }
4876
4877                                 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4878                                 g_free (type_argv);
4879                         }
4880
4881                         if (method->is_generic || mono_class_is_gtd (method->klass))
4882                                 declaring_method = method;
4883                         else
4884                                 declaring_method = mono_method_get_declaring_generic_method (method);
4885
4886                         method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4887                         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4888                 }
4889
4890                 /* 
4891                  * If the method is fully sharable, it was already added in place of its
4892                  * generic definition.
4893                  */
4894                 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4895                         continue;
4896
4897                 /*
4898                  * FIXME: Partially shared methods are not shared here, so we end up with
4899                  * many identical methods.
4900                  */
4901                 add_extra_method (acfg, method);
4902         }
4903
4904         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4905                 MonoError error;
4906                 MonoClass *klass;
4907
4908                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4909
4910                 klass = mono_class_get_checked (acfg->image, token, &error);
4911                 if (!klass || klass->rank) {
4912                         mono_error_cleanup (&error);
4913                         continue;
4914                 }
4915
4916                 add_generic_class (acfg, klass, FALSE, "typespec");
4917         }
4918
4919         /* Add types of args/locals */
4920         for (i = 0; i < acfg->methods->len; ++i) {
4921                 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4922                 add_types_from_method_header (acfg, method);
4923         }
4924
4925         if (acfg->image == mono_defaults.corlib) {
4926                 MonoClass *klass;
4927                 MonoType *insts [256];
4928                 int ninsts = 0;
4929
4930                 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4931                 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4932                 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4933                 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4934                 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4935                 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4936                 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4937                 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4938                 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4939                 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4940                 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4941                 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4942
4943                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4944                 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4945                 if (klass)
4946                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4947                 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4948                 if (klass)
4949                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4950
4951                 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4952                 {
4953                         MonoClass *enum_comparer;
4954                         MonoType *insts [16];
4955                         int ninsts;
4956
4957                         ninsts = 0;
4958                         insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4959                         insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4960                         insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4961                         insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4962                         enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4963                         add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4964
4965                         ninsts = 0;
4966                         insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4967                         enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4968                         add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4969
4970                         ninsts = 0;
4971                         insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4972                         enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4973                         add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4974
4975                         enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4976                         ninsts = 0;
4977                         insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4978                         insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4979                         add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4980                 }
4981
4982                 /* Add instances of the array generic interfaces for primitive types */
4983                 /* This will add instances of the InternalArray_ helper methods in Array too */
4984                 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4985                 if (klass)
4986                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4987
4988                 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4989                 if (klass)
4990                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4991
4992                 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4993                 if (klass)
4994                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4995
4996                 /* 
4997                  * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4998                  * used for all instances of GetGenericValueImpl by the AOT runtime.
4999                  */
5000                 {
5001                         MonoGenericContext ctx;
5002                         MonoType *args [16];
5003                         MonoMethod *get_method;
5004                         MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
5005
5006                         get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5007
5008                         if (get_method) {
5009                                 MonoError error;
5010                                 memset (&ctx, 0, sizeof (ctx));
5011                                 args [0] = &mono_defaults.object_class->byval_arg;
5012                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5013                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
5014                                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5015                         }
5016                 }
5017
5018                 /* Same for CompareExchange<T>/Exchange<T> */
5019                 {
5020                         MonoGenericContext ctx;
5021                         MonoType *args [16];
5022                         MonoMethod *m;
5023                         MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5024                         gpointer iter = NULL;
5025
5026                         while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5027                                 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5028                                         MonoError error;
5029                                         memset (&ctx, 0, sizeof (ctx));
5030                                         args [0] = &mono_defaults.object_class->byval_arg;
5031                                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5032                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5033                                         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5034                                 }
5035                         }
5036                 }
5037
5038                 /* Same for Volatile.Read/Write<T> */
5039                 {
5040                         MonoGenericContext ctx;
5041                         MonoType *args [16];
5042                         MonoMethod *m;
5043                         MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5044                         gpointer iter = NULL;
5045
5046                         if (volatile_klass) {
5047                                 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5048                                         if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5049                                                 MonoError error;
5050                                                 memset (&ctx, 0, sizeof (ctx));
5051                                                 args [0] = &mono_defaults.object_class->byval_arg;
5052                                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5053                                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5054                                                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5055                                         }
5056                                 }
5057                         }
5058                 }
5059
5060                 /* object[] accessor wrappers. */
5061                 for (i = 1; i < 4; ++i) {
5062                         MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
5063                         MonoMethod *m;
5064
5065                         m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5066                         g_assert (m);
5067
5068                         m = mono_marshal_get_array_accessor_wrapper (m);
5069                         add_extra_method (acfg, m);
5070
5071                         m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5072                         g_assert (m);
5073
5074                         m = mono_marshal_get_array_accessor_wrapper (m);
5075                         add_extra_method (acfg, m);
5076
5077                         m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5078                         g_assert (m);
5079
5080                         m = mono_marshal_get_array_accessor_wrapper (m);
5081                         add_extra_method (acfg, m);
5082                 }
5083         }
5084 }
5085
5086 /*
5087  * is_direct_callable:
5088  *
5089  *   Return whenever the method identified by JI is directly callable without 
5090  * going through the PLT.
5091  */
5092 static gboolean
5093 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5094 {
5095         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5096                 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5097                 if (callee_cfg) {
5098                         gboolean direct_callable = TRUE;
5099
5100                         if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5101                                 direct_callable = FALSE;
5102                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5103                                 // FIXME: Maybe call the wrapper directly ?
5104                                 direct_callable = FALSE;
5105
5106                         if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5107                                 /* Disable this so all calls go through load_method (), see the
5108                                  * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5109                                  * mono_debugger_agent_init ().
5110                                  */
5111                                 direct_callable = FALSE;
5112                         }
5113
5114                         if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5115                                 /* sgen does some initialization when the allocator method is created */
5116                                 direct_callable = FALSE;
5117                         if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5118                                 /* we don't know at compile time whether sgen is concurrent or not */
5119                                 direct_callable = FALSE;
5120
5121                         if (direct_callable)
5122                                 return TRUE;
5123                 }
5124         } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5125                 if (acfg->aot_opts.direct_pinvoke)
5126                         return TRUE;
5127         } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5128                 if (acfg->aot_opts.direct_icalls)
5129                         return TRUE;
5130                 return FALSE;
5131         }
5132
5133         return FALSE;
5134 }
5135
5136 #ifdef MONO_ARCH_AOT_SUPPORTED
5137 static const char *
5138 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5139 {
5140         MonoImage *image = method->klass->image;
5141         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5142         MonoTableInfo *tables = image->tables;
5143         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5144         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5145         guint32 im_cols [MONO_IMPLMAP_SIZE];
5146         char *import;
5147
5148         import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5149         if (import != NULL)
5150                 return import;
5151
5152         if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5153                 return NULL;
5154
5155         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5156
5157         if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5158                 return NULL;
5159
5160         import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5161
5162         g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5163         
5164         return import;
5165 }
5166 #else
5167 static const char *
5168 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5169 {
5170         return NULL;
5171 }
5172 #endif
5173
5174 static gint
5175 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5176 {
5177         if (a->native_offset == b->native_offset)
5178                 return a->il_offset - b->il_offset;
5179         else
5180                 return a->native_offset - b->native_offset;
5181 }
5182
5183 /*
5184  * compute_line_numbers:
5185  *
5186  * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5187  * entry.
5188  */
5189 static MonoDebugSourceLocation**
5190 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5191 {
5192         MonoDebugMethodInfo *minfo;
5193         MonoDebugLineNumberEntry *ln_array;
5194         MonoDebugSourceLocation *loc;
5195         int i, prev_line, prev_il_offset;
5196         int *native_to_il_offset = NULL;
5197         MonoDebugSourceLocation **res;
5198         gboolean first;
5199
5200         minfo = mono_debug_lookup_method (method);
5201         if (!minfo)
5202                 return NULL;
5203         // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5204         if (debug_info->code_size != code_size)
5205                 return NULL;
5206
5207         g_assert (code_size);
5208
5209         /* Compute the native->IL offset mapping */
5210
5211         ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5212         memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5213
5214         qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5215
5216         native_to_il_offset = g_new0 (int, code_size + 1);
5217
5218         for (i = 0; i < debug_info->num_line_numbers; ++i) {
5219                 int j;
5220                 MonoDebugLineNumberEntry *lne = &ln_array [i];
5221
5222                 if (i == 0) {
5223                         for (j = 0; j < lne->native_offset; ++j)
5224                                 native_to_il_offset [j] = -1;
5225                 }
5226
5227                 if (i < debug_info->num_line_numbers - 1) {
5228                         MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5229
5230                         for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5231                                 native_to_il_offset [j] = lne->il_offset;
5232                 } else {
5233                         for (j = lne->native_offset; j < code_size; ++j)
5234                                 native_to_il_offset [j] = lne->il_offset;
5235                 }
5236         }
5237         g_free (ln_array);
5238
5239         /* Compute the native->line number mapping */
5240         res = g_new0 (MonoDebugSourceLocation*, code_size);
5241         prev_il_offset = -1;
5242         prev_line = -1;
5243         first = TRUE;
5244         for (i = 0; i < code_size; ++i) {
5245                 int il_offset = native_to_il_offset [i];
5246
5247                 if (il_offset == -1 || il_offset == prev_il_offset)
5248                         continue;
5249                 prev_il_offset = il_offset;
5250                 loc = mono_debug_method_lookup_location (minfo, il_offset);
5251                 if (!(loc && loc->source_file))
5252                         continue;
5253                 if (loc->row == prev_line) {
5254                         mono_debug_free_source_location (loc);
5255                         continue;
5256                 }
5257                 prev_line = loc->row;
5258                 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5259                 if (first)
5260                         /* This will cover the prolog too */
5261                         res [0] = loc;
5262                 else
5263                         res [i] = loc;
5264                 first = FALSE;
5265         }
5266         return res;
5267 }
5268
5269 static int
5270 get_file_index (MonoAotCompile *acfg, const char *source_file)
5271 {
5272         int findex;
5273
5274         // FIXME: Free these
5275         if (!acfg->dwarf_ln_filenames)
5276                 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5277         findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5278         if (!findex) {
5279                 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5280                 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5281                 emit_unset_mode (acfg);
5282                 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5283         }
5284         return findex;
5285 }
5286
5287 #ifdef TARGET_ARM64
5288 #define INST_LEN 4
5289 #else
5290 #define INST_LEN 1
5291 #endif
5292
5293 /*
5294  * emit_and_reloc_code:
5295  *
5296  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5297  * is true, calls are made through the GOT too. This is used for emitting trampolines
5298  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5299  * since trampolines are needed to make PTL work.
5300  */
5301 static void
5302 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5303 {
5304         int i, pindex, start_index;
5305         GPtrArray *patches;
5306         MonoJumpInfo *patch_info;
5307         MonoDebugSourceLocation **locs = NULL;
5308         gboolean skip, prologue_end = FALSE;
5309 #ifdef MONO_ARCH_AOT_SUPPORTED
5310         gboolean direct_call, external_call;
5311         guint32 got_slot;
5312         const char *direct_call_target = 0;
5313         const char *direct_pinvoke;
5314 #endif
5315
5316         if (acfg->gas_line_numbers && method && debug_info) {
5317                 locs = compute_line_numbers (method, code_len, debug_info);
5318                 if (!locs) {
5319                         int findex = get_file_index (acfg, "<unknown>");
5320                         emit_unset_mode (acfg);
5321                         fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5322                 }
5323         }
5324
5325         /* Collect and sort relocations */
5326         patches = g_ptr_array_new ();
5327         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5328                 g_ptr_array_add (patches, patch_info);
5329         g_ptr_array_sort (patches, compare_patches);
5330
5331         start_index = 0;
5332         for (i = 0; i < code_len; i += INST_LEN) {
5333                 patch_info = NULL;
5334                 for (pindex = start_index; pindex < patches->len; ++pindex) {
5335                         patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5336                         if (patch_info->ip.i >= i)
5337                                 break;
5338                 }
5339
5340                 if (locs && locs [i]) {
5341                         MonoDebugSourceLocation *loc = locs [i];
5342                         int findex;
5343                         const char *options;
5344
5345                         findex = get_file_index (acfg, loc->source_file);
5346                         emit_unset_mode (acfg);
5347                         if (!prologue_end)
5348                                 options = " prologue_end";
5349                         else
5350                                 options = "";
5351                         prologue_end = TRUE;
5352                         fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5353                         mono_debug_free_source_location (loc);
5354                 }
5355
5356                 skip = FALSE;
5357 #ifdef MONO_ARCH_AOT_SUPPORTED
5358                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5359                         start_index = pindex;
5360
5361                         switch (patch_info->type) {
5362                         case MONO_PATCH_INFO_NONE:
5363                                 break;
5364                         case MONO_PATCH_INFO_GOT_OFFSET: {
5365                                 int code_size;
5366  
5367                                 arch_emit_got_offset (acfg, code + i, &code_size);
5368                                 i += code_size - INST_LEN;
5369                                 skip = TRUE;
5370                                 patch_info->type = MONO_PATCH_INFO_NONE;
5371                                 break;
5372                         }
5373                         case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5374                                 int code_size, index;
5375                                 char *selector = (char *)patch_info->data.target;
5376
5377                                 if (!acfg->objc_selector_to_index)
5378                                         acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5379                                 if (!acfg->objc_selectors)
5380                                         acfg->objc_selectors = g_ptr_array_new ();
5381                                 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5382                                 if (index)
5383                                         index --;
5384                                 else {
5385                                         index = acfg->objc_selector_index;
5386                                         g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5387                                         g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5388                                         acfg->objc_selector_index ++;
5389                                 }
5390
5391                                 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5392                                 i += code_size - INST_LEN;
5393                                 skip = TRUE;
5394                                 patch_info->type = MONO_PATCH_INFO_NONE;
5395                                 break;
5396                         }
5397                         default: {
5398                                 /*
5399                                  * If this patch is a call, try emitting a direct call instead of
5400                                  * through a PLT entry. This is possible if the called method is in
5401                                  * the same assembly and requires no initialization.
5402                                  */
5403                                 direct_call = FALSE;
5404                                 external_call = FALSE;
5405                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5406                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5407                                                 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5408                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5409                                                 direct_call = TRUE;
5410                                                 direct_call_target = callee_cfg->asm_symbol;
5411                                                 patch_info->type = MONO_PATCH_INFO_NONE;
5412                                                 acfg->stats.direct_calls ++;
5413                                         }
5414
5415                                         acfg->stats.all_calls ++;
5416                                 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5417                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5418                                                 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5419                                                         direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5420                                                 else
5421                                                         direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5422                                                 if (direct_pinvoke) {
5423                                                         direct_call = TRUE;
5424                                                         g_assert (strlen (direct_pinvoke) < 1000);
5425                                                         direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5426                                                 }
5427                                         }
5428                                 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5429                                         const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5430                                         if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5431                                                 /* Call to a C function implementing a jit icall */
5432                                                 direct_call = TRUE;
5433                                                 external_call = TRUE;
5434                                                 g_assert (strlen (sym) < 1000);
5435                                                 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5436                                         }
5437                                 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5438                                         MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5439                                         const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5440                                         if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5441                                                 /* Call to a jit icall without a wrapper */
5442                                                 direct_call = TRUE;
5443                                                 external_call = TRUE;
5444                                                 g_assert (strlen (sym) < 1000);
5445                                                 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5446                                         }
5447                                 }
5448
5449                                 if (direct_call) {
5450                                         patch_info->type = MONO_PATCH_INFO_NONE;
5451                                         acfg->stats.direct_calls ++;
5452                                 }
5453
5454                                 if (!got_only && !direct_call) {
5455                                         MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5456                                         if (plt_entry) {
5457                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5458                                                 direct_call = TRUE;
5459                                                 direct_call_target = plt_entry->symbol;
5460                 
5461                                                 /* Nullify the patch */
5462                                                 patch_info->type = MONO_PATCH_INFO_NONE;
5463                                                 plt_entry->jit_used = TRUE;
5464                                         }
5465                                 }
5466
5467                                 if (direct_call) {
5468                                         int call_size;
5469
5470                                         arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5471                                         i += call_size - INST_LEN;
5472                                 } else {
5473                                         int code_size;
5474
5475                                         got_slot = get_got_offset (acfg, FALSE, patch_info);
5476
5477                                         arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5478                                         i += code_size - INST_LEN;
5479                                 }
5480                                 skip = TRUE;
5481                         }
5482                         }
5483                 }
5484 #endif /* MONO_ARCH_AOT_SUPPORTED */
5485
5486                 if (!skip) {
5487                         /* Find next patch */
5488                         patch_info = NULL;
5489                         for (pindex = start_index; pindex < patches->len; ++pindex) {
5490                                 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5491                                 if (patch_info->ip.i >= i)
5492                                         break;
5493                         }
5494
5495                         /* Try to emit multiple bytes at once */
5496                         if (pindex < patches->len && patch_info->ip.i > i) {
5497                                 int limit;
5498
5499                                 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5500                                         if (locs && locs [limit])
5501                                                 break;
5502                                 }
5503
5504                                 emit_code_bytes (acfg, code + i, limit - i);
5505                                 i = limit - INST_LEN;
5506                         } else {
5507                                 emit_code_bytes (acfg, code + i, INST_LEN);
5508                         }
5509                 }
5510         }
5511
5512         g_ptr_array_free (patches, TRUE);
5513         g_free (locs);
5514 }
5515
5516 /*
5517  * sanitize_symbol:
5518  *
5519  *   Return a modified version of S which only includes characters permissible in symbols.
5520  */
5521 static char*
5522 sanitize_symbol (MonoAotCompile *acfg, char *s)
5523 {
5524         gboolean process = FALSE;
5525         int i, len;
5526         GString *gs;
5527         char *res;
5528
5529         if (!s)
5530                 return s;
5531
5532         len = strlen (s);
5533         for (i = 0; i < len; ++i)
5534                 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5535                         process = TRUE;
5536         if (!process)
5537                 return s;
5538
5539         gs = g_string_sized_new (len);
5540         for (i = 0; i < len; ++i) {
5541                 guint8 c = s [i];
5542                 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5543                         g_string_append_c (gs, c);
5544                 } else if (c > 0x7f) {
5545                         /* multi-byte utf8 */
5546                         g_string_append_printf (gs, "_0x%x", c);
5547                         i ++;
5548                         c = s [i];
5549                         while (c >> 6 == 0x2) {
5550                                 g_string_append_printf (gs, "%x", c);
5551                                 i ++;
5552                                 c = s [i];
5553                         }
5554                         g_string_append_printf (gs, "_");
5555                         i --;
5556                 } else {
5557                         g_string_append_c (gs, '_');
5558                 }
5559         }
5560
5561         res = mono_mempool_strdup (acfg->mempool, gs->str);
5562         g_string_free (gs, TRUE);
5563         return res;
5564 }
5565
5566 static char*
5567 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5568 {
5569         char *name1, *name2, *cached;
5570         int i, j, len, count;
5571         MonoMethod *cached_method;
5572
5573         name1 = mono_method_full_name (method, TRUE);
5574
5575 #ifdef TARGET_MACH
5576         // This is so that we don't accidentally create a local symbol (which starts with 'L')
5577         if ((!prefix || !*prefix) && name1 [0] == 'L')
5578                 prefix = "_";
5579 #endif
5580
5581 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5582         char adjustedPrefix [MAX_SYMBOL_SIZE];
5583         prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5584 #endif
5585
5586         len = strlen (name1);
5587         name2 = (char *)malloc (strlen (prefix) + len + 16);
5588         memcpy (name2, prefix, strlen (prefix));
5589         j = strlen (prefix);
5590         for (i = 0; i < len; ++i) {
5591                 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5592                         name2 [j ++] = '_';
5593                 } else if (isalnum (name1 [i])) {
5594                         name2 [j ++] = name1 [i];
5595                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5596                         i += 2;
5597                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5598                         name2 [j ++] = '_';
5599                         i++;
5600                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5601                 } else
5602                         name2 [j ++] = '_';
5603         }
5604         name2 [j] = '\0';
5605
5606         g_free (name1);
5607
5608         count = 0;
5609         while (TRUE) {
5610                 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5611                 if (!(cached_method && cached_method != method))
5612                         break;
5613                 sprintf (name2 + j, "_%d", count);
5614                 count ++;
5615         }
5616
5617         cached = g_strdup (name2);
5618         g_hash_table_insert (cache, cached, method);
5619
5620         return name2;
5621 }
5622
5623 static void
5624 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5625 {
5626         MonoMethod *method;
5627         int method_index;
5628         guint8 *code;
5629         char *debug_sym = NULL;
5630         char *symbol = NULL;
5631         int func_alignment = AOT_FUNC_ALIGNMENT;
5632         char *export_name;
5633
5634         method = cfg->orig_method;
5635         code = cfg->native_code;
5636
5637         method_index = get_method_index (acfg, method);
5638         symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5639
5640         /* Make the labels local */
5641         emit_section_change (acfg, ".text", 0);
5642         emit_alignment_code (acfg, func_alignment);
5643         
5644         if (acfg->global_symbols && acfg->need_no_dead_strip)
5645                 fprintf (acfg->fp, "    .no_dead_strip %s\n", cfg->asm_symbol);
5646         
5647         emit_label (acfg, cfg->asm_symbol);
5648
5649         if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5650                 /* 
5651                  * Write a C style symbol for every method, this has two uses:
5652                  * - it works on platforms where the dwarf debugging info is not
5653                  *   yet supported.
5654                  * - it allows the setting of breakpoints of aot-ed methods.
5655                  */
5656                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5657                 cfg->asm_debug_symbol = g_strdup (debug_sym);
5658
5659                 if (acfg->need_no_dead_strip)
5660                         fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
5661                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5662                 emit_label (acfg, debug_sym);
5663         }
5664
5665         export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5666         if (export_name) {
5667                 /* Emit a global symbol for the method */
5668                 emit_global_inner (acfg, export_name, TRUE);
5669                 emit_label (acfg, export_name);
5670         }
5671
5672         if (cfg->verbose_level > 0)
5673                 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5674
5675         acfg->stats.code_size += cfg->code_len;
5676
5677         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5678
5679         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 ()));
5680
5681         emit_line (acfg);
5682
5683         if (acfg->aot_opts.write_symbols) {
5684                 if (debug_sym)
5685                         emit_symbol_size (acfg, debug_sym, ".");
5686                 else
5687                         emit_symbol_size (acfg, cfg->asm_symbol, ".");
5688                 g_free (debug_sym);
5689         }
5690
5691         emit_label (acfg, symbol);
5692         g_free (symbol);
5693 }
5694
5695 /**
5696  * encode_patch:
5697  *
5698  *  Encode PATCH_INFO into its disk representation.
5699  */
5700 static void
5701 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5702 {
5703         guint8 *p = buf;
5704
5705         switch (patch_info->type) {
5706         case MONO_PATCH_INFO_NONE:
5707                 break;
5708         case MONO_PATCH_INFO_IMAGE:
5709                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5710                 break;
5711         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5712         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5713         case MONO_PATCH_INFO_GC_NURSERY_START:
5714         case MONO_PATCH_INFO_GC_NURSERY_BITS:
5715                 break;
5716         case MONO_PATCH_INFO_CASTCLASS_CACHE:
5717                 encode_value (patch_info->data.index, p, &p);
5718                 break;
5719         case MONO_PATCH_INFO_METHOD_REL:
5720                 encode_value ((gint)patch_info->data.offset, p, &p);
5721                 break;
5722         case MONO_PATCH_INFO_SWITCH: {
5723                 gpointer *table = (gpointer *)patch_info->data.table->table;
5724                 int k;
5725
5726                 encode_value (patch_info->data.table->table_size, p, &p);
5727                 for (k = 0; k < patch_info->data.table->table_size; k++)
5728                         encode_value ((int)(gssize)table [k], p, &p);
5729                 break;
5730         }
5731         case MONO_PATCH_INFO_METHODCONST:
5732         case MONO_PATCH_INFO_METHOD:
5733         case MONO_PATCH_INFO_METHOD_JUMP:
5734         case MONO_PATCH_INFO_ICALL_ADDR:
5735         case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5736         case MONO_PATCH_INFO_METHOD_RGCTX:
5737         case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5738                 encode_method_ref (acfg, patch_info->data.method, p, &p);
5739                 break;
5740         case MONO_PATCH_INFO_AOT_JIT_INFO:
5741         case MONO_PATCH_INFO_GET_TLS_TRAMP:
5742         case MONO_PATCH_INFO_SET_TLS_TRAMP:
5743                 encode_value (patch_info->data.index, p, &p);
5744                 break;
5745         case MONO_PATCH_INFO_INTERNAL_METHOD:
5746         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5747                 guint32 len = strlen (patch_info->data.name);
5748
5749                 encode_value (len, p, &p);
5750
5751                 memcpy (p, patch_info->data.name, len);
5752                 p += len;
5753                 *p++ = '\0';
5754                 break;
5755         }
5756         case MONO_PATCH_INFO_LDSTR: {
5757                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5758                 guint32 token = patch_info->data.token->token;
5759                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5760                 encode_value (image_index, p, &p);
5761                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5762                 break;
5763         }
5764         case MONO_PATCH_INFO_RVA:
5765         case MONO_PATCH_INFO_DECLSEC:
5766         case MONO_PATCH_INFO_LDTOKEN:
5767         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5768                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5769                 encode_value (patch_info->data.token->token, p, &p);
5770                 encode_value (patch_info->data.token->has_context, p, &p);
5771                 if (patch_info->data.token->has_context)
5772                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5773                 break;
5774         case MONO_PATCH_INFO_EXC_NAME: {
5775                 MonoClass *ex_class;
5776
5777                 ex_class =
5778                         mono_class_load_from_name (mono_defaults.exception_class->image,
5779                                                                   "System", (const char *)patch_info->data.target);
5780                 encode_klass_ref (acfg, ex_class, p, &p);
5781                 break;
5782         }
5783         case MONO_PATCH_INFO_R4:
5784                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5785                 break;
5786         case MONO_PATCH_INFO_R8:
5787                 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5788                 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5789                 break;
5790         case MONO_PATCH_INFO_VTABLE:
5791         case MONO_PATCH_INFO_CLASS:
5792         case MONO_PATCH_INFO_IID:
5793         case MONO_PATCH_INFO_ADJUSTED_IID:
5794                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5795                 break;
5796         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5797                 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5798                 if (patch_info->data.del_tramp->method) {
5799                         encode_value (1, p, &p);
5800                         encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5801                 } else {
5802                         encode_value (0, p, &p);
5803                 }
5804                 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5805                 break;
5806         case MONO_PATCH_INFO_FIELD:
5807         case MONO_PATCH_INFO_SFLDA:
5808                 encode_field_info (acfg, patch_info->data.field, p, &p);
5809                 break;
5810         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5811                 break;
5812         case MONO_PATCH_INFO_RGCTX_FETCH:
5813         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5814                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5815                 guint32 offset;
5816                 guint8 *buf2, *p2;
5817
5818                 /* 
5819                  * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5820                  * reference the same method, so encode the method only once.
5821                  */
5822                 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5823                 if (!offset) {
5824                         buf2 = (guint8 *)g_malloc (1024);
5825                         p2 = buf2;
5826
5827                         encode_method_ref (acfg, entry->method, p2, &p2);
5828                         g_assert (p2 - buf2 < 1024);
5829
5830                         offset = add_to_blob (acfg, buf2, p2 - buf2);
5831                         g_free (buf2);
5832
5833                         g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5834                 } else {
5835                         offset --;
5836                 }
5837
5838                 encode_value (offset, p, &p);
5839                 g_assert ((int)entry->info_type < 256);
5840                 g_assert (entry->data->type < 256);
5841                 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5842                 encode_patch (acfg, entry->data, p, &p);
5843                 break;
5844         }
5845         case MONO_PATCH_INFO_SEQ_POINT_INFO:
5846         case MONO_PATCH_INFO_AOT_MODULE:
5847                 break;
5848         case MONO_PATCH_INFO_SIGNATURE:
5849         case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5850                 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5851                 break;
5852         case MONO_PATCH_INFO_GSHAREDVT_CALL:
5853                 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5854                 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5855                 break;
5856         case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5857                 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5858                 int i;
5859
5860                 encode_method_ref (acfg, info->method, p, &p);
5861                 encode_value (info->num_entries, p, &p);
5862                 for (i = 0; i < info->num_entries; ++i) {
5863                         MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5864
5865                         encode_value (template_->info_type, p, &p);
5866                         switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5867                         case MONO_PATCH_INFO_CLASS:
5868                                 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5869                                 break;
5870                         case MONO_PATCH_INFO_FIELD:
5871                                 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5872                                 break;
5873                         default:
5874                                 g_assert_not_reached ();
5875                                 break;
5876                         }
5877                 }
5878                 break;
5879         }
5880         case MONO_PATCH_INFO_LDSTR_LIT: {
5881                 const char *s = (const char *)patch_info->data.target;
5882                 int len = strlen (s);
5883
5884                 encode_value (len, p, &p);
5885                 memcpy (p, s, len + 1);
5886                 p += len + 1;
5887                 break;
5888         }
5889         case MONO_PATCH_INFO_VIRT_METHOD:
5890                 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5891                 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5892                 break;
5893         case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5894         case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
5895                 break;
5896         default:
5897                 g_warning ("unable to handle jump info %d", patch_info->type);
5898                 g_assert_not_reached ();
5899         }
5900
5901         *endbuf = p;
5902 }
5903
5904 static void
5905 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5906 {
5907         guint8 *p = buf;
5908         guint32 pindex, offset;
5909         MonoJumpInfo *patch_info;
5910
5911         encode_value (n_patches, p, &p);
5912
5913         for (pindex = 0; pindex < patches->len; ++pindex) {
5914                 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5915
5916                 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5917                         /* Nothing to do */
5918                         continue;
5919
5920                 offset = get_got_offset (acfg, llvm, patch_info);
5921                 encode_value (offset, p, &p);
5922         }
5923
5924         *endbuf = p;
5925 }
5926
5927 static void
5928 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5929 {
5930         MonoMethod *method;
5931         int pindex, buf_size, n_patches;
5932         GPtrArray *patches;
5933         MonoJumpInfo *patch_info;
5934         guint32 method_index;
5935         guint8 *p, *buf;
5936         guint32 first_got_offset;
5937
5938         method = cfg->orig_method;
5939
5940         method_index = get_method_index (acfg, method);
5941
5942         /* Sort relocations */
5943         patches = g_ptr_array_new ();
5944         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5945                 g_ptr_array_add (patches, patch_info);
5946         g_ptr_array_sort (patches, compare_patches);
5947
5948         first_got_offset = acfg->cfgs [method_index]->got_offset;
5949
5950         /**********************/
5951         /* Encode method info */
5952         /**********************/
5953
5954         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5955         p = buf = (guint8 *)g_malloc (buf_size);
5956
5957         if (mono_class_get_cctor (method->klass)) {
5958                 encode_value (1, p, &p);
5959                 encode_klass_ref (acfg, method->klass, p, &p);
5960         } else {
5961                 /* Not needed when loading the method */
5962                 encode_value (0, p, &p);
5963         }
5964
5965         g_assert (!(cfg->opt & MONO_OPT_SHARED));
5966
5967         n_patches = 0;
5968         for (pindex = 0; pindex < patches->len; ++pindex) {
5969                 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5970                 
5971                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5972                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
5973                         patch_info->type = MONO_PATCH_INFO_NONE;
5974                         /* Nothing to do */
5975                         continue;
5976                 }
5977
5978                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5979                         /* Stored in a GOT slot initialized at module load time */
5980                         patch_info->type = MONO_PATCH_INFO_NONE;
5981                         continue;
5982                 }
5983
5984                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5985                         patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5986                         patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5987                         patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5988                         /* Stored in a GOT slot initialized at module load time */
5989                         patch_info->type = MONO_PATCH_INFO_NONE;
5990                         continue;
5991                 }
5992
5993                 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5994                         /* Calls are made through the PLT */
5995                         patch_info->type = MONO_PATCH_INFO_NONE;
5996                         continue;
5997                 }
5998
5999                 n_patches ++;
6000         }
6001
6002         if (n_patches)
6003                 g_assert (cfg->has_got_slots);
6004
6005         encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6006
6007         g_ptr_array_free (patches, TRUE);
6008
6009         acfg->stats.info_size += p - buf;
6010
6011         g_assert (p - buf < buf_size);
6012
6013         cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6014         g_free (buf);
6015 }
6016
6017 static guint32
6018 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6019 {
6020         guint32 cache_index;
6021         guint32 offset;
6022
6023         /* Reuse the unwind module to canonize and store unwind info entries */
6024         cache_index = mono_cache_unwind_info (encoded, encoded_len);
6025
6026         /* Use +/- 1 to distinguish 0s from missing entries */
6027         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6028         if (offset)
6029                 return offset - 1;
6030         else {
6031                 guint8 buf [16];
6032                 guint8 *p;
6033
6034                 /* 
6035                  * It would be easier to use assembler symbols, but the caller needs an
6036                  * offset now.
6037                  */
6038                 offset = acfg->unwind_info_offset;
6039                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6040                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6041
6042                 p = buf;
6043                 encode_value (encoded_len, p, &p);
6044
6045                 acfg->unwind_info_offset += encoded_len + (p - buf);
6046                 return offset;
6047         }
6048 }
6049
6050 static void
6051 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6052 {
6053         int i, k, buf_size;
6054         guint32 debug_info_size, seq_points_size;
6055         guint8 *code;
6056         MonoMethodHeader *header;
6057         guint8 *p, *buf, *debug_info;
6058         MonoJitInfo *jinfo = cfg->jit_info;
6059         guint32 flags;
6060         gboolean use_unwind_ops = FALSE;
6061         MonoSeqPointInfo *seq_points;
6062
6063         code = cfg->native_code;
6064         header = cfg->header;
6065
6066         if (!acfg->aot_opts.nodebug) {
6067                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6068         } else {
6069                 debug_info = NULL;
6070                 debug_info_size = 0;
6071         }
6072
6073         seq_points = cfg->seq_point_info;
6074         seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6075
6076         buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6077
6078         p = buf = (guint8 *)g_malloc (buf_size);
6079
6080         use_unwind_ops = cfg->unwind_ops != NULL;
6081
6082         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);
6083
6084         encode_value (flags, p, &p);
6085
6086         if (use_unwind_ops) {
6087                 guint32 encoded_len;
6088                 guint8 *encoded;
6089                 guint32 unwind_desc;
6090
6091                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6092
6093                 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6094                 encode_value (unwind_desc, p, &p);
6095
6096                 g_free (encoded);
6097         } else {
6098                 encode_value (jinfo->unwind_info, p, &p);
6099         }
6100
6101         /*Encode the number of holes before the number of clauses to make decoding easier*/
6102         if (jinfo->has_try_block_holes) {
6103                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6104                 encode_value (table->num_holes, p, &p);
6105         }
6106
6107         if (jinfo->has_arch_eh_info) {
6108                 /*
6109                  * In AOT mode, the code length is calculated from the address of the previous method,
6110                  * which could include alignment padding, so calculating the start of the epilog as
6111                  * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6112                  */
6113                 encode_value (jinfo->code_size, p, &p);
6114         }
6115
6116         /* Exception table */
6117         if (cfg->compile_llvm) {
6118                 /*
6119                  * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6120                  * since the information is only available to llc. Instead, we let llc save the data
6121                  * into the LSDA, and read it from there at runtime.
6122                  */
6123                 /* The assembly might be CIL stripped so emit the data ourselves */
6124                 if (header->num_clauses)
6125                         encode_value (header->num_clauses, p, &p);
6126
6127                 for (k = 0; k < header->num_clauses; ++k) {
6128                         MonoExceptionClause *clause;
6129
6130                         clause = &header->clauses [k];
6131
6132                         encode_value (clause->flags, p, &p);
6133                         if (clause->data.catch_class) {
6134                                 encode_value (1, p, &p);
6135                                 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6136                         } else {
6137                                 encode_value (0, p, &p);
6138                         }
6139
6140                         /* Emit the IL ranges too, since they might not be available at runtime */
6141                         encode_value (clause->try_offset, p, &p);
6142                         encode_value (clause->try_len, p, &p);
6143                         encode_value (clause->handler_offset, p, &p);
6144                         encode_value (clause->handler_len, p, &p);
6145
6146                         /* Emit a list of nesting clauses */
6147                         for (i = 0; i < header->num_clauses; ++i) {
6148                                 gint32 cindex1 = k;
6149                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6150                                 gint32 cindex2 = i;
6151                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6152
6153                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6154                                         encode_value (i, p, &p);
6155                         }
6156                         encode_value (-1, p, &p);
6157                 }
6158         } else {
6159                 if (jinfo->num_clauses)
6160                         encode_value (jinfo->num_clauses, p, &p);
6161
6162                 for (k = 0; k < jinfo->num_clauses; ++k) {
6163                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6164
6165                         encode_value (ei->flags, p, &p);
6166 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6167                         /* Not used for catch clauses */
6168                         if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6169                                 encode_value (ei->exvar_offset, p, &p);
6170 #else
6171                         encode_value (ei->exvar_offset, p, &p);
6172 #endif
6173
6174                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6175                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6176                         else {
6177                                 if (ei->data.catch_class) {
6178                                         guint8 *buf2, *p2;
6179                                         int len;
6180
6181                                         buf2 = (guint8 *)g_malloc (4096);
6182                                         p2 = buf2;
6183                                         encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6184                                         len = p2 - buf2;
6185                                         g_assert (len < 4096);
6186                                         encode_value (len, p, &p);
6187                                         memcpy (p, buf2, len);
6188                                         p += p2 - buf2;
6189                                         g_free (buf2);
6190                                 } else {
6191                                         encode_value (0, p, &p);
6192                                 }
6193                         }
6194
6195                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6196                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6197                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6198                 }
6199         }
6200
6201         if (jinfo->has_try_block_holes) {
6202                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6203                 for (i = 0; i < table->num_holes; ++i) {
6204                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6205                         encode_value (hole->clause, p, &p);
6206                         encode_value (hole->length, p, &p);
6207                         encode_value (hole->offset, p, &p);
6208                 }
6209         }
6210
6211         if (jinfo->has_arch_eh_info) {
6212                 MonoArchEHJitInfo *eh_info;
6213
6214                 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6215                 encode_value (eh_info->stack_size, p, &p);
6216                 encode_value (eh_info->epilog_size, p, &p);
6217         }
6218
6219         if (jinfo->has_generic_jit_info) {
6220                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6221                 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6222                 guint8 *buf2, *p2;
6223                 int len;
6224
6225                 encode_value (gi->nlocs, p, &p);
6226                 if (gi->nlocs) {
6227                         for (i = 0; i < gi->nlocs; ++i) {
6228                                 MonoDwarfLocListEntry *entry = &gi->locations [i];
6229
6230                                 encode_value (entry->is_reg ? 1 : 0, p, &p);
6231                                 encode_value (entry->reg, p, &p);
6232                                 if (!entry->is_reg)
6233                                         encode_value (entry->offset, p, &p);
6234                                 if (i == 0)
6235                                         g_assert (entry->from == 0);
6236                                 else
6237                                         encode_value (entry->from, p, &p);
6238                                 encode_value (entry->to, p, &p);
6239                         }
6240                 } else {
6241                         if (!cfg->compile_llvm) {
6242                                 encode_value (gi->has_this ? 1 : 0, p, &p);
6243                                 encode_value (gi->this_reg, p, &p);
6244                                 encode_value (gi->this_offset, p, &p);
6245                         }
6246                 }
6247
6248                 /* 
6249                  * Need to encode jinfo->method too, since it is not equal to 'method'
6250                  * when using generic sharing.
6251                  */
6252                 buf2 = (guint8 *)g_malloc (4096);
6253                 p2 = buf2;
6254                 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6255                 len = p2 - buf2;
6256                 g_assert (len < 4096);
6257                 encode_value (len, p, &p);
6258                 memcpy (p, buf2, len);
6259                 p += p2 - buf2;
6260                 g_free (buf2);
6261
6262                 if (gsctx && gsctx->is_gsharedvt) {
6263                         encode_value (1, p, &p);
6264                 } else {
6265                         encode_value (0, p, &p);
6266                 }
6267         }
6268
6269         if (seq_points_size)
6270                 p += mono_seq_point_info_write (seq_points, p);
6271
6272         g_assert (debug_info_size < buf_size);
6273
6274         encode_value (debug_info_size, p, &p);
6275         if (debug_info_size) {
6276                 memcpy (p, debug_info, debug_info_size);
6277                 p += debug_info_size;
6278                 g_free (debug_info);
6279         }
6280
6281         /* GC Map */
6282         if (cfg->gc_map) {
6283                 encode_value (cfg->gc_map_size, p, &p);
6284                 /* The GC map requires 4 bytes of alignment */
6285                 while ((gsize)p % 4)
6286                         p ++;
6287                 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6288                 p += cfg->gc_map_size;
6289         }
6290
6291         acfg->stats.ex_info_size += p - buf;
6292
6293         g_assert (p - buf < buf_size);
6294
6295         /* Emit info */
6296         /* The GC Map requires 4 byte alignment */
6297         cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6298         g_free (buf);
6299 }
6300
6301 static guint32
6302 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6303 {
6304         MonoError error;
6305         MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6306         guint8 *p, *buf;
6307         int i, buf_size, res;
6308         gboolean no_special_static, cant_encode;
6309         gpointer iter = NULL;
6310
6311         if (!klass) {
6312                 mono_error_cleanup (&error);
6313
6314                 buf_size = 16;
6315
6316                 p = buf = (guint8 *)g_malloc (buf_size);
6317
6318                 /* Mark as unusable */
6319                 encode_value (-1, p, &p);
6320
6321                 res = add_to_blob (acfg, buf, p - buf);
6322                 g_free (buf);
6323
6324                 return res;
6325         }
6326                 
6327         buf_size = 10240 + (klass->vtable_size * 16);
6328         p = buf = (guint8 *)g_malloc (buf_size);
6329
6330         g_assert (klass);
6331
6332         mono_class_init (klass);
6333
6334         mono_class_get_nested_types (klass, &iter);
6335         g_assert (klass->nested_classes_inited);
6336
6337         mono_class_setup_vtable (klass);
6338
6339         /* 
6340          * Emit all the information which is required for creating vtables so
6341          * the runtime does not need to create the MonoMethod structures which
6342          * take up a lot of space.
6343          */
6344
6345         no_special_static = !mono_class_has_special_static_fields (klass);
6346
6347         /* Check whenever we have enough info to encode the vtable */
6348         cant_encode = FALSE;
6349         for (i = 0; i < klass->vtable_size; ++i) {
6350                 MonoMethod *cm = klass->vtable [i];
6351
6352                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6353                         cant_encode = TRUE;
6354         }
6355
6356         mono_class_has_finalizer (klass);
6357         if (mono_class_has_failure (klass))
6358                 cant_encode = TRUE;
6359
6360         if (mono_class_is_gtd (klass) || cant_encode) {
6361                 encode_value (-1, p, &p);
6362         } else {
6363                 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6364                 encode_value (klass->vtable_size, p, &p);
6365                 encode_value ((mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | (has_nested ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
6366                 if (klass->has_cctor)
6367                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6368                 if (klass->has_finalize)
6369                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6370  
6371                 encode_value (klass->instance_size, p, &p);
6372                 encode_value (mono_class_data_size (klass), p, &p);
6373                 encode_value (klass->packing_size, p, &p);
6374                 encode_value (klass->min_align, p, &p);
6375
6376                 for (i = 0; i < klass->vtable_size; ++i) {
6377                         MonoMethod *cm = klass->vtable [i];
6378
6379                         if (cm)
6380                                 encode_method_ref (acfg, cm, p, &p);
6381                         else
6382                                 encode_value (0, p, &p);
6383                 }
6384         }
6385
6386         acfg->stats.class_info_size += p - buf;
6387
6388         g_assert (p - buf < buf_size);
6389         res = add_to_blob (acfg, buf, p - buf);
6390         g_free (buf);
6391
6392         return res;
6393 }
6394
6395 static char*
6396 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6397 {
6398         char *debug_sym = NULL;
6399         char *prefix;
6400
6401         if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6402                 /* Need to add a prefix to create unique symbols */
6403                 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6404         } else {
6405 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6406                 prefix = mangle_symbol_alloc ("plt_");
6407 #else
6408                 prefix = g_strdup ("plt_");
6409 #endif
6410         }
6411
6412         switch (ji->type) {
6413         case MONO_PATCH_INFO_METHOD:
6414                 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6415                 break;
6416         case MONO_PATCH_INFO_INTERNAL_METHOD:
6417                 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6418                 break;
6419         case MONO_PATCH_INFO_RGCTX_FETCH:
6420                 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6421                 break;
6422         case MONO_PATCH_INFO_ICALL_ADDR:
6423         case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6424                 char *s = get_debug_sym (ji->data.method, "", cache);
6425                 
6426                 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6427                 g_free (s);
6428                 break;
6429         }
6430         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6431                 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6432                 break;
6433         default:
6434                 break;
6435         }
6436
6437         g_free (prefix);
6438
6439         return sanitize_symbol (acfg, debug_sym);
6440 }
6441
6442 /*
6443  * Calls made from AOTed code are routed through a table of jumps similar to the
6444  * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6445  * control to the AOT runtime through a trampoline.
6446  */
6447 static void
6448 emit_plt (MonoAotCompile *acfg)
6449 {
6450         int i;
6451
6452         if (acfg->aot_opts.llvm_only) {
6453                 g_assert (acfg->plt_offset == 1);
6454                 return;
6455         }
6456
6457         emit_line (acfg);
6458
6459         emit_section_change (acfg, ".text", 0);
6460         emit_alignment_code (acfg, 16);
6461         emit_info_symbol (acfg, "plt");
6462         emit_label (acfg, acfg->plt_symbol);
6463
6464         for (i = 0; i < acfg->plt_offset; ++i) {
6465                 char *debug_sym = NULL;
6466                 MonoPltEntry *plt_entry = NULL;
6467
6468                 if (i == 0)
6469                         /* 
6470                          * The first plt entry is unused.
6471                          */
6472                         continue;
6473
6474                 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6475
6476                 debug_sym = plt_entry->debug_sym;
6477
6478                 if (acfg->thumb_mixed && !plt_entry->jit_used)
6479                         /* Emit only a thumb version */
6480                         continue;
6481
6482                 /* Skip plt entries not actually called */
6483                 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6484                         continue;
6485
6486                 if (acfg->llvm && !acfg->thumb_mixed) {
6487                         emit_label (acfg, plt_entry->llvm_symbol);
6488                         if (acfg->llvm) {
6489                                 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6490 #if defined(TARGET_MACH)
6491                                 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6492 #endif
6493                         }
6494                 }
6495
6496                 if (debug_sym) {
6497                         if (acfg->need_no_dead_strip) {
6498                                 emit_unset_mode (acfg);
6499                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
6500                         }
6501                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6502                         emit_label (acfg, debug_sym);
6503                 }
6504
6505                 emit_label (acfg, plt_entry->symbol);
6506
6507                 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6508
6509                 if (debug_sym)
6510                         emit_symbol_size (acfg, debug_sym, ".");
6511         }
6512
6513         if (acfg->thumb_mixed) {
6514                 /* Make sure the ARM symbols don't alias the thumb ones */
6515                 emit_zero_bytes (acfg, 16);
6516
6517                 /* 
6518                  * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6519                  * code.
6520                  */
6521                 for (i = 0; i < acfg->plt_offset; ++i) {
6522                         char *debug_sym = NULL;
6523                         MonoPltEntry *plt_entry = NULL;
6524
6525                         if (i == 0)
6526                                 continue;
6527
6528                         plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6529
6530                         /* Skip plt entries not actually called by LLVM code */
6531                         if (!plt_entry->llvm_used)
6532                                 continue;
6533
6534                         if (acfg->aot_opts.write_symbols) {
6535                                 if (plt_entry->debug_sym)
6536                                         debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6537                         }
6538
6539                         if (debug_sym) {
6540 #if defined(TARGET_MACH)
6541                                 fprintf (acfg->fp, "    .thumb_func %s\n", debug_sym);
6542                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
6543 #endif
6544                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6545                                 emit_label (acfg, debug_sym);
6546                         }
6547                         fprintf (acfg->fp, "\n.thumb_func\n");
6548
6549                         emit_label (acfg, plt_entry->llvm_symbol);
6550
6551                         if (acfg->llvm)
6552                                 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6553
6554                         arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6555
6556                         if (debug_sym) {
6557                                 emit_symbol_size (acfg, debug_sym, ".");
6558                                 g_free (debug_sym);
6559                         }
6560                 }
6561         }
6562
6563         emit_symbol_size (acfg, acfg->plt_symbol, ".");
6564
6565         emit_info_symbol (acfg, "plt_end");
6566 }
6567
6568 /*
6569  * emit_trampoline_full:
6570  *
6571  *   If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6572  * create_jit_info_for_trampoline ().
6573  */
6574 static G_GNUC_UNUSED void
6575 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6576 {
6577         char start_symbol [MAX_SYMBOL_SIZE];
6578         char end_symbol [MAX_SYMBOL_SIZE];
6579         char symbol [MAX_SYMBOL_SIZE];
6580         guint32 buf_size, info_offset;
6581         MonoJumpInfo *patch_info;
6582         guint8 *buf, *p;
6583         GPtrArray *patches;
6584         char *name;
6585         guint8 *code;
6586         guint32 code_size;
6587         MonoJumpInfo *ji;
6588         GSList *unwind_ops;
6589
6590         g_assert (info);
6591
6592         name = info->name;
6593         code = info->code;
6594         code_size = info->code_size;
6595         ji = info->ji;
6596         unwind_ops = info->unwind_ops;
6597
6598         /* Emit code */
6599
6600         sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6601
6602         emit_section_change (acfg, ".text", 0);
6603         emit_global (acfg, start_symbol, TRUE);
6604         emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6605         emit_label (acfg, start_symbol);
6606
6607         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6608         emit_label (acfg, symbol);
6609
6610         /* 
6611          * The code should access everything through the GOT, so we pass
6612          * TRUE here.
6613          */
6614         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6615
6616         emit_symbol_size (acfg, start_symbol, ".");
6617
6618         if (emit_tinfo) {
6619                 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6620                 emit_label (acfg, end_symbol);
6621         }
6622
6623         /* Emit info */
6624
6625         /* Sort relocations */
6626         patches = g_ptr_array_new ();
6627         for (patch_info = ji; patch_info; patch_info = patch_info->next)
6628                 if (patch_info->type != MONO_PATCH_INFO_NONE)
6629                         g_ptr_array_add (patches, patch_info);
6630         g_ptr_array_sort (patches, compare_patches);
6631
6632         buf_size = patches->len * 128 + 128;
6633         buf = (guint8 *)g_malloc (buf_size);
6634         p = buf;
6635
6636         encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6637         g_assert (p - buf < buf_size);
6638         g_ptr_array_free (patches, TRUE);
6639
6640         sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6641
6642         info_offset = add_to_blob (acfg, buf, p - buf);
6643
6644         emit_section_change (acfg, RODATA_SECT, 0);
6645         emit_global (acfg, symbol, FALSE);
6646         emit_label (acfg, symbol);
6647
6648         emit_int32 (acfg, info_offset);
6649
6650         if (emit_tinfo) {
6651                 guint8 *encoded;
6652                 guint32 encoded_len;
6653                 guint32 uw_offset;
6654
6655                 /*
6656                  * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6657                  */
6658                 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6659                 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6660                 g_free (encoded);
6661
6662                 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6663                 emit_int32 (acfg, uw_offset);
6664         }
6665
6666         /* Emit debug info */
6667         if (unwind_ops) {
6668                 char symbol2 [MAX_SYMBOL_SIZE];
6669
6670                 sprintf (symbol, "%s", name);
6671                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6672
6673                 if (acfg->dwarf)
6674                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6675         }
6676
6677         g_free (buf);
6678 }
6679
6680 static G_GNUC_UNUSED void
6681 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6682 {
6683         emit_trampoline_full (acfg, got_offset, info, TRUE);
6684 }
6685
6686 static void
6687 emit_trampolines (MonoAotCompile *acfg)
6688 {
6689         char symbol [MAX_SYMBOL_SIZE];
6690         char end_symbol [MAX_SYMBOL_SIZE];
6691         int i, tramp_got_offset;
6692         int ntype;
6693 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6694         int tramp_type;
6695 #endif
6696
6697         if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6698                 return;
6699         
6700         g_assert (acfg->image->assembly);
6701
6702         /* Currently, we emit most trampolines into the mscorlib AOT image. */
6703         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6704 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6705                 MonoTrampInfo *info;
6706
6707                 /*
6708                  * Emit the generic trampolines.
6709                  *
6710                  * We could save some code by treating the generic trampolines as a wrapper
6711                  * method, but that approach has its own complexities, so we choose the simpler
6712                  * method.
6713                  */
6714                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6715                         /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6716 #ifdef DISABLE_REMOTING
6717                         if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6718                                 continue;
6719 #endif
6720 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6721                         if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6722                                 continue;
6723 #endif
6724                         mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6725                         emit_trampoline (acfg, acfg->got_offset, info);
6726                 }
6727
6728                 /* Emit the exception related code pieces */
6729                 mono_arch_get_restore_context (&info, TRUE);
6730                 emit_trampoline (acfg, acfg->got_offset, info);
6731                 mono_arch_get_call_filter (&info, TRUE);
6732                 emit_trampoline (acfg, acfg->got_offset, info);
6733                 mono_arch_get_throw_exception (&info, TRUE);
6734                 emit_trampoline (acfg, acfg->got_offset, info);
6735                 mono_arch_get_rethrow_exception (&info, TRUE);
6736                 emit_trampoline (acfg, acfg->got_offset, info);
6737                 mono_arch_get_throw_corlib_exception (&info, TRUE);
6738                 emit_trampoline (acfg, acfg->got_offset, info);
6739
6740 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6741                 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6742                 emit_trampoline (acfg, acfg->got_offset, info);
6743                 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6744                 emit_trampoline (acfg, acfg->got_offset, info);
6745 #endif
6746
6747 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6748                 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6749                 if (info) {
6750                         emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6751
6752                         /* Create a separate out trampoline for more information in stack traces */
6753                         info->name = g_strdup ("gsharedvt_out_trampoline");
6754                         emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6755                 }
6756 #endif
6757
6758 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6759                 {
6760                         GSList *l = mono_arch_get_trampolines (TRUE);
6761
6762                         while (l) {
6763                                 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6764
6765                                 emit_trampoline (acfg, acfg->got_offset, info);
6766                                 l = l->next;
6767                         }
6768                 }
6769 #endif
6770
6771                 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6772                         int offset;
6773
6774                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6775                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6776                         emit_trampoline (acfg, acfg->got_offset, info);
6777                         g_free (info);
6778
6779                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6780                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6781                         emit_trampoline (acfg, acfg->got_offset, info);
6782                         g_free (info);
6783                 }
6784
6785 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6786                 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6787                 emit_trampoline (acfg, acfg->got_offset, info);
6788 #endif
6789
6790                 {
6791                         GSList *l;
6792
6793                         /* delegate_invoke_impl trampolines */
6794                         l = mono_arch_get_delegate_invoke_impls ();
6795                         while (l) {
6796                                 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6797
6798                                 emit_trampoline (acfg, acfg->got_offset, info);
6799                                 l = l->next;
6800                         }
6801                 }
6802
6803 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6804                 mono_arch_create_handler_block_trampoline (&info, TRUE);
6805                 emit_trampoline (acfg, acfg->got_offset, info);
6806 #endif
6807
6808 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6809
6810                 /* Emit trampolines which are numerous */
6811
6812                 /*
6813                  * These include the following:
6814                  * - specific trampolines
6815                  * - static rgctx invoke trampolines
6816                  * - imt trampolines
6817                  * These trampolines have the same code, they are parameterized by GOT 
6818                  * slots. 
6819                  * They are defined in this file, in the arch_... routines instead of
6820                  * in tramp-<ARCH>.c, since it is easier to do it this way.
6821                  */
6822
6823                 /*
6824                  * When running in aot-only mode, we can't create specific trampolines at 
6825                  * runtime, so we create a few, and save them in the AOT file. 
6826                  * Normal trampolines embed their argument as a literal inside the 
6827                  * trampoline code, we can't do that here, so instead we embed an offset
6828                  * which needs to be added to the trampoline address to get the address of
6829                  * the GOT slot which contains the argument value.
6830                  * The generated trampolines jump to the generic trampolines using another
6831                  * GOT slot, which will be setup by the AOT loader to point to the 
6832                  * generic trampoline code of the given type.
6833                  */
6834
6835                 /*
6836                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6837                  * each class).
6838                  */
6839
6840                 emit_section_change (acfg, ".text", 0);
6841
6842                 tramp_got_offset = acfg->got_offset;
6843
6844                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6845                         switch (ntype) {
6846                         case MONO_AOT_TRAMP_SPECIFIC:
6847                                 sprintf (symbol, "specific_trampolines");
6848                                 break;
6849                         case MONO_AOT_TRAMP_STATIC_RGCTX:
6850                                 sprintf (symbol, "static_rgctx_trampolines");
6851                                 break;
6852                         case MONO_AOT_TRAMP_IMT:
6853                                 sprintf (symbol, "imt_trampolines");
6854                                 break;
6855                         case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6856                                 sprintf (symbol, "gsharedvt_arg_trampolines");
6857                                 break;
6858                         default:
6859                                 g_assert_not_reached ();
6860                         }
6861
6862                         sprintf (end_symbol, "%s_e", symbol);
6863
6864                         if (acfg->aot_opts.write_symbols)
6865                                 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6866
6867                         emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6868                         emit_info_symbol (acfg, symbol);
6869
6870                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6871
6872                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6873                                 int tramp_size = 0;
6874
6875                                 switch (ntype) {
6876                                 case MONO_AOT_TRAMP_SPECIFIC:
6877                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6878                                         tramp_got_offset += 2;
6879                                 break;
6880                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
6881                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
6882                                         tramp_got_offset += 2;
6883                                         break;
6884                                 case MONO_AOT_TRAMP_IMT:
6885                                         arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6886                                         tramp_got_offset += 1;
6887                                         break;
6888                                 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6889                                         arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);                               
6890                                         tramp_got_offset += 2;
6891                                         break;
6892                                 default:
6893                                         g_assert_not_reached ();
6894                                 }
6895                                 if (!acfg->trampoline_size [ntype]) {
6896                                         g_assert (tramp_size);
6897                                         acfg->trampoline_size [ntype] = tramp_size;
6898                                 }
6899                         }
6900
6901                         emit_label (acfg, end_symbol);
6902                         emit_int32 (acfg, 0);
6903                 }
6904
6905                 arch_emit_specific_trampoline_pages (acfg);
6906
6907                 /* Reserve some entries at the end of the GOT for our use */
6908                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6909         }
6910
6911         acfg->got_offset += acfg->num_trampoline_got_entries;
6912 }
6913
6914 static gboolean
6915 str_begins_with (const char *str1, const char *str2)
6916 {
6917         int len = strlen (str2);
6918         return strncmp (str1, str2, len) == 0;
6919 }
6920
6921 void*
6922 mono_aot_readonly_field_override (MonoClassField *field)
6923 {
6924         ReadOnlyValue *rdv;
6925         for (rdv = readonly_values; rdv; rdv = rdv->next) {
6926                 char *p = rdv->name;
6927                 int len;
6928                 len = strlen (field->parent->name_space);
6929                 if (strncmp (p, field->parent->name_space, len))
6930                         continue;
6931                 p += len;
6932                 if (*p++ != '.')
6933                         continue;
6934                 len = strlen (field->parent->name);
6935                 if (strncmp (p, field->parent->name, len))
6936                         continue;
6937                 p += len;
6938                 if (*p++ != '.')
6939                         continue;
6940                 if (strcmp (p, field->name))
6941                         continue;
6942                 switch (rdv->type) {
6943                 case MONO_TYPE_I1:
6944                         return &rdv->value.i1;
6945                 case MONO_TYPE_I2:
6946                         return &rdv->value.i2;
6947                 case MONO_TYPE_I4:
6948                         return &rdv->value.i4;
6949                 default:
6950                         break;
6951                 }
6952         }
6953         return NULL;
6954 }
6955
6956 static void
6957 add_readonly_value (MonoAotOptions *opts, const char *val)
6958 {
6959         ReadOnlyValue *rdv;
6960         const char *fval;
6961         const char *tval;
6962         /* the format of val is:
6963          * namespace.typename.fieldname=type/value
6964          * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6965          */
6966         fval = strrchr (val, '/');
6967         if (!fval) {
6968                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6969                 exit (1);
6970         }
6971         tval = strrchr (val, '=');
6972         if (!tval) {
6973                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6974                 exit (1);
6975         }
6976         rdv = g_new0 (ReadOnlyValue, 1);
6977         rdv->name = (char *)g_malloc0 (tval - val + 1);
6978         memcpy (rdv->name, val, tval - val);
6979         tval++;
6980         fval++;
6981         if (strncmp (tval, "i1", 2) == 0) {
6982                 rdv->value.i1 = atoi (fval);
6983                 rdv->type = MONO_TYPE_I1;
6984         } else if (strncmp (tval, "i2", 2) == 0) {
6985                 rdv->value.i2 = atoi (fval);
6986                 rdv->type = MONO_TYPE_I2;
6987         } else if (strncmp (tval, "i4", 2) == 0) {
6988                 rdv->value.i4 = atoi (fval);
6989                 rdv->type = MONO_TYPE_I4;
6990         } else {
6991                 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6992                 exit (1);
6993         }
6994         rdv->next = readonly_values;
6995         readonly_values = rdv;
6996 }
6997
6998 static gchar *
6999 clean_path (gchar * path)
7000 {
7001         if (!path)
7002                 return NULL;
7003
7004         if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7005                 return path;
7006
7007         gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7008         g_free (path);
7009
7010         return clean;
7011 }
7012
7013 static gchar *
7014 wrap_path (gchar * path)
7015 {
7016         int len;
7017         if (!path)
7018                 return NULL;
7019
7020         // If the string contains no spaces, just return the original string.
7021         if (strstr (path, " ") == NULL)
7022                 return path;
7023
7024         // If the string is already wrapped in quotes, return it.
7025         len = strlen (path);
7026         if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7027                 return path;
7028
7029         // If the string contains spaces, then wrap it in quotes.
7030         gchar *clean = g_strdup_printf ("\"%s\"", path);
7031
7032         return clean;
7033 }
7034
7035 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7036 static void
7037 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7038 {
7039         ptrdiff_t len = end-start;
7040         if (len > 0)
7041                 g_ptr_array_add (args, g_strndup (start, len));
7042 }
7043
7044 static GPtrArray *
7045 mono_aot_split_options (const char *aot_options)
7046 {
7047         enum MonoAotOptionState {
7048                 MONO_AOT_OPTION_STATE_DEFAULT,
7049                 MONO_AOT_OPTION_STATE_STRING,
7050                 MONO_AOT_OPTION_STATE_ESCAPE,
7051         };
7052
7053         GPtrArray *args = g_ptr_array_new ();
7054         enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7055         gchar const *opt_start = aot_options;
7056         gboolean end_of_string = FALSE;
7057         gchar cur;
7058
7059         g_return_val_if_fail (aot_options != NULL, NULL);
7060
7061         while ((cur = *aot_options) != '\0') {
7062                 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7063                         goto next;
7064
7065                 switch (cur) {
7066                 case '"':
7067                         // If we find a quote, then if we're in the default case then
7068                         // it means we've found the start of a string, if not then it
7069                         // means we've found the end of the string and should switch
7070                         // back to the default case.            
7071                         switch (state) {
7072                         case MONO_AOT_OPTION_STATE_DEFAULT:
7073                                 state = MONO_AOT_OPTION_STATE_STRING;
7074                                 break;
7075                         case MONO_AOT_OPTION_STATE_STRING:
7076                                 state = MONO_AOT_OPTION_STATE_DEFAULT;
7077                                 break;
7078                         case MONO_AOT_OPTION_STATE_ESCAPE:
7079                                 g_assert_not_reached ();
7080                                 break;
7081                         }
7082                         break;
7083                 case '\\':
7084                         // If we've found an escaping operator, then this means we
7085                         // should not process the next character if inside a string.            
7086                         if (state == MONO_AOT_OPTION_STATE_STRING) 
7087                                 state = MONO_AOT_OPTION_STATE_ESCAPE;
7088                         break;
7089                 case ',':
7090                         // If we're in the default state then this means we've found
7091                         // an option, store it for later processing.
7092                         if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7093                                 goto new_opt;
7094                         break;
7095                 }
7096
7097         next:
7098                 aot_options++;
7099         restart:
7100                 // If the next character is end of string, then process the last option.
7101                 if (*(aot_options) == '\0') {
7102                         end_of_string = TRUE;
7103                         goto new_opt;
7104                 }
7105                 continue;
7106
7107         new_opt:
7108                 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7109                 opt_start = ++aot_options;
7110                 if (end_of_string)
7111                         break;
7112                 goto restart; // Check for null and continue loop
7113         }
7114
7115         return args;
7116 }
7117
7118 static void
7119 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7120 {
7121         GPtrArray* args;
7122
7123         args = mono_aot_split_options (aot_options ? aot_options : "");
7124         for (int i = 0; i < args->len; ++i) {
7125                 const char *arg = (const char *)g_ptr_array_index (args, i);
7126
7127                 if (str_begins_with (arg, "outfile=")) {
7128                         opts->outfile = g_strdup (arg + strlen ("outfile="));
7129                 } else if (str_begins_with (arg, "llvm-outfile=")) {
7130                         opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7131                 } else if (str_begins_with (arg, "temp-path=")) {
7132                         opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7133                 } else if (str_begins_with (arg, "save-temps")) {
7134                         opts->save_temps = TRUE;
7135                 } else if (str_begins_with (arg, "keep-temps")) {
7136                         opts->save_temps = TRUE;
7137                 } else if (str_begins_with (arg, "write-symbols")) {
7138                         opts->write_symbols = TRUE;
7139                 } else if (str_begins_with (arg, "no-write-symbols")) {
7140                         opts->write_symbols = FALSE;
7141                 } else if (str_begins_with (arg, "metadata-only")) {
7142                         opts->metadata_only = TRUE;
7143                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7144                         opts->bind_to_runtime_version = TRUE;
7145                 } else if (str_begins_with (arg, "full")) {
7146                         opts->mode = MONO_AOT_MODE_FULL;
7147                 } else if (str_begins_with (arg, "hybrid")) {
7148                         opts->mode = MONO_AOT_MODE_HYBRID;                      
7149                 } else if (str_begins_with (arg, "threads=")) {
7150                         opts->nthreads = atoi (arg + strlen ("threads="));
7151                 } else if (str_begins_with (arg, "static")) {
7152                         opts->static_link = TRUE;
7153                         opts->no_dlsym = TRUE;
7154                 } else if (str_begins_with (arg, "asmonly")) {
7155                         opts->asm_only = TRUE;
7156                 } else if (str_begins_with (arg, "asmwriter")) {
7157                         opts->asm_writer = TRUE;
7158                 } else if (str_begins_with (arg, "nodebug")) {
7159                         opts->nodebug = TRUE;
7160                 } else if (str_begins_with (arg, "dwarfdebug")) {
7161                         opts->dwarf_debug = TRUE;
7162                 } else if (str_begins_with (arg, "nopagetrampolines")) {
7163                         opts->use_trampolines_page = FALSE;
7164                 } else if (str_begins_with (arg, "ntrampolines=")) {
7165                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7166                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7167                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7168                 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7169                         opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7170                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7171                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7172                 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7173                         opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7174                 } else if (str_begins_with (arg, "tool-prefix=")) {
7175                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7176                 } else if (str_begins_with (arg, "ld-flags=")) {
7177                         opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));                 
7178                 } else if (str_begins_with (arg, "soft-debug")) {
7179                         opts->soft_debug = TRUE;
7180                 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7181                         fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7182                 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7183                         fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7184                 } else if (str_begins_with (arg, "msym-dir=")) {
7185                         debug_options.no_seq_points_compact_data = FALSE;
7186                         opts->gen_msym_dir = TRUE;
7187                         opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7188                 } else if (str_begins_with (arg, "direct-pinvoke")) {
7189                         opts->direct_pinvoke = TRUE;
7190                 } else if (str_begins_with (arg, "direct-icalls")) {
7191                         opts->direct_icalls = TRUE;
7192                 } else if (str_begins_with (arg, "no-direct-calls")) {
7193                         opts->no_direct_calls = TRUE;
7194                 } else if (str_begins_with (arg, "print-skipped")) {
7195                         opts->print_skipped_methods = TRUE;
7196                 } else if (str_begins_with (arg, "stats")) {
7197                         opts->stats = TRUE;
7198                 } else if (str_begins_with (arg, "no-instances")) {
7199                         opts->no_instances = TRUE;
7200                 } else if (str_begins_with (arg, "log-generics")) {
7201                         opts->log_generics = TRUE;
7202                 } else if (str_begins_with (arg, "log-instances=")) {
7203                         opts->log_instances = TRUE;
7204                         opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7205                 } else if (str_begins_with (arg, "log-instances")) {
7206                         opts->log_instances = TRUE;
7207                 } else if (str_begins_with (arg, "internal-logfile=")) {
7208                         opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7209                 } else if (str_begins_with (arg, "mtriple=")) {
7210                         opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7211                 } else if (str_begins_with (arg, "llvm-path=")) {
7212                         opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7213                 } else if (!strcmp (arg, "llvm")) {
7214                         opts->llvm = TRUE;
7215                 } else if (str_begins_with (arg, "readonly-value=")) {
7216                         add_readonly_value (opts, arg + strlen ("readonly-value="));
7217                 } else if (str_begins_with (arg, "info")) {
7218                         printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7219                         exit (0);
7220                 } else if (str_begins_with (arg, "gc-maps")) {
7221                         mini_gc_enable_gc_maps_for_aot ();
7222                 } else if (str_begins_with (arg, "dump")) {
7223                         opts->dump_json = TRUE;
7224                 } else if (str_begins_with (arg, "llvmonly")) {
7225                         opts->mode = MONO_AOT_MODE_FULL;
7226                         opts->llvm = TRUE;
7227                         opts->llvm_only = TRUE;
7228                 } else if (str_begins_with (arg, "data-outfile=")) {
7229                         opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7230                 } else if (str_begins_with (arg, "profile=")) {
7231                         opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7232                 } else if (!strcmp (arg, "profile-only")) {
7233                         opts->profile_only = TRUE;
7234                 } else if (!strcmp (arg, "verbose")) {
7235                         opts->verbose = TRUE;
7236                 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7237                         printf ("Supported options for --aot:\n");
7238                         printf ("    outfile=\n");
7239                         printf ("    llvm-outfile=\n");
7240                         printf ("    llvm-path=\n");
7241                         printf ("    temp-path=\n");
7242                         printf ("    save-temps\n");
7243                         printf ("    keep-temps\n");
7244                         printf ("    write-symbols\n");
7245                         printf ("    metadata-only\n");
7246                         printf ("    bind-to-runtime-version\n");
7247                         printf ("    full\n");
7248                         printf ("    threads=\n");
7249                         printf ("    static\n");
7250                         printf ("    asmonly\n");
7251                         printf ("    asmwriter\n");
7252                         printf ("    nodebug\n");
7253                         printf ("    dwarfdebug\n");
7254                         printf ("    ntrampolines=\n");
7255                         printf ("    nrgctx-trampolines=\n");
7256                         printf ("    nimt-trampolines=\n");
7257                         printf ("    ngsharedvt-trampolines=\n");
7258                         printf ("    tool-prefix=\n");
7259                         printf ("    readonly-value=\n");
7260                         printf ("    soft-debug\n");
7261                         printf ("    msym-dir=\n");
7262                         printf ("    gc-maps\n");
7263                         printf ("    print-skipped\n");
7264                         printf ("    no-instances\n");
7265                         printf ("    stats\n");
7266                         printf ("    dump\n");
7267                         printf ("    info\n");
7268                         printf ("    verbose\n");
7269                         printf ("    help/?\n");
7270                         exit (0);
7271                 } else {
7272                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7273                         exit (1);
7274                 }
7275
7276                 g_free ((gpointer) arg);
7277         }
7278
7279         if (opts->use_trampolines_page) {
7280                 opts->ntrampolines = 0;
7281                 opts->nrgctx_trampolines = 0;
7282                 opts->nimt_trampolines = 0;
7283                 opts->ngsharedvt_arg_trampolines = 0;
7284         }
7285
7286         g_ptr_array_free (args, /*free_seg=*/TRUE);
7287 }
7288
7289 static void
7290 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7291 {
7292         MonoMethod *method = (MonoMethod*)key;
7293         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7294         MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7295         MonoJumpInfoToken *new_ji;
7296
7297         new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7298         new_ji->image = ji->image;
7299         new_ji->token = ji->token;
7300         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7301 }
7302
7303 static gboolean
7304 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7305 {
7306         if (klass->type_token)
7307                 return TRUE;
7308         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7309                 return TRUE;
7310         if (klass->rank)
7311                 return can_encode_class (acfg, klass->element_class);
7312         return FALSE;
7313 }
7314
7315 static gboolean
7316 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7317 {
7318                 if (method->wrapper_type) {
7319                         switch (method->wrapper_type) {
7320                         case MONO_WRAPPER_NONE:
7321                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7322                         case MONO_WRAPPER_XDOMAIN_INVOKE:
7323                         case MONO_WRAPPER_STFLD:
7324                         case MONO_WRAPPER_LDFLD:
7325                         case MONO_WRAPPER_LDFLDA:
7326                         case MONO_WRAPPER_STELEMREF:
7327                         case MONO_WRAPPER_PROXY_ISINST:
7328                         case MONO_WRAPPER_ALLOC:
7329                         case MONO_WRAPPER_REMOTING_INVOKE:
7330                         case MONO_WRAPPER_UNKNOWN:
7331                         case MONO_WRAPPER_WRITE_BARRIER:
7332                         case MONO_WRAPPER_DELEGATE_INVOKE:
7333                         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7334                         case MONO_WRAPPER_DELEGATE_END_INVOKE:
7335                         case MONO_WRAPPER_SYNCHRONIZED:
7336                                 break;
7337                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
7338                         case MONO_WRAPPER_CASTCLASS: {
7339                                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7340
7341                                 if (info)
7342                                         return TRUE;
7343                                 else
7344                                         return FALSE;
7345                                 break;
7346                         }
7347                         default:
7348                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7349                                 return FALSE;
7350                         }
7351                 } else {
7352                         if (!method->token) {
7353                                 /* The method is part of a constructed type like Int[,].Set (). */
7354                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7355                                         if (method->klass->rank)
7356                                                 return TRUE;
7357                                         return FALSE;
7358                                 }
7359                         }
7360                 }
7361                 return TRUE;
7362 }
7363
7364 static gboolean
7365 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7366 {
7367         switch (patch_info->type) {
7368         case MONO_PATCH_INFO_METHOD:
7369         case MONO_PATCH_INFO_METHODCONST:
7370         case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7371                 MonoMethod *method = patch_info->data.method;
7372
7373                 return can_encode_method (acfg, method);
7374         }
7375         case MONO_PATCH_INFO_VTABLE:
7376         case MONO_PATCH_INFO_CLASS:
7377         case MONO_PATCH_INFO_IID:
7378         case MONO_PATCH_INFO_ADJUSTED_IID:
7379                 if (!can_encode_class (acfg, patch_info->data.klass)) {
7380                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7381                         return FALSE;
7382                 }
7383                 break;
7384         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7385                 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7386                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7387                         return FALSE;
7388                 }
7389                 break;
7390         }
7391         case MONO_PATCH_INFO_RGCTX_FETCH:
7392         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7393                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7394
7395                 if (!can_encode_method (acfg, entry->method))
7396                         return FALSE;
7397                 if (!can_encode_patch (acfg, entry->data))
7398                         return FALSE;
7399                 break;
7400         }
7401         default:
7402                 break;
7403         }
7404
7405         return TRUE;
7406 }
7407
7408 static gboolean
7409 is_concrete_type (MonoType *t)
7410 {
7411         MonoClass *klass;
7412         int i;
7413
7414         if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7415                 return FALSE;
7416         if (t->type == MONO_TYPE_GENERICINST) {
7417                 MonoGenericContext *orig_ctx;
7418                 MonoGenericInst *inst;
7419                 MonoType *arg;
7420
7421                 if (!MONO_TYPE_ISSTRUCT (t))
7422                         return TRUE;
7423                 klass = mono_class_from_mono_type (t);
7424                 orig_ctx = &mono_class_get_generic_class (klass)->context;
7425
7426                 inst = orig_ctx->class_inst;
7427                 if (inst) {
7428                         for (i = 0; i < inst->type_argc; ++i) {
7429                                 arg = mini_get_underlying_type (inst->type_argv [i]);
7430                                 if (!is_concrete_type (arg))
7431                                         return FALSE;
7432                         }
7433                 }
7434                 inst = orig_ctx->method_inst;
7435                 if (inst) {
7436                         for (i = 0; i < inst->type_argc; ++i) {
7437                                 arg = mini_get_underlying_type (inst->type_argv [i]);
7438                                 if (!is_concrete_type (arg))
7439                                         return FALSE;
7440                         }
7441                 }
7442         }
7443         return TRUE;
7444 }
7445
7446 /* LOCKING: Assumes the loader lock is held */
7447 static void
7448 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7449 {
7450         MonoMethod *wrapper;
7451         gboolean concrete = TRUE;
7452         gboolean add_in = gsharedvt_in;
7453         gboolean add_out = gsharedvt_out;
7454
7455         if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7456                 add_in = FALSE;
7457         if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7458                 add_out = FALSE;
7459
7460         if (!add_in && !add_out)
7461                 return;
7462
7463         if (mini_is_gsharedvt_variable_signature (sig))
7464                 return;
7465
7466         if (add_in)
7467                 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7468         if (add_out)
7469                 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7470
7471         if (!sig->has_type_parameters) {
7472                 //printf ("%s\n", mono_signature_full_name (sig));
7473
7474                 if (gsharedvt_in) {
7475                         wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7476                         add_extra_method (acfg, wrapper);
7477                 }
7478                 if (gsharedvt_out) {
7479                         wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7480                         add_extra_method (acfg, wrapper);
7481                 }
7482         } else {
7483                 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7484                 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7485                 int i;
7486
7487                 //printf ("%s\n", mono_signature_full_name (sig));
7488
7489                 copy->ret = mini_get_underlying_type (sig->ret);
7490                 if (!is_concrete_type (copy->ret))
7491                         concrete = FALSE;
7492                 for (i = 0; i < sig->param_count; ++i) {
7493                         copy->params [i] = mini_get_underlying_type (sig->params [i]);
7494                         if (!is_concrete_type (copy->params [i]))
7495                                 concrete = FALSE;
7496                 }
7497                 if (concrete) {
7498                         copy->has_type_parameters = 0;
7499
7500                         if (gsharedvt_in) {
7501                                 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7502                                 add_extra_method (acfg, wrapper);
7503                         }
7504
7505                         if (gsharedvt_out) {
7506                                 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7507                                 add_extra_method (acfg, wrapper);
7508                         }
7509
7510                         //printf ("%s\n", mono_method_full_name (wrapper, 1));
7511                 }
7512         }
7513 }
7514
7515 /*
7516  * compile_method:
7517  *
7518  *   AOT compile a given method.
7519  * This function might be called by multiple threads, so it must be thread-safe.
7520  */
7521 static void
7522 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7523 {
7524         MonoCompile *cfg;
7525         MonoJumpInfo *patch_info;
7526         gboolean skip;
7527         int index, depth;
7528         MonoMethod *wrapped;
7529         GTimer *jit_timer;
7530         JitFlags flags;
7531
7532         if (acfg->aot_opts.metadata_only)
7533                 return;
7534
7535         mono_acfg_lock (acfg);
7536         index = get_method_index (acfg, method);
7537         mono_acfg_unlock (acfg);
7538
7539         /* fixme: maybe we can also precompile wrapper methods */
7540         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7541                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7542                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7543                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7544                 return;
7545         }
7546
7547         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7548                 return;
7549
7550         wrapped = mono_marshal_method_from_wrapper (method);
7551         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7552                 // FIXME: The wrapper should be generic too, but it is not
7553                 return;
7554
7555         if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7556                 return;
7557
7558         if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7559                 return;
7560
7561         InterlockedIncrement (&acfg->stats.mcount);
7562
7563 #if 0
7564         if (method->is_generic || mono_class_is_gtd (method->klass)) {
7565                 InterlockedIncrement (&acfg->stats.genericcount);
7566                 return;
7567         }
7568 #endif
7569
7570         //acfg->aot_opts.print_skipped_methods = TRUE;
7571
7572         /*
7573          * Since these methods are the only ones which are compiled with
7574          * AOT support, and they are not used by runtime startup/shutdown code,
7575          * the runtime will not see AOT methods during AOT compilation,so it
7576          * does not need to support them by creating a fake GOT etc.
7577          */
7578         flags = JIT_FLAG_AOT;
7579         if (mono_aot_mode_is_full (&acfg->aot_opts))
7580                 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7581         if (acfg->llvm)
7582                 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7583         if (acfg->aot_opts.llvm_only)
7584                 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7585         if (acfg->aot_opts.no_direct_calls)
7586                 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7587         if (acfg->aot_opts.direct_pinvoke)
7588                 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7589
7590         jit_timer = mono_time_track_start ();
7591         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7592         mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7593
7594         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7595                 if (acfg->aot_opts.print_skipped_methods)
7596                         printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7597                 InterlockedIncrement (&acfg->stats.genericcount);
7598                 return;
7599         }
7600         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7601                 if (acfg->aot_opts.print_skipped_methods) {
7602                         printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7603                         if (cfg->exception_message)
7604                                 printf ("Caused by: %s\n", cfg->exception_message);
7605                 }
7606                 /* Let the exception happen at runtime */
7607                 return;
7608         }
7609
7610         if (cfg->disable_aot) {
7611                 if (acfg->aot_opts.print_skipped_methods)
7612                         printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7613                 InterlockedIncrement (&acfg->stats.ocount);
7614                 return;
7615         }
7616         cfg->method_index = index;
7617
7618         /* Nullify patches which need no aot processing */
7619         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7620                 switch (patch_info->type) {
7621                 case MONO_PATCH_INFO_LABEL:
7622                 case MONO_PATCH_INFO_BB:
7623                         patch_info->type = MONO_PATCH_INFO_NONE;
7624                         break;
7625                 default:
7626                         break;
7627                 }
7628         }
7629
7630         /* Collect method->token associations from the cfg */
7631         mono_acfg_lock (acfg);
7632         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7633         mono_acfg_unlock (acfg);
7634         g_hash_table_destroy (cfg->token_info_hash);
7635         cfg->token_info_hash = NULL;
7636
7637         /*
7638          * Check for absolute addresses.
7639          */
7640         skip = FALSE;
7641         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7642                 switch (patch_info->type) {
7643                 case MONO_PATCH_INFO_ABS:
7644                         /* unable to handle this */
7645                         skip = TRUE;    
7646                         break;
7647                 default:
7648                         break;
7649                 }
7650         }
7651
7652         if (skip) {
7653                 if (acfg->aot_opts.print_skipped_methods)
7654                         printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7655                 InterlockedIncrement (&acfg->stats.abscount);
7656                 return;
7657         }
7658
7659         /* Lock for the rest of the code */
7660         mono_acfg_lock (acfg);
7661
7662         if (cfg->gsharedvt)
7663                 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7664         else if (cfg->gshared)
7665                 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7666         else if (cfg->method->wrapper_type)
7667                 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7668         else
7669                 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7670
7671         /*
7672          * Check for methods/klasses we can't encode.
7673          */
7674         skip = FALSE;
7675         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7676                 if (!can_encode_patch (acfg, patch_info))
7677                         skip = TRUE;
7678         }
7679
7680         if (skip) {
7681                 if (acfg->aot_opts.print_skipped_methods)
7682                         printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7683                 acfg->stats.ocount++;
7684                 mono_acfg_unlock (acfg);
7685                 return;
7686         }
7687
7688         if (!cfg->compile_llvm)
7689                 acfg->has_jitted_code = TRUE;
7690
7691         if (method->is_inflated && acfg->aot_opts.log_instances) {
7692                 if (acfg->instances_logfile)
7693                         fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7694                 else
7695                         printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7696         }
7697
7698         /* Adds generic instances referenced by this method */
7699         /* 
7700          * The depth is used to avoid infinite loops when generic virtual recursion is 
7701          * encountered.
7702          */
7703         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7704         if (!acfg->aot_opts.no_instances && depth < 32 && mono_aot_mode_is_full (&acfg->aot_opts)) {
7705                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7706                         switch (patch_info->type) {
7707                         case MONO_PATCH_INFO_RGCTX_FETCH:
7708                         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7709                         case MONO_PATCH_INFO_METHOD: {
7710                                 MonoMethod *m = NULL;
7711
7712                                 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7713                                         MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7714
7715                                         if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7716                                                 m = e->data->data.method;
7717                                 } else {
7718                                         m = patch_info->data.method;
7719                                 }
7720
7721                                 if (!m)
7722                                         break;
7723                                 if (m->is_inflated && mono_aot_mode_is_full (&acfg->aot_opts)) {
7724                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
7725                                                   mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7726                                                 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7727                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7728                                                         if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7729                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7730                                                 } else {
7731                                                         add_extra_method_with_depth (acfg, m, depth + 1);
7732                                                         add_types_from_method_header (acfg, m);
7733                                                 }
7734                                         }
7735                                         add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7736                                 }
7737                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7738                                         WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7739
7740                                         if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7741                                                 add_extra_method_with_depth (acfg, m, depth + 1);
7742                                 }
7743                                 break;
7744                         }
7745                         case MONO_PATCH_INFO_VTABLE: {
7746                                 MonoClass *klass = patch_info->data.klass;
7747
7748                                 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7749                                         add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7750                                 break;
7751                         }
7752                         case MONO_PATCH_INFO_SFLDA: {
7753                                 MonoClass *klass = patch_info->data.field->parent;
7754
7755                                 /* The .cctor needs to run at runtime. */
7756                                 if (mono_class_is_ginst (klass) && !mono_generic_context_is_sharable_full (&mono_class_get_generic_class (klass)->context, FALSE, FALSE) && mono_class_get_cctor (klass))
7757                                         add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7758                                 break;
7759                         }
7760                         default:
7761                                 break;
7762                         }
7763                 }
7764         }
7765
7766         /* Determine whenever the method has GOT slots */
7767         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7768                 switch (patch_info->type) {
7769                 case MONO_PATCH_INFO_GOT_OFFSET:
7770                 case MONO_PATCH_INFO_NONE:
7771                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7772                 case MONO_PATCH_INFO_GC_NURSERY_START:
7773                 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7774                         break;
7775                 case MONO_PATCH_INFO_IMAGE:
7776                         /* The assembly is stored in GOT slot 0 */
7777                         if (patch_info->data.image != acfg->image)
7778                                 cfg->has_got_slots = TRUE;
7779                         break;
7780                 default:
7781                         if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7782                                 cfg->has_got_slots = TRUE;
7783                         break;
7784                 }
7785         }
7786
7787         if (!cfg->has_got_slots)
7788                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7789
7790         /* Add gsharedvt wrappers for signatures used by the method */
7791         if (acfg->aot_opts.llvm_only) {
7792                 GSList *l;
7793
7794                 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7795                         /* These only need out wrappers */
7796                         add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7797
7798                 for (l = cfg->signatures; l; l = l->next) {
7799                         MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7800
7801                         /* These only need in wrappers */
7802                         add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7803                 }
7804         }
7805
7806         /* 
7807          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7808          */
7809         /* Make a copy of the patch info which is in the mempool */
7810         {
7811                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7812
7813                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7814                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7815
7816                         if (!patches)
7817                                 patches = new_patch_info;
7818                         else
7819                                 patches_end->next = new_patch_info;
7820                         patches_end = new_patch_info;
7821                 }
7822                 cfg->patch_info = patches;
7823         }
7824         /* Make a copy of the unwind info */
7825         {
7826                 GSList *l, *unwind_ops;
7827                 MonoUnwindOp *op;
7828
7829                 unwind_ops = NULL;
7830                 for (l = cfg->unwind_ops; l; l = l->next) {
7831                         op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7832                         memcpy (op, l->data, sizeof (MonoUnwindOp));
7833                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7834                 }
7835                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7836         }
7837         /* Make a copy of the argument/local info */
7838         {
7839                 MonoError error;
7840                 MonoInst **args, **locals;
7841                 MonoMethodSignature *sig;
7842                 MonoMethodHeader *header;
7843                 int i;
7844                 
7845                 sig = mono_method_signature (method);
7846                 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7847                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7848                         args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7849                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7850                 }
7851                 cfg->args = args;
7852
7853                 header = mono_method_get_header_checked (method, &error);
7854                 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7855                 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7856                 for (i = 0; i < header->num_locals; ++i) {
7857                         locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7858                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7859                 }
7860                 mono_metadata_free_mh (header);
7861                 cfg->locals = locals;
7862         }
7863
7864         /* Free some fields used by cfg to conserve memory */
7865         mono_empty_compile (cfg);
7866
7867         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
7868
7869         while (index >= acfg->cfgs_size) {
7870                 MonoCompile **new_cfgs;
7871                 int new_size;
7872
7873                 new_size = acfg->cfgs_size * 2;
7874                 new_cfgs = g_new0 (MonoCompile*, new_size);
7875                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7876                 g_free (acfg->cfgs);
7877                 acfg->cfgs = new_cfgs;
7878                 acfg->cfgs_size = new_size;
7879         }
7880         acfg->cfgs [index] = cfg;
7881
7882         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7883
7884         mono_update_jit_stats (cfg);
7885
7886         /*
7887         if (cfg->orig_method->wrapper_type)
7888                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7889         */
7890
7891         mono_acfg_unlock (acfg);
7892
7893         InterlockedIncrement (&acfg->stats.ccount);
7894 }
7895  
7896 static mono_thread_start_return_t WINAPI
7897 compile_thread_main (gpointer user_data)
7898 {
7899         MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
7900         GPtrArray *methods = ((GPtrArray **)user_data) [1];
7901         int i;
7902
7903         MonoError error;
7904         MonoInternalThread *internal = mono_thread_internal_current ();
7905         mono_thread_set_name_internal (internal, mono_string_new (mono_domain_get (), "AOT compiler"), TRUE, FALSE, &error);
7906         mono_error_assert_ok (&error);
7907
7908         for (i = 0; i < methods->len; ++i)
7909                 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7910
7911         return 0;
7912 }
7913  
7914 /* Used by the LLVM backend */
7915 guint32
7916 mono_aot_get_got_offset (MonoJumpInfo *ji)
7917 {
7918         return get_got_offset (llvm_acfg, TRUE, ji);
7919 }
7920
7921 /*
7922  * mono_aot_is_shared_got_offset:
7923  *
7924  *   Return whenever OFFSET refers to a GOT slot which is preinitialized
7925  * when the AOT image is loaded.
7926  */
7927 gboolean
7928 mono_aot_is_shared_got_offset (int offset)
7929 {
7930         return offset < llvm_acfg->nshared_got_entries;
7931 }
7932
7933 char*
7934 mono_aot_get_method_name (MonoCompile *cfg)
7935 {
7936         if (llvm_acfg->aot_opts.static_link)
7937                 /* Include the assembly name too to avoid duplicate symbol errors */
7938                 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7939         else
7940                 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7941 }
7942
7943 /*
7944  * mono_aot_is_linkonce_method:
7945  *
7946  *   Return whenever METHOD should be emitted with linkonce linkage,
7947  * eliminating duplicate copies when compiling in static mode.
7948  */
7949 gboolean
7950 mono_aot_is_linkonce_method (MonoMethod *method)
7951 {
7952         return FALSE;
7953 #if 0
7954         WrapperInfo *info;
7955
7956         // FIXME: Add more cases
7957         if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7958                 return FALSE;
7959         info = mono_marshal_get_wrapper_info (method);
7960         if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7961                 return TRUE;
7962         return FALSE;
7963 #endif
7964 }
7965
7966 static gboolean
7967 append_mangled_type (GString *s, MonoType *t)
7968 {
7969         if (t->byref)
7970                 g_string_append_printf (s, "b");
7971         switch (t->type) {
7972         case MONO_TYPE_VOID:
7973                 g_string_append_printf (s, "void_");
7974                 break;
7975         case MONO_TYPE_I1:
7976                 g_string_append_printf (s, "i1");
7977                 break;
7978         case MONO_TYPE_U1:
7979                 g_string_append_printf (s, "u1");
7980                 break;
7981         case MONO_TYPE_I2:
7982                 g_string_append_printf (s, "i2");
7983                 break;
7984         case MONO_TYPE_U2:
7985                 g_string_append_printf (s, "u2");
7986                 break;
7987         case MONO_TYPE_I4:
7988                 g_string_append_printf (s, "i4");
7989                 break;
7990         case MONO_TYPE_U4:
7991                 g_string_append_printf (s, "u4");
7992                 break;
7993         case MONO_TYPE_I8:
7994                 g_string_append_printf (s, "i8");
7995                 break;
7996         case MONO_TYPE_U8:
7997                 g_string_append_printf (s, "u8");
7998                 break;
7999         case MONO_TYPE_I:
8000                 g_string_append_printf (s, "ii");
8001                 break;
8002         case MONO_TYPE_U:
8003                 g_string_append_printf (s, "ui");
8004                 break;
8005         case MONO_TYPE_R4:
8006                 g_string_append_printf (s, "fl");
8007                 break;
8008         case MONO_TYPE_R8:
8009                 g_string_append_printf (s, "do");
8010                 break;
8011         default: {
8012                 char *fullname = mono_type_full_name (t);
8013                 GString *temp;
8014                 char *temps;
8015                 int i, len;
8016
8017                 /*
8018                  * Have to create a mangled name which is:
8019                  * - a valid symbol
8020                  * - unique
8021                  */
8022                 temp = g_string_new ("");
8023                 len = strlen (fullname);
8024                 for (i = 0; i < len; ++i) {
8025                         char c = fullname [i];
8026                         if (isalnum (c)) {
8027                                 g_string_append_c (temp, c);
8028                         } else if (c == '_') {
8029                                 g_string_append_c (temp, '_');
8030                                 g_string_append_c (temp, '_');
8031                         } else {
8032                                 g_string_append_c (temp, '_');
8033                                 g_string_append_printf (temp, "%x", (int)c);
8034                         }
8035                 }
8036                 temps = g_string_free (temp, FALSE);
8037                 /* Include the length to avoid different length type names aliasing each other */
8038                 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8039                 g_free (temps);
8040                 return TRUE;
8041         }
8042         }
8043         return TRUE;
8044 }
8045
8046 static gboolean
8047 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8048 {
8049         int i;
8050         gboolean supported;
8051
8052         supported = append_mangled_type (s, sig->ret);
8053         if (!supported)
8054                 return FALSE;
8055         if (sig->hasthis)
8056                 g_string_append_printf (s, "this_");
8057         for (i = 0; i < sig->param_count; ++i) {
8058                 supported = append_mangled_type (s, sig->params [i]);
8059                 if (!supported)
8060                         return FALSE;
8061         }
8062
8063         return TRUE;
8064 }
8065
8066 static void
8067 append_mangled_wrapper_type (GString *s, guint32 wrapper_type) 
8068 {
8069         const char *label;
8070
8071         switch (wrapper_type) {
8072         case MONO_WRAPPER_REMOTING_INVOKE:
8073                 label = "remoting_invoke";
8074                 break;
8075         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8076                 label = "remoting_invoke_check";
8077                 break;
8078         case MONO_WRAPPER_XDOMAIN_INVOKE:
8079                 label = "remoting_invoke_xdomain";
8080                 break;
8081         case MONO_WRAPPER_PROXY_ISINST:
8082                 label = "proxy_isinst";
8083                 break;
8084         case MONO_WRAPPER_LDFLD:
8085                 label = "ldfld";
8086                 break;
8087         case MONO_WRAPPER_LDFLDA:
8088                 label = "ldflda";
8089                 break;
8090         case MONO_WRAPPER_STFLD: 
8091                 label = "stfld";
8092                 break;
8093         case MONO_WRAPPER_ALLOC:
8094                 label = "alloc";
8095                 break;
8096         case MONO_WRAPPER_WRITE_BARRIER:
8097                 label = "write_barrier";
8098                 break;
8099         case MONO_WRAPPER_STELEMREF:
8100                 label = "stelemref";
8101                 break;
8102         case MONO_WRAPPER_UNKNOWN:
8103                 label = "unknown";
8104                 break;
8105         case MONO_WRAPPER_MANAGED_TO_NATIVE:
8106                 label = "man2native";
8107                 break;
8108         case MONO_WRAPPER_SYNCHRONIZED:
8109                 label = "synch";
8110                 break;
8111         case MONO_WRAPPER_MANAGED_TO_MANAGED:
8112                 label = "man2man";
8113                 break;
8114         case MONO_WRAPPER_CASTCLASS:
8115                 label = "castclass";
8116                 break;
8117         case MONO_WRAPPER_RUNTIME_INVOKE:
8118                 label = "run_invoke";
8119                 break;
8120         case MONO_WRAPPER_DELEGATE_INVOKE:
8121                 label = "del_inv";
8122                 break;
8123         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8124                 label = "del_beg_inv";
8125                 break;
8126         case MONO_WRAPPER_DELEGATE_END_INVOKE:
8127                 label = "del_end_inv";
8128                 break;
8129         case MONO_WRAPPER_NATIVE_TO_MANAGED:
8130                 label = "native2man";
8131                 break;
8132         default:
8133                 g_assert_not_reached ();
8134         }
8135
8136         g_string_append_printf (s, "%s_", label);
8137 }
8138
8139 static void
8140 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype) 
8141 {
8142         const char *label;
8143
8144         switch (subtype) 
8145         {
8146         case WRAPPER_SUBTYPE_NONE:
8147                 return;
8148         case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8149                 label = "elem_addr";
8150                 break;
8151         case WRAPPER_SUBTYPE_STRING_CTOR:
8152                 label = "str_ctor";
8153                 break;
8154         case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8155                 label = "virt_stelem";
8156                 break;
8157         case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8158                 label = "fast_mon_enter";
8159                 break;
8160         case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8161                 label = "fast_mon_enter_4";
8162                 break;
8163         case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8164                 label = "fast_monitor_exit";
8165                 break;
8166         case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8167                 label = "ptr2struct";
8168                 break;
8169         case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8170                 label = "struct2ptr";
8171                 break;
8172         case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8173                 label = "castclass_w_cache";
8174                 break;
8175         case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8176                 label = "isinst_w_cache";
8177                 break;
8178         case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8179                 label = "run_inv_norm";
8180                 break;
8181         case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8182                 label = "run_inv_dyn";
8183                 break;
8184         case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8185                 label = "run_inv_dir";
8186                 break;
8187         case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8188                 label = "run_inv_vir";
8189                 break;
8190         case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8191                 label = "icall";
8192                 break;
8193         case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8194                 label = "native_func_aot";
8195                 break;
8196         case WRAPPER_SUBTYPE_PINVOKE:
8197                 label = "pinvoke";
8198                 break;
8199         case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8200                 label = "synch_inner";
8201                 break;
8202         case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8203                 label = "gshared_in";
8204                 break;
8205         case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8206                 label = "gshared_out";
8207                 break;
8208         case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8209                 label = "array_acc";
8210                 break;
8211         case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8212                 label = "generic_arry_help";
8213                 break;
8214         case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8215                 label = "del_inv_virt";
8216                 break;
8217         case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8218                 label = "del_inv_bound";
8219                 break;
8220         case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8221                 label = "gsharedvt_in_sig";
8222                 break;
8223         case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8224                 label = "gsharedvt_out_sig";
8225                 break;
8226         default:
8227                 g_assert_not_reached ();
8228         }
8229
8230         g_string_append_printf (s, "%s_", label);
8231 }
8232
8233 static char *
8234 sanitize_mangled_string (const char *input)
8235 {
8236         GString *s = g_string_new ("");
8237
8238         for (int i=0; input [i] != '\0'; i++) {
8239                 char c = input [i];
8240                 switch (c) {
8241                 case '.':
8242                         g_string_append (s, "_dot_");
8243                         break;
8244                 case ' ':
8245                         g_string_append (s, "_");
8246                         break;
8247                 case '`':
8248                         g_string_append (s, "_bt_");
8249                         break;
8250                 case '<':
8251                         g_string_append (s, "_le_");
8252                         break;
8253                 case '>':
8254                         g_string_append (s, "_gt_");
8255                         break;
8256                 case '/':
8257                         g_string_append (s, "_sl_");
8258                         break;
8259                 case '[':
8260                         g_string_append (s, "_lbrack_");
8261                         break;
8262                 case ']':
8263                         g_string_append (s, "_rbrack_");
8264                         break;
8265                 case '(':
8266                         g_string_append (s, "_lparen_");
8267                         break;
8268                 case '-':
8269                         g_string_append (s, "_dash_");
8270                         break;
8271                 case ')':
8272                         g_string_append (s, "_rparen_");
8273                         break;
8274                 case ',':
8275                         g_string_append (s, "_comma_");
8276                         break;
8277                 default:
8278                         g_string_append_c (s, c);
8279                 }
8280         }
8281
8282         return g_string_free (s, FALSE);
8283 }
8284
8285 static gboolean
8286 append_mangled_klass (GString *s, MonoClass *klass)
8287 {
8288         char *klass_desc = mono_class_full_name (klass);
8289         g_string_append_printf (s, "_%s_%s_", klass->name_space, klass_desc);
8290         g_free (klass_desc);
8291
8292         // Success
8293         return TRUE;
8294 }
8295
8296 static gboolean
8297 append_mangled_method (GString *s, MonoMethod *method);
8298
8299 static gboolean
8300 append_mangled_wrapper (GString *s, MonoMethod *method) 
8301 {
8302         gboolean success = TRUE;
8303         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8304         g_string_append_printf (s, "wrapper_");
8305
8306         append_mangled_wrapper_type (s, method->wrapper_type);
8307
8308         switch (method->wrapper_type) {
8309         case MONO_WRAPPER_REMOTING_INVOKE:
8310         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8311         case MONO_WRAPPER_XDOMAIN_INVOKE: {
8312                 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8313                 g_assert (m);
8314                 success = success && append_mangled_method (s, m);
8315                 break;
8316         }
8317         case MONO_WRAPPER_PROXY_ISINST:
8318         case MONO_WRAPPER_LDFLD:
8319         case MONO_WRAPPER_LDFLDA:
8320         case MONO_WRAPPER_STFLD: {
8321                 g_assert (info);
8322                 success = success && append_mangled_klass (s, info->d.proxy.klass);
8323                 break;
8324         }
8325         case MONO_WRAPPER_ALLOC: {
8326                 /* The GC name is saved once in MonoAotFileInfo */
8327                 g_assert (info->d.alloc.alloc_type != -1);
8328                 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8329                 // SlowAlloc, etc
8330                 g_string_append_printf (s, "%s_", method->name);
8331                 break;
8332         }
8333         case MONO_WRAPPER_WRITE_BARRIER: {
8334                 break;
8335         }
8336         case MONO_WRAPPER_STELEMREF: {
8337                 append_mangled_wrapper_subtype (s, info->subtype);
8338                 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8339                         g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8340                 break;
8341         }
8342         case MONO_WRAPPER_UNKNOWN: {
8343                 append_mangled_wrapper_subtype (s, info->subtype);
8344                 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8345                         info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8346                         success = success && append_mangled_klass (s, method->klass);
8347                 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8348                         success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8349                 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8350                         success = success && append_mangled_method (s, info->d.array_accessor.method);
8351                 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
8352                         append_mangled_signature (s, info->d.gsharedvt.sig);
8353                 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8354                         append_mangled_signature (s, info->d.gsharedvt.sig);
8355                 break;
8356         }
8357         case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8358                 append_mangled_wrapper_subtype (s, info->subtype);
8359                 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8360                         g_string_append_printf (s, "%s", method->name);
8361                 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8362                         success = success && append_mangled_method (s, info->d.managed_to_native.method);
8363                 } else {
8364                         g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8365                         success = success && append_mangled_method (s, info->d.managed_to_native.method);
8366                 }
8367                 break;
8368         }
8369         case MONO_WRAPPER_SYNCHRONIZED: {
8370                 MonoMethod *m;
8371
8372                 m = mono_marshal_method_from_wrapper (method);
8373                 g_assert (m);
8374                 g_assert (m != method);
8375                 success = success && append_mangled_method (s, m);
8376                 break;
8377         }
8378         case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8379                 append_mangled_wrapper_subtype (s, info->subtype);
8380
8381                 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8382                         g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8383                         g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8384                 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8385                         success = success && append_mangled_method (s, info->d.string_ctor.method);
8386                 } else {
8387                         g_assert_not_reached ();
8388                 }
8389                 break;
8390         }
8391         case MONO_WRAPPER_CASTCLASS: {
8392                 append_mangled_wrapper_subtype (s, info->subtype);
8393                 break;
8394         }
8395         case MONO_WRAPPER_RUNTIME_INVOKE: {
8396                 append_mangled_wrapper_subtype (s, info->subtype);
8397                 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
8398                         success = success && append_mangled_method (s, info->d.runtime_invoke.method);
8399                 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
8400                         success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
8401                 break;
8402         }
8403         case MONO_WRAPPER_DELEGATE_INVOKE:
8404         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8405         case MONO_WRAPPER_DELEGATE_END_INVOKE: {
8406                 if (method->is_inflated) {
8407                         /* These wrappers are identified by their class */
8408                         g_string_append_printf (s, "i_");
8409                         success = success && append_mangled_klass (s, method->klass);
8410                 } else {
8411                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8412
8413                         g_string_append_printf (s, "u_");
8414                         if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8415                                 append_mangled_wrapper_subtype (s, info->subtype);
8416                         g_string_append_printf (s, "u_sigstart");
8417                 }
8418                 break;
8419         }
8420         case MONO_WRAPPER_NATIVE_TO_MANAGED: {
8421                 g_assert (info);
8422                 success = success && append_mangled_method (s, info->d.native_to_managed.method);
8423                 success = success && append_mangled_klass (s, method->klass);
8424                 break;
8425         }
8426         default:
8427                 g_assert_not_reached ();
8428         }
8429         return success && append_mangled_signature (s, mono_method_signature (method));
8430 }
8431
8432 static void
8433 append_mangled_context (GString *str, MonoGenericContext *context)
8434 {
8435         GString *res = g_string_new ("");
8436
8437         g_string_append_printf (res, "gens_");
8438         g_string_append (res, "00");
8439
8440         gboolean good = context->class_inst && context->class_inst->type_argc > 0;
8441         good = good || (context->method_inst && context->method_inst->type_argc > 0);
8442         g_assert (good);
8443
8444         if (context->class_inst)
8445                 mono_ginst_get_desc (res, context->class_inst);
8446         if (context->method_inst) {
8447                 if (context->class_inst)
8448                         g_string_append (res, "11");
8449                 mono_ginst_get_desc (res, context->method_inst);
8450         }
8451         g_string_append_printf (str, "gens_%s", res->str);
8452 }       
8453
8454 static gboolean
8455 append_mangled_method (GString *s, MonoMethod *method)
8456 {
8457         if (method->wrapper_type)
8458                 return append_mangled_wrapper (s, method);
8459
8460         g_string_append_printf (s, "%s_", method->klass->image->assembly->aname.name);
8461
8462         if (method->is_inflated) {
8463                 g_string_append_printf (s, "inflated_");
8464                 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
8465                 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
8466
8467                 append_mangled_context (s, &imethod->context);
8468                 g_string_append_printf (s, "_declared_by_");
8469                 append_mangled_method (s, imethod->declaring);
8470         } else if (method->is_generic) {
8471                 g_string_append_printf (s, "generic_");
8472                 append_mangled_klass (s, method->klass);
8473                 g_string_append_printf (s, "_%s_", method->name);
8474
8475                 MonoGenericContainer *container = mono_method_get_generic_container (method);
8476                 g_string_append_printf (s, "_%s");
8477                 append_mangled_context (s, &container->context);
8478
8479                 return append_mangled_signature (s, mono_method_signature (method));
8480         } else {
8481                 g_string_append_printf (s, "_");
8482                 append_mangled_klass (s, method->klass);
8483                 g_string_append_printf (s, "_%s_", method->name);
8484                 if (!append_mangled_signature (s, mono_method_signature (method))) {
8485                         g_string_free (s, TRUE);
8486                         return FALSE;
8487                 }
8488         }
8489
8490         return TRUE;
8491 }
8492
8493 /*
8494  * mono_aot_get_mangled_method_name:
8495  *
8496  *   Return a unique mangled name for METHOD, or NULL.
8497  */
8498 char*
8499 mono_aot_get_mangled_method_name (MonoMethod *method)
8500 {
8501         GString *s = g_string_new ("aot_");
8502         if (!append_mangled_method (s, method)) {
8503                 g_string_free (s, TRUE);
8504                 return NULL;
8505         } else {
8506                 char *out = g_string_free (s, FALSE);
8507                 // Scrub method and class names
8508                 char *cleaned = sanitize_mangled_string (out);
8509                 g_free (out);
8510                 return cleaned;
8511         }
8512 }
8513
8514 gboolean
8515 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8516 {
8517         return is_direct_callable (llvm_acfg, NULL, patch_info);
8518 }
8519
8520 void
8521 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8522 {
8523         MonoPltEntry *plt_entry;
8524
8525         plt_entry = get_plt_entry (llvm_acfg, patch_info);
8526         plt_entry->llvm_used = FALSE;
8527 }
8528
8529 char*
8530 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8531 {
8532         const char *sym = NULL;
8533
8534         if (llvm_acfg->aot_opts.direct_icalls) {
8535                 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8536                         /* Call to a C function implementing a jit icall */
8537                         sym = mono_lookup_jit_icall_symbol ((const char *)data);
8538                 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8539                         MonoMethod *method = (MonoMethod *)data;
8540                         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8541                                 sym = mono_lookup_icall_symbol (method);
8542                         else if (llvm_acfg->aot_opts.direct_pinvoke)
8543                                 sym = get_pinvoke_import (llvm_acfg, method);
8544                 }
8545                 if (sym)
8546                         return g_strdup (sym);
8547         }
8548         return NULL;
8549 }
8550
8551 char*
8552 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8553 {
8554         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8555         MonoPltEntry *plt_entry;
8556         const char *sym = NULL;
8557
8558         ji->type = type;
8559         ji->data.target = data;
8560
8561         if (!can_encode_patch (llvm_acfg, ji))
8562                 return NULL;
8563
8564         if (llvm_acfg->aot_opts.direct_icalls) {
8565                 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8566                         /* Call to a C function implementing a jit icall */
8567                         sym = mono_lookup_jit_icall_symbol ((const char *)data);
8568                 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8569                         MonoMethod *method = (MonoMethod *)data;
8570                         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8571                                 sym = mono_lookup_icall_symbol (method);
8572                 }
8573                 if (sym)
8574                         return g_strdup (sym);
8575         }
8576
8577         plt_entry = get_plt_entry (llvm_acfg, ji);
8578         plt_entry->llvm_used = TRUE;
8579
8580 #if defined(TARGET_MACH)
8581         return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8582 #else
8583         return g_strdup_printf (plt_entry->llvm_symbol);
8584 #endif
8585 }
8586
8587 int
8588 mono_aot_get_method_index (MonoMethod *method)
8589 {
8590         g_assert (llvm_acfg);
8591         return get_method_index (llvm_acfg, method);
8592 }
8593
8594 MonoJumpInfo*
8595 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8596 {
8597         MonoJumpInfo *res;
8598
8599         mono_acfg_lock (llvm_acfg);
8600         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8601         mono_acfg_unlock (llvm_acfg);
8602
8603         return res;
8604 }
8605
8606 static int
8607 execute_system (const char * command)
8608 {
8609         int status = 0;
8610
8611 #if defined(HOST_WIN32) && defined(HAVE_SYSTEM)
8612         // We need an extra set of quotes around the whole command to properly handle commands 
8613         // with spaces since internally the command is called through "cmd /c.
8614         char * quoted_command = g_strdup_printf ("\"%s\"", command);
8615
8616         int size =  MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8617         wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8618         MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8619         status = _wsystem (wstr);
8620         g_free (wstr);
8621
8622         g_free (quoted_command);
8623 #elif defined (HAVE_SYSTEM)
8624         status = system (command);
8625 #else
8626         g_assert_not_reached ();
8627 #endif
8628
8629         return status;
8630 }
8631
8632 #ifdef ENABLE_LLVM
8633
8634 /*
8635  * emit_llvm_file:
8636  *
8637  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8638  * tools.
8639  */
8640 static gboolean
8641 emit_llvm_file (MonoAotCompile *acfg)
8642 {
8643         char *command, *opts, *tempbc, *optbc, *output_fname;
8644
8645         if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8646                 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8647                 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8648         } else {
8649                 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8650                 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8651         }
8652
8653         mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8654
8655         /*
8656          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8657          * a lot of time, and doesn't seem to save much space.
8658          * The following optimizations cannot be enabled:
8659          * - 'tailcallelim'
8660          * - 'jump-threading' changes our blockaddress references to int constants.
8661          * - 'basiccg' fails because it contains:
8662          * if (CS && !isa<IntrinsicInst>(II)) {
8663          * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8664          * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8665          * The opt list below was produced by taking the output of:
8666          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8667          * then removing tailcallelim + the global opts.
8668          * strip-dead-prototypes deletes unused intrinsics definitions.
8669          */
8670         /* The dse pass is disabled because of #13734 and #17616 */
8671         /*
8672          * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8673          * // If we have no DataLayout information around, then the size of the store
8674          *  // is inferrable from the pointee type.  If they are the same type, then
8675          * // we know that the store is safe.
8676          * if (AA.getDataLayout() == 0 &&
8677          * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8678          * return OverwriteComplete;
8679          * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8680          */
8681         if (acfg->aot_opts.llvm_only)
8682                 // FIXME: This doesn't work yet
8683                 opts = g_strdup ("");
8684         else
8685 #if LLVM_API_VERSION > 100
8686                 opts = g_strdup ("-O2 -disable-tail-calls");
8687 #else
8688                 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");
8689 #endif
8690         command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8691         aot_printf (acfg, "Executing opt: %s\n", command);
8692         if (execute_system (command) != 0)
8693                 return FALSE;
8694         g_free (opts);
8695
8696         if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8697                 /* Nothing else to do */
8698                 return TRUE;
8699
8700         if (acfg->aot_opts.llvm_only) {
8701                 /* Use the stock clang from xcode */
8702                 // FIXME: arch
8703                 command = g_strdup_printf ("clang++ -fexceptions -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
8704
8705                 aot_printf (acfg, "Executing clang: %s\n", command);
8706                 if (execute_system (command) != 0)
8707                         return FALSE;
8708                 return TRUE;
8709         }
8710
8711         if (!acfg->llc_args)
8712                 acfg->llc_args = g_string_new ("");
8713
8714         /* Verbose asm slows down llc greatly */
8715         g_string_append (acfg->llc_args, " -asm-verbose=false");
8716
8717         if (acfg->aot_opts.mtriple)
8718                 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8719
8720         g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8721
8722         g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8723
8724 #if LLVM_API_VERSION > 100
8725         g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8726 #endif
8727
8728 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8729         /* ios requires PIC code now */
8730         g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8731 #else
8732         if (llvm_acfg->aot_opts.static_link)
8733                 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8734         else
8735                 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8736 #endif
8737
8738         if (acfg->llvm_owriter) {
8739                 /* Emit an object file directly */
8740                 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8741                 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8742         } else {
8743                 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8744         }
8745         command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8746         g_free (output_fname);
8747
8748         aot_printf (acfg, "Executing llc: %s\n", command);
8749
8750         if (execute_system (command) != 0)
8751                 return FALSE;
8752         return TRUE;
8753 }
8754 #endif
8755
8756 static void
8757 emit_code (MonoAotCompile *acfg)
8758 {
8759         int oindex, i, prev_index;
8760         gboolean saved_unbox_info = FALSE;
8761         char symbol [MAX_SYMBOL_SIZE];
8762
8763         if (acfg->aot_opts.llvm_only)
8764                 return;
8765
8766 #if defined(TARGET_POWERPC64)
8767         sprintf (symbol, ".Lgot_addr");
8768         emit_section_change (acfg, ".text", 0);
8769         emit_alignment (acfg, 8);
8770         emit_label (acfg, symbol);
8771         emit_pointer (acfg, acfg->got_symbol);
8772 #endif
8773
8774         /* 
8775          * This global symbol is used to compute the address of each method using the
8776          * code_offsets array. It is also used to compute the memory ranges occupied by
8777          * AOT code, so it must be equal to the address of the first emitted method.
8778          */
8779         emit_section_change (acfg, ".text", 0);
8780         emit_alignment_code (acfg, 8);
8781         emit_info_symbol (acfg, "jit_code_start");
8782
8783         /* 
8784          * Emit some padding so the local symbol for the first method doesn't have the
8785          * same address as 'methods'.
8786          */
8787         emit_padding (acfg, 16);
8788
8789         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8790                 MonoCompile *cfg;
8791                 MonoMethod *method;
8792
8793                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8794
8795                 cfg = acfg->cfgs [i];
8796
8797                 if (!cfg)
8798                         continue;
8799
8800                 method = cfg->orig_method;
8801
8802                 /* Emit unbox trampoline */
8803                 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8804                         sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8805
8806                         emit_section_change (acfg, ".text", 0);
8807
8808                         if (acfg->thumb_mixed && cfg->compile_llvm) {
8809                                 emit_set_thumb_mode (acfg);
8810                                 fprintf (acfg->fp, "\n.thumb_func\n");
8811                         }
8812
8813                         emit_label (acfg, symbol);
8814
8815                         arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8816
8817                         if (acfg->thumb_mixed && cfg->compile_llvm)
8818                                 emit_set_arm_mode (acfg);
8819
8820                         if (!saved_unbox_info) {
8821                                 char user_symbol [128];
8822                                 GSList *unwind_ops;
8823                                 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8824
8825                                 emit_label (acfg, "ut_end");
8826
8827                                 unwind_ops = mono_unwind_get_cie_program ();
8828                                 save_unwind_info (acfg, user_symbol, unwind_ops);
8829                                 mono_free_unwind_info (unwind_ops);
8830
8831                                 /* Save the unbox trampoline size */
8832                                 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8833
8834                                 saved_unbox_info = TRUE;
8835                         }
8836                 }
8837
8838                 if (cfg->compile_llvm)
8839                         acfg->stats.llvm_count ++;
8840                 else
8841                         emit_method_code (acfg, cfg);
8842         }
8843
8844         emit_section_change (acfg, ".text", 0);
8845         emit_alignment_code (acfg, 8);
8846         emit_info_symbol (acfg, "jit_code_end");
8847
8848         /* To distinguish it from the next symbol */
8849         emit_padding (acfg, 4);
8850
8851         /* 
8852          * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8853          * from optimizing them away, since it doesn't see that code_offsets references them.
8854          * JITted methods don't need this since they are referenced using assembler local
8855          * symbols.
8856          * FIXME: This is why write-symbols doesn't work on OSX ?
8857          */
8858         if (acfg->llvm && acfg->need_no_dead_strip) {
8859                 fprintf (acfg->fp, "\n");
8860                 for (i = 0; i < acfg->nmethods; ++i) {
8861                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8862                                 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8863                 }
8864         }
8865
8866         /*
8867          * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8868          * This is PIE code, and the linker can update it if needed.
8869          */
8870         
8871         sprintf (symbol, "method_addresses");
8872         emit_section_change (acfg, ".text", 1);
8873         emit_alignment_code (acfg, 8);
8874         emit_info_symbol (acfg, symbol);
8875         if (acfg->aot_opts.write_symbols)
8876                 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8877         emit_unset_mode (acfg);
8878         if (acfg->need_no_dead_strip)
8879                 fprintf (acfg->fp, "    .no_dead_strip %s\n", symbol);
8880
8881         for (i = 0; i < acfg->nmethods; ++i) {
8882 #ifdef MONO_ARCH_AOT_SUPPORTED
8883                 int call_size;
8884
8885                 if (acfg->cfgs [i]) {
8886                         arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8887                 } else {
8888                         arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8889                 }
8890 #endif
8891         }
8892
8893         sprintf (symbol, "method_addresses_end");
8894         emit_label (acfg, symbol);
8895         emit_line (acfg);
8896
8897         /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8898         sprintf (symbol, "unbox_trampolines");
8899         emit_section_change (acfg, RODATA_SECT, 0);
8900         emit_alignment (acfg, 8);
8901         emit_info_symbol (acfg, symbol);
8902
8903         prev_index = -1;
8904         for (i = 0; i < acfg->nmethods; ++i) {
8905                 MonoCompile *cfg;
8906                 MonoMethod *method;
8907                 int index;
8908
8909                 cfg = acfg->cfgs [i];
8910                 if (!cfg)
8911                         continue;
8912
8913                 method = cfg->orig_method;
8914
8915                 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8916                         index = get_method_index (acfg, method);
8917
8918                         emit_int32 (acfg, index);
8919                         /* Make sure the table is sorted by index */
8920                         g_assert (index > prev_index);
8921                         prev_index = index;
8922                 }
8923         }
8924         sprintf (symbol, "unbox_trampolines_end");
8925         emit_info_symbol (acfg, symbol);
8926         emit_int32 (acfg, 0);
8927
8928         /* Emit a separate table with the trampoline addresses/offsets */
8929         sprintf (symbol, "unbox_trampoline_addresses");
8930         emit_section_change (acfg, ".text", 0);
8931         emit_alignment_code (acfg, 8);
8932         emit_info_symbol (acfg, symbol);
8933
8934         for (i = 0; i < acfg->nmethods; ++i) {
8935                 MonoCompile *cfg;
8936                 MonoMethod *method;
8937                 int index;
8938
8939                 cfg = acfg->cfgs [i];
8940                 if (!cfg)
8941                         continue;
8942
8943                 method = cfg->orig_method;
8944
8945                 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8946 #ifdef MONO_ARCH_AOT_SUPPORTED
8947                         int call_size;
8948
8949                         index = get_method_index (acfg, method);
8950                         sprintf (symbol, "ut_%d", index);
8951
8952                         arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8953 #endif
8954                 }
8955         }
8956         emit_int32 (acfg, 0);
8957 }
8958
8959 static void
8960 emit_info (MonoAotCompile *acfg)
8961 {
8962         int oindex, i;
8963         gint32 *offsets;
8964
8965         offsets = g_new0 (gint32, acfg->nmethods);
8966
8967         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8968                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8969
8970                 if (acfg->cfgs [i]) {
8971                         emit_method_info (acfg, acfg->cfgs [i]);
8972                         offsets [i] = acfg->cfgs [i]->method_info_offset;
8973                 } else {
8974                         offsets [i] = 0;
8975                 }
8976         }
8977
8978         acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8979
8980         g_free (offsets);
8981 }
8982
8983 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8984
8985 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8986 #define mix(a,b,c) { \
8987         a -= c;  a ^= rot(c, 4);  c += b; \
8988         b -= a;  b ^= rot(a, 6);  a += c; \
8989         c -= b;  c ^= rot(b, 8);  b += a; \
8990         a -= c;  a ^= rot(c,16);  c += b; \
8991         b -= a;  b ^= rot(a,19);  a += c; \
8992         c -= b;  c ^= rot(b, 4);  b += a; \
8993 }
8994 #define final(a,b,c) { \
8995         c ^= b; c -= rot(b,14); \
8996         a ^= c; a -= rot(c,11); \
8997         b ^= a; b -= rot(a,25); \
8998         c ^= b; c -= rot(b,16); \
8999         a ^= c; a -= rot(c,4);  \
9000         b ^= a; b -= rot(a,14); \
9001         c ^= b; c -= rot(b,24); \
9002 }
9003
9004 static guint
9005 mono_aot_type_hash (MonoType *t1)
9006 {
9007         guint hash = t1->type;
9008
9009         hash |= t1->byref << 6; /* do not collide with t1->type values */
9010         switch (t1->type) {
9011         case MONO_TYPE_VALUETYPE:
9012         case MONO_TYPE_CLASS:
9013         case MONO_TYPE_SZARRAY:
9014                 /* check if the distribution is good enough */
9015                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
9016         case MONO_TYPE_PTR:
9017                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9018         case MONO_TYPE_ARRAY:
9019                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
9020         case MONO_TYPE_GENERICINST:
9021                 return ((hash << 5) - hash) ^ 0;
9022         default:
9023                 return hash;
9024         }
9025 }
9026
9027 /*
9028  * mono_aot_method_hash:
9029  *
9030  *   Return a hash code for methods which only depends on metadata.
9031  */
9032 guint32
9033 mono_aot_method_hash (MonoMethod *method)
9034 {
9035         MonoMethodSignature *sig;
9036         MonoClass *klass;
9037         int i, hindex;
9038         int hashes_count;
9039         guint32 *hashes_start, *hashes;
9040         guint32 a, b, c;
9041         MonoGenericInst *class_ginst = NULL;
9042         MonoGenericInst *ginst = NULL;
9043
9044         /* Similar to the hash in mono_method_get_imt_slot () */
9045
9046         sig = mono_method_signature (method);
9047
9048         if (mono_class_is_ginst (method->klass))
9049                 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9050         if (method->is_inflated)
9051                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9052
9053         hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9054         hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9055         hashes = hashes_start;
9056
9057         /* Some wrappers are assigned to random classes */
9058         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9059                 klass = method->klass;
9060         else
9061                 klass = mono_defaults.object_class;
9062
9063         if (!method->wrapper_type) {
9064                 char *full_name;
9065
9066                 if (mono_class_is_ginst (klass))
9067                         full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
9068                 else
9069                         full_name = mono_type_full_name (&klass->byval_arg);
9070
9071                 hashes [0] = mono_metadata_str_hash (full_name);
9072                 hashes [1] = 0;
9073                 g_free (full_name);
9074         } else {
9075                 hashes [0] = mono_metadata_str_hash (klass->name);
9076                 hashes [1] = mono_metadata_str_hash (klass->name_space);
9077         }
9078         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9079                 /* The method name includes a stringified pointer */
9080                 hashes [2] = 0;
9081         else
9082                 hashes [2] = mono_metadata_str_hash (method->name);
9083         hashes [3] = method->wrapper_type;
9084         hashes [4] = mono_aot_type_hash (sig->ret);
9085         hindex = 5;
9086         for (i = 0; i < sig->param_count; i++) {
9087                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9088         }
9089         if (class_ginst) {
9090                 for (i = 0; i < class_ginst->type_argc; ++i)
9091                         hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9092         }
9093         if (ginst) {
9094                 for (i = 0; i < ginst->type_argc; ++i)
9095                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9096         }               
9097         g_assert (hindex == hashes_count);
9098
9099         /* Setup internal state */
9100         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9101
9102         /* Handle most of the hashes */
9103         while (hashes_count > 3) {
9104                 a += hashes [0];
9105                 b += hashes [1];
9106                 c += hashes [2];
9107                 mix (a,b,c);
9108                 hashes_count -= 3;
9109                 hashes += 3;
9110         }
9111
9112         /* Handle the last 3 hashes (all the case statements fall through) */
9113         switch (hashes_count) { 
9114         case 3 : c += hashes [2];
9115         case 2 : b += hashes [1];
9116         case 1 : a += hashes [0];
9117                 final (a,b,c);
9118         case 0: /* nothing left to add */
9119                 break;
9120         }
9121         
9122         g_free (hashes_start);
9123         
9124         return c;
9125 }
9126 #undef rot
9127 #undef mix
9128 #undef final
9129
9130 /*
9131  * mono_aot_get_array_helper_from_wrapper;
9132  *
9133  * Get the helper method in Array called by an array wrapper method.
9134  */
9135 MonoMethod*
9136 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9137 {
9138         MonoMethod *m;
9139         const char *prefix;
9140         MonoGenericContext ctx;
9141         MonoType *args [16];
9142         char *mname, *iname, *s, *s2, *helper_name = NULL;
9143
9144         prefix = "System.Collections.Generic";
9145         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9146         s2 = strstr (s, "`1.");
9147         g_assert (s2);
9148         s2 [0] = '\0';
9149         iname = s;
9150         mname = s2 + 3;
9151
9152         //printf ("X: %s %s\n", iname, mname);
9153
9154         if (!strcmp (iname, "IList"))
9155                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9156         else
9157                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9158         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
9159         g_assert (m);
9160         g_free (helper_name);
9161         g_free (s);
9162
9163         if (m->is_generic) {
9164                 MonoError error;
9165                 memset (&ctx, 0, sizeof (ctx));
9166                 args [0] = &method->klass->element_class->byval_arg;
9167                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9168                 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
9169                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9170         }
9171
9172         return m;
9173 }
9174
9175 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9176
9177 typedef struct HashEntry {
9178     guint32 key, value, index;
9179         struct HashEntry *next;
9180 } HashEntry;
9181
9182 /*
9183  * emit_extra_methods:
9184  *
9185  * Emit methods which are not in the METHOD table, like wrappers.
9186  */
9187 static void
9188 emit_extra_methods (MonoAotCompile *acfg)
9189 {
9190         int i, table_size, buf_size;
9191         guint8 *p, *buf;
9192         guint32 *info_offsets;
9193         guint32 hash;
9194         GPtrArray *table;
9195         HashEntry *entry, *new_entry;
9196         int nmethods, max_chain_length;
9197         int *chain_lengths;
9198
9199         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9200
9201         /* Emit method info */
9202         nmethods = 0;
9203         for (i = 0; i < acfg->extra_methods->len; ++i) {
9204                 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9205                 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9206
9207                 if (!cfg)
9208                         continue;
9209
9210                 buf_size = 10240;
9211                 p = buf = (guint8 *)g_malloc (buf_size);
9212
9213                 nmethods ++;
9214
9215                 method = cfg->method_to_register;
9216
9217                 encode_method_ref (acfg, method, p, &p);
9218
9219                 g_assert ((p - buf) < buf_size);
9220
9221                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9222                 g_free (buf);
9223         }
9224
9225         /*
9226          * Construct a chained hash table for mapping indexes in extra_method_info to
9227          * method indexes.
9228          */
9229         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9230         table = g_ptr_array_sized_new (table_size);
9231         for (i = 0; i < table_size; ++i)
9232                 g_ptr_array_add (table, NULL);
9233         chain_lengths = g_new0 (int, table_size);
9234         max_chain_length = 0;
9235         for (i = 0; i < acfg->extra_methods->len; ++i) {
9236                 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9237                 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9238                 guint32 key, value;
9239
9240                 if (!cfg)
9241                         continue;
9242
9243                 key = info_offsets [i];
9244                 value = get_method_index (acfg, method);
9245
9246                 hash = mono_aot_method_hash (method) % table_size;
9247                 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9248
9249                 chain_lengths [hash] ++;
9250                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9251
9252                 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9253                 new_entry->key = key;
9254                 new_entry->value = value;
9255
9256                 entry = (HashEntry *)g_ptr_array_index (table, hash);
9257                 if (entry == NULL) {
9258                         new_entry->index = hash;
9259                         g_ptr_array_index (table, hash) = new_entry;
9260                 } else {
9261                         while (entry->next)
9262                                 entry = entry->next;
9263                         
9264                         entry->next = new_entry;
9265                         new_entry->index = table->len;
9266                         g_ptr_array_add (table, new_entry);
9267                 }
9268         }
9269         g_free (chain_lengths);
9270
9271         //printf ("MAX: %d\n", max_chain_length);
9272
9273         buf_size = table->len * 12 + 4;
9274         p = buf = (guint8 *)g_malloc (buf_size);
9275         encode_int (table_size, p, &p);
9276
9277         for (i = 0; i < table->len; ++i) {
9278                 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9279
9280                 if (entry == NULL) {
9281                         encode_int (0, p, &p);
9282                         encode_int (0, p, &p);
9283                         encode_int (0, p, &p);
9284                 } else {
9285                         //g_assert (entry->key > 0);
9286                         encode_int (entry->key, p, &p);
9287                         encode_int (entry->value, p, &p);
9288                         if (entry->next)
9289                                 encode_int (entry->next->index, p, &p);
9290                         else
9291                                 encode_int (0, p, &p);
9292                 }
9293         }
9294         g_assert (p - buf <= buf_size);
9295
9296         /* Emit the table */
9297         emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9298
9299         g_free (buf);
9300
9301         /* 
9302          * Emit a table reverse mapping method indexes to their index in extra_method_info.
9303          * This is used by mono_aot_find_jit_info ().
9304          */
9305         buf_size = acfg->extra_methods->len * 8 + 4;
9306         p = buf = (guint8 *)g_malloc (buf_size);
9307         encode_int (acfg->extra_methods->len, p, &p);
9308         for (i = 0; i < acfg->extra_methods->len; ++i) {
9309                 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9310
9311                 encode_int (get_method_index (acfg, method), p, &p);
9312                 encode_int (info_offsets [i], p, &p);
9313         }
9314         emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9315
9316         g_free (buf);
9317         g_free (info_offsets);
9318         g_ptr_array_free (table, TRUE);
9319 }       
9320
9321 static void
9322 generate_aotid (guint8* aotid)
9323 {
9324         gpointer rand_handle;
9325         MonoError error;
9326
9327         mono_rand_open ();
9328         rand_handle = mono_rand_init (NULL, 0);
9329
9330         mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
9331         mono_error_assert_ok (&error);
9332
9333         mono_rand_close (rand_handle);
9334 }
9335
9336 static void
9337 emit_exception_info (MonoAotCompile *acfg)
9338 {
9339         int i;
9340         gint32 *offsets;
9341         SeqPointData sp_data;
9342         gboolean seq_points_to_file = FALSE;
9343
9344         offsets = g_new0 (gint32, acfg->nmethods);
9345         for (i = 0; i < acfg->nmethods; ++i) {
9346                 if (acfg->cfgs [i]) {
9347                         MonoCompile *cfg = acfg->cfgs [i];
9348
9349                         // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
9350                         // As it is not possible to load debug data from a file its is also not possible to store it in a file.
9351                         gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
9352                                 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
9353                         gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
9354                         
9355                         emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
9356                         offsets [i] = cfg->ex_info_offset;
9357
9358                         if (method_seq_points_to_file) {
9359                                 if (!seq_points_to_file) {
9360                                         mono_seq_point_data_init (&sp_data, acfg->nmethods);
9361                                         seq_points_to_file = TRUE;
9362                                 }
9363                                 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
9364                         }
9365                 } else {
9366                         offsets [i] = 0;
9367                 }
9368         }
9369
9370         if (seq_points_to_file) {
9371                 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
9372                 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
9373                 char *image_basename = g_path_get_basename (acfg->image->name);
9374                 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
9375                 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
9376
9377                 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
9378                         fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
9379                         exit (1);
9380                 }
9381
9382                 mono_seq_point_data_write (&sp_data, aot_file_path);
9383                 mono_seq_point_data_free (&sp_data);
9384
9385                 g_free (aotid);
9386                 g_free (dir);
9387                 g_free (image_basename);
9388                 g_free (aot_file);
9389                 g_free (aot_file_path);
9390         }
9391
9392         acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9393         g_free (offsets);
9394 }
9395
9396 static void
9397 emit_unwind_info (MonoAotCompile *acfg)
9398 {
9399         int i;
9400         char symbol [128];
9401
9402         if (acfg->aot_opts.llvm_only) {
9403                 g_assert (acfg->unwind_ops->len == 0);
9404                 return;
9405         }
9406
9407         /* 
9408          * The unwind info contains a lot of duplicates so we emit each unique
9409          * entry once, and only store the offset from the start of the table in the
9410          * exception info.
9411          */
9412
9413         sprintf (symbol, "unwind_info");
9414         emit_section_change (acfg, RODATA_SECT, 1);
9415         emit_alignment (acfg, 8);
9416         emit_info_symbol (acfg, symbol);
9417
9418         for (i = 0; i < acfg->unwind_ops->len; ++i) {
9419                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9420                 guint8 *unwind_info;
9421                 guint32 unwind_info_len;
9422                 guint8 buf [16];
9423                 guint8 *p;
9424
9425                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9426
9427                 p = buf;
9428                 encode_value (unwind_info_len, p, &p);
9429                 emit_bytes (acfg, buf, p - buf);
9430                 emit_bytes (acfg, unwind_info, unwind_info_len);
9431
9432                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9433         }
9434 }
9435
9436 static void
9437 emit_class_info (MonoAotCompile *acfg)
9438 {
9439         int i;
9440         gint32 *offsets;
9441
9442         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9443         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9444                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9445
9446         acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", MONO_AOT_TABLE_CLASS_INFO_OFFSETS, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
9447         g_free (offsets);
9448 }
9449
9450 typedef struct ClassNameTableEntry {
9451         guint32 token, index;
9452         struct ClassNameTableEntry *next;
9453 } ClassNameTableEntry;
9454
9455 static void
9456 emit_class_name_table (MonoAotCompile *acfg)
9457 {
9458         int i, table_size, buf_size;
9459         guint32 token, hash;
9460         MonoClass *klass;
9461         GPtrArray *table;
9462         char *full_name;
9463         guint8 *buf, *p;
9464         ClassNameTableEntry *entry, *new_entry;
9465
9466         /*
9467          * Construct a chained hash table for mapping class names to typedef tokens.
9468          */
9469         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9470         table = g_ptr_array_sized_new (table_size);
9471         for (i = 0; i < table_size; ++i)
9472                 g_ptr_array_add (table, NULL);
9473         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9474                 MonoError error;
9475                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9476                 klass = mono_class_get_checked (acfg->image, token, &error);
9477                 if (!klass) {
9478                         mono_error_cleanup (&error);
9479                         continue;
9480                 }
9481                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9482                 hash = mono_metadata_str_hash (full_name) % table_size;
9483                 g_free (full_name);
9484
9485                 /* FIXME: Allocate from the mempool */
9486                 new_entry = g_new0 (ClassNameTableEntry, 1);
9487                 new_entry->token = token;
9488
9489                 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9490                 if (entry == NULL) {
9491                         new_entry->index = hash;
9492                         g_ptr_array_index (table, hash) = new_entry;
9493                 } else {
9494                         while (entry->next)
9495                                 entry = entry->next;
9496                         
9497                         entry->next = new_entry;
9498                         new_entry->index = table->len;
9499                         g_ptr_array_add (table, new_entry);
9500                 }
9501         }
9502
9503         /* Emit the table */
9504         buf_size = table->len * 4 + 4;
9505         p = buf = (guint8 *)g_malloc0 (buf_size);
9506
9507         /* FIXME: Optimize memory usage */
9508         g_assert (table_size < 65000);
9509         encode_int16 (table_size, p, &p);
9510         g_assert (table->len < 65000);
9511         for (i = 0; i < table->len; ++i) {
9512                 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9513
9514                 if (entry == NULL) {
9515                         encode_int16 (0, p, &p);
9516                         encode_int16 (0, p, &p);
9517                 } else {
9518                         encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9519                         if (entry->next)
9520                                 encode_int16 (entry->next->index, p, &p);
9521                         else
9522                                 encode_int16 (0, p, &p);
9523                 }
9524                 g_free (entry);
9525         }
9526         g_assert (p - buf <= buf_size);
9527         g_ptr_array_free (table, TRUE);
9528
9529         emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9530
9531         g_free (buf);
9532 }
9533
9534 static void
9535 emit_image_table (MonoAotCompile *acfg)
9536 {
9537         int i, buf_size;
9538         guint8 *buf, *p;
9539
9540         /*
9541          * The image table is small but referenced in a lot of places.
9542          * So we emit it at once, and reference its elements by an index.
9543          */
9544         buf_size = acfg->image_table->len * 28 + 4;
9545         for (i = 0; i < acfg->image_table->len; i++) {
9546                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9547                 MonoAssemblyName *aname = &image->assembly->aname;
9548
9549                 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9550         }
9551
9552         buf = p = (guint8 *)g_malloc0 (buf_size);
9553         encode_int (acfg->image_table->len, p, &p);
9554         for (i = 0; i < acfg->image_table->len; i++) {
9555                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9556                 MonoAssemblyName *aname = &image->assembly->aname;
9557
9558                 /* FIXME: Support multi-module assemblies */
9559                 g_assert (image->assembly->image == image);
9560
9561                 encode_string (image->assembly_name, p, &p);
9562                 encode_string (image->guid, p, &p);
9563                 encode_string (aname->culture ? aname->culture : "", p, &p);
9564                 encode_string ((const char*)aname->public_key_token, p, &p);
9565
9566                 while (GPOINTER_TO_UINT (p) % 8 != 0)
9567                         p ++;
9568
9569                 encode_int (aname->flags, p, &p);
9570                 encode_int (aname->major, p, &p);
9571                 encode_int (aname->minor, p, &p);
9572                 encode_int (aname->build, p, &p);
9573                 encode_int (aname->revision, p, &p);
9574         }
9575         g_assert (p - buf <= buf_size);
9576
9577         emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9578
9579         g_free (buf);
9580 }
9581
9582 static void
9583 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9584 {
9585         int i, first_plt_got_patch = 0, buf_size;
9586         guint8 *p, *buf;
9587         guint32 *got_info_offsets;
9588         GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9589
9590         /* Add the patches needed by the PLT to the GOT */
9591         if (!llvm) {
9592                 acfg->plt_got_offset_base = acfg->got_offset;
9593                 first_plt_got_patch = info->got_patches->len;
9594                 for (i = 1; i < acfg->plt_offset; ++i) {
9595                         MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9596
9597                         g_ptr_array_add (info->got_patches, plt_entry->ji);
9598
9599                         acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9600                 }
9601
9602                 acfg->got_offset += acfg->plt_offset;
9603         }
9604
9605         /**
9606          * FIXME: 
9607          * - optimize offsets table.
9608          * - reduce number of exported symbols.
9609          * - emit info for a klass only once.
9610          * - determine when a method uses a GOT slot which is guaranteed to be already 
9611          *   initialized.
9612          * - clean up and document the code.
9613          * - use String.Empty in class libs.
9614          */
9615
9616         /* Encode info required to decode shared GOT entries */
9617         buf_size = info->got_patches->len * 128;
9618         p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9619         got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9620         if (!llvm) {
9621                 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9622                 /* Unused */
9623                 if (acfg->plt_offset)
9624                         acfg->plt_got_info_offsets [0] = 0;
9625         }
9626         for (i = 0; i < info->got_patches->len; ++i) {
9627                 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9628                 guint8 *p2;
9629
9630                 p = buf;
9631
9632                 encode_value (ji->type, p, &p);
9633                 p2 = p;
9634                 encode_patch (acfg, ji, p, &p);
9635                 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9636                 g_assert (p - buf <= buf_size);
9637                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9638
9639                 if (!llvm && i >= first_plt_got_patch)
9640                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9641                 acfg->stats.got_info_size += p - buf;
9642         }
9643
9644         /* Emit got_info_offsets table */
9645
9646         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9647         acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS : MONO_AOT_TABLE_GOT_INFO_OFFSETS, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
9648 }
9649
9650 static void
9651 emit_got (MonoAotCompile *acfg)
9652 {
9653         char symbol [MAX_SYMBOL_SIZE];
9654
9655         if (acfg->aot_opts.llvm_only)
9656                 return;
9657
9658         /* Don't make GOT global so accesses to it don't need relocations */
9659         sprintf (symbol, "%s", acfg->got_symbol);
9660
9661 #ifdef TARGET_MACH
9662         emit_unset_mode (acfg);
9663         fprintf (acfg->fp, ".section __DATA, __bss\n");
9664         emit_alignment (acfg, 8);
9665         if (acfg->llvm)
9666                 emit_info_symbol (acfg, "jit_got");
9667         fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9668 #else
9669         emit_section_change (acfg, ".bss", 0);
9670         emit_alignment (acfg, 8);
9671         if (acfg->aot_opts.write_symbols)
9672                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9673         emit_label (acfg, symbol);
9674         if (acfg->llvm)
9675                 emit_info_symbol (acfg, "jit_got");
9676         if (acfg->got_offset > 0)
9677                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9678 #endif
9679
9680         sprintf (symbol, "got_end");
9681         emit_label (acfg, symbol);
9682 }
9683
9684 typedef struct GlobalsTableEntry {
9685         guint32 value, index;
9686         struct GlobalsTableEntry *next;
9687 } GlobalsTableEntry;
9688
9689 #ifdef TARGET_WIN32_MSVC
9690 #define DLL_ENTRY_POINT "DllMain"
9691
9692 static void
9693 emit_library_info (MonoAotCompile *acfg)
9694 {
9695         // Only include for shared libraries linked directly from generated object.
9696         if (link_shared_library (acfg)) {
9697                 char    *name = NULL;
9698                 char    symbol [MAX_SYMBOL_SIZE];
9699
9700                 // Ask linker to export all global symbols.
9701                 emit_section_change (acfg, ".drectve", 0);
9702                 for (guint i = 0; i < acfg->globals->len; ++i) {
9703                         name = (char *)g_ptr_array_index (acfg->globals, i);
9704                         g_assert (name != NULL);
9705                         sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
9706                         emit_string (acfg, symbol);
9707                 }
9708
9709                 // Emit DLLMain function, needed by MSVC linker for DLL's.
9710                 // NOTE, DllMain should not go into exports above.
9711                 emit_section_change (acfg, ".text", 0);
9712                 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
9713                 emit_label (acfg, DLL_ENTRY_POINT);
9714
9715                 // Simple implementation of DLLMain, just returning TRUE.
9716                 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
9717                 fprintf (acfg->fp, "movl $1, %%eax\n");
9718                 fprintf (acfg->fp, "ret\n");
9719
9720                 // Inform linker about our dll entry function.
9721                 emit_section_change (acfg, ".drectve", 0);
9722                 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
9723                 return;
9724         }
9725 }
9726
9727 #else
9728
9729 static inline void
9730 emit_library_info (MonoAotCompile *acfg)
9731 {
9732         return;
9733 }
9734 #endif
9735
9736 static void
9737 emit_globals (MonoAotCompile *acfg)
9738 {
9739         int i, table_size;
9740         guint32 hash;
9741         GPtrArray *table;
9742         char symbol [1024];
9743         GlobalsTableEntry *entry, *new_entry;
9744
9745         if (!acfg->aot_opts.static_link)
9746                 return;
9747
9748         if (acfg->aot_opts.llvm_only) {
9749                 g_assert (acfg->globals->len == 0);
9750                 return;
9751         }
9752
9753         /* 
9754          * When static linking, we emit a table containing our globals.
9755          */
9756
9757         /*
9758          * Construct a chained hash table for mapping global names to their index in
9759          * the globals table.
9760          */
9761         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9762         table = g_ptr_array_sized_new (table_size);
9763         for (i = 0; i < table_size; ++i)
9764                 g_ptr_array_add (table, NULL);
9765         for (i = 0; i < acfg->globals->len; ++i) {
9766                 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9767
9768                 hash = mono_metadata_str_hash (name) % table_size;
9769
9770                 /* FIXME: Allocate from the mempool */
9771                 new_entry = g_new0 (GlobalsTableEntry, 1);
9772                 new_entry->value = i;
9773
9774                 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9775                 if (entry == NULL) {
9776                         new_entry->index = hash;
9777                         g_ptr_array_index (table, hash) = new_entry;
9778                 } else {
9779                         while (entry->next)
9780                                 entry = entry->next;
9781                         
9782                         entry->next = new_entry;
9783                         new_entry->index = table->len;
9784                         g_ptr_array_add (table, new_entry);
9785                 }
9786         }
9787
9788         /* Emit the table */
9789         sprintf (symbol, ".Lglobals_hash");
9790         emit_section_change (acfg, RODATA_SECT, 0);
9791         emit_alignment (acfg, 8);
9792         emit_label (acfg, symbol);
9793
9794         /* FIXME: Optimize memory usage */
9795         g_assert (table_size < 65000);
9796         emit_int16 (acfg, table_size);
9797         for (i = 0; i < table->len; ++i) {
9798                 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9799
9800                 if (entry == NULL) {
9801                         emit_int16 (acfg, 0);
9802                         emit_int16 (acfg, 0);
9803                 } else {
9804                         emit_int16 (acfg, entry->value + 1);
9805                         if (entry->next)
9806                                 emit_int16 (acfg, entry->next->index);
9807                         else
9808                                 emit_int16 (acfg, 0);
9809                 }
9810         }
9811
9812         /* Emit the names */
9813         for (i = 0; i < acfg->globals->len; ++i) {
9814                 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9815
9816                 sprintf (symbol, "name_%d", i);
9817                 emit_section_change (acfg, RODATA_SECT, 1);
9818 #ifdef TARGET_MACH
9819                 emit_alignment (acfg, 4);
9820 #endif
9821                 emit_label (acfg, symbol);
9822                 emit_string (acfg, name);
9823         }
9824
9825         /* Emit the globals table */
9826         sprintf (symbol, "globals");
9827         emit_section_change (acfg, ".data", 0);
9828         /* This is not a global, since it is accessed by the init function */
9829         emit_alignment (acfg, 8);
9830         emit_info_symbol (acfg, symbol);
9831
9832         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9833         emit_pointer (acfg, symbol);
9834
9835         for (i = 0; i < acfg->globals->len; ++i) {
9836                 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9837
9838                 sprintf (symbol, "name_%d", i);
9839                 emit_pointer (acfg, symbol);
9840
9841                 g_assert (strlen (name) < sizeof (symbol));
9842                 sprintf (symbol, "%s", name);
9843                 emit_pointer (acfg, symbol);
9844         }
9845         /* Null terminate the table */
9846         emit_int32 (acfg, 0);
9847         emit_int32 (acfg, 0);
9848 }
9849
9850 static void
9851 emit_mem_end (MonoAotCompile *acfg)
9852 {
9853         char symbol [128];
9854
9855         if (acfg->aot_opts.llvm_only)
9856                 return;
9857
9858         sprintf (symbol, "mem_end");
9859         emit_section_change (acfg, ".text", 1);
9860         emit_alignment_code (acfg, 8);
9861         emit_label (acfg, symbol);
9862 }
9863
9864 static void
9865 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9866 {
9867         int i;
9868
9869         info->version = MONO_AOT_FILE_VERSION;
9870         info->plt_got_offset_base = acfg->plt_got_offset_base;
9871         info->got_size = acfg->got_offset * sizeof (gpointer);
9872         info->plt_size = acfg->plt_offset;
9873         info->nmethods = acfg->nmethods;
9874         info->flags = acfg->flags;
9875         info->opts = acfg->opts;
9876         info->simd_opts = acfg->simd_opts;
9877         info->gc_name_index = acfg->gc_name_offset;
9878         info->datafile_size = acfg->datafile_offset;
9879         for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9880                 info->table_offsets [i] = acfg->table_offsets [i];
9881         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9882                 info->num_trampolines [i] = acfg->num_trampolines [i];
9883         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9884                 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9885         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9886                 info->trampoline_size [i] = acfg->trampoline_size [i];
9887         info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9888
9889         info->double_align = MONO_ABI_ALIGNOF (double);
9890         info->long_align = MONO_ABI_ALIGNOF (gint64);
9891         info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9892         info->tramp_page_size = acfg->tramp_page_size;
9893         info->nshared_got_entries = acfg->nshared_got_entries;
9894         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9895                 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9896
9897         memcpy(&info->aotid, acfg->image->aotid, 16);
9898 }
9899
9900 static void
9901 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9902 {
9903         char symbol [MAX_SYMBOL_SIZE];
9904         int i, sindex;
9905         const char **symbols;
9906
9907         symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9908         sindex = 0;
9909         symbols [sindex ++] = acfg->got_symbol;
9910         if (acfg->llvm) {
9911                 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9912                 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9913         } else {
9914                 symbols [sindex ++] = NULL;
9915                 symbols [sindex ++] = NULL;
9916         }
9917         /* llvm_get_method */
9918         symbols [sindex ++] = NULL;
9919         /* llvm_get_unbox_tramp */
9920         symbols [sindex ++] = NULL;
9921         if (!acfg->aot_opts.llvm_only) {
9922                 symbols [sindex ++] = "jit_code_start";
9923                 symbols [sindex ++] = "jit_code_end";
9924                 symbols [sindex ++] = "method_addresses";
9925         } else {
9926                 symbols [sindex ++] = NULL;
9927                 symbols [sindex ++] = NULL;
9928                 symbols [sindex ++] = NULL;
9929         }
9930         if (acfg->data_outfile) {
9931                 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9932                         symbols [sindex ++] = NULL;
9933         } else {
9934                 symbols [sindex ++] = "blob";
9935                 symbols [sindex ++] = "class_name_table";
9936                 symbols [sindex ++] = "class_info_offsets";
9937                 symbols [sindex ++] = "method_info_offsets";
9938                 symbols [sindex ++] = "ex_info_offsets";
9939                 symbols [sindex ++] = "extra_method_info_offsets";
9940                 symbols [sindex ++] = "extra_method_table";
9941                 symbols [sindex ++] = "got_info_offsets";
9942                 if (acfg->llvm)
9943                         symbols [sindex ++] = "llvm_got_info_offsets";
9944                 else
9945                         symbols [sindex ++] = NULL;
9946                 symbols [sindex ++] = "image_table";
9947         }
9948         symbols [sindex ++] = "mem_end";
9949         symbols [sindex ++] = "assembly_guid";
9950         symbols [sindex ++] = "runtime_version";
9951         if (acfg->num_trampoline_got_entries) {
9952                 symbols [sindex ++] = "specific_trampolines";
9953                 symbols [sindex ++] = "static_rgctx_trampolines";
9954                 symbols [sindex ++] = "imt_trampolines";
9955                 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9956         } else {
9957                 symbols [sindex ++] = NULL;
9958                 symbols [sindex ++] = NULL;
9959                 symbols [sindex ++] = NULL;
9960                 symbols [sindex ++] = NULL;
9961         }
9962         if (acfg->aot_opts.static_link) {
9963                 symbols [sindex ++] = "globals";
9964         } else {
9965                 symbols [sindex ++] = NULL;
9966         }
9967         symbols [sindex ++] = "assembly_name";
9968         symbols [sindex ++] = "plt";
9969         symbols [sindex ++] = "plt_end";
9970         symbols [sindex ++] = "unwind_info";
9971         if (!acfg->aot_opts.llvm_only) {
9972                 symbols [sindex ++] = "unbox_trampolines";
9973                 symbols [sindex ++] = "unbox_trampolines_end";
9974                 symbols [sindex ++] = "unbox_trampoline_addresses";
9975         } else {
9976                 symbols [sindex ++] = NULL;
9977                 symbols [sindex ++] = NULL;
9978                 symbols [sindex ++] = NULL;
9979         }
9980
9981         g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9982
9983         sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9984         emit_section_change (acfg, ".data", 0);
9985         emit_alignment (acfg, 8);
9986         emit_label (acfg, symbol);
9987         if (!acfg->aot_opts.static_link)
9988                 emit_global (acfg, symbol, FALSE);
9989
9990         /* The data emitted here must match MonoAotFileInfo. */
9991
9992         emit_int32 (acfg, info->version);
9993         emit_int32 (acfg, info->dummy);
9994
9995         /* 
9996          * We emit pointers to our data structures instead of emitting global symbols which
9997          * point to them, to reduce the number of globals, and because using globals leads to
9998          * various problems (i.e. arm/thumb).
9999          */
10000         for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10001                 emit_pointer (acfg, symbols [i]);
10002
10003         emit_int32 (acfg, info->plt_got_offset_base);
10004         emit_int32 (acfg, info->got_size);
10005         emit_int32 (acfg, info->plt_size);
10006         emit_int32 (acfg, info->nmethods);
10007         emit_int32 (acfg, info->flags);
10008         emit_int32 (acfg, info->opts);
10009         emit_int32 (acfg, info->simd_opts);
10010         emit_int32 (acfg, info->gc_name_index);
10011         emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10012         emit_int32 (acfg, info->double_align);
10013         emit_int32 (acfg, info->long_align);
10014         emit_int32 (acfg, info->generic_tramp_num);
10015         emit_int32 (acfg, info->tramp_page_size);
10016         emit_int32 (acfg, info->nshared_got_entries);
10017         emit_int32 (acfg, info->datafile_size);
10018
10019         for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10020                 emit_int32 (acfg, info->table_offsets [i]);
10021         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10022                 emit_int32 (acfg, info->num_trampolines [i]);
10023         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10024                 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10025         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10026                 emit_int32 (acfg, info->trampoline_size [i]);
10027         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10028                 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10029
10030         emit_bytes (acfg, info->aotid, 16);
10031
10032         if (acfg->aot_opts.static_link) {
10033                 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10034                 emit_alignment (acfg, sizeof (gpointer));
10035                 emit_label (acfg, acfg->static_linking_symbol);
10036                 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10037         }
10038 }
10039
10040 /*
10041  * Emit a structure containing all the information not stored elsewhere.
10042  */
10043 static void
10044 emit_file_info (MonoAotCompile *acfg)
10045 {
10046         char *build_info;
10047         MonoAotFileInfo *info;
10048
10049         if (acfg->aot_opts.bind_to_runtime_version) {
10050                 build_info = mono_get_runtime_build_info ();
10051                 emit_string_symbol (acfg, "runtime_version", build_info);
10052                 g_free (build_info);
10053         } else {
10054                 emit_string_symbol (acfg, "runtime_version", "");
10055         }
10056
10057         emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10058
10059         /* Emit a string holding the assembly name */
10060         emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10061
10062         info = g_new0 (MonoAotFileInfo, 1);
10063         init_aot_file_info (acfg, info);
10064
10065         if (acfg->aot_opts.static_link) {
10066                 char symbol [MAX_SYMBOL_SIZE];
10067                 char *p;
10068
10069                 /*
10070                  * Emit a global symbol which can be passed by an embedding app to
10071                  * mono_aot_register_module (). The symbol points to a pointer to the the file info
10072                  * structure.
10073                  */
10074                 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10075
10076                 /* Get rid of characters which cannot occur in symbols */
10077                 p = symbol;
10078                 for (p = symbol; *p; ++p) {
10079                         if (!(isalnum (*p) || *p == '_'))
10080                                 *p = '_';
10081                 }
10082                 acfg->static_linking_symbol = g_strdup (symbol);
10083         }
10084
10085         if (acfg->llvm)
10086                 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10087         else
10088                 emit_aot_file_info (acfg, info);
10089 }
10090
10091 static void
10092 emit_blob (MonoAotCompile *acfg)
10093 {
10094         acfg->blob_closed = TRUE;
10095
10096         emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10097 }
10098
10099 static void
10100 emit_objc_selectors (MonoAotCompile *acfg)
10101 {
10102         int i;
10103         char symbol [128];
10104
10105         if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10106                 return;
10107
10108         /*
10109          * From
10110          * cat > foo.m << EOF
10111          * void *ret ()
10112          * {
10113          * return @selector(print:);
10114          * }
10115          * EOF
10116          */
10117
10118         mono_img_writer_emit_unset_mode (acfg->w);
10119         g_assert (acfg->fp);
10120         fprintf (acfg->fp, ".section    __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10121         fprintf (acfg->fp, ".align      3\n");
10122         for (i = 0; i < acfg->objc_selectors->len; ++i) {
10123                 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10124                 emit_label (acfg, symbol);
10125                 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10126                 emit_pointer (acfg, symbol);
10127
10128         }
10129         fprintf (acfg->fp, ".section    __TEXT,__cstring,cstring_literals\n");
10130         for (i = 0; i < acfg->objc_selectors->len; ++i) {
10131                 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10132                 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10133         }
10134
10135         fprintf (acfg->fp, ".section    __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10136         fprintf (acfg->fp, ".align      3\n");
10137         fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10138         fprintf (acfg->fp, ".long       0\n");
10139         fprintf (acfg->fp, ".long       16\n");
10140 }
10141
10142 static void
10143 emit_dwarf_info (MonoAotCompile *acfg)
10144 {
10145 #ifdef EMIT_DWARF_INFO
10146         int i;
10147         char symbol2 [128];
10148
10149         /* DIEs for methods */
10150         for (i = 0; i < acfg->nmethods; ++i) {
10151                 MonoCompile *cfg = acfg->cfgs [i];
10152
10153                 if (!cfg)
10154                         continue;
10155
10156                 // FIXME: LLVM doesn't define .Lme_...
10157                 if (cfg->compile_llvm)
10158                         continue;
10159
10160                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10161
10162                 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, (guint8 *)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 ()));
10163         }
10164 #endif
10165 }
10166
10167 static gboolean
10168 collect_methods (MonoAotCompile *acfg)
10169 {
10170         int mindex, i;
10171         MonoImage *image = acfg->image;
10172
10173         /* Collect methods */
10174         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
10175                 MonoError error;
10176                 MonoMethod *method;
10177                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
10178
10179                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10180
10181                 if (!method) {
10182                         aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
10183                         aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
10184                         mono_error_cleanup (&error);
10185                         return FALSE;
10186                 }
10187                         
10188                 /* Load all methods eagerly to skip the slower lazy loading code */
10189                 mono_class_setup_methods (method->klass);
10190
10191                 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
10192                         /* Compile the wrapper instead */
10193                         /* We do this here instead of add_wrappers () because it is easy to do it here */
10194                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
10195                         method = wrapper;
10196                 }
10197
10198                 /* FIXME: Some mscorlib methods don't have debug info */
10199                 /*
10200                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
10201                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
10202                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
10203                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10204                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
10205                                 if (!mono_debug_lookup_method (method)) {
10206                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
10207                                         exit (1);
10208                                 }
10209                         }
10210                 }
10211                 */
10212
10213                 if (method->is_generic || mono_class_is_gtd (method->klass))
10214                         /* Compile the ref shared version instead */
10215                         method = mini_get_shared_method (method);
10216
10217                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
10218                 add_method_with_index (acfg, method, i, FALSE);
10219                 acfg->method_index ++;
10220         }
10221
10222         /* gsharedvt methods */
10223         for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
10224                 MonoError error;
10225                 MonoMethod *method;
10226                 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
10227
10228                 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
10229                         continue;
10230
10231                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10232                 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
10233
10234                 if (method->is_generic || mono_class_is_gtd (method->klass)) {
10235                         MonoMethod *gshared;
10236
10237                         gshared = mini_get_shared_method_full (method, TRUE, TRUE);
10238                         add_extra_method (acfg, gshared);
10239                 }
10240         }
10241
10242         if (mono_aot_mode_is_full (&acfg->aot_opts))
10243                 add_generic_instances (acfg);
10244
10245         if (mono_aot_mode_is_full (&acfg->aot_opts))
10246                 add_wrappers (acfg);
10247         return TRUE;
10248 }
10249
10250 static void
10251 compile_methods (MonoAotCompile *acfg)
10252 {
10253         int i, methods_len;
10254
10255         if (acfg->aot_opts.nthreads > 0) {
10256                 GPtrArray *frag;
10257                 int len, j;
10258                 GPtrArray *threads;
10259                 MonoThreadHandle *thread_handle;
10260                 gpointer *user_data;
10261                 MonoMethod **methods;
10262
10263                 methods_len = acfg->methods->len;
10264
10265                 len = acfg->methods->len / acfg->aot_opts.nthreads;
10266                 g_assert (len > 0);
10267                 /* 
10268                  * Partition the list of methods into fragments, and hand it to threads to
10269                  * process.
10270                  */
10271                 threads = g_ptr_array_new ();
10272                 /* Make a copy since acfg->methods is modified by compile_method () */
10273                 methods = g_new0 (MonoMethod*, methods_len);
10274                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
10275                 for (i = 0; i < methods_len; ++i)
10276                         methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
10277                 i = 0;
10278                 while (i < methods_len) {
10279                         MonoError error;
10280                         MonoInternalThread *thread;
10281
10282                         frag = g_ptr_array_new ();
10283                         for (j = 0; j < len; ++j) {
10284                                 if (i < methods_len) {
10285                                         g_ptr_array_add (frag, methods [i]);
10286                                         i ++;
10287                                 }
10288                         }
10289
10290                         user_data = g_new0 (gpointer, 3);
10291                         user_data [0] = acfg;
10292                         user_data [1] = frag;
10293                         
10294                         thread = mono_thread_create_internal (mono_domain_get (), compile_thread_main, (gpointer) user_data, MONO_THREAD_CREATE_FLAGS_NONE, &error);
10295                         mono_error_assert_ok (&error);
10296
10297                         thread_handle = mono_threads_open_thread_handle (thread->handle);
10298                         g_ptr_array_add (threads, thread_handle);
10299                 }
10300                 g_free (methods);
10301
10302                 for (i = 0; i < threads->len; ++i) {
10303                         mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
10304                         mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
10305                 }
10306         } else {
10307                 methods_len = 0;
10308         }
10309
10310         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
10311         for (i = methods_len; i < acfg->methods->len; ++i) {
10312                 /* This can add new methods to acfg->methods */
10313                 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
10314         }
10315 }
10316
10317 static int
10318 compile_asm (MonoAotCompile *acfg)
10319 {
10320         char *command, *objfile;
10321         char *outfile_name, *tmp_outfile_name, *llvm_ofile;
10322         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
10323         char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
10324
10325 #ifdef TARGET_WIN32_MSVC
10326 #define AS_OPTIONS "-c -x assembler"
10327 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
10328 #define AS_OPTIONS "--64"
10329 #elif defined(TARGET_POWERPC64)
10330 #define AS_OPTIONS "-a64 -mppc64"
10331 #elif defined(sparc) && SIZEOF_VOID_P == 8
10332 #define AS_OPTIONS "-xarch=v9"
10333 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10334 #define AS_OPTIONS "-arch i386"
10335 #else
10336 #define AS_OPTIONS ""
10337 #endif
10338
10339 #ifdef __native_client_codegen__
10340 #if defined(TARGET_AMD64)
10341 #define AS_NAME "nacl64-as"
10342 #else
10343 #define AS_NAME "nacl-as"
10344 #endif
10345 #elif defined(TARGET_OSX)
10346 #define AS_NAME "clang"
10347 #elif defined(TARGET_WIN32_MSVC)
10348 #define AS_NAME "clang.exe"
10349 #else
10350 #define AS_NAME "as"
10351 #endif
10352
10353 #ifdef TARGET_WIN32_MSVC
10354 #define AS_OBJECT_FILE_SUFFIX "obj"
10355 #else
10356 #define AS_OBJECT_FILE_SUFFIX "o"
10357 #endif
10358
10359 #if defined(sparc)
10360 #define LD_NAME "ld"
10361 #define LD_OPTIONS "-shared -G"
10362 #elif defined(__ppc__) && defined(TARGET_MACH)
10363 #define LD_NAME "gcc"
10364 #define LD_OPTIONS "-dynamiclib"
10365 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
10366 #define LD_NAME "clang"
10367 #define LD_OPTIONS "--shared"
10368 #elif defined(TARGET_WIN32_MSVC)
10369 #define LD_NAME "link.exe"
10370 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO"
10371 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
10372 #define LD_NAME "gcc"
10373 #define LD_OPTIONS "-shared"
10374 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10375 #define LD_NAME "clang"
10376 #define LD_OPTIONS "-m32 -dynamiclib"
10377 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
10378 #define LD_NAME "gcc"
10379 #define LD_OPTIONS "--shared"
10380 #elif defined(TARGET_POWERPC64)
10381 #define LD_OPTIONS "-m elf64ppc"
10382 #endif
10383
10384 #ifndef LD_OPTIONS
10385 #define LD_OPTIONS ""
10386 #endif
10387
10388         if (acfg->aot_opts.asm_only) {
10389                 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
10390                 if (acfg->aot_opts.static_link)
10391                         aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10392                 if (acfg->llvm)
10393                         aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
10394                 return 0;
10395         }
10396
10397         if (acfg->aot_opts.static_link) {
10398                 if (acfg->aot_opts.outfile)
10399                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10400                 else
10401                         objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
10402         } else {
10403                 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
10404         }
10405
10406 #ifdef TARGET_OSX
10407         g_string_append (acfg->as_args, "-c -x assembler");
10408 #endif
10409
10410         command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10411                         acfg->as_args ? acfg->as_args->str : "", 
10412                         wrap_path (objfile), wrap_path (acfg->tmpfname));
10413         aot_printf (acfg, "Executing the native assembler: %s\n", command);
10414         if (execute_system (command) != 0) {
10415                 g_free (command);
10416                 g_free (objfile);
10417                 return 1;
10418         }
10419
10420         if (acfg->llvm && !acfg->llvm_owriter) {
10421                 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10422                         acfg->as_args ? acfg->as_args->str : "",
10423                         wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
10424                 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10425                 if (execute_system (command) != 0) {
10426                         g_free (command);
10427                         g_free (objfile);
10428                         return 1;
10429                 }
10430         }
10431
10432         g_free (command);
10433
10434         if (acfg->aot_opts.static_link) {
10435                 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10436                 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10437                 g_free (objfile);
10438                 return 0;
10439         }
10440
10441         if (acfg->aot_opts.outfile)
10442                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10443         else
10444                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10445
10446         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10447
10448         if (acfg->llvm) {
10449                 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10450         } else {
10451                 llvm_ofile = g_strdup ("");
10452         }
10453
10454         /* replace the ; flags separators with spaces */
10455         g_strdelimit (ld_flags, ";", ' ');
10456
10457         if (acfg->aot_opts.llvm_only)
10458                 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10459
10460 #ifdef TARGET_WIN32_MSVC
10461         g_assert (tmp_outfile_name != NULL);
10462         g_assert (objfile != NULL);
10463         command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME, LD_OPTIONS,
10464                 ld_flags, tmp_outfile_name, objfile);
10465 #elif defined(LD_NAME)
10466         command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10467                 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10468                 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10469 #else
10470         // Default (linux)
10471         if (acfg->aot_opts.tool_prefix) {
10472                 /* Cross compiling */
10473                 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10474                                                                    wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10475                                                                    wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10476         } else {
10477                 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
10478                                                                           wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10479                                                                           wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10480
10481                 if (acfg->aot_opts.llvm_only) {
10482                         command = g_strdup_printf ("clang++ %s", args);
10483                 } else {
10484                         command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
10485                 }
10486                 g_free (args);
10487         }
10488 #endif
10489         aot_printf (acfg, "Executing the native linker: %s\n", command);
10490         if (execute_system (command) != 0) {
10491                 g_free (tmp_outfile_name);
10492                 g_free (outfile_name);
10493                 g_free (command);
10494                 g_free (objfile);
10495                 g_free (ld_flags);
10496                 return 1;
10497         }
10498
10499         g_free (command);
10500
10501         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10502         printf ("Stripping the binary: %s\n", com);
10503         execute_system (com);
10504         g_free (com);*/
10505
10506 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10507         /* 
10508          * gas generates 'mapping symbols' each time code and data is mixed, which 
10509          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10510          */
10511         command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10512         aot_printf (acfg, "Stripping the binary: %s\n", command);
10513         if (execute_system (command) != 0) {
10514                 g_free (tmp_outfile_name);
10515                 g_free (outfile_name);
10516                 g_free (command);
10517                 g_free (objfile);
10518                 return 1;
10519         }
10520 #endif
10521
10522         if (0 != rename (tmp_outfile_name, outfile_name)) {
10523                 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10524                         /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10525                         unlink (outfile_name);
10526                         rename (tmp_outfile_name, outfile_name);
10527                 }
10528         }
10529
10530 #if defined(TARGET_MACH)
10531         command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10532         aot_printf (acfg, "Executing dsymutil: %s\n", command);
10533         if (execute_system (command) != 0) {
10534                 return 1;
10535         }
10536 #endif
10537
10538         if (!acfg->aot_opts.save_temps)
10539                 unlink (objfile);
10540
10541         g_free (tmp_outfile_name);
10542         g_free (outfile_name);
10543         g_free (objfile);
10544
10545         if (acfg->aot_opts.save_temps)
10546                 aot_printf (acfg, "Retained input file.\n");
10547         else
10548                 unlink (acfg->tmpfname);
10549
10550         return 0;
10551 }
10552
10553 static guint8
10554 profread_byte (FILE *infile)
10555 {
10556         guint8 i;
10557         int res;
10558
10559         res = fread (&i, 1, 1, infile);
10560         g_assert (res == 1);
10561         return i;
10562 }
10563
10564 static int
10565 profread_int (FILE *infile)
10566 {
10567         int i, res;
10568
10569         res = fread (&i, 4, 1, infile);
10570         g_assert (res == 1);
10571         return i;
10572 }
10573
10574 static char*
10575 profread_string (FILE *infile)
10576 {
10577         int len, res;
10578         char buf [1024];
10579         char *pbuf;
10580
10581         len = profread_int (infile);
10582         if (len + 1 > 1024)
10583                 pbuf = g_malloc (len + 1);
10584         else
10585                 pbuf = buf;
10586         res = fread (pbuf, 1, len, infile);
10587         g_assert (res == len);
10588         pbuf [len] = '\0';
10589         if (pbuf == buf)
10590                 return g_strdup (buf);
10591         else
10592                 return pbuf;
10593 }
10594
10595 static void
10596 load_profile_file (MonoAotCompile *acfg, char *filename)
10597 {
10598         FILE *infile;
10599         char buf [1024];
10600         int res, len, version;
10601         char magic [32];
10602
10603         infile = fopen (filename, "r");
10604         if (!infile) {
10605                 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
10606                 exit (1);
10607         }
10608
10609         printf ("Using profile data file '%s'\n", filename);
10610
10611         sprintf (magic, AOT_PROFILER_MAGIC);
10612         len = strlen (magic);
10613         res = fread (buf, 1, len, infile);
10614         magic [len] = '\0';
10615         buf [len] = '\0';
10616         if ((res != len) || strcmp (buf, magic) != 0) {
10617                 printf ("Profile file has wrong header: '%s'.\n", buf);
10618                 fclose (infile);
10619                 exit (1);
10620         }
10621         guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
10622         version = profread_int (infile);
10623         if (version != expected_version) {
10624                 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
10625                 fclose (infile);
10626                 exit (1);
10627         }
10628
10629         ProfileData *data = g_new0 (ProfileData, 1);
10630         data->images = g_hash_table_new (NULL, NULL);
10631         data->classes = g_hash_table_new (NULL, NULL);
10632         data->ginsts = g_hash_table_new (NULL, NULL);
10633         data->methods = g_hash_table_new (NULL, NULL);
10634
10635         while (TRUE) {
10636                 int type = profread_byte (infile);
10637                 int id = profread_int (infile);
10638
10639                 if (type == AOTPROF_RECORD_NONE)
10640                         break;
10641
10642                 switch (type) {
10643                 case AOTPROF_RECORD_IMAGE: {
10644                         ImageProfileData *idata = g_new0 (ImageProfileData, 1);
10645                         idata->name = profread_string (infile);
10646                         char *mvid = profread_string (infile);
10647                         g_free (mvid);
10648                         g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
10649                         break;
10650                 }
10651                 case AOTPROF_RECORD_GINST: {
10652                         int i;
10653                         int len = profread_int (infile);
10654
10655                         GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
10656                         gdata->argc = len;
10657                         gdata->argv = g_new0 (ClassProfileData*, len);
10658
10659                         for (i = 0; i < len; ++i) {
10660                                 int class_id = profread_int (infile);
10661
10662                                 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10663                                 g_assert (gdata->argv [i]);
10664                         }
10665                         g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
10666                         break;
10667                 }
10668                 case AOTPROF_RECORD_TYPE: {
10669                         int type = profread_byte (infile);
10670
10671                         switch (type) {
10672                         case MONO_TYPE_CLASS: {
10673                                 int image_id = profread_int (infile);
10674                                 int ginst_id = profread_int (infile);
10675                                 char *class_name = profread_string (infile);
10676
10677                                 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
10678                                 g_assert (image);
10679
10680                                 char *p = strrchr (class_name, '.');
10681                                 g_assert (p);
10682                                 *p = '\0';
10683
10684                                 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
10685                                 cdata->image = image;
10686                                 cdata->ns = g_strdup (class_name);
10687                                 cdata->name = g_strdup (p + 1);
10688
10689                                 if (ginst_id != -1) {
10690                                         cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10691                                         g_assert (cdata->inst);
10692                                 }
10693                                 g_free (class_name);
10694
10695                                 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
10696                                 break;
10697                         }
10698 #if 0
10699                         case MONO_TYPE_SZARRAY: {
10700                                 int elem_id = profread_int (infile);
10701                                 // FIXME:
10702                                 break;
10703                         }
10704 #endif
10705                         default:
10706                                 g_assert_not_reached ();
10707                                 break;
10708                         }
10709                         break;
10710                 }
10711                 case AOTPROF_RECORD_METHOD: {
10712                         int class_id = profread_int (infile);
10713                         int ginst_id = profread_int (infile);
10714                         int param_count = profread_int (infile);
10715                         char *method_name = profread_string (infile);
10716                         char *sig = profread_string (infile);
10717
10718                         ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10719                         g_assert (klass);
10720
10721                         MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
10722                         mdata->id = id;
10723                         mdata->klass = klass;
10724                         mdata->name = method_name;
10725                         mdata->signature = sig;
10726                         mdata->param_count = param_count;
10727
10728                         if (ginst_id != -1) {
10729                                 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10730                                 g_assert (mdata->inst);
10731                         }
10732                         g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
10733                         break;
10734                 }
10735                 default:
10736                         printf ("%d\n", type);
10737                         g_assert_not_reached ();
10738                         break;
10739                 }
10740         }
10741
10742         fclose (infile);
10743         acfg->profile_data = g_list_append (acfg->profile_data, data);
10744 }
10745
10746 static void
10747 resolve_class (ClassProfileData *cdata);
10748
10749 static void
10750 resolve_ginst (GInstProfileData *inst_data)
10751 {
10752         int i;
10753
10754         if (inst_data->inst)
10755                 return;
10756
10757         for (i = 0; i < inst_data->argc; ++i) {
10758                 resolve_class (inst_data->argv [i]);
10759                 if (!inst_data->argv [i]->klass)
10760                         return;
10761         }
10762         MonoType **args = g_new0 (MonoType*, inst_data->argc);
10763         for (i = 0; i < inst_data->argc; ++i)
10764                 args [i] = &inst_data->argv [i]->klass->byval_arg;
10765
10766         inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
10767 }
10768
10769 static void
10770 resolve_class (ClassProfileData *cdata)
10771 {
10772         MonoError error;
10773         MonoClass *klass;
10774
10775         if (!cdata->image->image)
10776                 return;
10777
10778         klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, &error);
10779         if (!klass) {
10780                 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
10781                 return;
10782         }
10783         if (cdata->inst) {
10784                 resolve_ginst (cdata->inst);
10785                 if (!cdata->inst->inst)
10786                         return;
10787                 MonoGenericContext ctx;
10788
10789                 memset (&ctx, 0, sizeof (ctx));
10790                 ctx.class_inst = cdata->inst->inst;
10791                 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
10792         } else {
10793                 cdata->klass = klass;
10794         }
10795 }
10796
10797 /*
10798  * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
10799  */
10800 static void
10801 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
10802 {
10803         GHashTableIter iter;
10804         gpointer key, value;
10805         int i;
10806
10807         if (!data)
10808                 return;
10809
10810         /* Images */
10811         GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
10812         g_hash_table_iter_init (&iter, data->images);
10813         while (g_hash_table_iter_next (&iter, &key, &value)) {
10814                 ImageProfileData *idata = (ImageProfileData*)value;
10815
10816                 for (i = 0; i < assemblies->len; ++i) {
10817                         MonoAssembly *ass = g_ptr_array_index (assemblies, i);
10818
10819                         if (!strcmp (ass->aname.name, idata->name)) {
10820                                 idata->image = ass->image;
10821                                 break;
10822                         }
10823                 }
10824         }
10825         g_ptr_array_free (assemblies, TRUE);
10826
10827         /* Classes */
10828         g_hash_table_iter_init (&iter, data->classes);
10829         while (g_hash_table_iter_next (&iter, &key, &value)) {
10830                 ClassProfileData *cdata = (ClassProfileData*)value;
10831
10832                 if (!cdata->image->image) {
10833                         if (acfg->aot_opts.verbose)
10834                                 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
10835                         continue;
10836                 }
10837
10838                 resolve_class (cdata);
10839                 /*
10840                 if (cdata->klass)
10841                         printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
10842                 */
10843         }
10844
10845         /* Methods */
10846         g_hash_table_iter_init (&iter, data->methods);
10847         while (g_hash_table_iter_next (&iter, &key, &value)) {
10848                 MethodProfileData *mdata = (MethodProfileData*)value;
10849                 MonoClass *klass;
10850                 MonoMethod *m;
10851                 gpointer miter;
10852
10853                 resolve_class (mdata->klass);
10854                 klass = mdata->klass->klass;
10855                 if (!klass) {
10856                         if (acfg->aot_opts.verbose)
10857                                 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
10858                         continue;
10859                 }
10860                 miter = NULL;
10861                 while ((m = mono_class_get_methods (klass, &miter))) {
10862                         MonoError error;
10863
10864                         if (strcmp (m->name, mdata->name))
10865                                 continue;
10866                         MonoMethodSignature *sig = mono_method_signature (m);
10867                         if (!sig)
10868                                 continue;
10869                         if (sig->param_count != mdata->param_count)
10870                                 continue;
10871                         if (mdata->inst) {
10872                                 resolve_ginst (mdata->inst);
10873                                 if (!mdata->inst->inst)
10874                                         continue;
10875                                 MonoGenericContext ctx;
10876
10877                                 memset (&ctx, 0, sizeof (ctx));
10878                                 ctx.method_inst = mdata->inst->inst;
10879
10880                                 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
10881                                 if (!m)
10882                                         continue;
10883                                 sig = mono_method_signature_checked (m, &error);
10884                                 if (!is_ok (&error)) {
10885                                         mono_error_cleanup (&error);
10886                                         continue;
10887                                 }
10888                         }
10889                         char *sig_str = mono_signature_full_name (sig);
10890                         gboolean match = !strcmp (sig_str, mdata->signature);
10891                         g_free (sig_str);
10892                         if (!match)
10893
10894                                 continue;
10895                         //printf ("%s\n", mono_method_full_name (m, 1));
10896                         mdata->method = m;
10897                         break;
10898                 }
10899                 if (!mdata->method) {
10900                         if (acfg->aot_opts.verbose)
10901                                 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
10902                 }
10903         }
10904 }
10905
10906 static gboolean
10907 inst_references_image (MonoGenericInst *inst, MonoImage *image)
10908 {
10909         int i;
10910
10911         for (i = 0; i < inst->type_argc; ++i) {
10912                 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10913                 if (k->image == image)
10914                         return TRUE;
10915                 if (mono_class_is_ginst (k)) {
10916                         MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
10917                         if (inst_references_image (kinst, image))
10918                                 return TRUE;
10919                 }
10920         }
10921         return FALSE;
10922 }
10923
10924 static gboolean
10925 is_local_inst (MonoGenericInst *inst, MonoImage *image)
10926 {
10927         int i;
10928
10929         for (i = 0; i < inst->type_argc; ++i) {
10930                 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10931                 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
10932                         return FALSE;
10933         }
10934         return TRUE;
10935 }
10936
10937 static void
10938 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
10939 {
10940         GHashTableIter iter;
10941         gpointer key, value;
10942         int count = 0;
10943
10944         if (!data)
10945                 return;
10946
10947         if (acfg->aot_opts.profile_only) {
10948                 /* Add methods referenced by the profile */
10949                 g_hash_table_iter_init (&iter, data->methods);
10950                 while (g_hash_table_iter_next (&iter, &key, &value)) {
10951                         MethodProfileData *mdata = (MethodProfileData*)value;
10952                         MonoMethod *m = mdata->method;
10953
10954                         if (!m)
10955                                 continue;
10956                         if (m->is_inflated)
10957                                 continue;
10958                         add_extra_method (acfg, m);
10959                         g_hash_table_insert (acfg->profile_methods, m, m);
10960                         count ++;
10961                 }
10962         }
10963
10964         /*
10965          * Add method instances 'related' to this assembly to the AOT image.
10966          */
10967         g_hash_table_iter_init (&iter, data->methods);
10968         while (g_hash_table_iter_next (&iter, &key, &value)) {
10969                 MethodProfileData *mdata = (MethodProfileData*)value;
10970                 MonoMethod *m = mdata->method;
10971                 MonoGenericContext *ctx;
10972
10973                 if (!m)
10974                         continue;
10975                 if (!m->is_inflated)
10976                         continue;
10977
10978                 ctx = mono_method_get_context (m);
10979                 /* For simplicity, add instances which reference the assembly we are compiling */
10980                 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
10981                          (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
10982                         !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10983                         //printf ("%s\n", mono_method_full_name (m, TRUE));
10984                         add_extra_method (acfg, m);
10985                         count ++;
10986                 } else if (m->klass->image == acfg->image &&
10987                         ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
10988                          (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
10989                         !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE))  {
10990                         /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
10991                         //printf ("%s\n", mono_method_full_name (m, TRUE));
10992                         add_extra_method (acfg, m);
10993                         count ++;
10994                 }
10995                 /*
10996                  * FIXME: We might skip some instances, for example:
10997                  * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
10998                  * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
10999                  */
11000         }
11001
11002         printf ("Added %d methods from profile.\n", count);
11003 }
11004
11005 static void
11006 init_got_info (GotInfo *info)
11007 {
11008         int i;
11009
11010         info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11011         info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11012         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11013                 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11014         info->got_patches = g_ptr_array_new ();
11015 }
11016
11017 static MonoAotCompile*
11018 acfg_create (MonoAssembly *ass, guint32 opts)
11019 {
11020         MonoImage *image = ass->image;
11021         MonoAotCompile *acfg;
11022
11023         acfg = g_new0 (MonoAotCompile, 1);
11024         acfg->methods = g_ptr_array_new ();
11025         acfg->method_indexes = g_hash_table_new (NULL, NULL);
11026         acfg->method_depth = g_hash_table_new (NULL, NULL);
11027         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
11028         acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11029         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
11030         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
11031         acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
11032         acfg->image_hash = g_hash_table_new (NULL, NULL);
11033         acfg->image_table = g_ptr_array_new ();
11034         acfg->globals = g_ptr_array_new ();
11035         acfg->image = image;
11036         acfg->opts = opts;
11037         /* TODO: Write out set of SIMD instructions used, rather than just those available */
11038         acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
11039         acfg->mempool = mono_mempool_new ();
11040         acfg->extra_methods = g_ptr_array_new ();
11041         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
11042         acfg->unwind_ops = g_ptr_array_new ();
11043         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
11044         acfg->method_order = g_ptr_array_new ();
11045         acfg->export_names = g_hash_table_new (NULL, NULL);
11046         acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
11047         acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
11048         acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
11049         acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11050         acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11051         acfg->profile_methods = g_hash_table_new (NULL, NULL);
11052         mono_os_mutex_init_recursive (&acfg->mutex);
11053
11054         init_got_info (&acfg->got_info);
11055         init_got_info (&acfg->llvm_got_info);
11056
11057         return acfg;
11058 }
11059
11060 static void
11061 got_info_free (GotInfo *info)
11062 {
11063         int i;
11064
11065         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11066                 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
11067         g_free (info->patch_to_got_offset_by_type);
11068         g_hash_table_destroy (info->patch_to_got_offset);
11069         g_ptr_array_free (info->got_patches, TRUE);
11070 }
11071
11072 static void
11073 acfg_free (MonoAotCompile *acfg)
11074 {
11075         int i;
11076
11077         mono_img_writer_destroy (acfg->w);
11078         for (i = 0; i < acfg->nmethods; ++i)
11079                 if (acfg->cfgs [i])
11080                         mono_destroy_compile (acfg->cfgs [i]);
11081
11082         g_free (acfg->cfgs);
11083
11084         g_free (acfg->static_linking_symbol);
11085         g_free (acfg->got_symbol);
11086         g_free (acfg->plt_symbol);
11087         g_ptr_array_free (acfg->methods, TRUE);
11088         g_ptr_array_free (acfg->image_table, TRUE);
11089         g_ptr_array_free (acfg->globals, TRUE);
11090         g_ptr_array_free (acfg->unwind_ops, TRUE);
11091         g_hash_table_destroy (acfg->method_indexes);
11092         g_hash_table_destroy (acfg->method_depth);
11093         g_hash_table_destroy (acfg->plt_offset_to_entry);
11094         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
11095                 if (acfg->patch_to_plt_entry [i])
11096                         g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
11097         }
11098         g_free (acfg->patch_to_plt_entry);
11099         g_hash_table_destroy (acfg->method_to_cfg);
11100         g_hash_table_destroy (acfg->token_info_hash);
11101         g_hash_table_destroy (acfg->method_to_pinvoke_import);
11102         g_hash_table_destroy (acfg->image_hash);
11103         g_hash_table_destroy (acfg->unwind_info_offsets);
11104         g_hash_table_destroy (acfg->method_label_hash);
11105         if (acfg->typespec_classes)
11106                 g_hash_table_destroy (acfg->typespec_classes);
11107         g_hash_table_destroy (acfg->export_names);
11108         g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
11109         g_hash_table_destroy (acfg->klass_blob_hash);
11110         g_hash_table_destroy (acfg->method_blob_hash);
11111         got_info_free (&acfg->got_info);
11112         got_info_free (&acfg->llvm_got_info);
11113         mono_mempool_destroy (acfg->mempool);
11114         g_free (acfg);
11115 }
11116
11117 #define WRAPPER(e,n) n,
11118 static const char* const
11119 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
11120 #include "mono/metadata/wrapper-types.h"
11121         NULL
11122 };
11123
11124 static G_GNUC_UNUSED const char*
11125 get_wrapper_type_name (int type)
11126 {
11127         return wrapper_type_names [type];
11128 }
11129
11130 //#define DUMP_PLT
11131 //#define DUMP_GOT
11132
11133 static void aot_dump (MonoAotCompile *acfg)
11134 {
11135         FILE *dumpfile;
11136         char * dumpname;
11137
11138         JsonWriter writer;
11139         mono_json_writer_init (&writer);
11140
11141         mono_json_writer_object_begin(&writer);
11142
11143         // Methods
11144         mono_json_writer_indent (&writer);
11145         mono_json_writer_object_key(&writer, "methods");
11146         mono_json_writer_array_begin (&writer);
11147
11148         int i;
11149         for (i = 0; i < acfg->nmethods; ++i) {
11150                 MonoCompile *cfg;
11151                 MonoMethod *method;
11152                 MonoClass *klass;
11153
11154                 cfg = acfg->cfgs [i];
11155                 if (!cfg)
11156                         continue;
11157
11158                 method = cfg->orig_method;
11159
11160                 mono_json_writer_indent (&writer);
11161                 mono_json_writer_object_begin(&writer);
11162
11163                 mono_json_writer_indent (&writer);
11164                 mono_json_writer_object_key(&writer, "name");
11165                 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
11166
11167                 mono_json_writer_indent (&writer);
11168                 mono_json_writer_object_key(&writer, "signature");
11169                 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
11170
11171                 mono_json_writer_indent (&writer);
11172                 mono_json_writer_object_key(&writer, "code_size");
11173                 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
11174
11175                 klass = method->klass;
11176
11177                 mono_json_writer_indent (&writer);
11178                 mono_json_writer_object_key(&writer, "class");
11179                 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
11180
11181                 mono_json_writer_indent (&writer);
11182                 mono_json_writer_object_key(&writer, "namespace");
11183                 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
11184
11185                 mono_json_writer_indent (&writer);
11186                 mono_json_writer_object_key(&writer, "wrapper_type");
11187                 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
11188
11189                 mono_json_writer_indent_pop (&writer);
11190                 mono_json_writer_indent (&writer);
11191                 mono_json_writer_object_end (&writer);
11192                 mono_json_writer_printf (&writer, ",\n");
11193         }
11194
11195         mono_json_writer_indent_pop (&writer);
11196         mono_json_writer_indent (&writer);
11197         mono_json_writer_array_end (&writer);
11198         mono_json_writer_printf (&writer, ",\n");
11199
11200         // PLT entries
11201 #ifdef DUMP_PLT
11202         mono_json_writer_indent_push (&writer);
11203         mono_json_writer_indent (&writer);
11204         mono_json_writer_object_key(&writer, "plt");
11205         mono_json_writer_array_begin (&writer);
11206
11207         for (i = 0; i < acfg->plt_offset; ++i) {
11208                 MonoPltEntry *plt_entry = NULL;
11209                 MonoJumpInfo *ji;
11210
11211                 if (i == 0)
11212                         /* 
11213                          * The first plt entry is unused.
11214                          */
11215                         continue;
11216
11217                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
11218                 ji = plt_entry->ji;
11219
11220                 mono_json_writer_indent (&writer);
11221                 mono_json_writer_printf (&writer, "{ ");
11222                 mono_json_writer_object_key(&writer, "symbol");
11223                 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
11224         }
11225
11226         mono_json_writer_indent_pop (&writer);
11227         mono_json_writer_indent (&writer);
11228         mono_json_writer_array_end (&writer);
11229         mono_json_writer_printf (&writer, ",\n");
11230 #endif
11231
11232         // GOT entries
11233 #ifdef DUMP_GOT
11234         mono_json_writer_indent_push (&writer);
11235         mono_json_writer_indent (&writer);
11236         mono_json_writer_object_key(&writer, "got");
11237         mono_json_writer_array_begin (&writer);
11238
11239         mono_json_writer_indent_push (&writer);
11240         for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
11241                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
11242
11243                 mono_json_writer_indent (&writer);
11244                 mono_json_writer_printf (&writer, "{ ");
11245                 mono_json_writer_object_key(&writer, "patch_name");
11246                 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
11247         }
11248
11249         mono_json_writer_indent_pop (&writer);
11250         mono_json_writer_indent (&writer);
11251         mono_json_writer_array_end (&writer);
11252         mono_json_writer_printf (&writer, ",\n");
11253 #endif
11254
11255         mono_json_writer_indent_pop (&writer);
11256         mono_json_writer_indent (&writer);
11257         mono_json_writer_object_end (&writer);
11258
11259         dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
11260         dumpfile = fopen (dumpname, "w+");
11261         g_free (dumpname);
11262
11263         fprintf (dumpfile, "%s", writer.text->str);
11264         fclose (dumpfile);
11265
11266         mono_json_writer_destroy (&writer);
11267 }
11268
11269 static const char *preinited_jit_icalls[] = {
11270         "mono_aot_init_llvm_method",
11271         "mono_aot_init_gshared_method_this",
11272         "mono_aot_init_gshared_method_mrgctx",
11273         "mono_aot_init_gshared_method_vtable",
11274         "mono_llvm_throw_corlib_exception",
11275         "mono_init_vtable_slot",
11276         "mono_helper_ldstr_mscorlib"
11277 };
11278
11279 static void
11280 add_preinit_got_slots (MonoAotCompile *acfg)
11281 {
11282         MonoJumpInfo *ji;
11283         int i;
11284
11285         /*
11286          * Allocate the first few GOT entries to information which is needed frequently, or it is needed
11287          * during method initialization etc.
11288          */
11289
11290         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11291         ji->type = MONO_PATCH_INFO_IMAGE;
11292         ji->data.image = acfg->image;
11293         get_got_offset (acfg, FALSE, ji);
11294         get_got_offset (acfg, TRUE, ji);
11295
11296         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11297         ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
11298         get_got_offset (acfg, FALSE, ji);
11299         get_got_offset (acfg, TRUE, ji);
11300
11301         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11302         ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
11303         get_got_offset (acfg, FALSE, ji);
11304         get_got_offset (acfg, TRUE, ji);
11305
11306         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11307         ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
11308         get_got_offset (acfg, FALSE, ji);
11309         get_got_offset (acfg, TRUE, ji);
11310
11311         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11312         ji->type = MONO_PATCH_INFO_AOT_MODULE;
11313         get_got_offset (acfg, FALSE, ji);
11314         get_got_offset (acfg, TRUE, ji);
11315
11316         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11317         ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
11318         get_got_offset (acfg, FALSE, ji);
11319         get_got_offset (acfg, TRUE, ji);
11320
11321         for (i = 0; i < TLS_KEY_NUM; i++) {
11322                 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11323                 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
11324                 ji->data.index = i;
11325                 get_got_offset (acfg, FALSE, ji);
11326                 get_got_offset (acfg, TRUE, ji);
11327
11328                 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11329                 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
11330                 ji->data.index = i;
11331                 get_got_offset (acfg, FALSE, ji);
11332                 get_got_offset (acfg, TRUE, ji);
11333         }
11334
11335         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11336         ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
11337         get_got_offset (acfg, FALSE, ji);
11338         get_got_offset (acfg, TRUE, ji);
11339
11340         for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
11341                 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
11342                 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11343                 ji->data.name = preinited_jit_icalls [i];
11344                 get_got_offset (acfg, FALSE, ji);
11345                 get_got_offset (acfg, TRUE, ji);
11346         }
11347
11348         acfg->nshared_got_entries = acfg->got_offset;
11349 }
11350
11351 int
11352 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11353 {
11354         MonoImage *image = ass->image;
11355         int i, res;
11356         gint64 all_sizes;
11357         MonoAotCompile *acfg;
11358         char *outfile_name, *tmp_outfile_name, *p;
11359         char llvm_stats_msg [256];
11360         TV_DECLARE (atv);
11361         TV_DECLARE (btv);
11362
11363         acfg = acfg_create (ass, opts);
11364
11365         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
11366         acfg->aot_opts.write_symbols = TRUE;
11367         acfg->aot_opts.ntrampolines = 4096;
11368         acfg->aot_opts.nrgctx_trampolines = 4096;
11369         acfg->aot_opts.nimt_trampolines = 512;
11370         acfg->aot_opts.nrgctx_fetch_trampolines = 128;
11371         acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
11372         acfg->aot_opts.llvm_path = g_strdup ("");
11373         acfg->aot_opts.temp_path = g_strdup ("");
11374 #ifdef MONOTOUCH
11375         acfg->aot_opts.use_trampolines_page = TRUE;
11376 #endif
11377
11378         mono_aot_parse_options (aot_options, &acfg->aot_opts);
11379
11380         if (acfg->aot_opts.logfile) {
11381                 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
11382         }
11383
11384         if (acfg->aot_opts.data_outfile) {
11385                 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
11386                 if (!acfg->data_outfile) {
11387                         aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
11388                         return 1;
11389                 }
11390                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
11391         }
11392
11393         //acfg->aot_opts.print_skipped_methods = TRUE;
11394
11395 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
11396         if (acfg->opts & MONO_OPT_GSHAREDVT) {
11397                 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
11398                 return 1;
11399         }
11400         if (acfg->aot_opts.llvm_only) {
11401                 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
11402                 return 1;
11403         }
11404 #else
11405         if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11406                 acfg->opts |= MONO_OPT_GSHAREDVT;
11407 #endif
11408
11409 #if !defined(ENABLE_LLVM)
11410         if (acfg->aot_opts.llvm_only) {
11411                 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
11412                 return 1;
11413         }
11414 #endif
11415
11416         if (acfg->opts & MONO_OPT_GSHAREDVT)
11417                 mono_set_generic_sharing_vt_supported (TRUE);
11418
11419         aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
11420
11421         generate_aotid ((guint8*) &acfg->image->aotid);
11422
11423         char *aotid = mono_guid_to_string (acfg->image->aotid);
11424         aot_printf (acfg, "AOTID %s\n", aotid);
11425         g_free (aotid);
11426
11427 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
11428         if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11429                 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
11430                 return 1;
11431         }
11432 #endif
11433
11434         if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
11435                 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
11436                 return 1;
11437         }
11438
11439         if (acfg->aot_opts.static_link)
11440                 acfg->aot_opts.asm_writer = TRUE;
11441
11442         if (acfg->aot_opts.soft_debug) {
11443                 MonoDebugOptions *opt = mini_get_debug_options ();
11444
11445                 opt->mdb_optimizations = TRUE;
11446                 opt->gen_sdb_seq_points = TRUE;
11447
11448                 if (!mono_debug_enabled ()) {
11449                         aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
11450                         return 1;
11451                 }
11452                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
11453         }
11454
11455         if (mono_use_llvm || acfg->aot_opts.llvm) {
11456                 acfg->llvm = TRUE;
11457                 acfg->aot_opts.asm_writer = TRUE;
11458                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
11459
11460                 if (acfg->aot_opts.soft_debug) {
11461                         aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
11462                         return 1;
11463                 }
11464
11465                 mini_llvm_init ();
11466
11467                 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
11468                         aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
11469                         return 1;
11470                 }
11471         }
11472
11473         if (mono_aot_mode_is_full (&acfg->aot_opts))
11474                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
11475
11476         if (mono_threads_is_coop_enabled ())
11477                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
11478
11479         if (acfg->aot_opts.instances_logfile_path) {
11480                 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
11481                 if (!acfg->instances_logfile) {
11482                         aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
11483                         return 1;
11484                 }
11485         }
11486
11487         if (acfg->aot_opts.profile_files) {
11488                 GList *l;
11489
11490                 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
11491                         load_profile_file (acfg, (char*)l->data);
11492                 }
11493         }
11494
11495         {
11496                 int method_index;
11497
11498        for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
11499                    g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
11500        }
11501         }
11502
11503         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
11504 #ifdef MONO_ARCH_GSHARED_SUPPORTED
11505         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
11506 #endif
11507         acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
11508 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
11509         if (acfg->opts & MONO_OPT_GSHAREDVT)
11510                 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
11511 #endif
11512
11513         acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
11514
11515         arch_init (acfg);
11516
11517         if (mono_use_llvm || acfg->aot_opts.llvm) {
11518
11519                 /*
11520                  * Emit all LLVM code into a separate assembly/object file and link with it
11521                  * normally.
11522                  */
11523                 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
11524                         acfg->llvm_owriter = TRUE;
11525                 } else if (acfg->aot_opts.llvm_outfile) {
11526                         int len = strlen (acfg->aot_opts.llvm_outfile);
11527
11528                         if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
11529                                 acfg->llvm_owriter = TRUE;
11530                 }
11531         }
11532
11533         if (acfg->llvm && acfg->thumb_mixed)
11534                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
11535         if (acfg->aot_opts.llvm_only)
11536                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
11537
11538         acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
11539         /* Get rid of characters which cannot occur in symbols */
11540         for (p = acfg->assembly_name_sym; *p; ++p) {
11541                 if (!(isalnum (*p) || *p == '_'))
11542                         *p = '_';
11543         }
11544
11545         acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
11546         acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
11547         acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
11548         if (acfg->llvm) {
11549                 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
11550                 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
11551         }
11552
11553         acfg->method_index = 1;
11554
11555         if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11556                 mono_set_partial_sharing_supported (TRUE);
11557
11558         res = collect_methods (acfg);
11559         if (!res)
11560                 return 1;
11561
11562         {
11563                 GList *l;
11564
11565                 for (l = acfg->profile_data; l; l = l->next)
11566                         resolve_profile_data (acfg, (ProfileData*)l->data);
11567                 for (l = acfg->profile_data; l; l = l->next)
11568                         add_profile_instances (acfg, (ProfileData*)l->data);
11569         }
11570
11571         acfg->cfgs_size = acfg->methods->len + 32;
11572         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
11573
11574         /* PLT offset 0 is reserved for the PLT trampoline */
11575         acfg->plt_offset = 1;
11576         add_preinit_got_slots (acfg);
11577
11578 #ifdef ENABLE_LLVM
11579         if (acfg->llvm) {
11580                 llvm_acfg = acfg;
11581                 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
11582         }
11583 #endif
11584
11585         TV_GETTIME (atv);
11586
11587         compile_methods (acfg);
11588
11589         TV_GETTIME (btv);
11590
11591         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
11592
11593         TV_GETTIME (atv);
11594
11595 #ifdef ENABLE_LLVM
11596         if (acfg->llvm) {
11597                 if (acfg->aot_opts.asm_only) {
11598                         if (acfg->aot_opts.outfile) {
11599                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11600                                 acfg->tmpbasename = g_strdup (acfg->tmpfname);
11601                         } else {
11602                                 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
11603                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11604                         }
11605                         g_assert (acfg->aot_opts.llvm_outfile);
11606                         acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11607                         if (acfg->llvm_owriter)
11608                                 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
11609                         else
11610                                 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11611                 } else {
11612                         acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
11613                                 g_strdup_printf ("%s", "temp") :
11614                                 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
11615                                 
11616                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11617                         acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
11618                         acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
11619                 }
11620         }
11621 #endif
11622
11623         if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
11624                 if (acfg->aot_opts.outfile)
11625                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11626                 else
11627                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
11628                 acfg->fp = fopen (acfg->tmpfname, "w+");
11629         } else {
11630                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
11631                 acfg->fp = fdopen (i, "w+");
11632         }
11633         if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
11634                 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
11635                 return 1;
11636         }
11637         if (acfg->fp)
11638                 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
11639
11640         tmp_outfile_name = NULL;
11641         outfile_name = NULL;
11642
11643         /* Compute symbols for methods */
11644         for (i = 0; i < acfg->nmethods; ++i) {
11645                 if (acfg->cfgs [i]) {
11646                         MonoCompile *cfg = acfg->cfgs [i];
11647                         int method_index = get_method_index (acfg, cfg->orig_method);
11648
11649                         if (COMPILE_LLVM (cfg))
11650                                 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
11651                         else if (acfg->global_symbols || acfg->llvm)
11652                                 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
11653                         else
11654                                 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
11655                         cfg->asm_debug_symbol = cfg->asm_symbol;
11656                 }
11657         }
11658
11659         if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
11660                 /*
11661                  * CLANG supports GAS .file/.loc directives, so emit line number information this way
11662                  */
11663                 acfg->gas_line_numbers = TRUE;
11664         }
11665
11666 #ifdef EMIT_DWARF_INFO
11667         if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
11668                 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
11669                         aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
11670                         return 1;
11671                 }
11672                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
11673         }
11674 #endif /* EMIT_DWARF_INFO */
11675
11676         if (acfg->w)
11677                 mono_img_writer_emit_start (acfg->w);
11678
11679         if (acfg->dwarf)
11680                 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
11681
11682         emit_code (acfg);
11683
11684         emit_info (acfg);
11685
11686         emit_extra_methods (acfg);
11687
11688         emit_trampolines (acfg);
11689
11690         emit_class_name_table (acfg);
11691
11692         emit_got_info (acfg, FALSE);
11693         if (acfg->llvm)
11694                 emit_got_info (acfg, TRUE);
11695
11696         emit_exception_info (acfg);
11697
11698         emit_unwind_info (acfg);
11699
11700         emit_class_info (acfg);
11701
11702         emit_plt (acfg);
11703
11704         emit_image_table (acfg);
11705
11706         emit_got (acfg);
11707
11708         {
11709                 /*
11710                  * The managed allocators are GC specific, so can't use an AOT image created by one GC
11711                  * in another.
11712                  */
11713                 const char *gc_name = mono_gc_get_gc_name ();
11714                 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
11715         }
11716
11717         emit_blob (acfg);
11718
11719         emit_objc_selectors (acfg);
11720
11721         emit_globals (acfg);
11722
11723         emit_file_info (acfg);
11724
11725         emit_library_info (acfg);
11726
11727         if (acfg->dwarf) {
11728                 emit_dwarf_info (acfg);
11729                 mono_dwarf_writer_close (acfg->dwarf);
11730         }
11731
11732         emit_mem_end (acfg);
11733
11734         if (acfg->need_pt_gnu_stack) {
11735                 /* This is required so the .so doesn't have an executable stack */
11736                 /* The bin writer already emits this */
11737                 fprintf (acfg->fp, "\n.section  .note.GNU-stack,\"\",@progbits\n");
11738         }
11739
11740         if (acfg->aot_opts.data_outfile)
11741                 fclose (acfg->data_outfile);
11742
11743 #ifdef ENABLE_LLVM
11744         if (acfg->llvm) {
11745                 gboolean res;
11746
11747                 res = emit_llvm_file (acfg);
11748                 if (!res)
11749                         return 1;
11750         }
11751 #endif
11752
11753         TV_GETTIME (btv);
11754
11755         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
11756
11757         if (acfg->llvm)
11758                 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
11759         else
11760                 strcpy (llvm_stats_msg, "");
11761
11762         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;
11763
11764         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",
11765                                 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
11766                                 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
11767                                 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
11768                                 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
11769                                 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
11770                                 acfg->stats.plt_size ? (int)acfg->stats.plt_size : (int)acfg->plt_offset, acfg->stats.plt_size ? (int)(acfg->stats.plt_size * 100 / all_sizes) : 0,
11771                                 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
11772                                 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
11773                         (int)(acfg->got_offset * sizeof (gpointer)));
11774         aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n", 
11775                         acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
11776                         llvm_stats_msg,
11777                         acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
11778                         acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
11779         if (acfg->stats.genericcount)
11780                 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
11781         if (acfg->stats.abscount)
11782                 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
11783         if (acfg->stats.lmfcount)
11784                 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
11785         if (acfg->stats.ocount)
11786                 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
11787
11788         TV_GETTIME (atv);
11789         if (acfg->w) {
11790                 res = mono_img_writer_emit_writeout (acfg->w);
11791                 if (res != 0) {
11792                         acfg_free (acfg);
11793                         return res;
11794                 }
11795                 res = compile_asm (acfg);
11796                 if (res != 0) {
11797                         acfg_free (acfg);
11798                         return res;
11799                 }
11800         }
11801         TV_GETTIME (btv);
11802         acfg->stats.link_time = TV_ELAPSED (atv, btv);
11803
11804         if (acfg->aot_opts.stats) {
11805                 int i;
11806
11807                 aot_printf (acfg, "GOT slot distribution:\n");
11808                 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11809                         if (acfg->stats.got_slot_types [i])
11810                                 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]);
11811                 aot_printf (acfg, "\nMethod stats:\n");
11812                 aot_printf (acfg, "\tNormal:    %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
11813                 aot_printf (acfg, "\tInstance:  %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
11814                 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
11815                 aot_printf (acfg, "\tWrapper:   %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
11816         }
11817
11818         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);
11819
11820         if (acfg->aot_opts.dump_json)
11821                 aot_dump (acfg);
11822
11823         acfg_free (acfg);
11824         
11825         return 0;
11826 }
11827
11828 #else
11829
11830 /* AOT disabled */
11831
11832 void*
11833 mono_aot_readonly_field_override (MonoClassField *field)
11834 {
11835         return NULL;
11836 }
11837
11838 int
11839 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11840 {
11841         return 0;
11842 }
11843
11844 gboolean
11845 mono_aot_is_shared_got_offset (int offset)
11846 {
11847         return FALSE;
11848 }
11849
11850 #endif