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