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