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