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