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