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