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