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