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