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