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