ce970a86be2b2300e26fdbf9d138b6a6b813a2b1
[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_NONE];
157         int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
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:
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 (n, acfg->image);
3964                                 g_assert (t);
3965                                 g_free (n);
3966
3967                                 klass = mono_class_from_mono_type (t);
3968                                 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3969
3970                                 p += slen;
3971
3972                                 num_named = read16 (p);
3973                                 p += 2;
3974
3975                                 g_assert (num_named < 2);
3976                                 if (num_named == 1) {
3977                                         int name_len;
3978                                         char *name;
3979
3980                                         /* parse ExportSymbol attribute */
3981                                         named = p;
3982                                         named_type = *named;
3983                                         named += 1;
3984                                         /* data_type = *named; */
3985                                         named += 1;
3986
3987                                         name_len = mono_metadata_decode_blob_size (named, &named);
3988                                         name = (char *)g_malloc (name_len + 1);
3989                                         memcpy (name, named, name_len);
3990                                         name [name_len] = 0;
3991                                         named += name_len;
3992
3993                                         g_assert (named_type == 0x54);
3994                                         g_assert (!strcmp (name, "ExportSymbol"));
3995
3996                                         /* load_cattr_value (), string case */
3997                                         g_assert (*named != (char)0xff);
3998                                         slen = mono_metadata_decode_value (named, &named);
3999                                         export_name = (char *)g_malloc (slen + 1);
4000                                         memcpy (export_name, named, slen);
4001                                         export_name [slen] = 0;
4002                                         named += slen;
4003                                 }
4004
4005                                 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4006                                 add_method (acfg, wrapper);
4007                                 if (export_name)
4008                                         g_hash_table_insert (acfg->export_names, wrapper, export_name);
4009                         }
4010                 }
4011
4012                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4013                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4014                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4015                 }
4016         }
4017
4018         /* StructureToPtr/PtrToStructure wrappers */
4019         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4020                 MonoError error;
4021                 MonoClass *klass;
4022                 
4023                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4024                 klass = mono_class_get_checked (acfg->image, token, &error);
4025
4026                 if (!klass) {
4027                         mono_error_cleanup (&error);
4028                         continue;
4029                 }
4030
4031                 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4032                         !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4033                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4034                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4035                 }
4036         }
4037 }
4038
4039 static gboolean
4040 has_type_vars (MonoClass *klass)
4041 {
4042         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4043                 return TRUE;
4044         if (klass->rank)
4045                 return has_type_vars (klass->element_class);
4046         if (klass->generic_class) {
4047                 MonoGenericContext *context = &klass->generic_class->context;
4048                 if (context->class_inst) {
4049                         int i;
4050
4051                         for (i = 0; i < context->class_inst->type_argc; ++i)
4052                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4053                                         return TRUE;
4054                 }
4055         }
4056         if (klass->generic_container)
4057                 return TRUE;
4058         return FALSE;
4059 }
4060
4061 static gboolean
4062 is_vt_inst (MonoGenericInst *inst)
4063 {
4064         int i;
4065
4066         for (i = 0; i < inst->type_argc; ++i) {
4067                 MonoType *t = inst->type_argv [i];
4068                 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4069                         return TRUE;
4070         }
4071         return FALSE;
4072 }
4073
4074 static gboolean
4075 method_has_type_vars (MonoMethod *method)
4076 {
4077         if (has_type_vars (method->klass))
4078                 return TRUE;
4079
4080         if (method->is_inflated) {
4081                 MonoGenericContext *context = mono_method_get_context (method);
4082                 if (context->method_inst) {
4083                         int i;
4084
4085                         for (i = 0; i < context->method_inst->type_argc; ++i)
4086                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4087                                         return TRUE;
4088                 }
4089         }
4090         return FALSE;
4091 }
4092
4093 static
4094 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4095 {
4096         return opts->mode == MONO_AOT_MODE_FULL;
4097 }
4098
4099 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4100
4101 static void
4102 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4103 {
4104         /* This might lead to a huge code blowup so only do it if neccesary */
4105         if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4106                 return;
4107
4108         add_generic_class_with_depth (acfg, klass, 0, ref);
4109 }
4110
4111 static gboolean
4112 check_type_depth (MonoType *t, int depth)
4113 {
4114         int i;
4115
4116         if (depth > 8)
4117                 return TRUE;
4118
4119         switch (t->type) {
4120         case MONO_TYPE_GENERICINST: {
4121                 MonoGenericClass *gklass = t->data.generic_class;
4122                 MonoGenericInst *ginst = gklass->context.class_inst;
4123
4124                 if (ginst) {
4125                         for (i = 0; i < ginst->type_argc; ++i) {
4126                                 if (check_type_depth (ginst->type_argv [i], depth + 1))
4127                                         return TRUE;
4128                         }
4129                 }
4130                 break;
4131         }
4132         default:
4133                 break;
4134         }
4135
4136         return FALSE;
4137 }
4138
4139 static void
4140 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4141
4142 /*
4143  * add_generic_class:
4144  *
4145  *   Add all methods of a generic class.
4146  */
4147 static void
4148 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4149 {
4150         MonoMethod *method;
4151         MonoClassField *field;
4152         gpointer iter;
4153         gboolean use_gsharedvt = FALSE;
4154
4155         if (!acfg->ginst_hash)
4156                 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4157
4158         mono_class_init (klass);
4159
4160         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4161                 return;
4162
4163         if (has_type_vars (klass))
4164                 return;
4165
4166         if (!klass->generic_class && !klass->rank)
4167                 return;
4168
4169         if (mono_class_has_failure (klass))
4170                 return;
4171
4172         if (!acfg->ginst_hash)
4173                 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4174
4175         if (g_hash_table_lookup (acfg->ginst_hash, klass))
4176                 return;
4177
4178         if (check_type_depth (&klass->byval_arg, 0))
4179                 return;
4180
4181         if (acfg->aot_opts.log_generics)
4182                 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4183
4184         g_hash_table_insert (acfg->ginst_hash, klass, klass);
4185
4186         /*
4187          * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4188          * Enable this only for some classes since gsharedvt might not support all methods.
4189          */
4190         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) &&
4191                 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4192                 use_gsharedvt = TRUE;
4193
4194         iter = NULL;
4195         while ((method = mono_class_get_methods (klass, &iter))) {
4196                 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4197                         /*
4198                          * This is partial sharing, and we can't handle it yet
4199                          */
4200                         continue;
4201                 }
4202                 
4203                 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4204                         /* Already added */
4205                         add_types_from_method_header (acfg, method);
4206                         continue;
4207                 }
4208
4209                 if (method->is_generic)
4210                         /* FIXME: */
4211                         continue;
4212
4213                 /*
4214                  * FIXME: Instances which are referenced by these methods are not added,
4215                  * for example Array.Resize<int> for List<int>.Add ().
4216                  */
4217                 add_extra_method_with_depth (acfg, method, depth + 1);
4218         }
4219
4220         iter = NULL;
4221         while ((field = mono_class_get_fields (klass, &iter))) {
4222                 if (field->type->type == MONO_TYPE_GENERICINST)
4223                         add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4224         }
4225
4226         if (klass->delegate) {
4227                 method = mono_get_delegate_invoke (klass);
4228
4229                 method = mono_marshal_get_delegate_invoke (method, NULL);
4230
4231                 if (acfg->aot_opts.log_generics)
4232                         aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4233
4234                 add_method (acfg, method);
4235         }
4236
4237         /* Add superclasses */
4238         if (klass->parent)
4239                 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4240
4241         /* 
4242          * For ICollection<T>, add instances of the helper methods
4243          * in Array, since a T[] could be cast to ICollection<T>.
4244          */
4245         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4246                 (!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"))) {
4247                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4248                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4249                 gpointer iter;
4250                 char *name_prefix;
4251
4252                 if (!strcmp (klass->name, "IEnumerator`1"))
4253                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4254                 else
4255                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4256
4257                 /* Add the T[]/InternalEnumerator class */
4258                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4259                         MonoError error;
4260                         MonoClass *nclass;
4261
4262                         iter = NULL;
4263                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4264                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4265                                         break;
4266                         }
4267                         g_assert (nclass);
4268                         nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (klass->generic_class), &error);
4269                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4270                         add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4271                 }
4272
4273                 iter = NULL;
4274                 while ((method = mono_class_get_methods (array_class, &iter))) {
4275                         if (strstr (method->name, name_prefix)) {
4276                                 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4277
4278                                 add_extra_method_with_depth (acfg, m, depth);
4279                         }
4280                 }
4281
4282                 g_free (name_prefix);
4283         }
4284
4285         /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4286         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4287                 MonoError error;
4288                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4289                 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4290                 MonoGenericContext ctx;
4291                 MonoType *args [16];
4292
4293                 memset (&ctx, 0, sizeof (ctx));
4294
4295                 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4296
4297                 args [0] = &tclass->byval_arg;
4298                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4299
4300                 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4301                 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4302
4303                 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4304                         MonoClass *gcomparer_inst;
4305                         gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4306                         gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4307                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4308
4309                         add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4310                 }
4311         }
4312
4313         /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4314         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4315                 MonoError error;
4316                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4317                 MonoClass *iface, *gcomparer, *iface_inst;
4318                 MonoGenericContext ctx;
4319                 MonoType *args [16];
4320
4321                 memset (&ctx, 0, sizeof (ctx));
4322
4323                 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4324                 g_assert (iface);
4325                 args [0] = &tclass->byval_arg;
4326                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4327
4328                 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4329                 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4330
4331                 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4332                         MonoClass *gcomparer_inst;
4333                         MonoError error;
4334
4335                         gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4336                         gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4337                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4338                         add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4339                 }
4340         }
4341
4342         /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4343         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4344                 MonoClass *enum_comparer;
4345                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4346                 MonoGenericContext ctx;
4347                 MonoType *args [16];
4348
4349                 if (mono_class_is_enum (tclass)) {
4350                         MonoClass *enum_comparer_inst;
4351                         MonoError error;
4352
4353                         memset (&ctx, 0, sizeof (ctx));
4354                         args [0] = &tclass->byval_arg;
4355                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4356
4357                         enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4358                         enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4359                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4360                         add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4361                 }
4362         }
4363
4364         /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4365         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4366                 MonoClass *comparer;
4367                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4368                 MonoGenericContext ctx;
4369                 MonoType *args [16];
4370
4371                 if (mono_class_is_enum (tclass)) {
4372                         MonoClass *comparer_inst;
4373                         MonoError error;
4374
4375                         memset (&ctx, 0, sizeof (ctx));
4376                         args [0] = &tclass->byval_arg;
4377                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4378
4379                         comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4380                         comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4381                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4382                         add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4383                 }
4384         }
4385 }
4386
4387 static void
4388 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4389 {
4390         int i;
4391         MonoGenericContext ctx;
4392         MonoType *args [16];
4393
4394         if (acfg->aot_opts.no_instances)
4395                 return;
4396
4397         memset (&ctx, 0, sizeof (ctx));
4398
4399         for (i = 0; i < ninsts; ++i) {
4400                 MonoError error;
4401                 MonoClass *generic_inst;
4402                 args [0] = insts [i];
4403                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4404                 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4405                 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4406                 add_generic_class (acfg, generic_inst, force, "");
4407         }
4408 }
4409
4410 static void
4411 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4412 {
4413         MonoError error;
4414         MonoMethodHeader *header;
4415         MonoMethodSignature *sig;
4416         int j, depth;
4417
4418         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4419
4420         sig = mono_method_signature (method);
4421
4422         if (sig) {
4423                 for (j = 0; j < sig->param_count; ++j)
4424                         if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4425                                 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4426         }
4427
4428         header = mono_method_get_header_checked (method, &error);
4429
4430         if (header) {
4431                 for (j = 0; j < header->num_locals; ++j)
4432                         if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4433                                 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4434         } else {
4435                 mono_error_cleanup (&error); /* FIXME report the error */
4436         }
4437 }
4438
4439 /*
4440  * add_generic_instances:
4441  *
4442  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
4443  */
4444 static void
4445 add_generic_instances (MonoAotCompile *acfg)
4446 {
4447         int i;
4448         guint32 token;
4449         MonoMethod *method;
4450         MonoGenericContext *context;
4451
4452         if (acfg->aot_opts.no_instances)
4453                 return;
4454
4455         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4456                 MonoError error;
4457                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4458                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4459
4460                 if (!method) {
4461                         aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4462                         aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4463                         mono_error_cleanup (&error);
4464                         continue;
4465                 }
4466
4467                 if (method->klass->image != acfg->image)
4468                         continue;
4469
4470                 context = mono_method_get_context (method);
4471
4472                 if (context && ((context->class_inst && context->class_inst->is_open)))
4473                         continue;
4474
4475                 /*
4476                  * For open methods, create an instantiation which can be passed to the JIT.
4477                  * FIXME: Handle class_inst as well.
4478                  */
4479                 if (context && context->method_inst && context->method_inst->is_open) {
4480                         MonoError error;
4481                         MonoGenericContext shared_context;
4482                         MonoGenericInst *inst;
4483                         MonoType **type_argv;
4484                         int i;
4485                         MonoMethod *declaring_method;
4486                         gboolean supported = TRUE;
4487
4488                         /* Check that the context doesn't contain open constructed types */
4489                         if (context->class_inst) {
4490                                 inst = context->class_inst;
4491                                 for (i = 0; i < inst->type_argc; ++i) {
4492                                         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)
4493                                                 continue;
4494                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4495                                                 supported = FALSE;
4496                                 }
4497                         }
4498                         if (context->method_inst) {
4499                                 inst = context->method_inst;
4500                                 for (i = 0; i < inst->type_argc; ++i) {
4501                                         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)
4502                                                 continue;
4503                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4504                                                 supported = FALSE;
4505                                 }
4506                         }
4507
4508                         if (!supported)
4509                                 continue;
4510
4511                         memset (&shared_context, 0, sizeof (MonoGenericContext));
4512
4513                         inst = context->class_inst;
4514                         if (inst) {
4515                                 type_argv = g_new0 (MonoType*, inst->type_argc);
4516                                 for (i = 0; i < inst->type_argc; ++i) {
4517                                         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)
4518                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
4519                                         else
4520                                                 type_argv [i] = inst->type_argv [i];
4521                                 }
4522                                 
4523                                 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4524                                 g_free (type_argv);
4525                         }
4526
4527                         inst = context->method_inst;
4528                         if (inst) {
4529                                 type_argv = g_new0 (MonoType*, inst->type_argc);
4530                                 for (i = 0; i < inst->type_argc; ++i) {
4531                                         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)
4532                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
4533                                         else
4534                                                 type_argv [i] = inst->type_argv [i];
4535                                 }
4536
4537                                 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4538                                 g_free (type_argv);
4539                         }
4540
4541                         if (method->is_generic || method->klass->generic_container)
4542                                 declaring_method = method;
4543                         else
4544                                 declaring_method = mono_method_get_declaring_generic_method (method);
4545
4546                         method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4547                         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4548                 }
4549
4550                 /* 
4551                  * If the method is fully sharable, it was already added in place of its
4552                  * generic definition.
4553                  */
4554                 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4555                         continue;
4556
4557                 /*
4558                  * FIXME: Partially shared methods are not shared here, so we end up with
4559                  * many identical methods.
4560                  */
4561                 add_extra_method (acfg, method);
4562         }
4563
4564         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4565                 MonoError error;
4566                 MonoClass *klass;
4567
4568                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4569
4570                 klass = mono_class_get_checked (acfg->image, token, &error);
4571                 if (!klass || klass->rank) {
4572                         mono_error_cleanup (&error);
4573                         continue;
4574                 }
4575
4576                 add_generic_class (acfg, klass, FALSE, "typespec");
4577         }
4578
4579         /* Add types of args/locals */
4580         for (i = 0; i < acfg->methods->len; ++i) {
4581                 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4582                 add_types_from_method_header (acfg, method);
4583         }
4584
4585         if (acfg->image == mono_defaults.corlib) {
4586                 MonoClass *klass;
4587                 MonoType *insts [256];
4588                 int ninsts = 0;
4589
4590                 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4591                 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4592                 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4593                 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4594                 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4595                 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4596                 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4597                 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4598                 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4599                 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4600                 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4601                 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4602
4603                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4604                 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4605                 if (klass)
4606                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4607                 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4608                 if (klass)
4609                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4610
4611                 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4612                 {
4613                         MonoClass *enum_comparer;
4614                         MonoType *insts [16];
4615                         int ninsts;
4616
4617                         ninsts = 0;
4618                         insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4619                         insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4620                         insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4621                         insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4622                         enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4623                         add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4624
4625                         ninsts = 0;
4626                         insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4627                         enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4628                         add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4629
4630                         ninsts = 0;
4631                         insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4632                         enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4633                         add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4634
4635                         enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4636                         ninsts = 0;
4637                         insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4638                         insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4639                         add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4640                 }
4641
4642                 /* Add instances of the array generic interfaces for primitive types */
4643                 /* This will add instances of the InternalArray_ helper methods in Array too */
4644                 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4645                 if (klass)
4646                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4647
4648                 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4649                 if (klass)
4650                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4651
4652                 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4653                 if (klass)
4654                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4655
4656                 /* 
4657                  * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4658                  * used for all instances of GetGenericValueImpl by the AOT runtime.
4659                  */
4660                 {
4661                         MonoGenericContext ctx;
4662                         MonoType *args [16];
4663                         MonoMethod *get_method;
4664                         MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4665
4666                         get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4667
4668                         if (get_method) {
4669                                 MonoError error;
4670                                 memset (&ctx, 0, sizeof (ctx));
4671                                 args [0] = &mono_defaults.object_class->byval_arg;
4672                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4673                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4674                                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4675                         }
4676                 }
4677
4678                 /* Same for CompareExchange<T>/Exchange<T> */
4679                 {
4680                         MonoGenericContext ctx;
4681                         MonoType *args [16];
4682                         MonoMethod *m;
4683                         MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4684                         gpointer iter = NULL;
4685
4686                         while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4687                                 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4688                                         MonoError error;
4689                                         memset (&ctx, 0, sizeof (ctx));
4690                                         args [0] = &mono_defaults.object_class->byval_arg;
4691                                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4692                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4693                                         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4694                                 }
4695                         }
4696                 }
4697
4698                 /* Same for Volatile.Read/Write<T> */
4699                 {
4700                         MonoGenericContext ctx;
4701                         MonoType *args [16];
4702                         MonoMethod *m;
4703                         MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4704                         gpointer iter = NULL;
4705
4706                         if (volatile_klass) {
4707                                 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4708                                         if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4709                                                 MonoError error;
4710                                                 memset (&ctx, 0, sizeof (ctx));
4711                                                 args [0] = &mono_defaults.object_class->byval_arg;
4712                                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4713                                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4714                                                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4715                                         }
4716                                 }
4717                         }
4718                 }
4719
4720                 /* object[] accessor wrappers. */
4721                 {
4722                         MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
4723                         MonoMethod *m;
4724
4725                         m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
4726                         g_assert (m);
4727
4728                         m = mono_marshal_get_array_accessor_wrapper (m);
4729                         add_extra_method (acfg, m);
4730
4731                         m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
4732                         g_assert (m);
4733
4734                         m = mono_marshal_get_array_accessor_wrapper (m);
4735                         add_extra_method (acfg, m);
4736
4737                         m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
4738                         g_assert (m);
4739
4740                         m = mono_marshal_get_array_accessor_wrapper (m);
4741                         add_extra_method (acfg, m);
4742                 }
4743         }
4744 }
4745
4746 /*
4747  * is_direct_callable:
4748  *
4749  *   Return whenever the method identified by JI is directly callable without 
4750  * going through the PLT.
4751  */
4752 static gboolean
4753 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4754 {
4755         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4756                 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4757                 if (callee_cfg) {
4758                         gboolean direct_callable = TRUE;
4759
4760                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4761                                 direct_callable = FALSE;
4762                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4763                                 // FIXME: Maybe call the wrapper directly ?
4764                                 direct_callable = FALSE;
4765
4766                         if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4767                                 /* Disable this so all calls go through load_method (), see the
4768                                  * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4769                                  * mono_debugger_agent_init ().
4770                                  */
4771                                 direct_callable = FALSE;
4772                         }
4773
4774                         if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4775                                 /* sgen does some initialization when the allocator method is created */
4776                                 direct_callable = FALSE;
4777                         if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4778                                 /* we don't know at compile time whether sgen is concurrent or not */
4779                                 direct_callable = FALSE;
4780
4781                         if (direct_callable)
4782                                 return TRUE;
4783                 }
4784         } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4785                 if (acfg->aot_opts.direct_pinvoke)
4786                         return TRUE;
4787         } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4788                 if (acfg->aot_opts.direct_icalls)
4789                         return TRUE;
4790                 return FALSE;
4791         }
4792
4793         return FALSE;
4794 }
4795
4796 #ifdef MONO_ARCH_AOT_SUPPORTED
4797 static const char *
4798 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4799 {
4800         MonoImage *image = method->klass->image;
4801         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4802         MonoTableInfo *tables = image->tables;
4803         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4804         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4805         guint32 im_cols [MONO_IMPLMAP_SIZE];
4806         char *import;
4807
4808         import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4809         if (import != NULL)
4810                 return import;
4811
4812         if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4813                 return NULL;
4814
4815         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4816
4817         if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4818                 return NULL;
4819
4820         import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4821
4822         g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4823         
4824         return import;
4825 }
4826 #else
4827 static const char *
4828 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4829 {
4830         return NULL;
4831 }
4832 #endif
4833
4834 static gint
4835 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4836 {
4837         if (a->native_offset == b->native_offset)
4838                 return a->il_offset - b->il_offset;
4839         else
4840                 return a->native_offset - b->native_offset;
4841 }
4842
4843 /*
4844  * compute_line_numbers:
4845  *
4846  * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4847  * entry.
4848  */
4849 static MonoDebugSourceLocation**
4850 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4851 {
4852         MonoDebugMethodInfo *minfo;
4853         MonoDebugLineNumberEntry *ln_array;
4854         MonoDebugSourceLocation *loc;
4855         int i, prev_line, prev_il_offset;
4856         int *native_to_il_offset = NULL;
4857         MonoDebugSourceLocation **res;
4858         gboolean first;
4859
4860         minfo = mono_debug_lookup_method (method);
4861         if (!minfo)
4862                 return NULL;
4863         // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4864         if (debug_info->code_size != code_size)
4865                 return NULL;
4866
4867         g_assert (code_size);
4868
4869         /* Compute the native->IL offset mapping */
4870
4871         ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4872         memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4873
4874         qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
4875
4876         native_to_il_offset = g_new0 (int, code_size + 1);
4877
4878         for (i = 0; i < debug_info->num_line_numbers; ++i) {
4879                 int j;
4880                 MonoDebugLineNumberEntry *lne = &ln_array [i];
4881
4882                 if (i == 0) {
4883                         for (j = 0; j < lne->native_offset; ++j)
4884                                 native_to_il_offset [j] = -1;
4885                 }
4886
4887                 if (i < debug_info->num_line_numbers - 1) {
4888                         MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4889
4890                         for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4891                                 native_to_il_offset [j] = lne->il_offset;
4892                 } else {
4893                         for (j = lne->native_offset; j < code_size; ++j)
4894                                 native_to_il_offset [j] = lne->il_offset;
4895                 }
4896         }
4897         g_free (ln_array);
4898
4899         /* Compute the native->line number mapping */
4900         res = g_new0 (MonoDebugSourceLocation*, code_size);
4901         prev_il_offset = -1;
4902         prev_line = -1;
4903         first = TRUE;
4904         for (i = 0; i < code_size; ++i) {
4905                 int il_offset = native_to_il_offset [i];
4906
4907                 if (il_offset == -1 || il_offset == prev_il_offset)
4908                         continue;
4909                 prev_il_offset = il_offset;
4910                 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4911                 if (!(loc && loc->source_file))
4912                         continue;
4913                 if (loc->row == prev_line) {
4914                         mono_debug_symfile_free_location (loc);
4915                         continue;
4916                 }
4917                 prev_line = loc->row;
4918                 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4919                 if (first)
4920                         /* This will cover the prolog too */
4921                         res [0] = loc;
4922                 else
4923                         res [i] = loc;
4924                 first = FALSE;
4925         }
4926         return res;
4927 }
4928
4929 static int
4930 get_file_index (MonoAotCompile *acfg, const char *source_file)
4931 {
4932         int findex;
4933
4934         // FIXME: Free these
4935         if (!acfg->dwarf_ln_filenames)
4936                 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4937         findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4938         if (!findex) {
4939                 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4940                 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4941                 emit_unset_mode (acfg);
4942                 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4943         }
4944         return findex;
4945 }
4946
4947 #ifdef TARGET_ARM64
4948 #define INST_LEN 4
4949 #else
4950 #define INST_LEN 1
4951 #endif
4952
4953 /*
4954  * emit_and_reloc_code:
4955  *
4956  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4957  * is true, calls are made through the GOT too. This is used for emitting trampolines
4958  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4959  * since trampolines are needed to make PTL work.
4960  */
4961 static void
4962 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4963 {
4964         int i, pindex, start_index;
4965         GPtrArray *patches;
4966         MonoJumpInfo *patch_info;
4967         MonoDebugSourceLocation **locs = NULL;
4968         gboolean skip;
4969 #ifdef MONO_ARCH_AOT_SUPPORTED
4970         gboolean direct_call, external_call;
4971         guint32 got_slot;
4972         const char *direct_call_target = 0;
4973         const char *direct_pinvoke;
4974 #endif
4975
4976         if (acfg->gas_line_numbers && method && debug_info) {
4977                 locs = compute_line_numbers (method, code_len, debug_info);
4978                 if (!locs) {
4979                         int findex = get_file_index (acfg, "<unknown>");
4980                         emit_unset_mode (acfg);
4981                         fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4982                 }
4983         }
4984
4985         /* Collect and sort relocations */
4986         patches = g_ptr_array_new ();
4987         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4988                 g_ptr_array_add (patches, patch_info);
4989         g_ptr_array_sort (patches, compare_patches);
4990
4991         start_index = 0;
4992         for (i = 0; i < code_len; i += INST_LEN) {
4993                 patch_info = NULL;
4994                 for (pindex = start_index; pindex < patches->len; ++pindex) {
4995                         patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
4996                         if (patch_info->ip.i >= i)
4997                                 break;
4998                 }
4999
5000                 if (locs && locs [i]) {
5001                         MonoDebugSourceLocation *loc = locs [i];
5002                         int findex;
5003
5004                         findex = get_file_index (acfg, loc->source_file);
5005                         emit_unset_mode (acfg);
5006                         fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
5007                         mono_debug_symfile_free_location (loc);
5008                 }
5009
5010                 skip = FALSE;
5011 #ifdef MONO_ARCH_AOT_SUPPORTED
5012                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5013                         start_index = pindex;
5014
5015                         switch (patch_info->type) {
5016                         case MONO_PATCH_INFO_NONE:
5017                                 break;
5018                         case MONO_PATCH_INFO_GOT_OFFSET: {
5019                                 int code_size;
5020  
5021                                 arch_emit_got_offset (acfg, code + i, &code_size);
5022                                 i += code_size - INST_LEN;
5023                                 skip = TRUE;
5024                                 patch_info->type = MONO_PATCH_INFO_NONE;
5025                                 break;
5026                         }
5027                         case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5028                                 int code_size, index;
5029                                 char *selector = (char *)patch_info->data.target;
5030
5031                                 if (!acfg->objc_selector_to_index)
5032                                         acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5033                                 if (!acfg->objc_selectors)
5034                                         acfg->objc_selectors = g_ptr_array_new ();
5035                                 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5036                                 if (index)
5037                                         index --;
5038                                 else {
5039                                         index = acfg->objc_selector_index;
5040                                         g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5041                                         g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5042                                         acfg->objc_selector_index ++;
5043                                 }
5044
5045                                 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5046                                 i += code_size - INST_LEN;
5047                                 skip = TRUE;
5048                                 patch_info->type = MONO_PATCH_INFO_NONE;
5049                                 break;
5050                         }
5051                         default: {
5052                                 /*
5053                                  * If this patch is a call, try emitting a direct call instead of
5054                                  * through a PLT entry. This is possible if the called method is in
5055                                  * the same assembly and requires no initialization.
5056                                  */
5057                                 direct_call = FALSE;
5058                                 external_call = FALSE;
5059                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5060                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5061                                                 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5062                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5063                                                 direct_call = TRUE;
5064                                                 direct_call_target = callee_cfg->asm_symbol;
5065                                                 patch_info->type = MONO_PATCH_INFO_NONE;
5066                                                 acfg->stats.direct_calls ++;
5067                                         }
5068
5069                                         acfg->stats.all_calls ++;
5070                                 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
5071                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5072                                                 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5073                                                         direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5074                                                 else
5075                                                         direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5076                                                 if (direct_pinvoke) {
5077                                                         direct_call = TRUE;
5078                                                         g_assert (strlen (direct_pinvoke) < 1000);
5079                                                         direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5080                                                 }
5081                                         }
5082                                 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5083                                         const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5084                                         if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5085                                                 /* Call to a C function implementing a jit icall */
5086                                                 direct_call = TRUE;
5087                                                 external_call = TRUE;
5088                                                 g_assert (strlen (sym) < 1000);
5089                                                 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5090                                         }
5091                                 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5092                                         MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5093                                         const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5094                                         if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5095                                                 /* Call to a jit icall without a wrapper */
5096                                                 direct_call = TRUE;
5097                                                 external_call = TRUE;
5098                                                 g_assert (strlen (sym) < 1000);
5099                                                 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5100                                         }
5101                                 }
5102
5103                                 if (direct_call) {
5104                                         patch_info->type = MONO_PATCH_INFO_NONE;
5105                                         acfg->stats.direct_calls ++;
5106                                 }
5107
5108                                 if (!got_only && !direct_call) {
5109                                         MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5110                                         if (plt_entry) {
5111                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5112                                                 direct_call = TRUE;
5113                                                 direct_call_target = plt_entry->symbol;
5114                 
5115                                                 /* Nullify the patch */
5116                                                 patch_info->type = MONO_PATCH_INFO_NONE;
5117                                                 plt_entry->jit_used = TRUE;
5118                                         }
5119                                 }
5120
5121                                 if (direct_call) {
5122                                         int call_size;
5123
5124                                         arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5125                                         i += call_size - INST_LEN;
5126                                 } else {
5127                                         int code_size;
5128
5129                                         got_slot = get_got_offset (acfg, FALSE, patch_info);
5130
5131                                         arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5132                                         i += code_size - INST_LEN;
5133                                 }
5134                                 skip = TRUE;
5135                         }
5136                         }
5137                 }
5138 #endif /* MONO_ARCH_AOT_SUPPORTED */
5139
5140                 if (!skip) {
5141                         /* Find next patch */
5142                         patch_info = NULL;
5143                         for (pindex = start_index; pindex < patches->len; ++pindex) {
5144                                 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5145                                 if (patch_info->ip.i >= i)
5146                                         break;
5147                         }
5148
5149                         /* Try to emit multiple bytes at once */
5150                         if (pindex < patches->len && patch_info->ip.i > i) {
5151                                 int limit;
5152
5153                                 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5154                                         if (locs && locs [limit])
5155                                                 break;
5156                                 }
5157
5158                                 emit_code_bytes (acfg, code + i, limit - i);
5159                                 i = limit - INST_LEN;
5160                         } else {
5161                                 emit_code_bytes (acfg, code + i, INST_LEN);
5162                         }
5163                 }
5164         }
5165
5166         g_free (locs);
5167 }
5168
5169 /*
5170  * sanitize_symbol:
5171  *
5172  *   Return a modified version of S which only includes characters permissible in symbols.
5173  */
5174 static char*
5175 sanitize_symbol (MonoAotCompile *acfg, char *s)
5176 {
5177         gboolean process = FALSE;
5178         int i, len;
5179         GString *gs;
5180         char *res;
5181
5182         if (!s)
5183                 return s;
5184
5185         len = strlen (s);
5186         for (i = 0; i < len; ++i)
5187                 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5188                         process = TRUE;
5189         if (!process)
5190                 return s;
5191
5192         gs = g_string_sized_new (len);
5193         for (i = 0; i < len; ++i) {
5194                 guint8 c = s [i];
5195                 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5196                         g_string_append_c (gs, c);
5197                 } else if (c > 0x7f) {
5198                         /* multi-byte utf8 */
5199                         g_string_append_printf (gs, "_0x%x", c);
5200                         i ++;
5201                         c = s [i];
5202                         while (c >> 6 == 0x2) {
5203                                 g_string_append_printf (gs, "%x", c);
5204                                 i ++;
5205                                 c = s [i];
5206                         }
5207                         g_string_append_printf (gs, "_");
5208                         i --;
5209                 } else {
5210                         g_string_append_c (gs, '_');
5211                 }
5212         }
5213
5214         res = mono_mempool_strdup (acfg->mempool, gs->str);
5215         g_string_free (gs, TRUE);
5216         return res;
5217 }
5218
5219 static char*
5220 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5221 {
5222         char *name1, *name2, *cached;
5223         int i, j, len, count;
5224         MonoMethod *cached_method;
5225
5226         name1 = mono_method_full_name (method, TRUE);
5227
5228 #ifdef TARGET_MACH
5229         // This is so that we don't accidentally create a local symbol (which starts with 'L')
5230         if ((!prefix || !*prefix) && name1 [0] == 'L')
5231                 prefix = "_";
5232 #endif
5233
5234         len = strlen (name1);
5235         name2 = (char *)malloc (strlen (prefix) + len + 16);
5236         memcpy (name2, prefix, strlen (prefix));
5237         j = strlen (prefix);
5238         for (i = 0; i < len; ++i) {
5239                 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5240                         name2 [j ++] = '_';
5241                 } else if (isalnum (name1 [i])) {
5242                         name2 [j ++] = name1 [i];
5243                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5244                         i += 2;
5245                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5246                         name2 [j ++] = '_';
5247                         i++;
5248                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5249                 } else
5250                         name2 [j ++] = '_';
5251         }
5252         name2 [j] = '\0';
5253
5254         g_free (name1);
5255
5256         count = 0;
5257         while (TRUE) {
5258                 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5259                 if (!(cached_method && cached_method != method))
5260                         break;
5261                 sprintf (name2 + j, "_%d", count);
5262                 count ++;
5263         }
5264
5265         cached = g_strdup (name2);
5266         g_hash_table_insert (cache, cached, method);
5267
5268         return name2;
5269 }
5270
5271 static void
5272 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5273 {
5274         MonoMethod *method;
5275         int method_index;
5276         guint8 *code;
5277         char *debug_sym = NULL;
5278         char *symbol = NULL;
5279         int func_alignment = AOT_FUNC_ALIGNMENT;
5280         char *export_name;
5281
5282         method = cfg->orig_method;
5283         code = cfg->native_code;
5284
5285         method_index = get_method_index (acfg, method);
5286         symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5287
5288         /* Make the labels local */
5289         emit_section_change (acfg, ".text", 0);
5290         emit_alignment_code (acfg, func_alignment);
5291         
5292         if (acfg->global_symbols && acfg->need_no_dead_strip)
5293                 fprintf (acfg->fp, "    .no_dead_strip %s\n", cfg->asm_symbol);
5294         
5295         emit_label (acfg, cfg->asm_symbol);
5296
5297         if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5298                 /* 
5299                  * Write a C style symbol for every method, this has two uses:
5300                  * - it works on platforms where the dwarf debugging info is not
5301                  *   yet supported.
5302                  * - it allows the setting of breakpoints of aot-ed methods.
5303                  */
5304                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5305                 cfg->asm_debug_symbol = g_strdup (debug_sym);
5306
5307                 if (acfg->need_no_dead_strip)
5308                         fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
5309                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5310                 emit_label (acfg, debug_sym);
5311         }
5312
5313         export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5314         if (export_name) {
5315                 /* Emit a global symbol for the method */
5316                 emit_global_inner (acfg, export_name, TRUE);
5317                 emit_label (acfg, export_name);
5318         }
5319
5320         if (cfg->verbose_level > 0)
5321                 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5322
5323         acfg->stats.code_size += cfg->code_len;
5324
5325         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5326
5327         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 ()));
5328
5329         emit_line (acfg);
5330
5331         if (acfg->aot_opts.write_symbols) {
5332                 if (debug_sym)
5333                         emit_symbol_size (acfg, debug_sym, ".");
5334                 else
5335                         emit_symbol_size (acfg, cfg->asm_symbol, ".");
5336                 g_free (debug_sym);
5337         }
5338
5339         emit_label (acfg, symbol);
5340         g_free (symbol);
5341 }
5342
5343 /**
5344  * encode_patch:
5345  *
5346  *  Encode PATCH_INFO into its disk representation.
5347  */
5348 static void
5349 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5350 {
5351         guint8 *p = buf;
5352
5353         switch (patch_info->type) {
5354         case MONO_PATCH_INFO_NONE:
5355                 break;
5356         case MONO_PATCH_INFO_IMAGE:
5357                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5358                 break;
5359         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5360         case MONO_PATCH_INFO_JIT_TLS_ID:
5361         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5362         case MONO_PATCH_INFO_GC_NURSERY_START:
5363         case MONO_PATCH_INFO_GC_NURSERY_BITS:
5364                 break;
5365         case MONO_PATCH_INFO_CASTCLASS_CACHE:
5366                 encode_value (patch_info->data.index, p, &p);
5367                 break;
5368         case MONO_PATCH_INFO_METHOD_REL:
5369                 encode_value ((gint)patch_info->data.offset, p, &p);
5370                 break;
5371         case MONO_PATCH_INFO_SWITCH: {
5372                 gpointer *table = (gpointer *)patch_info->data.table->table;
5373                 int k;
5374
5375                 encode_value (patch_info->data.table->table_size, p, &p);
5376                 for (k = 0; k < patch_info->data.table->table_size; k++)
5377                         encode_value ((int)(gssize)table [k], p, &p);
5378                 break;
5379         }
5380         case MONO_PATCH_INFO_METHODCONST:
5381         case MONO_PATCH_INFO_METHOD:
5382         case MONO_PATCH_INFO_METHOD_JUMP:
5383         case MONO_PATCH_INFO_ICALL_ADDR:
5384         case MONO_PATCH_INFO_METHOD_RGCTX:
5385         case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5386                 encode_method_ref (acfg, patch_info->data.method, p, &p);
5387                 break;
5388         case MONO_PATCH_INFO_AOT_JIT_INFO:
5389                 encode_value (patch_info->data.index, p, &p);
5390                 break;
5391         case MONO_PATCH_INFO_INTERNAL_METHOD:
5392         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5393                 guint32 len = strlen (patch_info->data.name);
5394
5395                 encode_value (len, p, &p);
5396
5397                 memcpy (p, patch_info->data.name, len);
5398                 p += len;
5399                 *p++ = '\0';
5400                 break;
5401         }
5402         case MONO_PATCH_INFO_LDSTR: {
5403                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5404                 guint32 token = patch_info->data.token->token;
5405                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5406                 encode_value (image_index, p, &p);
5407                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5408                 break;
5409         }
5410         case MONO_PATCH_INFO_RVA:
5411         case MONO_PATCH_INFO_DECLSEC:
5412         case MONO_PATCH_INFO_LDTOKEN:
5413         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5414                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5415                 encode_value (patch_info->data.token->token, p, &p);
5416                 encode_value (patch_info->data.token->has_context, p, &p);
5417                 if (patch_info->data.token->has_context)
5418                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5419                 break;
5420         case MONO_PATCH_INFO_EXC_NAME: {
5421                 MonoClass *ex_class;
5422
5423                 ex_class =
5424                         mono_class_load_from_name (mono_defaults.exception_class->image,
5425                                                                   "System", (const char *)patch_info->data.target);
5426                 encode_klass_ref (acfg, ex_class, p, &p);
5427                 break;
5428         }
5429         case MONO_PATCH_INFO_R4:
5430                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5431                 break;
5432         case MONO_PATCH_INFO_R8:
5433                 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5434                 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5435                 break;
5436         case MONO_PATCH_INFO_VTABLE:
5437         case MONO_PATCH_INFO_CLASS:
5438         case MONO_PATCH_INFO_IID:
5439         case MONO_PATCH_INFO_ADJUSTED_IID:
5440                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5441                 break;
5442         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5443                 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5444                 if (patch_info->data.del_tramp->method) {
5445                         encode_value (1, p, &p);
5446                         encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5447                 } else {
5448                         encode_value (0, p, &p);
5449                 }
5450                 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5451                 break;
5452         case MONO_PATCH_INFO_FIELD:
5453         case MONO_PATCH_INFO_SFLDA:
5454                 encode_field_info (acfg, patch_info->data.field, p, &p);
5455                 break;
5456         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5457                 break;
5458         case MONO_PATCH_INFO_RGCTX_FETCH:
5459         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5460                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5461                 guint32 offset;
5462                 guint8 *buf2, *p2;
5463
5464                 /* 
5465                  * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5466                  * reference the same method, so encode the method only once.
5467                  */
5468                 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5469                 if (!offset) {
5470                         buf2 = (guint8 *)g_malloc (1024);
5471                         p2 = buf2;
5472
5473                         encode_method_ref (acfg, entry->method, p2, &p2);
5474                         g_assert (p2 - buf2 < 1024);
5475
5476                         offset = add_to_blob (acfg, buf2, p2 - buf2);
5477                         g_free (buf2);
5478
5479                         g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5480                 } else {
5481                         offset --;
5482                 }
5483
5484                 encode_value (offset, p, &p);
5485                 g_assert ((int)entry->info_type < 256);
5486                 g_assert (entry->data->type < 256);
5487                 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5488                 encode_patch (acfg, entry->data, p, &p);
5489                 break;
5490         }
5491         case MONO_PATCH_INFO_SEQ_POINT_INFO:
5492         case MONO_PATCH_INFO_AOT_MODULE:
5493                 break;
5494         case MONO_PATCH_INFO_SIGNATURE:
5495         case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5496                 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5497                 break;
5498         case MONO_PATCH_INFO_TLS_OFFSET:
5499                 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5500                 break;
5501         case MONO_PATCH_INFO_GSHAREDVT_CALL:
5502                 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5503                 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5504                 break;
5505         case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5506                 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5507                 int i;
5508
5509                 encode_method_ref (acfg, info->method, p, &p);
5510                 encode_value (info->num_entries, p, &p);
5511                 for (i = 0; i < info->num_entries; ++i) {
5512                         MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5513
5514                         encode_value (template_->info_type, p, &p);
5515                         switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5516                         case MONO_PATCH_INFO_CLASS:
5517                                 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5518                                 break;
5519                         case MONO_PATCH_INFO_FIELD:
5520                                 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5521                                 break;
5522                         default:
5523                                 g_assert_not_reached ();
5524                                 break;
5525                         }
5526                 }
5527                 break;
5528         }
5529         case MONO_PATCH_INFO_LDSTR_LIT: {
5530                 const char *s = (const char *)patch_info->data.target;
5531                 int len = strlen (s);
5532
5533                 encode_value (len, p, &p);
5534                 memcpy (p, s, len + 1);
5535                 p += len + 1;
5536                 break;
5537         }
5538         case MONO_PATCH_INFO_VIRT_METHOD:
5539                 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5540                 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5541                 break;
5542         case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5543                 break;
5544         default:
5545                 g_warning ("unable to handle jump info %d", patch_info->type);
5546                 g_assert_not_reached ();
5547         }
5548
5549         *endbuf = p;
5550 }
5551
5552 static void
5553 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5554 {
5555         guint8 *p = buf;
5556         guint32 pindex, offset;
5557         MonoJumpInfo *patch_info;
5558
5559         encode_value (n_patches, p, &p);
5560
5561         for (pindex = 0; pindex < patches->len; ++pindex) {
5562                 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5563
5564                 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5565                         /* Nothing to do */
5566                         continue;
5567
5568                 offset = get_got_offset (acfg, llvm, patch_info);
5569                 encode_value (offset, p, &p);
5570         }
5571
5572         *endbuf = p;
5573 }
5574
5575 static void
5576 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5577 {
5578         MonoMethod *method;
5579         int pindex, buf_size, n_patches;
5580         GPtrArray *patches;
5581         MonoJumpInfo *patch_info;
5582         guint32 method_index;
5583         guint8 *p, *buf;
5584         guint32 first_got_offset;
5585
5586         method = cfg->orig_method;
5587
5588         method_index = get_method_index (acfg, method);
5589
5590         /* Sort relocations */
5591         patches = g_ptr_array_new ();
5592         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5593                 g_ptr_array_add (patches, patch_info);
5594         g_ptr_array_sort (patches, compare_patches);
5595
5596         first_got_offset = acfg->cfgs [method_index]->got_offset;
5597
5598         /**********************/
5599         /* Encode method info */
5600         /**********************/
5601
5602         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5603         p = buf = (guint8 *)g_malloc (buf_size);
5604
5605         if (mono_class_get_cctor (method->klass)) {
5606                 encode_value (1, p, &p);
5607                 encode_klass_ref (acfg, method->klass, p, &p);
5608         } else {
5609                 /* Not needed when loading the method */
5610                 encode_value (0, p, &p);
5611         }
5612
5613         g_assert (!(cfg->opt & MONO_OPT_SHARED));
5614
5615         n_patches = 0;
5616         for (pindex = 0; pindex < patches->len; ++pindex) {
5617                 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5618                 
5619                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5620                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
5621                         patch_info->type = MONO_PATCH_INFO_NONE;
5622                         /* Nothing to do */
5623                         continue;
5624                 }
5625
5626                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5627                         /* Stored in a GOT slot initialized at module load time */
5628                         patch_info->type = MONO_PATCH_INFO_NONE;
5629                         continue;
5630                 }
5631
5632                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5633                         patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5634                         patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5635                         patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5636                         /* Stored in a GOT slot initialized at module load time */
5637                         patch_info->type = MONO_PATCH_INFO_NONE;
5638                         continue;
5639                 }
5640
5641                 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5642                         /* Calls are made through the PLT */
5643                         patch_info->type = MONO_PATCH_INFO_NONE;
5644                         continue;
5645                 }
5646
5647                 n_patches ++;
5648         }
5649
5650         if (n_patches)
5651                 g_assert (cfg->has_got_slots);
5652
5653         encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5654
5655         acfg->stats.info_size += p - buf;
5656
5657         g_assert (p - buf < buf_size);
5658
5659         cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5660         g_free (buf);
5661 }
5662
5663 static guint32
5664 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5665 {
5666         guint32 cache_index;
5667         guint32 offset;
5668
5669         /* Reuse the unwind module to canonize and store unwind info entries */
5670         cache_index = mono_cache_unwind_info (encoded, encoded_len);
5671
5672         /* Use +/- 1 to distinguish 0s from missing entries */
5673         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5674         if (offset)
5675                 return offset - 1;
5676         else {
5677                 guint8 buf [16];
5678                 guint8 *p;
5679
5680                 /* 
5681                  * It would be easier to use assembler symbols, but the caller needs an
5682                  * offset now.
5683                  */
5684                 offset = acfg->unwind_info_offset;
5685                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5686                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5687
5688                 p = buf;
5689                 encode_value (encoded_len, p, &p);
5690
5691                 acfg->unwind_info_offset += encoded_len + (p - buf);
5692                 return offset;
5693         }
5694 }
5695
5696 static void
5697 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5698 {
5699         int i, k, buf_size;
5700         guint32 debug_info_size, seq_points_size;
5701         guint8 *code;
5702         MonoMethodHeader *header;
5703         guint8 *p, *buf, *debug_info;
5704         MonoJitInfo *jinfo = cfg->jit_info;
5705         guint32 flags;
5706         gboolean use_unwind_ops = FALSE;
5707         MonoSeqPointInfo *seq_points;
5708
5709         code = cfg->native_code;
5710         header = cfg->header;
5711
5712         if (!acfg->aot_opts.nodebug) {
5713                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5714         } else {
5715                 debug_info = NULL;
5716                 debug_info_size = 0;
5717         }
5718
5719         seq_points = cfg->seq_point_info;
5720         seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5721
5722         buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5723
5724         p = buf = (guint8 *)g_malloc (buf_size);
5725
5726         use_unwind_ops = cfg->unwind_ops != NULL;
5727
5728         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);
5729
5730         encode_value (flags, p, &p);
5731
5732         if (use_unwind_ops) {
5733                 guint32 encoded_len;
5734                 guint8 *encoded;
5735                 guint32 unwind_desc;
5736
5737                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5738
5739                 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5740                 encode_value (unwind_desc, p, &p);
5741         } else {
5742                 encode_value (jinfo->unwind_info, p, &p);
5743         }
5744
5745         /*Encode the number of holes before the number of clauses to make decoding easier*/
5746         if (jinfo->has_try_block_holes) {
5747                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5748                 encode_value (table->num_holes, p, &p);
5749         }
5750
5751         if (jinfo->has_arch_eh_info) {
5752                 /*
5753                  * In AOT mode, the code length is calculated from the address of the previous method,
5754                  * which could include alignment padding, so calculating the start of the epilog as
5755                  * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5756                  */
5757                 encode_value (jinfo->code_size, p, &p);
5758         }
5759
5760         /* Exception table */
5761         if (cfg->compile_llvm) {
5762                 /*
5763                  * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5764                  * since the information is only available to llc. Instead, we let llc save the data
5765                  * into the LSDA, and read it from there at runtime.
5766                  */
5767                 /* The assembly might be CIL stripped so emit the data ourselves */
5768                 if (header->num_clauses)
5769                         encode_value (header->num_clauses, p, &p);
5770
5771                 for (k = 0; k < header->num_clauses; ++k) {
5772                         MonoExceptionClause *clause;
5773
5774                         clause = &header->clauses [k];
5775
5776                         encode_value (clause->flags, p, &p);
5777                         if (clause->data.catch_class) {
5778                                 encode_value (1, p, &p);
5779                                 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5780                         } else {
5781                                 encode_value (0, p, &p);
5782                         }
5783
5784                         /* Emit the IL ranges too, since they might not be available at runtime */
5785                         encode_value (clause->try_offset, p, &p);
5786                         encode_value (clause->try_len, p, &p);
5787                         encode_value (clause->handler_offset, p, &p);
5788                         encode_value (clause->handler_len, p, &p);
5789
5790                         /* Emit a list of nesting clauses */
5791                         for (i = 0; i < header->num_clauses; ++i) {
5792                                 gint32 cindex1 = k;
5793                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5794                                 gint32 cindex2 = i;
5795                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5796
5797                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5798                                         encode_value (i, p, &p);
5799                         }
5800                         encode_value (-1, p, &p);
5801                 }
5802         } else {
5803                 if (jinfo->num_clauses)
5804                         encode_value (jinfo->num_clauses, p, &p);
5805
5806                 for (k = 0; k < jinfo->num_clauses; ++k) {
5807                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5808
5809                         encode_value (ei->flags, p, &p);
5810 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5811                         /* Not used for catch clauses */
5812                         if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5813                                 encode_value (ei->exvar_offset, p, &p);
5814 #else
5815                         encode_value (ei->exvar_offset, p, &p);
5816 #endif
5817
5818                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5819                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5820                         else {
5821                                 if (ei->data.catch_class) {
5822                                         guint8 *buf2, *p2;
5823                                         int len;
5824
5825                                         buf2 = (guint8 *)g_malloc (4096);
5826                                         p2 = buf2;
5827                                         encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5828                                         len = p2 - buf2;
5829                                         g_assert (len < 4096);
5830                                         encode_value (len, p, &p);
5831                                         memcpy (p, buf2, len);
5832                                         p += p2 - buf2;
5833                                         g_free (buf2);
5834                                 } else {
5835                                         encode_value (0, p, &p);
5836                                 }
5837                         }
5838
5839                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5840                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5841                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5842                 }
5843         }
5844
5845         if (jinfo->has_try_block_holes) {
5846                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5847                 for (i = 0; i < table->num_holes; ++i) {
5848                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5849                         encode_value (hole->clause, p, &p);
5850                         encode_value (hole->length, p, &p);
5851                         encode_value (hole->offset, p, &p);
5852                 }
5853         }
5854
5855         if (jinfo->has_arch_eh_info) {
5856                 MonoArchEHJitInfo *eh_info;
5857
5858                 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5859                 encode_value (eh_info->stack_size, p, &p);
5860                 encode_value (eh_info->epilog_size, p, &p);
5861         }
5862
5863         if (jinfo->has_generic_jit_info) {
5864                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5865                 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5866                 guint8 *buf2, *p2;
5867                 int len;
5868
5869                 encode_value (gi->nlocs, p, &p);
5870                 if (gi->nlocs) {
5871                         for (i = 0; i < gi->nlocs; ++i) {
5872                                 MonoDwarfLocListEntry *entry = &gi->locations [i];
5873
5874                                 encode_value (entry->is_reg ? 1 : 0, p, &p);
5875                                 encode_value (entry->reg, p, &p);
5876                                 if (!entry->is_reg)
5877                                         encode_value (entry->offset, p, &p);
5878                                 if (i == 0)
5879                                         g_assert (entry->from == 0);
5880                                 else
5881                                         encode_value (entry->from, p, &p);
5882                                 encode_value (entry->to, p, &p);
5883                         }
5884                 } else {
5885                         if (!cfg->compile_llvm) {
5886                                 encode_value (gi->has_this ? 1 : 0, p, &p);
5887                                 encode_value (gi->this_reg, p, &p);
5888                                 encode_value (gi->this_offset, p, &p);
5889                         }
5890                 }
5891
5892                 /* 
5893                  * Need to encode jinfo->method too, since it is not equal to 'method'
5894                  * when using generic sharing.
5895                  */
5896                 buf2 = (guint8 *)g_malloc (4096);
5897                 p2 = buf2;
5898                 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5899                 len = p2 - buf2;
5900                 g_assert (len < 4096);
5901                 encode_value (len, p, &p);
5902                 memcpy (p, buf2, len);
5903                 p += p2 - buf2;
5904                 g_free (buf2);
5905
5906                 if (gsctx && gsctx->is_gsharedvt) {
5907                         encode_value (1, p, &p);
5908                 } else {
5909                         encode_value (0, p, &p);
5910                 }
5911         }
5912
5913         if (seq_points_size)
5914                 p += mono_seq_point_info_write (seq_points, p);
5915
5916         g_assert (debug_info_size < buf_size);
5917
5918         encode_value (debug_info_size, p, &p);
5919         if (debug_info_size) {
5920                 memcpy (p, debug_info, debug_info_size);
5921                 p += debug_info_size;
5922                 g_free (debug_info);
5923         }
5924
5925         /* GC Map */
5926         if (cfg->gc_map) {
5927                 encode_value (cfg->gc_map_size, p, &p);
5928                 /* The GC map requires 4 bytes of alignment */
5929                 while ((gsize)p % 4)
5930                         p ++;
5931                 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5932                 p += cfg->gc_map_size;
5933         }
5934
5935         acfg->stats.ex_info_size += p - buf;
5936
5937         g_assert (p - buf < buf_size);
5938
5939         /* Emit info */
5940         /* The GC Map requires 4 byte alignment */
5941         cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5942         g_free (buf);
5943 }
5944
5945 static guint32
5946 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5947 {
5948         MonoError error;
5949         MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5950         guint8 *p, *buf;
5951         int i, buf_size, res;
5952         gboolean no_special_static, cant_encode;
5953         gpointer iter = NULL;
5954
5955         if (!klass) {
5956                 mono_error_cleanup (&error);
5957
5958                 buf_size = 16;
5959
5960                 p = buf = (guint8 *)g_malloc (buf_size);
5961
5962                 /* Mark as unusable */
5963                 encode_value (-1, p, &p);
5964
5965                 res = add_to_blob (acfg, buf, p - buf);
5966                 g_free (buf);
5967
5968                 return res;
5969         }
5970                 
5971         buf_size = 10240 + (klass->vtable_size * 16);
5972         p = buf = (guint8 *)g_malloc (buf_size);
5973
5974         g_assert (klass);
5975
5976         mono_class_init (klass);
5977
5978         mono_class_get_nested_types (klass, &iter);
5979         g_assert (klass->nested_classes_inited);
5980
5981         mono_class_setup_vtable (klass);
5982
5983         /* 
5984          * Emit all the information which is required for creating vtables so
5985          * the runtime does not need to create the MonoMethod structures which
5986          * take up a lot of space.
5987          */
5988
5989         no_special_static = !mono_class_has_special_static_fields (klass);
5990
5991         /* Check whenever we have enough info to encode the vtable */
5992         cant_encode = FALSE;
5993         for (i = 0; i < klass->vtable_size; ++i) {
5994                 MonoMethod *cm = klass->vtable [i];
5995
5996                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5997                         cant_encode = TRUE;
5998         }
5999
6000         mono_class_has_finalizer (klass);
6001
6002         if (klass->generic_container || cant_encode) {
6003                 encode_value (-1, p, &p);
6004         } else {
6005                 encode_value (klass->vtable_size, p, &p);
6006                 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);
6007                 if (klass->has_cctor)
6008                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6009                 if (klass->has_finalize)
6010                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6011  
6012                 encode_value (klass->instance_size, p, &p);
6013                 encode_value (mono_class_data_size (klass), p, &p);
6014                 encode_value (klass->packing_size, p, &p);
6015                 encode_value (klass->min_align, p, &p);
6016
6017                 for (i = 0; i < klass->vtable_size; ++i) {
6018                         MonoMethod *cm = klass->vtable [i];
6019
6020                         if (cm)
6021                                 encode_method_ref (acfg, cm, p, &p);
6022                         else
6023                                 encode_value (0, p, &p);
6024                 }
6025         }
6026
6027         acfg->stats.class_info_size += p - buf;
6028
6029         g_assert (p - buf < buf_size);
6030         res = add_to_blob (acfg, buf, p - buf);
6031         g_free (buf);
6032
6033         return res;
6034 }
6035
6036 static char*
6037 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6038 {
6039         char *debug_sym = NULL;
6040         char *prefix;
6041
6042         if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6043                 /* Need to add a prefix to create unique symbols */
6044                 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6045         } else {
6046                 prefix = g_strdup ("plt_");
6047         }
6048
6049         switch (ji->type) {
6050         case MONO_PATCH_INFO_METHOD:
6051                 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6052                 break;
6053         case MONO_PATCH_INFO_INTERNAL_METHOD:
6054                 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6055                 break;
6056         case MONO_PATCH_INFO_RGCTX_FETCH:
6057                 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6058                 break;
6059         case MONO_PATCH_INFO_ICALL_ADDR: {
6060                 char *s = get_debug_sym (ji->data.method, "", cache);
6061                 
6062                 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6063                 g_free (s);
6064                 break;
6065         }
6066         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6067                 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6068                 break;
6069         default:
6070                 break;
6071         }
6072
6073         g_free (prefix);
6074
6075         return sanitize_symbol (acfg, debug_sym);
6076 }
6077
6078 /*
6079  * Calls made from AOTed code are routed through a table of jumps similar to the
6080  * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6081  * control to the AOT runtime through a trampoline.
6082  */
6083 static void
6084 emit_plt (MonoAotCompile *acfg)
6085 {
6086         int i;
6087
6088         if (acfg->aot_opts.llvm_only) {
6089                 g_assert (acfg->plt_offset == 1);
6090                 return;
6091         }
6092
6093         emit_line (acfg);
6094
6095         emit_section_change (acfg, ".text", 0);
6096         emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
6097         emit_info_symbol (acfg, "plt");
6098         emit_label (acfg, acfg->plt_symbol);
6099
6100         for (i = 0; i < acfg->plt_offset; ++i) {
6101                 char *debug_sym = NULL;
6102                 MonoPltEntry *plt_entry = NULL;
6103
6104                 if (i == 0)
6105                         /* 
6106                          * The first plt entry is unused.
6107                          */
6108                         continue;
6109
6110                 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6111
6112                 debug_sym = plt_entry->debug_sym;
6113
6114                 if (acfg->thumb_mixed && !plt_entry->jit_used)
6115                         /* Emit only a thumb version */
6116                         continue;
6117
6118                 /* Skip plt entries not actually called */
6119                 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6120                         continue;
6121
6122                 if (acfg->llvm && !acfg->thumb_mixed) {
6123                         emit_label (acfg, plt_entry->llvm_symbol);
6124                         if (acfg->llvm) {
6125                                 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6126 #if defined(TARGET_MACH)
6127                                 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6128 #endif
6129                         }
6130                 }
6131
6132                 if (debug_sym) {
6133                         if (acfg->need_no_dead_strip) {
6134                                 emit_unset_mode (acfg);
6135                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
6136                         }
6137                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6138                         emit_label (acfg, debug_sym);
6139                 }
6140
6141                 emit_label (acfg, plt_entry->symbol);
6142
6143                 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6144
6145                 if (debug_sym)
6146                         emit_symbol_size (acfg, debug_sym, ".");
6147         }
6148
6149         if (acfg->thumb_mixed) {
6150                 /* Make sure the ARM symbols don't alias the thumb ones */
6151                 emit_zero_bytes (acfg, 16);
6152
6153                 /* 
6154                  * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6155                  * code.
6156                  */
6157                 for (i = 0; i < acfg->plt_offset; ++i) {
6158                         char *debug_sym = NULL;
6159                         MonoPltEntry *plt_entry = NULL;
6160
6161                         if (i == 0)
6162                                 continue;
6163
6164                         plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6165
6166                         /* Skip plt entries not actually called by LLVM code */
6167                         if (!plt_entry->llvm_used)
6168                                 continue;
6169
6170                         if (acfg->aot_opts.write_symbols) {
6171                                 if (plt_entry->debug_sym)
6172                                         debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6173                         }
6174
6175                         if (debug_sym) {
6176 #if defined(TARGET_MACH)
6177                                 fprintf (acfg->fp, "    .thumb_func %s\n", debug_sym);
6178                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
6179 #endif
6180                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6181                                 emit_label (acfg, debug_sym);
6182                         }
6183                         fprintf (acfg->fp, "\n.thumb_func\n");
6184
6185                         emit_label (acfg, plt_entry->llvm_symbol);
6186
6187                         if (acfg->llvm)
6188                                 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6189
6190                         arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6191
6192                         if (debug_sym) {
6193                                 emit_symbol_size (acfg, debug_sym, ".");
6194                                 g_free (debug_sym);
6195                         }
6196                 }
6197         }
6198
6199         emit_symbol_size (acfg, acfg->plt_symbol, ".");
6200
6201         emit_info_symbol (acfg, "plt_end");
6202 }
6203
6204 /*
6205  * emit_trampoline_full:
6206  *
6207  *   If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6208  * create_jit_info_for_trampoline ().
6209  */
6210 static G_GNUC_UNUSED void
6211 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6212 {
6213         char start_symbol [256];
6214         char end_symbol [256];
6215         char symbol [256];
6216         guint32 buf_size, info_offset;
6217         MonoJumpInfo *patch_info;
6218         guint8 *buf, *p;
6219         GPtrArray *patches;
6220         char *name;
6221         guint8 *code;
6222         guint32 code_size;
6223         MonoJumpInfo *ji;
6224         GSList *unwind_ops;
6225
6226         g_assert (info);
6227
6228         name = info->name;
6229         code = info->code;
6230         code_size = info->code_size;
6231         ji = info->ji;
6232         unwind_ops = info->unwind_ops;
6233
6234 #ifdef __native_client_codegen__
6235         mono_nacl_fix_patches (code, ji);
6236 #endif
6237
6238         /* Emit code */
6239
6240         sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6241
6242         emit_section_change (acfg, ".text", 0);
6243         emit_global (acfg, start_symbol, TRUE);
6244         emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6245         emit_label (acfg, start_symbol);
6246
6247         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6248         emit_label (acfg, symbol);
6249
6250         /* 
6251          * The code should access everything through the GOT, so we pass
6252          * TRUE here.
6253          */
6254         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6255
6256         emit_symbol_size (acfg, start_symbol, ".");
6257
6258         if (emit_tinfo) {
6259                 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6260                 emit_label (acfg, end_symbol);
6261         }
6262
6263         /* Emit info */
6264
6265         /* Sort relocations */
6266         patches = g_ptr_array_new ();
6267         for (patch_info = ji; patch_info; patch_info = patch_info->next)
6268                 if (patch_info->type != MONO_PATCH_INFO_NONE)
6269                         g_ptr_array_add (patches, patch_info);
6270         g_ptr_array_sort (patches, compare_patches);
6271
6272         buf_size = patches->len * 128 + 128;
6273         buf = (guint8 *)g_malloc (buf_size);
6274         p = buf;
6275
6276         encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6277         g_assert (p - buf < buf_size);
6278
6279         sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6280
6281         info_offset = add_to_blob (acfg, buf, p - buf);
6282
6283         emit_section_change (acfg, RODATA_SECT, 0);
6284         emit_global (acfg, symbol, FALSE);
6285         emit_label (acfg, symbol);
6286
6287         emit_int32 (acfg, info_offset);
6288
6289         if (emit_tinfo) {
6290                 guint8 *encoded;
6291                 guint32 encoded_len;
6292                 guint32 uw_offset;
6293
6294                 /*
6295                  * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6296                  */
6297                 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6298                 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6299                 g_free (encoded);
6300
6301                 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6302                 emit_int32 (acfg, uw_offset);
6303         }
6304
6305         /* Emit debug info */
6306         if (unwind_ops) {
6307                 char symbol2 [256];
6308
6309                 sprintf (symbol, "%s", name);
6310                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6311
6312                 if (acfg->dwarf)
6313                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6314         }
6315 }
6316
6317 static G_GNUC_UNUSED void
6318 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6319 {
6320         emit_trampoline_full (acfg, got_offset, info, TRUE);
6321 }
6322
6323 static void
6324 emit_trampolines (MonoAotCompile *acfg)
6325 {
6326         char symbol [256];
6327         char end_symbol [256];
6328         int i, tramp_got_offset;
6329         int ntype;
6330 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6331         int tramp_type;
6332 #endif
6333
6334         if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6335                 return;
6336         
6337         g_assert (acfg->image->assembly);
6338
6339         /* Currently, we emit most trampolines into the mscorlib AOT image. */
6340         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6341 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6342                 MonoTrampInfo *info;
6343
6344                 /*
6345                  * Emit the generic trampolines.
6346                  *
6347                  * We could save some code by treating the generic trampolines as a wrapper
6348                  * method, but that approach has its own complexities, so we choose the simpler
6349                  * method.
6350                  */
6351                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6352                         /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6353 #ifdef DISABLE_REMOTING
6354                         if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6355                                 continue;
6356 #endif
6357 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6358                         if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6359                                 continue;
6360 #endif
6361                         mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6362                         emit_trampoline (acfg, acfg->got_offset, info);
6363                 }
6364
6365                 /* Emit the exception related code pieces */
6366                 mono_arch_get_restore_context (&info, TRUE);
6367                 emit_trampoline (acfg, acfg->got_offset, info);
6368                 mono_arch_get_call_filter (&info, TRUE);
6369                 emit_trampoline (acfg, acfg->got_offset, info);
6370                 mono_arch_get_throw_exception (&info, TRUE);
6371                 emit_trampoline (acfg, acfg->got_offset, info);
6372                 mono_arch_get_rethrow_exception (&info, TRUE);
6373                 emit_trampoline (acfg, acfg->got_offset, info);
6374                 mono_arch_get_throw_corlib_exception (&info, TRUE);
6375                 emit_trampoline (acfg, acfg->got_offset, info);
6376
6377 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6378                 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6379                 emit_trampoline (acfg, acfg->got_offset, info);
6380                 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6381                 emit_trampoline (acfg, acfg->got_offset, info);
6382 #endif
6383
6384 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6385                 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6386                 if (info) {
6387                         emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6388
6389                         /* Create a separate out trampoline for more information in stack traces */
6390                         info->name = g_strdup ("gsharedvt_out_trampoline");
6391                         emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6392                 }
6393 #endif
6394
6395 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6396                 {
6397                         GSList *l = mono_arch_get_trampolines (TRUE);
6398
6399                         while (l) {
6400                                 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6401
6402                                 emit_trampoline (acfg, acfg->got_offset, info);
6403                                 l = l->next;
6404                         }
6405                 }
6406 #endif
6407
6408                 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6409                         int offset;
6410
6411                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6412                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6413                         emit_trampoline (acfg, acfg->got_offset, info);
6414
6415                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6416                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6417                         emit_trampoline (acfg, acfg->got_offset, info);
6418                 }
6419
6420 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6421                 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6422                 emit_trampoline (acfg, acfg->got_offset, info);
6423 #endif
6424
6425                 {
6426                         GSList *l;
6427
6428                         /* delegate_invoke_impl trampolines */
6429                         l = mono_arch_get_delegate_invoke_impls ();
6430                         while (l) {
6431                                 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6432
6433                                 emit_trampoline (acfg, acfg->got_offset, info);
6434                                 l = l->next;
6435                         }
6436                 }
6437
6438 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6439
6440                 /* Emit trampolines which are numerous */
6441
6442                 /*
6443                  * These include the following:
6444                  * - specific trampolines
6445                  * - static rgctx invoke trampolines
6446                  * - imt thunks
6447                  * These trampolines have the same code, they are parameterized by GOT 
6448                  * slots. 
6449                  * They are defined in this file, in the arch_... routines instead of
6450                  * in tramp-<ARCH>.c, since it is easier to do it this way.
6451                  */
6452
6453                 /*
6454                  * When running in aot-only mode, we can't create specific trampolines at 
6455                  * runtime, so we create a few, and save them in the AOT file. 
6456                  * Normal trampolines embed their argument as a literal inside the 
6457                  * trampoline code, we can't do that here, so instead we embed an offset
6458                  * which needs to be added to the trampoline address to get the address of
6459                  * the GOT slot which contains the argument value.
6460                  * The generated trampolines jump to the generic trampolines using another
6461                  * GOT slot, which will be setup by the AOT loader to point to the 
6462                  * generic trampoline code of the given type.
6463                  */
6464
6465                 /*
6466                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6467                  * each class).
6468                  */
6469
6470                 emit_section_change (acfg, ".text", 0);
6471
6472                 tramp_got_offset = acfg->got_offset;
6473
6474                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6475                         switch (ntype) {
6476                         case MONO_AOT_TRAMP_SPECIFIC:
6477                                 sprintf (symbol, "specific_trampolines");
6478                                 break;
6479                         case MONO_AOT_TRAMP_STATIC_RGCTX:
6480                                 sprintf (symbol, "static_rgctx_trampolines");
6481                                 break;
6482                         case MONO_AOT_TRAMP_IMT_THUNK:
6483                                 sprintf (symbol, "imt_thunks");
6484                                 break;
6485                         case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6486                                 sprintf (symbol, "gsharedvt_arg_trampolines");
6487                                 break;
6488                         default:
6489                                 g_assert_not_reached ();
6490                         }
6491
6492                         sprintf (end_symbol, "%s_e", symbol);
6493
6494                         if (acfg->aot_opts.write_symbols)
6495                                 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6496
6497                         emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6498                         emit_info_symbol (acfg, symbol);
6499
6500                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6501
6502                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6503                                 int tramp_size = 0;
6504
6505                                 switch (ntype) {
6506                                 case MONO_AOT_TRAMP_SPECIFIC:
6507                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6508                                         tramp_got_offset += 2;
6509                                 break;
6510                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
6511                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
6512                                         tramp_got_offset += 2;
6513                                         break;
6514                                 case MONO_AOT_TRAMP_IMT_THUNK:
6515                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6516                                         tramp_got_offset += 1;
6517                                         break;
6518                                 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6519                                         arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);                               
6520                                         tramp_got_offset += 2;
6521                                         break;
6522                                 default:
6523                                         g_assert_not_reached ();
6524                                 }
6525 #ifdef __native_client_codegen__
6526                                 /* align to avoid 32-byte boundary crossings */
6527                                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6528 #endif
6529
6530                                 if (!acfg->trampoline_size [ntype]) {
6531                                         g_assert (tramp_size);
6532                                         acfg->trampoline_size [ntype] = tramp_size;
6533                                 }
6534                         }
6535
6536                         emit_label (acfg, end_symbol);
6537                         emit_int32 (acfg, 0);
6538                 }
6539
6540                 arch_emit_specific_trampoline_pages (acfg);
6541
6542                 /* Reserve some entries at the end of the GOT for our use */
6543                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6544         }
6545
6546         acfg->got_offset += acfg->num_trampoline_got_entries;
6547 }
6548
6549 static gboolean
6550 str_begins_with (const char *str1, const char *str2)
6551 {
6552         int len = strlen (str2);
6553         return strncmp (str1, str2, len) == 0;
6554 }
6555
6556 void*
6557 mono_aot_readonly_field_override (MonoClassField *field)
6558 {
6559         ReadOnlyValue *rdv;
6560         for (rdv = readonly_values; rdv; rdv = rdv->next) {
6561                 char *p = rdv->name;
6562                 int len;
6563                 len = strlen (field->parent->name_space);
6564                 if (strncmp (p, field->parent->name_space, len))
6565                         continue;
6566                 p += len;
6567                 if (*p++ != '.')
6568                         continue;
6569                 len = strlen (field->parent->name);
6570                 if (strncmp (p, field->parent->name, len))
6571                         continue;
6572                 p += len;
6573                 if (*p++ != '.')
6574                         continue;
6575                 if (strcmp (p, field->name))
6576                         continue;
6577                 switch (rdv->type) {
6578                 case MONO_TYPE_I1:
6579                         return &rdv->value.i1;
6580                 case MONO_TYPE_I2:
6581                         return &rdv->value.i2;
6582                 case MONO_TYPE_I4:
6583                         return &rdv->value.i4;
6584                 default:
6585                         break;
6586                 }
6587         }
6588         return NULL;
6589 }
6590
6591 static void
6592 add_readonly_value (MonoAotOptions *opts, const char *val)
6593 {
6594         ReadOnlyValue *rdv;
6595         const char *fval;
6596         const char *tval;
6597         /* the format of val is:
6598          * namespace.typename.fieldname=type/value
6599          * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6600          */
6601         fval = strrchr (val, '/');
6602         if (!fval) {
6603                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6604                 exit (1);
6605         }
6606         tval = strrchr (val, '=');
6607         if (!tval) {
6608                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6609                 exit (1);
6610         }
6611         rdv = g_new0 (ReadOnlyValue, 1);
6612         rdv->name = (char *)g_malloc0 (tval - val + 1);
6613         memcpy (rdv->name, val, tval - val);
6614         tval++;
6615         fval++;
6616         if (strncmp (tval, "i1", 2) == 0) {
6617                 rdv->value.i1 = atoi (fval);
6618                 rdv->type = MONO_TYPE_I1;
6619         } else if (strncmp (tval, "i2", 2) == 0) {
6620                 rdv->value.i2 = atoi (fval);
6621                 rdv->type = MONO_TYPE_I2;
6622         } else if (strncmp (tval, "i4", 2) == 0) {
6623                 rdv->value.i4 = atoi (fval);
6624                 rdv->type = MONO_TYPE_I4;
6625         } else {
6626                 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6627                 exit (1);
6628         }
6629         rdv->next = readonly_values;
6630         readonly_values = rdv;
6631 }
6632
6633 static gchar *
6634 clean_path (gchar * path)
6635 {
6636         if (!path)
6637                 return NULL;
6638
6639         if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6640                 return path;
6641
6642         gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6643         g_free (path);
6644
6645         return clean;
6646 }
6647
6648 static gchar *
6649 wrap_path (gchar * path)
6650 {
6651         int len;
6652         if (!path)
6653                 return NULL;
6654
6655         // If the string contains no spaces, just return the original string.
6656         if (strstr (path, " ") == NULL)
6657                 return path;
6658
6659         // If the string is already wrapped in quotes, return it.
6660         len = strlen (path);
6661         if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6662                 return path;
6663
6664         // If the string contains spaces, then wrap it in quotes.
6665         gchar *clean = g_strdup_printf ("\"%s\"", path);
6666
6667         return clean;
6668 }
6669
6670 static GPtrArray *
6671 mono_aot_split_options (const char *aot_options)
6672 {
6673         enum MonoAotOptionState {
6674                 MONO_AOT_OPTION_STATE_DEFAULT,
6675                 MONO_AOT_OPTION_STATE_STRING,
6676                 MONO_AOT_OPTION_STATE_ESCAPE,
6677         };
6678
6679         GPtrArray *args = g_ptr_array_new ();
6680         enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6681         gchar const *opt_start = aot_options;
6682         gboolean end_of_string = FALSE;
6683         gchar cur;
6684
6685         g_return_val_if_fail (aot_options != NULL, NULL);
6686
6687         while ((cur = *aot_options) != '\0') {
6688                 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6689                         goto next;
6690
6691                 switch (cur) {
6692                 case '"':
6693                         // If we find a quote, then if we're in the default case then
6694                         // it means we've found the start of a string, if not then it
6695                         // means we've found the end of the string and should switch
6696                         // back to the default case.            
6697                         switch (state) {
6698                         case MONO_AOT_OPTION_STATE_DEFAULT:
6699                                 state = MONO_AOT_OPTION_STATE_STRING;
6700                                 break;
6701                         case MONO_AOT_OPTION_STATE_STRING:
6702                                 state = MONO_AOT_OPTION_STATE_DEFAULT;
6703                                 break;
6704                         case MONO_AOT_OPTION_STATE_ESCAPE:
6705                                 g_assert_not_reached ();
6706                                 break;
6707                         }
6708                         break;
6709                 case '\\':
6710                         // If we've found an escaping operator, then this means we
6711                         // should not process the next character if inside a string.            
6712                         if (state == MONO_AOT_OPTION_STATE_STRING) 
6713                                 state = MONO_AOT_OPTION_STATE_ESCAPE;
6714                         break;
6715                 case ',':
6716                         // If we're in the default state then this means we've found
6717                         // an option, store it for later processing.
6718                         if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6719                                 goto new_opt;
6720                         break;
6721                 }
6722
6723         next:
6724                 aot_options++;
6725                 // If the next character is end of string, then process the last option.
6726                 if (*(aot_options) == '\0') {
6727                         end_of_string = TRUE;
6728                         goto new_opt;
6729                 }
6730                 continue;
6731
6732         new_opt:
6733                 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6734                 opt_start = ++aot_options;
6735                 if (end_of_string)
6736                         break;
6737                 goto next;
6738         }
6739
6740         return args;
6741 }
6742
6743 static void
6744 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6745 {
6746         GPtrArray* args;
6747
6748         args = mono_aot_split_options (aot_options ? aot_options : "");
6749         for (int i = 0; i < args->len; ++i) {
6750                 const char *arg = (const char *)g_ptr_array_index (args, i);
6751
6752                 if (str_begins_with (arg, "outfile=")) {
6753                         opts->outfile = g_strdup (arg + strlen ("outfile="));
6754                 } else if (str_begins_with (arg, "llvm-outfile=")) {
6755                         opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6756                 } else if (str_begins_with (arg, "temp-path=")) {
6757                         opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6758                 } else if (str_begins_with (arg, "save-temps")) {
6759                         opts->save_temps = TRUE;
6760                 } else if (str_begins_with (arg, "keep-temps")) {
6761                         opts->save_temps = TRUE;
6762                 } else if (str_begins_with (arg, "write-symbols")) {
6763                         opts->write_symbols = TRUE;
6764                 } else if (str_begins_with (arg, "no-write-symbols")) {
6765                         opts->write_symbols = FALSE;
6766                 } else if (str_begins_with (arg, "metadata-only")) {
6767                         opts->metadata_only = TRUE;
6768                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6769                         opts->bind_to_runtime_version = TRUE;
6770                 } else if (str_begins_with (arg, "full")) {
6771                         opts->mode = MONO_AOT_MODE_FULL;
6772                 } else if (str_begins_with (arg, "hybrid")) {
6773                         opts->mode = MONO_AOT_MODE_HYBRID;                      
6774                 } else if (str_begins_with (arg, "threads=")) {
6775                         opts->nthreads = atoi (arg + strlen ("threads="));
6776                 } else if (str_begins_with (arg, "static")) {
6777                         opts->static_link = TRUE;
6778                         opts->no_dlsym = TRUE;
6779                 } else if (str_begins_with (arg, "asmonly")) {
6780                         opts->asm_only = TRUE;
6781                 } else if (str_begins_with (arg, "asmwriter")) {
6782                         opts->asm_writer = TRUE;
6783                 } else if (str_begins_with (arg, "nodebug")) {
6784                         opts->nodebug = TRUE;
6785                 } else if (str_begins_with (arg, "dwarfdebug")) {
6786                         opts->dwarf_debug = TRUE;
6787                 } else if (str_begins_with (arg, "nopagetrampolines")) {
6788                         opts->use_trampolines_page = FALSE;
6789                 } else if (str_begins_with (arg, "ntrampolines=")) {
6790                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6791                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6792                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6793                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6794                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6795                 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6796                         opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6797                 } else if (str_begins_with (arg, "tool-prefix=")) {
6798                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6799                 } else if (str_begins_with (arg, "ld-flags=")) {
6800                         opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));                 
6801                 } else if (str_begins_with (arg, "soft-debug")) {
6802                         opts->soft_debug = TRUE;
6803                 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
6804                         debug_options.gen_seq_points_compact_data = TRUE;
6805                         opts->gen_seq_points_file = TRUE;
6806                         opts->gen_seq_points_file_path = g_strdup (arg + strlen ("gen-seq-points-file="));;
6807                 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6808                         debug_options.gen_seq_points_compact_data = TRUE;
6809                         opts->gen_seq_points_file = TRUE;
6810                 } else if (str_begins_with (arg, "direct-pinvoke")) {
6811                         opts->direct_pinvoke = TRUE;
6812                 } else if (str_begins_with (arg, "direct-icalls")) {
6813                         opts->direct_icalls = TRUE;
6814                 } else if (str_begins_with (arg, "no-direct-calls")) {
6815                         opts->no_direct_calls = TRUE;
6816                 } else if (str_begins_with (arg, "print-skipped")) {
6817                         opts->print_skipped_methods = TRUE;
6818                 } else if (str_begins_with (arg, "stats")) {
6819                         opts->stats = TRUE;
6820                 } else if (str_begins_with (arg, "no-instances")) {
6821                         opts->no_instances = TRUE;
6822                 } else if (str_begins_with (arg, "log-generics")) {
6823                         opts->log_generics = TRUE;
6824                 } else if (str_begins_with (arg, "log-instances=")) {
6825                         opts->log_instances = TRUE;
6826                         opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6827                 } else if (str_begins_with (arg, "log-instances")) {
6828                         opts->log_instances = TRUE;
6829                 } else if (str_begins_with (arg, "internal-logfile=")) {
6830                         opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6831                 } else if (str_begins_with (arg, "mtriple=")) {
6832                         opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6833                 } else if (str_begins_with (arg, "llvm-path=")) {
6834                         opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6835                 } else if (!strcmp (arg, "llvm")) {
6836                         opts->llvm = TRUE;
6837                 } else if (str_begins_with (arg, "readonly-value=")) {
6838                         add_readonly_value (opts, arg + strlen ("readonly-value="));
6839                 } else if (str_begins_with (arg, "info")) {
6840                         printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6841                         exit (0);
6842                 } else if (str_begins_with (arg, "gc-maps")) {
6843                         mini_gc_enable_gc_maps_for_aot ();
6844                 } else if (str_begins_with (arg, "dump")) {
6845                         opts->dump_json = TRUE;
6846                 } else if (str_begins_with (arg, "llvmonly")) {
6847                         opts->mode = MONO_AOT_MODE_FULL;
6848                         opts->llvm = TRUE;
6849                         opts->llvm_only = TRUE;
6850                 } else if (str_begins_with (arg, "data-outfile=")) {
6851                         opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
6852                 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6853                         printf ("Supported options for --aot:\n");
6854                         printf ("    outfile=\n");
6855                         printf ("    llvm-outfile=\n");
6856                         printf ("    llvm-path=\n");
6857                         printf ("    temp-path=\n");
6858                         printf ("    save-temps\n");
6859                         printf ("    keep-temps\n");
6860                         printf ("    write-symbols\n");
6861                         printf ("    metadata-only\n");
6862                         printf ("    bind-to-runtime-version\n");
6863                         printf ("    full\n");
6864                         printf ("    threads=\n");
6865                         printf ("    static\n");
6866                         printf ("    asmonly\n");
6867                         printf ("    asmwriter\n");
6868                         printf ("    nodebug\n");
6869                         printf ("    dwarfdebug\n");
6870                         printf ("    ntrampolines=\n");
6871                         printf ("    nrgctx-trampolines=\n");
6872                         printf ("    nimt-trampolines=\n");
6873                         printf ("    ngsharedvt-trampolines=\n");
6874                         printf ("    tool-prefix=\n");
6875                         printf ("    readonly-value=\n");
6876                         printf ("    soft-debug\n");
6877                         printf ("    gen-seq-points-file\n");
6878                         printf ("    gc-maps\n");
6879                         printf ("    print-skipped\n");
6880                         printf ("    no-instances\n");
6881                         printf ("    stats\n");
6882                         printf ("    dump\n");
6883                         printf ("    info\n");
6884                         printf ("    help/?\n");
6885                         exit (0);
6886                 } else {
6887                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6888                         exit (1);
6889                 }
6890
6891                 g_free ((gpointer) arg);
6892         }
6893
6894         if (opts->use_trampolines_page) {
6895                 opts->ntrampolines = 0;
6896                 opts->nrgctx_trampolines = 0;
6897                 opts->nimt_trampolines = 0;
6898                 opts->ngsharedvt_arg_trampolines = 0;
6899         }
6900
6901         g_ptr_array_free (args, /*free_seg=*/TRUE);
6902 }
6903
6904 static void
6905 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6906 {
6907         MonoMethod *method = (MonoMethod*)key;
6908         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6909         MonoAotCompile *acfg = (MonoAotCompile *)user_data;
6910         MonoJumpInfoToken *new_ji;
6911
6912         new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6913         new_ji->image = ji->image;
6914         new_ji->token = ji->token;
6915         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6916 }
6917
6918 static gboolean
6919 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6920 {
6921         if (klass->type_token)
6922                 return TRUE;
6923         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6924                 return TRUE;
6925         if (klass->rank)
6926                 return can_encode_class (acfg, klass->element_class);
6927         return FALSE;
6928 }
6929
6930 static gboolean
6931 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6932 {
6933                 if (method->wrapper_type) {
6934                         switch (method->wrapper_type) {
6935                         case MONO_WRAPPER_NONE:
6936                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6937                         case MONO_WRAPPER_XDOMAIN_INVOKE:
6938                         case MONO_WRAPPER_STFLD:
6939                         case MONO_WRAPPER_LDFLD:
6940                         case MONO_WRAPPER_LDFLDA:
6941                         case MONO_WRAPPER_LDFLD_REMOTE:
6942                         case MONO_WRAPPER_STFLD_REMOTE:
6943                         case MONO_WRAPPER_STELEMREF:
6944                         case MONO_WRAPPER_ISINST:
6945                         case MONO_WRAPPER_PROXY_ISINST:
6946                         case MONO_WRAPPER_ALLOC:
6947                         case MONO_WRAPPER_REMOTING_INVOKE:
6948                         case MONO_WRAPPER_UNKNOWN:
6949                         case MONO_WRAPPER_WRITE_BARRIER:
6950                         case MONO_WRAPPER_DELEGATE_INVOKE:
6951                         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6952                         case MONO_WRAPPER_DELEGATE_END_INVOKE:
6953                         case MONO_WRAPPER_SYNCHRONIZED:
6954                                 break;
6955                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
6956                         case MONO_WRAPPER_CASTCLASS: {
6957                                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6958
6959                                 if (info)
6960                                         return TRUE;
6961                                 else
6962                                         return FALSE;
6963                                 break;
6964                         }
6965                         default:
6966                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6967                                 return FALSE;
6968                         }
6969                 } else {
6970                         if (!method->token) {
6971                                 /* The method is part of a constructed type like Int[,].Set (). */
6972                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6973                                         if (method->klass->rank)
6974                                                 return TRUE;
6975                                         return FALSE;
6976                                 }
6977                         }
6978                 }
6979                 return TRUE;
6980 }
6981
6982 static gboolean
6983 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6984 {
6985         switch (patch_info->type) {
6986         case MONO_PATCH_INFO_METHOD:
6987         case MONO_PATCH_INFO_METHODCONST:
6988         case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6989                 MonoMethod *method = patch_info->data.method;
6990
6991                 return can_encode_method (acfg, method);
6992         }
6993         case MONO_PATCH_INFO_VTABLE:
6994         case MONO_PATCH_INFO_CLASS:
6995         case MONO_PATCH_INFO_IID:
6996         case MONO_PATCH_INFO_ADJUSTED_IID:
6997                 if (!can_encode_class (acfg, patch_info->data.klass)) {
6998                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6999                         return FALSE;
7000                 }
7001                 break;
7002         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7003                 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7004                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7005                         return FALSE;
7006                 }
7007                 break;
7008         }
7009         case MONO_PATCH_INFO_RGCTX_FETCH:
7010         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7011                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7012
7013                 if (!can_encode_method (acfg, entry->method))
7014                         return FALSE;
7015                 if (!can_encode_patch (acfg, entry->data))
7016                         return FALSE;
7017                 break;
7018         }
7019         default:
7020                 break;
7021         }
7022
7023         return TRUE;
7024 }
7025
7026 static gboolean
7027 is_concrete_type (MonoType *t)
7028 {
7029         MonoClass *klass;
7030         int i;
7031
7032         if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7033                 return FALSE;
7034         if (t->type == MONO_TYPE_GENERICINST) {
7035                 MonoGenericContext *orig_ctx;
7036                 MonoGenericInst *inst;
7037                 MonoType *arg;
7038
7039                 if (!MONO_TYPE_ISSTRUCT (t))
7040                         return TRUE;
7041                 klass = mono_class_from_mono_type (t);
7042                 orig_ctx = &klass->generic_class->context;
7043
7044                 inst = orig_ctx->class_inst;
7045                 if (inst) {
7046                         for (i = 0; i < inst->type_argc; ++i) {
7047                                 arg = mini_get_underlying_type (inst->type_argv [i]);
7048                                 if (!is_concrete_type (arg))
7049                                         return FALSE;
7050                         }
7051                 }
7052                 inst = orig_ctx->method_inst;
7053                 if (inst) {
7054                         for (i = 0; i < inst->type_argc; ++i) {
7055                                 arg = mini_get_underlying_type (inst->type_argv [i]);
7056                                 if (!is_concrete_type (arg))
7057                                         return FALSE;
7058                         }
7059                 }
7060         }
7061         return TRUE;
7062 }
7063
7064 /* LOCKING: Assumes the loader lock is held */
7065 static void
7066 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7067 {
7068         MonoMethod *wrapper;
7069         gboolean concrete = TRUE;
7070         gboolean add_in = gsharedvt_in;
7071         gboolean add_out = gsharedvt_out;
7072
7073         if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7074                 add_in = FALSE;
7075         if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7076                 add_out = FALSE;
7077
7078         if (!add_in && !add_out)
7079                 return;
7080
7081         if (mini_is_gsharedvt_variable_signature (sig))
7082                 return;
7083
7084         if (add_in)
7085                 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7086         if (add_out)
7087                 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7088
7089         if (!sig->has_type_parameters) {
7090                 //printf ("%s\n", mono_signature_full_name (sig));
7091
7092                 if (gsharedvt_in) {
7093                         wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7094                         add_extra_method (acfg, wrapper);
7095                 }
7096                 if (gsharedvt_out) {
7097                         wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7098                         add_extra_method (acfg, wrapper);
7099                 }
7100         } else {
7101                 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7102                 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7103                 int i;
7104
7105                 //printf ("%s\n", mono_signature_full_name (sig));
7106
7107                 copy->ret = mini_get_underlying_type (sig->ret);
7108                 if (!is_concrete_type (copy->ret))
7109                         concrete = FALSE;
7110                 for (i = 0; i < sig->param_count; ++i) {
7111                         copy->params [i] = mini_get_underlying_type (sig->params [i]);
7112                         if (!is_concrete_type (copy->params [i]))
7113                                 concrete = FALSE;
7114                 }
7115                 if (concrete) {
7116                         copy->has_type_parameters = 0;
7117
7118                         if (gsharedvt_in) {
7119                                 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7120                                 add_extra_method (acfg, wrapper);
7121                         }
7122
7123                         if (gsharedvt_out) {
7124                                 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7125                                 add_extra_method (acfg, wrapper);
7126                         }
7127
7128                         //printf ("%s\n", mono_method_full_name (wrapper, 1));
7129                 }
7130         }
7131 }
7132
7133 /*
7134  * compile_method:
7135  *
7136  *   AOT compile a given method.
7137  * This function might be called by multiple threads, so it must be thread-safe.
7138  */
7139 static void
7140 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7141 {
7142         MonoCompile *cfg;
7143         MonoJumpInfo *patch_info;
7144         gboolean skip;
7145         int index, depth;
7146         MonoMethod *wrapped;
7147         GTimer *jit_timer;
7148         JitFlags flags;
7149
7150         if (acfg->aot_opts.metadata_only)
7151                 return;
7152
7153         mono_acfg_lock (acfg);
7154         index = get_method_index (acfg, method);
7155         mono_acfg_unlock (acfg);
7156
7157         /* fixme: maybe we can also precompile wrapper methods */
7158         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7159                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7160                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7161                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7162                 return;
7163         }
7164
7165         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7166                 return;
7167
7168         wrapped = mono_marshal_method_from_wrapper (method);
7169         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7170                 // FIXME: The wrapper should be generic too, but it is not
7171                 return;
7172
7173         if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7174                 return;
7175
7176         InterlockedIncrement (&acfg->stats.mcount);
7177
7178 #if 0
7179         if (method->is_generic || method->klass->generic_container) {
7180                 InterlockedIncrement (&acfg->stats.genericcount);
7181                 return;
7182         }
7183 #endif
7184
7185         //acfg->aot_opts.print_skipped_methods = TRUE;
7186
7187         /*
7188          * Since these methods are the only ones which are compiled with
7189          * AOT support, and they are not used by runtime startup/shutdown code,
7190          * the runtime will not see AOT methods during AOT compilation,so it
7191          * does not need to support them by creating a fake GOT etc.
7192          */
7193         flags = JIT_FLAG_AOT;
7194         if (mono_aot_mode_is_full (&acfg->aot_opts))
7195                 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7196         if (acfg->llvm)
7197                 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7198         if (acfg->aot_opts.llvm_only)
7199                 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7200         if (acfg->aot_opts.no_direct_calls)
7201                 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7202
7203         jit_timer = mono_time_track_start ();
7204         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7205         mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7206
7207         mono_loader_clear_error ();
7208
7209         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7210                 if (acfg->aot_opts.print_skipped_methods)
7211                         printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7212                 InterlockedIncrement (&acfg->stats.genericcount);
7213                 return;
7214         }
7215         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7216                 if (acfg->aot_opts.print_skipped_methods)
7217                         printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7218                 /* Let the exception happen at runtime */
7219                 return;
7220         }
7221
7222         if (cfg->disable_aot) {
7223                 if (acfg->aot_opts.print_skipped_methods)
7224                         printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7225                 InterlockedIncrement (&acfg->stats.ocount);
7226                 mono_destroy_compile (cfg);
7227                 return;
7228         }
7229         cfg->method_index = index;
7230
7231         /* Nullify patches which need no aot processing */
7232         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7233                 switch (patch_info->type) {
7234                 case MONO_PATCH_INFO_LABEL:
7235                 case MONO_PATCH_INFO_BB:
7236                         patch_info->type = MONO_PATCH_INFO_NONE;
7237                         break;
7238                 default:
7239                         break;
7240                 }
7241         }
7242
7243         /* Collect method->token associations from the cfg */
7244         mono_acfg_lock (acfg);
7245         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7246         mono_acfg_unlock (acfg);
7247         g_hash_table_destroy (cfg->token_info_hash);
7248         cfg->token_info_hash = NULL;
7249
7250         /*
7251          * Check for absolute addresses.
7252          */
7253         skip = FALSE;
7254         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7255                 switch (patch_info->type) {
7256                 case MONO_PATCH_INFO_ABS:
7257                         /* unable to handle this */
7258                         skip = TRUE;    
7259                         break;
7260                 default:
7261                         break;
7262                 }
7263         }
7264
7265         if (skip) {
7266                 if (acfg->aot_opts.print_skipped_methods)
7267                         printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7268                 InterlockedIncrement (&acfg->stats.abscount);
7269                 mono_destroy_compile (cfg);
7270                 return;
7271         }
7272
7273         /* Lock for the rest of the code */
7274         mono_acfg_lock (acfg);
7275
7276         if (cfg->gsharedvt)
7277                 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7278         else if (cfg->gshared)
7279                 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7280         else if (cfg->method->wrapper_type)
7281                 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7282         else
7283                 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7284
7285         /*
7286          * Check for methods/klasses we can't encode.
7287          */
7288         skip = FALSE;
7289         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7290                 if (!can_encode_patch (acfg, patch_info))
7291                         skip = TRUE;
7292         }
7293
7294         if (skip) {
7295                 if (acfg->aot_opts.print_skipped_methods)
7296                         printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7297                 acfg->stats.ocount++;
7298                 mono_destroy_compile (cfg);
7299                 mono_acfg_unlock (acfg);
7300                 return;
7301         }
7302
7303         if (!cfg->compile_llvm)
7304                 acfg->has_jitted_code = TRUE;
7305
7306         if (method->is_inflated && acfg->aot_opts.log_instances) {
7307                 if (acfg->instances_logfile)
7308                         fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7309                 else
7310                         printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7311         }
7312
7313         /* Adds generic instances referenced by this method */
7314         /* 
7315          * The depth is used to avoid infinite loops when generic virtual recursion is 
7316          * encountered.
7317          */
7318         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7319         if (!acfg->aot_opts.no_instances && depth < 32) {
7320                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7321                         switch (patch_info->type) {
7322                         case MONO_PATCH_INFO_RGCTX_FETCH:
7323                         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7324                         case MONO_PATCH_INFO_METHOD: {
7325                                 MonoMethod *m = NULL;
7326
7327                                 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7328                                         MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7329
7330                                         if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7331                                                 m = e->data->data.method;
7332                                 } else {
7333                                         m = patch_info->data.method;
7334                                 }
7335
7336                                 if (!m)
7337                                         break;
7338                                 if (m->is_inflated) {
7339                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
7340                                                   mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7341                                                 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7342                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7343                                                         if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7344                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7345                                                 } else {
7346                                                         add_extra_method_with_depth (acfg, m, depth + 1);
7347                                                         add_types_from_method_header (acfg, m);
7348                                                 }
7349                                         }
7350                                         add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7351                                 }
7352                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7353                                         WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7354
7355                                         if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7356                                                 add_extra_method_with_depth (acfg, m, depth + 1);
7357                                 }
7358                                 break;
7359                         }
7360                         case MONO_PATCH_INFO_VTABLE: {
7361                                 MonoClass *klass = patch_info->data.klass;
7362
7363                                 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7364                                         add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7365                                 break;
7366                         }
7367                         case MONO_PATCH_INFO_SFLDA: {
7368                                 MonoClass *klass = patch_info->data.field->parent;
7369
7370                                 /* The .cctor needs to run at runtime. */
7371                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7372                                         add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7373                                 break;
7374                         }
7375                         default:
7376                                 break;
7377                         }
7378                 }
7379         }
7380
7381         /* Determine whenever the method has GOT slots */
7382         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7383                 switch (patch_info->type) {
7384                 case MONO_PATCH_INFO_GOT_OFFSET:
7385                 case MONO_PATCH_INFO_NONE:
7386                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7387                 case MONO_PATCH_INFO_GC_NURSERY_START:
7388                 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7389                         break;
7390                 case MONO_PATCH_INFO_IMAGE:
7391                         /* The assembly is stored in GOT slot 0 */
7392                         if (patch_info->data.image != acfg->image)
7393                                 cfg->has_got_slots = TRUE;
7394                         break;
7395                 default:
7396                         if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7397                                 cfg->has_got_slots = TRUE;
7398                         break;
7399                 }
7400         }
7401
7402         if (!cfg->has_got_slots)
7403                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7404
7405         /* Add gsharedvt wrappers for signatures used by the method */
7406         if (acfg->aot_opts.llvm_only) {
7407                 GSList *l;
7408
7409                 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7410                         /* These only need out wrappers */
7411                         add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7412
7413                 for (l = cfg->signatures; l; l = l->next) {
7414                         MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7415
7416                         /* These only need in wrappers */
7417                         add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7418                 }
7419         }
7420
7421         /* 
7422          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7423          */
7424         /* Make a copy of the patch info which is in the mempool */
7425         {
7426                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7427
7428                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7429                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7430
7431                         if (!patches)
7432                                 patches = new_patch_info;
7433                         else
7434                                 patches_end->next = new_patch_info;
7435                         patches_end = new_patch_info;
7436                 }
7437                 cfg->patch_info = patches;
7438         }
7439         /* Make a copy of the unwind info */
7440         {
7441                 GSList *l, *unwind_ops;
7442                 MonoUnwindOp *op;
7443
7444                 unwind_ops = NULL;
7445                 for (l = cfg->unwind_ops; l; l = l->next) {
7446                         op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7447                         memcpy (op, l->data, sizeof (MonoUnwindOp));
7448                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7449                 }
7450                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7451         }
7452         /* Make a copy of the argument/local info */
7453         {
7454                 MonoError error;
7455                 MonoInst **args, **locals;
7456                 MonoMethodSignature *sig;
7457                 MonoMethodHeader *header;
7458                 int i;
7459                 
7460                 sig = mono_method_signature (method);
7461                 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7462                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7463                         args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7464                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7465                 }
7466                 cfg->args = args;
7467
7468                 header = mono_method_get_header_checked (method, &error);
7469                 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7470                 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7471                 for (i = 0; i < header->num_locals; ++i) {
7472                         locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7473                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7474                 }
7475                 cfg->locals = locals;
7476         }
7477
7478         /* Free some fields used by cfg to conserve memory */
7479         mono_mempool_destroy (cfg->mempool);
7480         cfg->mempool = NULL;
7481         g_free (cfg->varinfo);
7482         cfg->varinfo = NULL;
7483         g_free (cfg->vars);
7484         cfg->vars = NULL;
7485         if (cfg->rs) {
7486                 mono_regstate_free (cfg->rs);
7487                 cfg->rs = NULL;
7488         }
7489
7490         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
7491
7492         while (index >= acfg->cfgs_size) {
7493                 MonoCompile **new_cfgs;
7494                 int new_size;
7495
7496                 new_size = acfg->cfgs_size * 2;
7497                 new_cfgs = g_new0 (MonoCompile*, new_size);
7498                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7499                 g_free (acfg->cfgs);
7500                 acfg->cfgs = new_cfgs;
7501                 acfg->cfgs_size = new_size;
7502         }
7503         acfg->cfgs [index] = cfg;
7504
7505         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7506
7507         mono_update_jit_stats (cfg);
7508
7509         /*
7510         if (cfg->orig_method->wrapper_type)
7511                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7512         */
7513
7514         mono_acfg_unlock (acfg);
7515
7516         InterlockedIncrement (&acfg->stats.ccount);
7517 }
7518  
7519 static void
7520 compile_thread_main (gpointer *user_data)
7521 {
7522         MonoDomain *domain = (MonoDomain *)user_data [0];
7523         MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7524         GPtrArray *methods = (GPtrArray *)user_data [2];
7525         int i;
7526
7527         mono_thread_attach (domain);
7528
7529         for (i = 0; i < methods->len; ++i)
7530                 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7531 }
7532
7533 static void
7534 load_profile_files (MonoAotCompile *acfg)
7535 {
7536         FILE *infile;
7537         char *tmp;
7538         int file_index, res, method_index, i;
7539         char ver [256];
7540         guint32 token;
7541         GList *unordered, *l;
7542         gboolean found;
7543
7544         file_index = 0;
7545         while (TRUE) {
7546                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7547
7548                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7549                         g_free (tmp);
7550                         break;
7551                 }
7552
7553                 infile = fopen (tmp, "r");
7554                 g_assert (infile);
7555
7556                 printf ("Using profile data file '%s'\n", tmp);
7557                 g_free (tmp);
7558
7559                 file_index ++;
7560
7561                 res = fscanf (infile, "%32s\n", ver);
7562                 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7563                         printf ("Profile file has wrong version or invalid.\n");
7564                         fclose (infile);
7565                         continue;
7566                 }
7567
7568                 while (TRUE) {
7569                         char name [1024];
7570                         MonoMethodDesc *desc;
7571                         MonoMethod *method;
7572
7573                         if (fgets (name, 1023, infile) == NULL)
7574                                 break;
7575
7576                         /* Kill the newline */
7577                         if (strlen (name) > 0)
7578                                 name [strlen (name) - 1] = '\0';
7579
7580                         desc = mono_method_desc_new (name, TRUE);
7581
7582                         method = mono_method_desc_search_in_image (desc, acfg->image);
7583
7584                         if (method && mono_method_get_token (method)) {
7585                                 token = mono_method_get_token (method);
7586                                 method_index = mono_metadata_token_index (token) - 1;
7587
7588                                 found = FALSE;
7589                                 for (i = 0; i < acfg->method_order->len; ++i) {
7590                                         if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7591                                                 found = TRUE;
7592                                                 break;
7593                                         }
7594                                 }
7595                                 if (!found)
7596                                         g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7597                         } else {
7598                                 //printf ("No method found matching '%s'.\n", name);
7599                         }
7600                 }
7601                 fclose (infile);
7602         }
7603
7604         /* Add missing methods */
7605         unordered = NULL;
7606         for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7607                 found = FALSE;
7608                 for (i = 0; i < acfg->method_order->len; ++i) {
7609                         if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7610                                 found = TRUE;
7611                                 break;
7612                         }
7613                 }
7614                 if (!found)
7615                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7616         }
7617         unordered = g_list_reverse (unordered);
7618         for (l = unordered; l; l = l->next)
7619                 g_ptr_array_add (acfg->method_order, l->data);
7620 }
7621  
7622 /* Used by the LLVM backend */
7623 guint32
7624 mono_aot_get_got_offset (MonoJumpInfo *ji)
7625 {
7626         return get_got_offset (llvm_acfg, TRUE, ji);
7627 }
7628
7629 /*
7630  * mono_aot_is_shared_got_offset:
7631  *
7632  *   Return whenever OFFSET refers to a GOT slot which is preinitialized
7633  * when the AOT image is loaded.
7634  */
7635 gboolean
7636 mono_aot_is_shared_got_offset (int offset)
7637 {
7638         return offset < llvm_acfg->nshared_got_entries;
7639 }
7640
7641 char*
7642 mono_aot_get_method_name (MonoCompile *cfg)
7643 {
7644         if (llvm_acfg->aot_opts.static_link)
7645                 /* Include the assembly name too to avoid duplicate symbol errors */
7646                 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7647         else
7648                 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7649 }
7650
7651 /*
7652  * mono_aot_is_linkonce_method:
7653  *
7654  *   Return whenever METHOD should be emitted with linkonce linkage,
7655  * eliminating duplicate copies when compiling in static mode.
7656  */
7657 gboolean
7658 mono_aot_is_linkonce_method (MonoMethod *method)
7659 {
7660         WrapperInfo *info;
7661
7662         // FIXME: Add more cases
7663         if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7664                 return FALSE;
7665         info = mono_marshal_get_wrapper_info (method);
7666         if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7667                 return TRUE;
7668         return FALSE;
7669 }
7670
7671 static gboolean
7672 append_mangled_type (GString *s, MonoType *t)
7673 {
7674         if (t->byref)
7675                 g_string_append_printf (s, "b");
7676         switch (t->type) {
7677         case MONO_TYPE_VOID:
7678                 g_string_append_printf (s, "void_");
7679                 break;
7680         case MONO_TYPE_I1:
7681                 g_string_append_printf (s, "i1");
7682                 break;
7683         case MONO_TYPE_U1:
7684                 g_string_append_printf (s, "u1");
7685                 break;
7686         case MONO_TYPE_I2:
7687                 g_string_append_printf (s, "i2");
7688                 break;
7689         case MONO_TYPE_U2:
7690                 g_string_append_printf (s, "u2");
7691                 break;
7692         case MONO_TYPE_I4:
7693                 g_string_append_printf (s, "i4");
7694                 break;
7695         case MONO_TYPE_U4:
7696                 g_string_append_printf (s, "u4");
7697                 break;
7698         case MONO_TYPE_I8:
7699                 g_string_append_printf (s, "i8");
7700                 break;
7701         case MONO_TYPE_U8:
7702                 g_string_append_printf (s, "u8");
7703                 break;
7704         case MONO_TYPE_I:
7705                 g_string_append_printf (s, "ii");
7706                 break;
7707         case MONO_TYPE_U:
7708                 g_string_append_printf (s, "ui");
7709                 break;
7710         case MONO_TYPE_R4:
7711                 g_string_append_printf (s, "fl");
7712                 break;
7713         case MONO_TYPE_R8:
7714                 g_string_append_printf (s, "do");
7715                 break;
7716         default: {
7717                 char *fullname = mono_type_full_name (t);
7718                 GString *temp;
7719                 char *temps;
7720                 int i, len;
7721
7722                 /*
7723                  * Have to create a mangled name which is:
7724                  * - a valid symbol
7725                  * - unique
7726                  */
7727                 temp = g_string_new ("");
7728                 len = strlen (fullname);
7729                 for (i = 0; i < len; ++i) {
7730                         char c = fullname [i];
7731                         if (isalnum (c)) {
7732                                 g_string_append_c (temp, c);
7733                         } else if (c == '_') {
7734                                 g_string_append_c (temp, '_');
7735                                 g_string_append_c (temp, '_');
7736                         } else {
7737                                 g_string_append_c (temp, '_');
7738                                 g_string_append_printf (temp, "%x", (int)c);
7739                         }
7740                 }
7741                 temps = g_string_free (temp, FALSE);
7742                 /* Include the length to avoid different length type names aliasing each other */
7743                 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
7744                 g_free (temps);
7745                 return TRUE;
7746         }
7747         }
7748         return TRUE;
7749 }
7750
7751 static gboolean
7752 append_mangled_signature (GString *s, MonoMethodSignature *sig)
7753 {
7754         int i;
7755         gboolean supported;
7756
7757         supported = append_mangled_type (s, sig->ret);
7758         if (!supported)
7759                 return FALSE;
7760         if (sig->hasthis)
7761                 g_string_append_printf (s, "this_");
7762         for (i = 0; i < sig->param_count; ++i) {
7763                 supported = append_mangled_type (s, sig->params [i]);
7764                 if (!supported)
7765                         return FALSE;
7766         }
7767
7768         return TRUE;
7769 }
7770
7771 /*
7772  * mono_aot_get_mangled_method_name:
7773  *
7774  *   Return a unique mangled name for METHOD, or NULL.
7775  */
7776 char*
7777 mono_aot_get_mangled_method_name (MonoMethod *method)
7778 {
7779         WrapperInfo *info;
7780         GString *s;
7781         gboolean supported;
7782
7783         // FIXME: Add more cases
7784         if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7785                 return NULL;
7786         info = mono_marshal_get_wrapper_info (method);
7787         if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7788                 return NULL;
7789
7790         s = g_string_new ("");
7791
7792         g_string_append_printf (s, "aot_method_w_");
7793
7794         switch (info->subtype) {
7795         case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
7796                 g_string_append_printf (s, "gsharedvt_in_");
7797                 break;
7798         case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
7799                 g_string_append_printf (s, "gsharedvt_out_");
7800                 break;
7801         default:
7802                 g_assert_not_reached ();
7803                 break;
7804         }
7805
7806         supported = append_mangled_signature (s, info->d.gsharedvt.sig);
7807         if (!supported) {
7808                 g_string_free (s, TRUE);
7809                 return NULL;
7810         }
7811
7812         return g_string_free (s, FALSE);
7813 }
7814
7815 gboolean
7816 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7817 {
7818         return is_direct_callable (llvm_acfg, NULL, patch_info);
7819 }
7820
7821 void
7822 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7823 {
7824         MonoPltEntry *plt_entry;
7825
7826         plt_entry = get_plt_entry (llvm_acfg, patch_info);
7827         plt_entry->llvm_used = FALSE;
7828 }
7829
7830 char*
7831 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
7832 {
7833         const char *sym = NULL;
7834
7835         if (llvm_acfg->aot_opts.direct_icalls) {
7836                 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7837                         /* Call to a C function implementing a jit icall */
7838                         sym = mono_lookup_jit_icall_symbol ((const char *)data);
7839                 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7840                         MonoMethod *method = (MonoMethod *)data;
7841                         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7842                                 sym = mono_lookup_icall_symbol (method);
7843                         else if (llvm_acfg->aot_opts.direct_pinvoke)
7844                                 sym = get_pinvoke_import (llvm_acfg, method);
7845                 }
7846                 if (sym)
7847                         return g_strdup (sym);
7848         }
7849         return NULL;
7850 }
7851
7852 char*
7853 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7854 {
7855         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7856         MonoPltEntry *plt_entry;
7857         const char *sym = NULL;
7858
7859         ji->type = type;
7860         ji->data.target = data;
7861
7862         if (!can_encode_patch (llvm_acfg, ji))
7863                 return NULL;
7864
7865         if (llvm_acfg->aot_opts.direct_icalls) {
7866                 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7867                         /* Call to a C function implementing a jit icall */
7868                         sym = mono_lookup_jit_icall_symbol ((const char *)data);
7869                 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7870                         MonoMethod *method = (MonoMethod *)data;
7871                         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7872                                 sym = mono_lookup_icall_symbol (method);
7873                 }
7874                 if (sym)
7875                         return g_strdup (sym);
7876         }
7877
7878         plt_entry = get_plt_entry (llvm_acfg, ji);
7879         plt_entry->llvm_used = TRUE;
7880
7881 #if defined(TARGET_MACH)
7882         return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7883 #else
7884         return g_strdup_printf (plt_entry->llvm_symbol);
7885 #endif
7886 }
7887
7888 int
7889 mono_aot_get_method_index (MonoMethod *method)
7890 {
7891         g_assert (llvm_acfg);
7892         return get_method_index (llvm_acfg, method);
7893 }
7894
7895 MonoJumpInfo*
7896 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7897 {
7898         MonoJumpInfo *res;
7899
7900         mono_acfg_lock (llvm_acfg);
7901         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7902         mono_acfg_unlock (llvm_acfg);
7903
7904         return res;
7905 }
7906
7907 static int
7908 execute_system (const char * command)
7909 {
7910         int status;
7911
7912 #if _WIN32
7913         // We need an extra set of quotes around the whole command to properly handle commands 
7914         // with spaces since internally the command is called through "cmd /c.
7915         command = g_strdup_printf ("\"%s\"", command);
7916
7917         int size =  MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7918         wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7919         MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7920         status = _wsystem (wstr);
7921         g_free (wstr);
7922
7923         g_free (command);
7924 #elif defined (HAVE_SYSTEM)
7925         status = system (command);
7926 #else
7927         g_assert_not_reached ();
7928 #endif
7929
7930         return status;
7931 }
7932
7933 #ifdef ENABLE_LLVM
7934
7935 /*
7936  * emit_llvm_file:
7937  *
7938  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7939  * tools.
7940  */
7941 static gboolean
7942 emit_llvm_file (MonoAotCompile *acfg)
7943 {
7944         char *command, *opts, *tempbc, *optbc, *output_fname;
7945
7946         if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
7947                 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7948                 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
7949         } else {
7950                 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7951                 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
7952         }
7953
7954         mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7955
7956         /*
7957          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7958          * a lot of time, and doesn't seem to save much space.
7959          * The following optimizations cannot be enabled:
7960          * - 'tailcallelim'
7961          * - 'jump-threading' changes our blockaddress references to int constants.
7962          * - 'basiccg' fails because it contains:
7963          * if (CS && !isa<IntrinsicInst>(II)) {
7964          * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7965          * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7966          * The opt list below was produced by taking the output of:
7967          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7968          * then removing tailcallelim + the global opts.
7969          * strip-dead-prototypes deletes unused intrinsics definitions.
7970          */
7971         /* The dse pass is disabled because of #13734 and #17616 */
7972         /*
7973          * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7974          * // If we have no DataLayout information around, then the size of the store
7975          *  // is inferrable from the pointee type.  If they are the same type, then
7976          * // we know that the store is safe.
7977          * if (AA.getDataLayout() == 0 &&
7978          * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7979          * return OverwriteComplete;
7980          * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7981          */
7982         if (acfg->aot_opts.llvm_only)
7983                 // FIXME: This doesn't work yet
7984                 opts = g_strdup ("");
7985         else
7986 #if LLVM_API_VERSION > 100
7987                 opts = g_strdup ("-O2");
7988 #else
7989                 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");
7990 #endif
7991         command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
7992         aot_printf (acfg, "Executing opt: %s\n", command);
7993         if (execute_system (command) != 0)
7994                 return FALSE;
7995         g_free (opts);
7996
7997         if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
7998                 /* Nothing else to do */
7999                 return TRUE;
8000
8001         if (acfg->aot_opts.llvm_only) {
8002                 /* Use the stock clang from xcode */
8003                 // FIXME: arch
8004                 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);
8005
8006                 aot_printf (acfg, "Executing clang: %s\n", command);
8007                 if (execute_system (command) != 0)
8008                         return FALSE;
8009                 return TRUE;
8010         }
8011
8012         if (!acfg->llc_args)
8013                 acfg->llc_args = g_string_new ("");
8014
8015         /* Verbose asm slows down llc greatly */
8016         g_string_append (acfg->llc_args, " -asm-verbose=false");
8017
8018         if (acfg->aot_opts.mtriple)
8019                 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8020
8021         g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8022
8023         g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8024
8025 #if LLVM_API_VERSION > 100
8026         g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8027 #endif
8028
8029 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8030         /* ios requires PIC code now */
8031         g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8032 #else
8033         if (llvm_acfg->aot_opts.static_link)
8034                 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8035         else
8036                 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8037 #endif
8038
8039         if (acfg->llvm_owriter) {
8040                 /* Emit an object file directly */
8041                 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8042                 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8043         } else {
8044                 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8045         }
8046         command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8047         g_free (output_fname);
8048
8049         aot_printf (acfg, "Executing llc: %s\n", command);
8050
8051         if (execute_system (command) != 0)
8052                 return FALSE;
8053         return TRUE;
8054 }
8055 #endif
8056
8057 static void
8058 emit_code (MonoAotCompile *acfg)
8059 {
8060         int oindex, i, prev_index;
8061         gboolean saved_unbox_info = FALSE;
8062         char symbol [256];
8063
8064         if (acfg->aot_opts.llvm_only)
8065                 return;
8066
8067 #if defined(TARGET_POWERPC64)
8068         sprintf (symbol, ".Lgot_addr");
8069         emit_section_change (acfg, ".text", 0);
8070         emit_alignment (acfg, 8);
8071         emit_label (acfg, symbol);
8072         emit_pointer (acfg, acfg->got_symbol);
8073 #endif
8074
8075         /* 
8076          * This global symbol is used to compute the address of each method using the
8077          * code_offsets array. It is also used to compute the memory ranges occupied by
8078          * AOT code, so it must be equal to the address of the first emitted method.
8079          */
8080         emit_section_change (acfg, ".text", 0);
8081         emit_alignment_code (acfg, 8);
8082         emit_info_symbol (acfg, "jit_code_start");
8083
8084         /* 
8085          * Emit some padding so the local symbol for the first method doesn't have the
8086          * same address as 'methods'.
8087          */
8088 #if defined(__default_codegen__)
8089         emit_padding (acfg, 16);
8090 #elif defined(__native_client_codegen__)
8091         {
8092                 const int kPaddingSize = 16;
8093                 guint8 pad_buffer[kPaddingSize];
8094                 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
8095                 emit_bytes (acfg, pad_buffer, kPaddingSize);
8096         }
8097 #endif
8098
8099         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8100                 MonoCompile *cfg;
8101                 MonoMethod *method;
8102
8103                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8104
8105                 cfg = acfg->cfgs [i];
8106
8107                 if (!cfg)
8108                         continue;
8109
8110                 method = cfg->orig_method;
8111
8112                 /* Emit unbox trampoline */
8113                 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8114                         sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8115
8116                         emit_section_change (acfg, ".text", 0);
8117 #ifdef __native_client_codegen__
8118                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
8119 #endif
8120
8121                         if (acfg->thumb_mixed && cfg->compile_llvm) {
8122                                 emit_set_thumb_mode (acfg);
8123                                 fprintf (acfg->fp, "\n.thumb_func\n");
8124                         }
8125
8126                         emit_label (acfg, symbol);
8127
8128                         arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8129
8130                         if (acfg->thumb_mixed && cfg->compile_llvm)
8131                                 emit_set_arm_mode (acfg);
8132
8133                         if (!saved_unbox_info) {
8134                                 char user_symbol [128];
8135                                 GSList *unwind_ops;
8136                                 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8137
8138                                 emit_label (acfg, "ut_end");
8139
8140                                 unwind_ops = mono_unwind_get_cie_program ();
8141                                 save_unwind_info (acfg, user_symbol, unwind_ops);
8142                                 mono_free_unwind_info (unwind_ops);
8143
8144                                 /* Save the unbox trampoline size */
8145                                 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8146
8147                                 saved_unbox_info = TRUE;
8148                         }
8149                 }
8150
8151                 if (cfg->compile_llvm)
8152                         acfg->stats.llvm_count ++;
8153                 else
8154                         emit_method_code (acfg, cfg);
8155         }
8156
8157         emit_section_change (acfg, ".text", 0);
8158         emit_alignment_code (acfg, 8);
8159         emit_info_symbol (acfg, "jit_code_end");
8160
8161         /* To distinguish it from the next symbol */
8162         emit_padding (acfg, 4);
8163
8164         /* 
8165          * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8166          * from optimizing them away, since it doesn't see that code_offsets references them.
8167          * JITted methods don't need this since they are referenced using assembler local
8168          * symbols.
8169          * FIXME: This is why write-symbols doesn't work on OSX ?
8170          */
8171         if (acfg->llvm && acfg->need_no_dead_strip) {
8172                 fprintf (acfg->fp, "\n");
8173                 for (i = 0; i < acfg->nmethods; ++i) {
8174                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8175                                 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8176                 }
8177         }
8178
8179         /*
8180          * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8181          * This is PIE code, and the linker can update it if needed.
8182          */
8183         sprintf (symbol, "method_addresses");
8184         emit_section_change (acfg, ".text", 1);
8185         emit_alignment_code (acfg, 8);
8186         emit_info_symbol (acfg, symbol);
8187         emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8188         emit_unset_mode (acfg);
8189         if (acfg->need_no_dead_strip)
8190                 fprintf (acfg->fp, "    .no_dead_strip %s\n", symbol);
8191
8192         for (i = 0; i < acfg->nmethods; ++i) {
8193 #ifdef MONO_ARCH_AOT_SUPPORTED
8194                 int call_size;
8195
8196                 if (acfg->cfgs [i]) {
8197                         if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
8198                                 /* Obtained by calling a generated function in the LLVM image */
8199                                 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8200                         else
8201                                 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8202                 } else {
8203                         arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8204                 }
8205 #endif
8206         }
8207
8208         sprintf (symbol, "method_addresses_end");
8209         emit_label (acfg, symbol);
8210         emit_line (acfg);
8211
8212         /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8213         sprintf (symbol, "unbox_trampolines");
8214         emit_section_change (acfg, RODATA_SECT, 0);
8215         emit_alignment (acfg, 8);
8216         emit_info_symbol (acfg, symbol);
8217
8218         prev_index = -1;
8219         for (i = 0; i < acfg->nmethods; ++i) {
8220                 MonoCompile *cfg;
8221                 MonoMethod *method;
8222                 int index;
8223
8224                 cfg = acfg->cfgs [i];
8225                 if (!cfg)
8226                         continue;
8227
8228                 method = cfg->orig_method;
8229
8230                 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8231                         index = get_method_index (acfg, method);
8232
8233                         emit_int32 (acfg, index);
8234                         /* Make sure the table is sorted by index */
8235                         g_assert (index > prev_index);
8236                         prev_index = index;
8237                 }
8238         }
8239         sprintf (symbol, "unbox_trampolines_end");
8240         emit_info_symbol (acfg, symbol);
8241         emit_int32 (acfg, 0);
8242
8243         /* Emit a separate table with the trampoline addresses/offsets */
8244         sprintf (symbol, "unbox_trampoline_addresses");
8245         emit_section_change (acfg, ".text", 0);
8246         emit_alignment_code (acfg, 8);
8247         emit_info_symbol (acfg, symbol);
8248
8249         for (i = 0; i < acfg->nmethods; ++i) {
8250                 MonoCompile *cfg;
8251                 MonoMethod *method;
8252                 int index;
8253
8254                 cfg = acfg->cfgs [i];
8255                 if (!cfg)
8256                         continue;
8257
8258                 method = cfg->orig_method;
8259
8260                 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8261 #ifdef MONO_ARCH_AOT_SUPPORTED
8262                         int call_size;
8263
8264                         index = get_method_index (acfg, method);
8265                         sprintf (symbol, "ut_%d", index);
8266
8267                         arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8268 #endif
8269                 }
8270         }
8271         emit_int32 (acfg, 0);
8272 }
8273
8274 static void
8275 emit_info (MonoAotCompile *acfg)
8276 {
8277         int oindex, i;
8278         gint32 *offsets;
8279
8280         offsets = g_new0 (gint32, acfg->nmethods);
8281
8282         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8283                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8284
8285                 if (acfg->cfgs [i]) {
8286                         emit_method_info (acfg, acfg->cfgs [i]);
8287                         offsets [i] = acfg->cfgs [i]->method_info_offset;
8288                 } else {
8289                         offsets [i] = 0;
8290                 }
8291         }
8292
8293         acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8294
8295         g_free (offsets);
8296 }
8297
8298 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8299
8300 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8301 #define mix(a,b,c) { \
8302         a -= c;  a ^= rot(c, 4);  c += b; \
8303         b -= a;  b ^= rot(a, 6);  a += c; \
8304         c -= b;  c ^= rot(b, 8);  b += a; \
8305         a -= c;  a ^= rot(c,16);  c += b; \
8306         b -= a;  b ^= rot(a,19);  a += c; \
8307         c -= b;  c ^= rot(b, 4);  b += a; \
8308 }
8309 #define final(a,b,c) { \
8310         c ^= b; c -= rot(b,14); \
8311         a ^= c; a -= rot(c,11); \
8312         b ^= a; b -= rot(a,25); \
8313         c ^= b; c -= rot(b,16); \
8314         a ^= c; a -= rot(c,4);  \
8315         b ^= a; b -= rot(a,14); \
8316         c ^= b; c -= rot(b,24); \
8317 }
8318
8319 static guint
8320 mono_aot_type_hash (MonoType *t1)
8321 {
8322         guint hash = t1->type;
8323
8324         hash |= t1->byref << 6; /* do not collide with t1->type values */
8325         switch (t1->type) {
8326         case MONO_TYPE_VALUETYPE:
8327         case MONO_TYPE_CLASS:
8328         case MONO_TYPE_SZARRAY:
8329                 /* check if the distribution is good enough */
8330                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8331         case MONO_TYPE_PTR:
8332                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8333         case MONO_TYPE_ARRAY:
8334                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8335         case MONO_TYPE_GENERICINST:
8336                 return ((hash << 5) - hash) ^ 0;
8337         default:
8338                 return hash;
8339         }
8340 }
8341
8342 /*
8343  * mono_aot_method_hash:
8344  *
8345  *   Return a hash code for methods which only depends on metadata.
8346  */
8347 guint32
8348 mono_aot_method_hash (MonoMethod *method)
8349 {
8350         MonoMethodSignature *sig;
8351         MonoClass *klass;
8352         int i, hindex;
8353         int hashes_count;
8354         guint32 *hashes_start, *hashes;
8355         guint32 a, b, c;
8356         MonoGenericInst *class_ginst = NULL;
8357         MonoGenericInst *ginst = NULL;
8358
8359         /* Similar to the hash in mono_method_get_imt_slot () */
8360
8361         sig = mono_method_signature (method);
8362
8363         if (method->klass->generic_class)
8364                 class_ginst = method->klass->generic_class->context.class_inst;
8365         if (method->is_inflated)
8366                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8367
8368         hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8369         hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8370         hashes = hashes_start;
8371
8372         /* Some wrappers are assigned to random classes */
8373         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8374                 klass = method->klass;
8375         else
8376                 klass = mono_defaults.object_class;
8377
8378         if (!method->wrapper_type) {
8379                 char *full_name;
8380
8381                 if (klass->generic_class)
8382                         full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8383                 else
8384                         full_name = mono_type_full_name (&klass->byval_arg);
8385
8386                 hashes [0] = mono_metadata_str_hash (full_name);
8387                 hashes [1] = 0;
8388                 g_free (full_name);
8389         } else {
8390                 hashes [0] = mono_metadata_str_hash (klass->name);
8391                 hashes [1] = mono_metadata_str_hash (klass->name_space);
8392         }
8393         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8394                 /* The method name includes a stringified pointer */
8395                 hashes [2] = 0;
8396         else
8397                 hashes [2] = mono_metadata_str_hash (method->name);
8398         hashes [3] = method->wrapper_type;
8399         hashes [4] = mono_aot_type_hash (sig->ret);
8400         hindex = 5;
8401         for (i = 0; i < sig->param_count; i++) {
8402                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8403         }
8404         if (class_ginst) {
8405                 for (i = 0; i < class_ginst->type_argc; ++i)
8406                         hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8407         }
8408         if (ginst) {
8409                 for (i = 0; i < ginst->type_argc; ++i)
8410                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8411         }               
8412         g_assert (hindex == hashes_count);
8413
8414         /* Setup internal state */
8415         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8416
8417         /* Handle most of the hashes */
8418         while (hashes_count > 3) {
8419                 a += hashes [0];
8420                 b += hashes [1];
8421                 c += hashes [2];
8422                 mix (a,b,c);
8423                 hashes_count -= 3;
8424                 hashes += 3;
8425         }
8426
8427         /* Handle the last 3 hashes (all the case statements fall through) */
8428         switch (hashes_count) { 
8429         case 3 : c += hashes [2];
8430         case 2 : b += hashes [1];
8431         case 1 : a += hashes [0];
8432                 final (a,b,c);
8433         case 0: /* nothing left to add */
8434                 break;
8435         }
8436         
8437         free (hashes_start);
8438         
8439         return c;
8440 }
8441 #undef rot
8442 #undef mix
8443 #undef final
8444
8445 /*
8446  * mono_aot_get_array_helper_from_wrapper;
8447  *
8448  * Get the helper method in Array called by an array wrapper method.
8449  */
8450 MonoMethod*
8451 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8452 {
8453         MonoMethod *m;
8454         const char *prefix;
8455         MonoGenericContext ctx;
8456         MonoType *args [16];
8457         char *mname, *iname, *s, *s2, *helper_name = NULL;
8458
8459         prefix = "System.Collections.Generic";
8460         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8461         s2 = strstr (s, "`1.");
8462         g_assert (s2);
8463         s2 [0] = '\0';
8464         iname = s;
8465         mname = s2 + 3;
8466
8467         //printf ("X: %s %s\n", iname, mname);
8468
8469         if (!strcmp (iname, "IList"))
8470                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8471         else
8472                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8473         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8474         g_assert (m);
8475         g_free (helper_name);
8476         g_free (s);
8477
8478         if (m->is_generic) {
8479                 MonoError error;
8480                 memset (&ctx, 0, sizeof (ctx));
8481                 args [0] = &method->klass->element_class->byval_arg;
8482                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8483                 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8484                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8485         }
8486
8487         return m;
8488 }
8489
8490 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8491
8492 typedef struct HashEntry {
8493     guint32 key, value, index;
8494         struct HashEntry *next;
8495 } HashEntry;
8496
8497 /*
8498  * emit_extra_methods:
8499  *
8500  * Emit methods which are not in the METHOD table, like wrappers.
8501  */
8502 static void
8503 emit_extra_methods (MonoAotCompile *acfg)
8504 {
8505         int i, table_size, buf_size;
8506         guint8 *p, *buf;
8507         guint32 *info_offsets;
8508         guint32 hash;
8509         GPtrArray *table;
8510         HashEntry *entry, *new_entry;
8511         int nmethods, max_chain_length;
8512         int *chain_lengths;
8513
8514         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8515
8516         /* Emit method info */
8517         nmethods = 0;
8518         for (i = 0; i < acfg->extra_methods->len; ++i) {
8519                 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8520                 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8521
8522                 if (!cfg)
8523                         continue;
8524
8525                 buf_size = 10240;
8526                 p = buf = (guint8 *)g_malloc (buf_size);
8527
8528                 nmethods ++;
8529
8530                 method = cfg->method_to_register;
8531
8532                 encode_method_ref (acfg, method, p, &p);
8533
8534                 g_assert ((p - buf) < buf_size);
8535
8536                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8537                 g_free (buf);
8538         }
8539
8540         /*
8541          * Construct a chained hash table for mapping indexes in extra_method_info to
8542          * method indexes.
8543          */
8544         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8545         table = g_ptr_array_sized_new (table_size);
8546         for (i = 0; i < table_size; ++i)
8547                 g_ptr_array_add (table, NULL);
8548         chain_lengths = g_new0 (int, table_size);
8549         max_chain_length = 0;
8550         for (i = 0; i < acfg->extra_methods->len; ++i) {
8551                 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8552                 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8553                 guint32 key, value;
8554
8555                 if (!cfg)
8556                         continue;
8557
8558                 key = info_offsets [i];
8559                 value = get_method_index (acfg, method);
8560
8561                 hash = mono_aot_method_hash (method) % table_size;
8562                 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8563
8564                 chain_lengths [hash] ++;
8565                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8566
8567                 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8568                 new_entry->key = key;
8569                 new_entry->value = value;
8570
8571                 entry = (HashEntry *)g_ptr_array_index (table, hash);
8572                 if (entry == NULL) {
8573                         new_entry->index = hash;
8574                         g_ptr_array_index (table, hash) = new_entry;
8575                 } else {
8576                         while (entry->next)
8577                                 entry = entry->next;
8578                         
8579                         entry->next = new_entry;
8580                         new_entry->index = table->len;
8581                         g_ptr_array_add (table, new_entry);
8582                 }
8583         }
8584
8585         //printf ("MAX: %d\n", max_chain_length);
8586
8587         buf_size = table->len * 12 + 4;
8588         p = buf = (guint8 *)g_malloc (buf_size);
8589         encode_int (table_size, p, &p);
8590
8591         for (i = 0; i < table->len; ++i) {
8592                 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8593
8594                 if (entry == NULL) {
8595                         encode_int (0, p, &p);
8596                         encode_int (0, p, &p);
8597                         encode_int (0, p, &p);
8598                 } else {
8599                         //g_assert (entry->key > 0);
8600                         encode_int (entry->key, p, &p);
8601                         encode_int (entry->value, p, &p);
8602                         if (entry->next)
8603                                 encode_int (entry->next->index, p, &p);
8604                         else
8605                                 encode_int (0, p, &p);
8606                 }
8607         }
8608         g_assert (p - buf <= buf_size);
8609
8610         /* Emit the table */
8611         emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8612
8613         /* 
8614          * Emit a table reverse mapping method indexes to their index in extra_method_info.
8615          * This is used by mono_aot_find_jit_info ().
8616          */
8617         buf_size = acfg->extra_methods->len * 8 + 4;
8618         p = buf = (guint8 *)g_malloc (buf_size);
8619         encode_int (acfg->extra_methods->len, p, &p);
8620         for (i = 0; i < acfg->extra_methods->len; ++i) {
8621                 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8622
8623                 encode_int (get_method_index (acfg, method), p, &p);
8624                 encode_int (info_offsets [i], p, &p);
8625         }
8626         emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8627 }       
8628
8629 static void
8630 emit_exception_info (MonoAotCompile *acfg)
8631 {
8632         int i;
8633         gint32 *offsets;
8634         SeqPointData sp_data;
8635         gboolean seq_points_to_file = FALSE;
8636
8637         offsets = g_new0 (gint32, acfg->nmethods);
8638         for (i = 0; i < acfg->nmethods; ++i) {
8639                 if (acfg->cfgs [i]) {
8640                         MonoCompile *cfg = acfg->cfgs [i];
8641
8642                         // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8643                         // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8644                         gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8645                                 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8646                         gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8647                         
8648                         emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8649                         offsets [i] = cfg->ex_info_offset;
8650
8651                         if (method_seq_points_to_file) {
8652                                 if (!seq_points_to_file) {
8653                                         mono_seq_point_data_init (&sp_data, acfg->nmethods);
8654                                         seq_points_to_file = TRUE;
8655                                 }
8656                                 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8657                         }
8658                 } else {
8659                         offsets [i] = 0;
8660                 }
8661         }
8662
8663         if (seq_points_to_file) {
8664                 char *seq_points_aot_file = acfg->aot_opts.gen_seq_points_file_path ? acfg->aot_opts.gen_seq_points_file_path
8665                         : g_strdup_printf("%s%s", acfg->image->name, SEQ_POINT_AOT_EXT);
8666                 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8667                 mono_seq_point_data_free (&sp_data);
8668                 g_free (seq_points_aot_file);
8669         }
8670
8671         acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8672         g_free (offsets);
8673 }
8674
8675 static void
8676 emit_unwind_info (MonoAotCompile *acfg)
8677 {
8678         int i;
8679         char symbol [128];
8680
8681         if (acfg->aot_opts.llvm_only) {
8682                 g_assert (acfg->unwind_ops->len == 0);
8683                 return;
8684         }
8685
8686         /* 
8687          * The unwind info contains a lot of duplicates so we emit each unique
8688          * entry once, and only store the offset from the start of the table in the
8689          * exception info.
8690          */
8691
8692         sprintf (symbol, "unwind_info");
8693         emit_section_change (acfg, RODATA_SECT, 1);
8694         emit_alignment (acfg, 8);
8695         emit_info_symbol (acfg, symbol);
8696
8697         for (i = 0; i < acfg->unwind_ops->len; ++i) {
8698                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8699                 guint8 *unwind_info;
8700                 guint32 unwind_info_len;
8701                 guint8 buf [16];
8702                 guint8 *p;
8703
8704                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8705
8706                 p = buf;
8707                 encode_value (unwind_info_len, p, &p);
8708                 emit_bytes (acfg, buf, p - buf);
8709                 emit_bytes (acfg, unwind_info, unwind_info_len);
8710
8711                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8712         }
8713 }
8714
8715 static void
8716 emit_class_info (MonoAotCompile *acfg)
8717 {
8718         int i;
8719         gint32 *offsets;
8720
8721         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8722         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8723                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8724
8725         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);
8726         g_free (offsets);
8727 }
8728
8729 typedef struct ClassNameTableEntry {
8730         guint32 token, index;
8731         struct ClassNameTableEntry *next;
8732 } ClassNameTableEntry;
8733
8734 static void
8735 emit_class_name_table (MonoAotCompile *acfg)
8736 {
8737         int i, table_size, buf_size;
8738         guint32 token, hash;
8739         MonoClass *klass;
8740         GPtrArray *table;
8741         char *full_name;
8742         guint8 *buf, *p;
8743         ClassNameTableEntry *entry, *new_entry;
8744
8745         /*
8746          * Construct a chained hash table for mapping class names to typedef tokens.
8747          */
8748         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8749         table = g_ptr_array_sized_new (table_size);
8750         for (i = 0; i < table_size; ++i)
8751                 g_ptr_array_add (table, NULL);
8752         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8753                 MonoError error;
8754                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8755                 klass = mono_class_get_checked (acfg->image, token, &error);
8756                 if (!klass) {
8757                         mono_error_cleanup (&error);
8758                         continue;
8759                 }
8760                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8761                 hash = mono_metadata_str_hash (full_name) % table_size;
8762                 g_free (full_name);
8763
8764                 /* FIXME: Allocate from the mempool */
8765                 new_entry = g_new0 (ClassNameTableEntry, 1);
8766                 new_entry->token = token;
8767
8768                 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
8769                 if (entry == NULL) {
8770                         new_entry->index = hash;
8771                         g_ptr_array_index (table, hash) = new_entry;
8772                 } else {
8773                         while (entry->next)
8774                                 entry = entry->next;
8775                         
8776                         entry->next = new_entry;
8777                         new_entry->index = table->len;
8778                         g_ptr_array_add (table, new_entry);
8779                 }
8780         }
8781
8782         /* Emit the table */
8783         buf_size = table->len * 4 + 4;
8784         p = buf = (guint8 *)g_malloc0 (buf_size);
8785
8786         /* FIXME: Optimize memory usage */
8787         g_assert (table_size < 65000);
8788         encode_int16 (table_size, p, &p);
8789         g_assert (table->len < 65000);
8790         for (i = 0; i < table->len; ++i) {
8791                 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
8792
8793                 if (entry == NULL) {
8794                         encode_int16 (0, p, &p);
8795                         encode_int16 (0, p, &p);
8796                 } else {
8797                         encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8798                         if (entry->next)
8799                                 encode_int16 (entry->next->index, p, &p);
8800                         else
8801                                 encode_int16 (0, p, &p);
8802                 }
8803         }
8804         g_assert (p - buf <= buf_size);
8805
8806         emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
8807 }
8808
8809 static void
8810 emit_image_table (MonoAotCompile *acfg)
8811 {
8812         int i, buf_size;
8813         guint8 *buf, *p;
8814
8815         /*
8816          * The image table is small but referenced in a lot of places.
8817          * So we emit it at once, and reference its elements by an index.
8818          */
8819         buf_size = acfg->image_table->len * 28 + 4;
8820         for (i = 0; i < acfg->image_table->len; i++) {
8821                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8822                 MonoAssemblyName *aname = &image->assembly->aname;
8823
8824                 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8825         }
8826
8827         buf = p = (guint8 *)g_malloc0 (buf_size);
8828         encode_int (acfg->image_table->len, p, &p);
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                 /* FIXME: Support multi-module assemblies */
8834                 g_assert (image->assembly->image == image);
8835
8836                 encode_string (image->assembly_name, p, &p);
8837                 encode_string (image->guid, p, &p);
8838                 encode_string (aname->culture ? aname->culture : "", p, &p);
8839                 encode_string ((const char*)aname->public_key_token, p, &p);
8840
8841                 while (GPOINTER_TO_UINT (p) % 8 != 0)
8842                         p ++;
8843
8844                 encode_int (aname->flags, p, &p);
8845                 encode_int (aname->major, p, &p);
8846                 encode_int (aname->minor, p, &p);
8847                 encode_int (aname->build, p, &p);
8848                 encode_int (aname->revision, p, &p);
8849         }
8850         g_assert (p - buf <= buf_size);
8851
8852         emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
8853
8854         g_free (buf);
8855 }
8856
8857 static void
8858 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8859 {
8860         int i, first_plt_got_patch = 0, buf_size;
8861         guint8 *p, *buf;
8862         guint32 *got_info_offsets;
8863         GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8864
8865         /* Add the patches needed by the PLT to the GOT */
8866         if (!llvm) {
8867                 acfg->plt_got_offset_base = acfg->got_offset;
8868                 first_plt_got_patch = info->got_patches->len;
8869                 for (i = 1; i < acfg->plt_offset; ++i) {
8870                         MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8871
8872                         g_ptr_array_add (info->got_patches, plt_entry->ji);
8873
8874                         acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8875                 }
8876
8877                 acfg->got_offset += acfg->plt_offset;
8878         }
8879
8880         /**
8881          * FIXME: 
8882          * - optimize offsets table.
8883          * - reduce number of exported symbols.
8884          * - emit info for a klass only once.
8885          * - determine when a method uses a GOT slot which is guaranteed to be already 
8886          *   initialized.
8887          * - clean up and document the code.
8888          * - use String.Empty in class libs.
8889          */
8890
8891         /* Encode info required to decode shared GOT entries */
8892         buf_size = info->got_patches->len * 128;
8893         p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
8894         got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8895         if (!llvm) {
8896                 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8897                 /* Unused */
8898                 if (acfg->plt_offset)
8899                         acfg->plt_got_info_offsets [0] = 0;
8900         }
8901         for (i = 0; i < info->got_patches->len; ++i) {
8902                 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
8903                 guint8 *p2;
8904
8905                 p = buf;
8906
8907                 encode_value (ji->type, p, &p);
8908                 p2 = p;
8909                 encode_patch (acfg, ji, p, &p);
8910                 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8911                 g_assert (p - buf <= buf_size);
8912                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8913
8914                 if (!llvm && i >= first_plt_got_patch)
8915                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8916                 acfg->stats.got_info_size += p - buf;
8917         }
8918
8919         /* Emit got_info_offsets table */
8920
8921         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8922         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);
8923 }
8924
8925 static void
8926 emit_got (MonoAotCompile *acfg)
8927 {
8928         char symbol [256];
8929
8930         if (acfg->aot_opts.llvm_only)
8931                 return;
8932
8933         /* Don't make GOT global so accesses to it don't need relocations */
8934         sprintf (symbol, "%s", acfg->got_symbol);
8935
8936 #ifdef TARGET_MACH
8937         emit_unset_mode (acfg);
8938         fprintf (acfg->fp, ".section __DATA, __bss\n");
8939         emit_alignment (acfg, 8);
8940         if (acfg->llvm)
8941                 emit_info_symbol (acfg, "jit_got");
8942         fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8943 #else
8944         emit_section_change (acfg, ".bss", 0);
8945         emit_alignment (acfg, 8);
8946         emit_local_symbol (acfg, symbol, "got_end", FALSE);
8947         emit_label (acfg, symbol);
8948         if (acfg->llvm)
8949                 emit_info_symbol (acfg, "jit_got");
8950         if (acfg->got_offset > 0)
8951                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8952 #endif
8953
8954         sprintf (symbol, "got_end");
8955         emit_label (acfg, symbol);
8956 }
8957
8958 typedef struct GlobalsTableEntry {
8959         guint32 value, index;
8960         struct GlobalsTableEntry *next;
8961 } GlobalsTableEntry;
8962
8963 static void
8964 emit_globals (MonoAotCompile *acfg)
8965 {
8966         int i, table_size;
8967         guint32 hash;
8968         GPtrArray *table;
8969         char symbol [1024];
8970         GlobalsTableEntry *entry, *new_entry;
8971
8972         if (!acfg->aot_opts.static_link)
8973                 return;
8974         if (acfg->aot_opts.llvm_only) {
8975                 g_assert (acfg->globals->len == 0);
8976                 return;
8977         }
8978
8979         /* 
8980          * When static linking, we emit a table containing our globals.
8981          */
8982
8983         /*
8984          * Construct a chained hash table for mapping global names to their index in
8985          * the globals table.
8986          */
8987         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8988         table = g_ptr_array_sized_new (table_size);
8989         for (i = 0; i < table_size; ++i)
8990                 g_ptr_array_add (table, NULL);
8991         for (i = 0; i < acfg->globals->len; ++i) {
8992                 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8993
8994                 hash = mono_metadata_str_hash (name) % table_size;
8995
8996                 /* FIXME: Allocate from the mempool */
8997                 new_entry = g_new0 (GlobalsTableEntry, 1);
8998                 new_entry->value = i;
8999
9000                 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9001                 if (entry == NULL) {
9002                         new_entry->index = hash;
9003                         g_ptr_array_index (table, hash) = new_entry;
9004                 } else {
9005                         while (entry->next)
9006                                 entry = entry->next;
9007                         
9008                         entry->next = new_entry;
9009                         new_entry->index = table->len;
9010                         g_ptr_array_add (table, new_entry);
9011                 }
9012         }
9013
9014         /* Emit the table */
9015         sprintf (symbol, ".Lglobals_hash");
9016         emit_section_change (acfg, RODATA_SECT, 0);
9017         emit_alignment (acfg, 8);
9018         emit_label (acfg, symbol);
9019
9020         /* FIXME: Optimize memory usage */
9021         g_assert (table_size < 65000);
9022         emit_int16 (acfg, table_size);
9023         for (i = 0; i < table->len; ++i) {
9024                 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9025
9026                 if (entry == NULL) {
9027                         emit_int16 (acfg, 0);
9028                         emit_int16 (acfg, 0);
9029                 } else {
9030                         emit_int16 (acfg, entry->value + 1);
9031                         if (entry->next)
9032                                 emit_int16 (acfg, entry->next->index);
9033                         else
9034                                 emit_int16 (acfg, 0);
9035                 }
9036         }
9037
9038         /* Emit the names */
9039         for (i = 0; i < acfg->globals->len; ++i) {
9040                 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9041
9042                 sprintf (symbol, "name_%d", i);
9043                 emit_section_change (acfg, RODATA_SECT, 1);
9044 #ifdef TARGET_MACH
9045                 emit_alignment (acfg, 4);
9046 #endif
9047                 emit_label (acfg, symbol);
9048                 emit_string (acfg, name);
9049         }
9050
9051         /* Emit the globals table */
9052         sprintf (symbol, "globals");
9053         emit_section_change (acfg, ".data", 0);
9054         /* This is not a global, since it is accessed by the init function */
9055         emit_alignment (acfg, 8);
9056         emit_info_symbol (acfg, symbol);
9057
9058         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9059         emit_pointer (acfg, symbol);
9060
9061         for (i = 0; i < acfg->globals->len; ++i) {
9062                 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9063
9064                 sprintf (symbol, "name_%d", i);
9065                 emit_pointer (acfg, symbol);
9066
9067                 g_assert (strlen (name) < sizeof (symbol));
9068                 sprintf (symbol, "%s", name);
9069                 emit_pointer (acfg, symbol);
9070         }
9071         /* Null terminate the table */
9072         emit_int32 (acfg, 0);
9073         emit_int32 (acfg, 0);
9074 }
9075
9076 static void
9077 emit_mem_end (MonoAotCompile *acfg)
9078 {
9079         char symbol [128];
9080
9081         if (acfg->aot_opts.llvm_only)
9082                 return;
9083
9084         sprintf (symbol, "mem_end");
9085         emit_section_change (acfg, ".text", 1);
9086         emit_alignment_code (acfg, 8);
9087         emit_label (acfg, symbol);
9088 }
9089
9090 static void
9091 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9092 {
9093         int i;
9094
9095         info->version = MONO_AOT_FILE_VERSION;
9096         info->plt_got_offset_base = acfg->plt_got_offset_base;
9097         info->got_size = acfg->got_offset * sizeof (gpointer);
9098         info->plt_size = acfg->plt_offset;
9099         info->nmethods = acfg->nmethods;
9100         info->flags = acfg->flags;
9101         info->opts = acfg->opts;
9102         info->simd_opts = acfg->simd_opts;
9103         info->gc_name_index = acfg->gc_name_offset;
9104         info->datafile_size = acfg->datafile_offset;
9105         for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9106                 info->table_offsets [i] = acfg->table_offsets [i];
9107         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9108                 info->num_trampolines [i] = acfg->num_trampolines [i];
9109         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9110                 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9111         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9112                 info->trampoline_size [i] = acfg->trampoline_size [i];
9113         info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9114
9115         info->double_align = MONO_ABI_ALIGNOF (double);
9116         info->long_align = MONO_ABI_ALIGNOF (gint64);
9117         info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9118         info->tramp_page_size = acfg->tramp_page_size;
9119         info->nshared_got_entries = acfg->nshared_got_entries;
9120         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9121                 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9122 }
9123
9124 static void
9125 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9126 {
9127         char symbol [256];
9128         int i, sindex;
9129         const char **symbols;
9130
9131         symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9132         sindex = 0;
9133         symbols [sindex ++] = acfg->got_symbol;
9134         if (acfg->llvm) {
9135                 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9136                 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9137         } else {
9138                 symbols [sindex ++] = NULL;
9139                 symbols [sindex ++] = NULL;
9140         }
9141         /* llvm_get_method */
9142         symbols [sindex ++] = NULL;
9143         /* llvm_get_unbox_tramp */
9144         symbols [sindex ++] = NULL;
9145         if (!acfg->aot_opts.llvm_only) {
9146                 symbols [sindex ++] = "jit_code_start";
9147                 symbols [sindex ++] = "jit_code_end";
9148                 symbols [sindex ++] = "method_addresses";
9149         } else {
9150                 symbols [sindex ++] = NULL;
9151                 symbols [sindex ++] = NULL;
9152                 symbols [sindex ++] = NULL;
9153         }
9154         if (acfg->data_outfile) {
9155                 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9156                         symbols [sindex ++] = NULL;
9157         } else {
9158                 symbols [sindex ++] = "blob";
9159                 symbols [sindex ++] = "class_name_table";
9160                 symbols [sindex ++] = "class_info_offsets";
9161                 symbols [sindex ++] = "method_info_offsets";
9162                 symbols [sindex ++] = "ex_info_offsets";
9163                 symbols [sindex ++] = "extra_method_info_offsets";
9164                 symbols [sindex ++] = "extra_method_table";
9165                 symbols [sindex ++] = "got_info_offsets";
9166                 if (acfg->llvm)
9167                         symbols [sindex ++] = "llvm_got_info_offsets";
9168                 else
9169                         symbols [sindex ++] = NULL;
9170                 symbols [sindex ++] = "image_table";
9171         }
9172         symbols [sindex ++] = "mem_end";
9173         symbols [sindex ++] = "assembly_guid";
9174         symbols [sindex ++] = "runtime_version";
9175         if (acfg->num_trampoline_got_entries) {
9176                 symbols [sindex ++] = "specific_trampolines";
9177                 symbols [sindex ++] = "static_rgctx_trampolines";
9178                 symbols [sindex ++] = "imt_thunks";
9179                 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9180         } else {
9181                 symbols [sindex ++] = NULL;
9182                 symbols [sindex ++] = NULL;
9183                 symbols [sindex ++] = NULL;
9184                 symbols [sindex ++] = NULL;
9185         }
9186         if (acfg->aot_opts.static_link) {
9187                 symbols [sindex ++] = "globals";
9188         } else {
9189                 symbols [sindex ++] = NULL;
9190         }
9191         symbols [sindex ++] = "assembly_name";
9192         symbols [sindex ++] = "plt";
9193         symbols [sindex ++] = "plt_end";
9194         symbols [sindex ++] = "unwind_info";
9195         if (!acfg->aot_opts.llvm_only) {
9196                 symbols [sindex ++] = "unbox_trampolines";
9197                 symbols [sindex ++] = "unbox_trampolines_end";
9198                 symbols [sindex ++] = "unbox_trampoline_addresses";
9199         } else {
9200                 symbols [sindex ++] = NULL;
9201                 symbols [sindex ++] = NULL;
9202                 symbols [sindex ++] = NULL;
9203         }
9204
9205         g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9206
9207         sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9208         emit_section_change (acfg, ".data", 0);
9209         emit_alignment (acfg, 8);
9210         emit_label (acfg, symbol);
9211         if (!acfg->aot_opts.static_link)
9212                 emit_global (acfg, symbol, FALSE);
9213
9214         /* The data emitted here must match MonoAotFileInfo. */
9215
9216         emit_int32 (acfg, info->version);
9217         emit_int32 (acfg, info->dummy);
9218
9219         /* 
9220          * We emit pointers to our data structures instead of emitting global symbols which
9221          * point to them, to reduce the number of globals, and because using globals leads to
9222          * various problems (i.e. arm/thumb).
9223          */
9224         for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9225                 emit_pointer (acfg, symbols [i]);
9226
9227         emit_int32 (acfg, info->plt_got_offset_base);
9228         emit_int32 (acfg, info->got_size);
9229         emit_int32 (acfg, info->plt_size);
9230         emit_int32 (acfg, info->nmethods);
9231         emit_int32 (acfg, info->flags);
9232         emit_int32 (acfg, info->opts);
9233         emit_int32 (acfg, info->simd_opts);
9234         emit_int32 (acfg, info->gc_name_index);
9235         emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9236         emit_int32 (acfg, info->double_align);
9237         emit_int32 (acfg, info->long_align);
9238         emit_int32 (acfg, info->generic_tramp_num);
9239         emit_int32 (acfg, info->tramp_page_size);
9240         emit_int32 (acfg, info->nshared_got_entries);
9241         emit_int32 (acfg, info->datafile_size);
9242
9243         for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9244                 emit_int32 (acfg, info->table_offsets [i]);
9245         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9246                 emit_int32 (acfg, info->num_trampolines [i]);
9247         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9248                 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9249         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9250                 emit_int32 (acfg, info->trampoline_size [i]);
9251         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9252                 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9253
9254         if (acfg->aot_opts.static_link) {
9255                 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9256                 emit_alignment (acfg, sizeof (gpointer));
9257                 emit_label (acfg, acfg->static_linking_symbol);
9258                 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9259         }
9260 }
9261
9262 /*
9263  * Emit a structure containing all the information not stored elsewhere.
9264  */
9265 static void
9266 emit_file_info (MonoAotCompile *acfg)
9267 {
9268         char *build_info;
9269         MonoAotFileInfo *info;
9270
9271         if (acfg->aot_opts.bind_to_runtime_version) {
9272                 build_info = mono_get_runtime_build_info ();
9273                 emit_string_symbol (acfg, "runtime_version", build_info);
9274                 g_free (build_info);
9275         } else {
9276                 emit_string_symbol (acfg, "runtime_version", "");
9277         }
9278
9279         emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9280
9281         /* Emit a string holding the assembly name */
9282         emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9283
9284         info = g_new0 (MonoAotFileInfo, 1);
9285         init_aot_file_info (acfg, info);
9286
9287         if (acfg->aot_opts.static_link) {
9288                 char symbol [256];
9289                 char *p;
9290
9291                 /*
9292                  * Emit a global symbol which can be passed by an embedding app to
9293                  * mono_aot_register_module (). The symbol points to a pointer to the the file info
9294                  * structure.
9295                  */
9296                 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9297
9298                 /* Get rid of characters which cannot occur in symbols */
9299                 p = symbol;
9300                 for (p = symbol; *p; ++p) {
9301                         if (!(isalnum (*p) || *p == '_'))
9302                                 *p = '_';
9303                 }
9304                 acfg->static_linking_symbol = g_strdup (symbol);
9305         }
9306
9307         if (acfg->llvm)
9308                 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9309         else
9310                 emit_aot_file_info (acfg, info);
9311 }
9312
9313 static void
9314 emit_blob (MonoAotCompile *acfg)
9315 {
9316         acfg->blob_closed = TRUE;
9317
9318         emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9319 }
9320
9321 static void
9322 emit_objc_selectors (MonoAotCompile *acfg)
9323 {
9324         int i;
9325         char symbol [128];
9326
9327         if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9328                 return;
9329
9330         /*
9331          * From
9332          * cat > foo.m << EOF
9333          * void *ret ()
9334          * {
9335          * return @selector(print:);
9336          * }
9337          * EOF
9338          */
9339
9340         mono_img_writer_emit_unset_mode (acfg->w);
9341         g_assert (acfg->fp);
9342         fprintf (acfg->fp, ".section    __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9343         fprintf (acfg->fp, ".align      3\n");
9344         for (i = 0; i < acfg->objc_selectors->len; ++i) {
9345                 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9346                 emit_label (acfg, symbol);
9347                 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9348                 emit_pointer (acfg, symbol);
9349
9350         }
9351         fprintf (acfg->fp, ".section    __TEXT,__cstring,cstring_literals\n");
9352         for (i = 0; i < acfg->objc_selectors->len; ++i) {
9353                 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9354                 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9355         }
9356
9357         fprintf (acfg->fp, ".section    __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9358         fprintf (acfg->fp, ".align      3\n");
9359         fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9360         fprintf (acfg->fp, ".long       0\n");
9361         fprintf (acfg->fp, ".long       16\n");
9362 }
9363
9364 static void
9365 emit_dwarf_info (MonoAotCompile *acfg)
9366 {
9367 #ifdef EMIT_DWARF_INFO
9368         int i;
9369         char symbol2 [128];
9370
9371         /* DIEs for methods */
9372         for (i = 0; i < acfg->nmethods; ++i) {
9373                 MonoCompile *cfg = acfg->cfgs [i];
9374
9375                 if (!cfg)
9376                         continue;
9377
9378                 // FIXME: LLVM doesn't define .Lme_...
9379                 if (cfg->compile_llvm)
9380                         continue;
9381
9382                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9383
9384                 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 ()));
9385         }
9386 #endif
9387 }
9388
9389 static gboolean
9390 collect_methods (MonoAotCompile *acfg)
9391 {
9392         int mindex, i;
9393         MonoImage *image = acfg->image;
9394
9395         /* Collect methods */
9396         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9397                 MonoError error;
9398                 MonoMethod *method;
9399                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9400
9401                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9402
9403                 if (!method) {
9404                         aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9405                         aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9406                         mono_error_cleanup (&error);
9407                         return FALSE;
9408                 }
9409                         
9410                 /* Load all methods eagerly to skip the slower lazy loading code */
9411                 mono_class_setup_methods (method->klass);
9412
9413                 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9414                         /* Compile the wrapper instead */
9415                         /* We do this here instead of add_wrappers () because it is easy to do it here */
9416                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9417                         method = wrapper;
9418                 }
9419
9420                 /* FIXME: Some mscorlib methods don't have debug info */
9421                 /*
9422                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9423                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9424                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9425                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9426                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9427                                 if (!mono_debug_lookup_method (method)) {
9428                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9429                                         exit (1);
9430                                 }
9431                         }
9432                 }
9433                 */
9434
9435                 if (method->is_generic || method->klass->generic_container)
9436                         /* Compile the ref shared version instead */
9437                         method = mini_get_shared_method (method);
9438
9439                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9440                 add_method_with_index (acfg, method, i, FALSE);
9441                 acfg->method_index ++;
9442         }
9443
9444         /* gsharedvt methods */
9445         for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9446                 MonoError error;
9447                 MonoMethod *method;
9448                 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9449
9450                 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9451                         continue;
9452
9453                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9454                 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9455
9456                 if (method->is_generic || method->klass->generic_container) {
9457                         MonoMethod *gshared;
9458
9459                         gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9460                         add_extra_method (acfg, gshared);
9461                 }
9462         }
9463
9464         add_generic_instances (acfg);
9465
9466         if (mono_aot_mode_is_full (&acfg->aot_opts))
9467                 add_wrappers (acfg);
9468         return TRUE;
9469 }
9470
9471 static void
9472 compile_methods (MonoAotCompile *acfg)
9473 {
9474         int i, methods_len;
9475
9476         if (acfg->aot_opts.nthreads > 0) {
9477                 GPtrArray *frag;
9478                 int len, j;
9479                 GPtrArray *threads;
9480                 HANDLE handle;
9481                 gpointer *user_data;
9482                 MonoMethod **methods;
9483
9484                 methods_len = acfg->methods->len;
9485
9486                 len = acfg->methods->len / acfg->aot_opts.nthreads;
9487                 g_assert (len > 0);
9488                 /* 
9489                  * Partition the list of methods into fragments, and hand it to threads to
9490                  * process.
9491                  */
9492                 threads = g_ptr_array_new ();
9493                 /* Make a copy since acfg->methods is modified by compile_method () */
9494                 methods = g_new0 (MonoMethod*, methods_len);
9495                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9496                 for (i = 0; i < methods_len; ++i)
9497                         methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9498                 i = 0;
9499                 while (i < methods_len) {
9500                         frag = g_ptr_array_new ();
9501                         for (j = 0; j < len; ++j) {
9502                                 if (i < methods_len) {
9503                                         g_ptr_array_add (frag, methods [i]);
9504                                         i ++;
9505                                 }
9506                         }
9507
9508                         user_data = g_new0 (gpointer, 3);
9509                         user_data [0] = mono_domain_get ();
9510                         user_data [1] = acfg;
9511                         user_data [2] = frag;
9512                         
9513                         handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9514                         g_ptr_array_add (threads, handle);
9515                 }
9516                 g_free (methods);
9517
9518                 for (i = 0; i < threads->len; ++i) {
9519                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9520                 }
9521         } else {
9522                 methods_len = 0;
9523         }
9524
9525         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9526         for (i = methods_len; i < acfg->methods->len; ++i) {
9527                 /* This can new methods to acfg->methods */
9528                 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9529         }
9530 }
9531
9532 static int
9533 compile_asm (MonoAotCompile *acfg)
9534 {
9535         char *command, *objfile;
9536         char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9537         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9538         char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9539
9540 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9541 #define AS_OPTIONS "--64"
9542 #elif defined(TARGET_POWERPC64)
9543 #define AS_OPTIONS "-a64 -mppc64"
9544 #define LD_OPTIONS "-m elf64ppc"
9545 #elif defined(sparc) && SIZEOF_VOID_P == 8
9546 #define AS_OPTIONS "-xarch=v9"
9547 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9548 #define AS_OPTIONS "-arch i386"
9549 #else
9550 #define AS_OPTIONS ""
9551 #endif
9552
9553 #ifdef __native_client_codegen__
9554 #if defined(TARGET_AMD64)
9555 #define AS_NAME "nacl64-as"
9556 #else
9557 #define AS_NAME "nacl-as"
9558 #endif
9559 #elif defined(TARGET_OSX)
9560 #define AS_NAME "clang"
9561 #else
9562 #define AS_NAME "as"
9563 #endif
9564
9565 #ifndef LD_OPTIONS
9566 #define LD_OPTIONS ""
9567 #endif
9568
9569 #if defined(sparc)
9570 #define LD_NAME "ld -shared -G"
9571 #elif defined(__ppc__) && defined(TARGET_MACH)
9572 #define LD_NAME "gcc -dynamiclib"
9573 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9574 #define LD_NAME "clang --shared"
9575 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9576 #define LD_NAME "gcc -shared --dll"
9577 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9578 #define LD_NAME "clang -m32 -dynamiclib"
9579 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9580 #define LD_NAME "gcc --shared"
9581 #endif
9582
9583         if (acfg->aot_opts.asm_only) {
9584                 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9585                 if (acfg->aot_opts.static_link)
9586                         aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9587                 if (acfg->llvm)
9588                         aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9589                 return 0;
9590         }
9591
9592         if (acfg->aot_opts.static_link) {
9593                 if (acfg->aot_opts.outfile)
9594                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9595                 else
9596                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
9597         } else {
9598                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9599         }
9600
9601 #ifdef TARGET_OSX
9602         g_string_append (acfg->as_args, "-c -x assembler");
9603 #endif
9604
9605         command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9606                         acfg->as_args ? acfg->as_args->str : "", 
9607                         wrap_path (objfile), wrap_path (acfg->tmpfname));
9608         aot_printf (acfg, "Executing the native assembler: %s\n", command);
9609         if (execute_system (command) != 0) {
9610                 g_free (command);
9611                 g_free (objfile);
9612                 return 1;
9613         }
9614
9615         if (acfg->llvm && !acfg->llvm_owriter) {
9616                 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9617                         acfg->as_args ? acfg->as_args->str : "",
9618                         wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9619                 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9620                 if (execute_system (command) != 0) {
9621                         g_free (command);
9622                         g_free (objfile);
9623                         return 1;
9624                 }
9625         }
9626
9627         g_free (command);
9628
9629         if (acfg->aot_opts.static_link) {
9630                 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9631                 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9632                 g_free (objfile);
9633                 return 0;
9634         }
9635
9636         if (acfg->aot_opts.outfile)
9637                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9638         else
9639                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9640
9641         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9642
9643         if (acfg->llvm) {
9644                 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9645         } else {
9646                 llvm_ofile = g_strdup ("");
9647         }
9648
9649         /* replace the ; flags separators with spaces */
9650         g_strdelimit (ld_flags, ";", ' ');
9651
9652         if (acfg->aot_opts.llvm_only)
9653                 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9654
9655 #ifdef LD_NAME
9656         command = g_strdup_printf ("%s -o %s %s %s %s", LD_NAME,
9657                 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9658                 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9659 #else
9660         command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9661                 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9662                 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9663 #endif
9664         aot_printf (acfg, "Executing the native linker: %s\n", command);
9665         if (execute_system (command) != 0) {
9666                 g_free (tmp_outfile_name);
9667                 g_free (outfile_name);
9668                 g_free (command);
9669                 g_free (objfile);
9670                 g_free (ld_flags);
9671                 return 1;
9672         }
9673
9674         g_free (command);
9675
9676         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9677         printf ("Stripping the binary: %s\n", com);
9678         execute_system (com);
9679         g_free (com);*/
9680
9681 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9682         /* 
9683          * gas generates 'mapping symbols' each time code and data is mixed, which 
9684          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9685          */
9686         command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9687         aot_printf (acfg, "Stripping the binary: %s\n", command);
9688         if (execute_system (command) != 0) {
9689                 g_free (tmp_outfile_name);
9690                 g_free (outfile_name);
9691                 g_free (command);
9692                 g_free (objfile);
9693                 return 1;
9694         }
9695 #endif
9696
9697         rename (tmp_outfile_name, outfile_name);
9698
9699 #if defined(TARGET_MACH)
9700         command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9701         aot_printf (acfg, "Executing dsymutil: %s\n", command);
9702         if (execute_system (command) != 0) {
9703                 return 1;
9704         }
9705 #endif
9706
9707         if (!acfg->aot_opts.save_temps)
9708                 unlink (objfile);
9709
9710         g_free (tmp_outfile_name);
9711         g_free (outfile_name);
9712         g_free (objfile);
9713
9714         if (acfg->aot_opts.save_temps)
9715                 aot_printf (acfg, "Retained input file.\n");
9716         else
9717                 unlink (acfg->tmpfname);
9718
9719         return 0;
9720 }
9721
9722 static void init_got_info (GotInfo *info)
9723 {
9724         int i;
9725
9726         info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9727         info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9728         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9729                 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9730         info->got_patches = g_ptr_array_new ();
9731 }
9732
9733 static MonoAotCompile*
9734 acfg_create (MonoAssembly *ass, guint32 opts)
9735 {
9736         MonoImage *image = ass->image;
9737         MonoAotCompile *acfg;
9738
9739         acfg = g_new0 (MonoAotCompile, 1);
9740         acfg->methods = g_ptr_array_new ();
9741         acfg->method_indexes = g_hash_table_new (NULL, NULL);
9742         acfg->method_depth = g_hash_table_new (NULL, NULL);
9743         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9744         acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9745         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9746         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9747         acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9748         acfg->image_hash = g_hash_table_new (NULL, NULL);
9749         acfg->image_table = g_ptr_array_new ();
9750         acfg->globals = g_ptr_array_new ();
9751         acfg->image = image;
9752         acfg->opts = opts;
9753         /* TODO: Write out set of SIMD instructions used, rather than just those available */
9754         acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9755         acfg->mempool = mono_mempool_new ();
9756         acfg->extra_methods = g_ptr_array_new ();
9757         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9758         acfg->unwind_ops = g_ptr_array_new ();
9759         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9760         acfg->method_order = g_ptr_array_new ();
9761         acfg->export_names = g_hash_table_new (NULL, NULL);
9762         acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9763         acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9764         acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9765         acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9766         acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9767         mono_os_mutex_init_recursive (&acfg->mutex);
9768
9769         init_got_info (&acfg->got_info);
9770         init_got_info (&acfg->llvm_got_info);
9771
9772         return acfg;
9773 }
9774
9775 static void
9776 got_info_free (GotInfo *info)
9777 {
9778         int i;
9779
9780         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9781                 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9782         g_free (info->patch_to_got_offset_by_type);
9783         g_hash_table_destroy (info->patch_to_got_offset);
9784         g_ptr_array_free (info->got_patches, TRUE);
9785 }
9786
9787 static void
9788 acfg_free (MonoAotCompile *acfg)
9789 {
9790         int i;
9791
9792         mono_img_writer_destroy (acfg->w);
9793         for (i = 0; i < acfg->nmethods; ++i)
9794                 if (acfg->cfgs [i])
9795                         g_free (acfg->cfgs [i]);
9796         g_free (acfg->cfgs);
9797         g_free (acfg->static_linking_symbol);
9798         g_free (acfg->got_symbol);
9799         g_free (acfg->plt_symbol);
9800         g_ptr_array_free (acfg->methods, TRUE);
9801         g_ptr_array_free (acfg->image_table, TRUE);
9802         g_ptr_array_free (acfg->globals, TRUE);
9803         g_ptr_array_free (acfg->unwind_ops, TRUE);
9804         g_hash_table_destroy (acfg->method_indexes);
9805         g_hash_table_destroy (acfg->method_depth);
9806         g_hash_table_destroy (acfg->plt_offset_to_entry);
9807         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9808                 if (acfg->patch_to_plt_entry [i])
9809                         g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9810         }
9811         g_free (acfg->patch_to_plt_entry);
9812         g_hash_table_destroy (acfg->method_to_cfg);
9813         g_hash_table_destroy (acfg->token_info_hash);
9814         g_hash_table_destroy (acfg->method_to_pinvoke_import);
9815         g_hash_table_destroy (acfg->image_hash);
9816         g_hash_table_destroy (acfg->unwind_info_offsets);
9817         g_hash_table_destroy (acfg->method_label_hash);
9818         g_hash_table_destroy (acfg->export_names);
9819         g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9820         g_hash_table_destroy (acfg->klass_blob_hash);
9821         g_hash_table_destroy (acfg->method_blob_hash);
9822         got_info_free (&acfg->got_info);
9823         got_info_free (&acfg->llvm_got_info);
9824         mono_mempool_destroy (acfg->mempool);
9825         g_free (acfg);
9826 }
9827
9828 #define WRAPPER(e,n) n,
9829 static const char* const
9830 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9831 #include "mono/metadata/wrapper-types.h"
9832         NULL
9833 };
9834
9835 static G_GNUC_UNUSED const char*
9836 get_wrapper_type_name (int type)
9837 {
9838         return wrapper_type_names [type];
9839 }
9840
9841 //#define DUMP_PLT
9842 //#define DUMP_GOT
9843
9844 static void aot_dump (MonoAotCompile *acfg)
9845 {
9846         FILE *dumpfile;
9847         char * dumpname;
9848
9849         JsonWriter writer;
9850         mono_json_writer_init (&writer);
9851
9852         mono_json_writer_object_begin(&writer);
9853
9854         // Methods
9855         mono_json_writer_indent (&writer);
9856         mono_json_writer_object_key(&writer, "methods");
9857         mono_json_writer_array_begin (&writer);
9858
9859         int i;
9860         for (i = 0; i < acfg->nmethods; ++i) {
9861                 MonoCompile *cfg;
9862                 MonoMethod *method;
9863                 MonoClass *klass;
9864
9865                 cfg = acfg->cfgs [i];
9866                 if (!cfg)
9867                         continue;
9868
9869                 method = cfg->orig_method;
9870
9871                 mono_json_writer_indent (&writer);
9872                 mono_json_writer_object_begin(&writer);
9873
9874                 mono_json_writer_indent (&writer);
9875                 mono_json_writer_object_key(&writer, "name");
9876                 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9877
9878                 mono_json_writer_indent (&writer);
9879                 mono_json_writer_object_key(&writer, "signature");
9880                 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
9881
9882                 mono_json_writer_indent (&writer);
9883                 mono_json_writer_object_key(&writer, "code_size");
9884                 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9885
9886                 klass = method->klass;
9887
9888                 mono_json_writer_indent (&writer);
9889                 mono_json_writer_object_key(&writer, "class");
9890                 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9891
9892                 mono_json_writer_indent (&writer);
9893                 mono_json_writer_object_key(&writer, "namespace");
9894                 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9895
9896                 mono_json_writer_indent (&writer);
9897                 mono_json_writer_object_key(&writer, "wrapper_type");
9898                 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9899
9900                 mono_json_writer_indent_pop (&writer);
9901                 mono_json_writer_indent (&writer);
9902                 mono_json_writer_object_end (&writer);
9903                 mono_json_writer_printf (&writer, ",\n");
9904         }
9905
9906         mono_json_writer_indent_pop (&writer);
9907         mono_json_writer_indent (&writer);
9908         mono_json_writer_array_end (&writer);
9909         mono_json_writer_printf (&writer, ",\n");
9910
9911         // PLT entries
9912 #ifdef DUMP_PLT
9913         mono_json_writer_indent_push (&writer);
9914         mono_json_writer_indent (&writer);
9915         mono_json_writer_object_key(&writer, "plt");
9916         mono_json_writer_array_begin (&writer);
9917
9918         for (i = 0; i < acfg->plt_offset; ++i) {
9919                 MonoPltEntry *plt_entry = NULL;
9920                 MonoJumpInfo *ji;
9921
9922                 if (i == 0)
9923                         /* 
9924                          * The first plt entry is unused.
9925                          */
9926                         continue;
9927
9928                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9929                 ji = plt_entry->ji;
9930
9931                 mono_json_writer_indent (&writer);
9932                 mono_json_writer_printf (&writer, "{ ");
9933                 mono_json_writer_object_key(&writer, "symbol");
9934                 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9935         }
9936
9937         mono_json_writer_indent_pop (&writer);
9938         mono_json_writer_indent (&writer);
9939         mono_json_writer_array_end (&writer);
9940         mono_json_writer_printf (&writer, ",\n");
9941 #endif
9942
9943         // GOT entries
9944 #ifdef DUMP_GOT
9945         mono_json_writer_indent_push (&writer);
9946         mono_json_writer_indent (&writer);
9947         mono_json_writer_object_key(&writer, "got");
9948         mono_json_writer_array_begin (&writer);
9949
9950         mono_json_writer_indent_push (&writer);
9951         for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9952                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9953
9954                 mono_json_writer_indent (&writer);
9955                 mono_json_writer_printf (&writer, "{ ");
9956                 mono_json_writer_object_key(&writer, "patch_name");
9957                 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9958         }
9959
9960         mono_json_writer_indent_pop (&writer);
9961         mono_json_writer_indent (&writer);
9962         mono_json_writer_array_end (&writer);
9963         mono_json_writer_printf (&writer, ",\n");
9964 #endif
9965
9966         mono_json_writer_indent_pop (&writer);
9967         mono_json_writer_indent (&writer);
9968         mono_json_writer_object_end (&writer);
9969
9970         dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9971         dumpfile = fopen (dumpname, "w+");
9972         g_free (dumpname);
9973
9974         fprintf (dumpfile, "%s", writer.text->str);
9975         fclose (dumpfile);
9976
9977         mono_json_writer_destroy (&writer);
9978 }
9979
9980 static const char *preinited_jit_icalls[] = {
9981         "mono_aot_init_llvm_method",
9982         "mono_aot_init_gshared_method_this",
9983         "mono_aot_init_gshared_method_mrgctx",
9984         "mono_aot_init_gshared_method_vtable",
9985         "mono_llvm_throw_corlib_exception",
9986         "mono_init_vtable_slot",
9987         "mono_helper_ldstr_mscorlib"
9988 };
9989
9990 static void
9991 add_preinit_got_slots (MonoAotCompile *acfg)
9992 {
9993         MonoJumpInfo *ji;
9994         int i;
9995
9996         /*
9997          * Allocate the first few GOT entries to information which is needed frequently, or it is needed
9998          * during method initialization etc.
9999          */
10000
10001         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10002         ji->type = MONO_PATCH_INFO_IMAGE;
10003         ji->data.image = acfg->image;
10004         get_got_offset (acfg, FALSE, ji);
10005         get_got_offset (acfg, TRUE, ji);
10006
10007         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10008         ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10009         get_got_offset (acfg, FALSE, ji);
10010         get_got_offset (acfg, TRUE, ji);
10011
10012         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10013         ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10014         get_got_offset (acfg, FALSE, ji);
10015         get_got_offset (acfg, TRUE, ji);
10016
10017         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10018         ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10019         get_got_offset (acfg, FALSE, ji);
10020         get_got_offset (acfg, TRUE, ji);
10021
10022         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10023         ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
10024         get_got_offset (acfg, FALSE, ji);
10025         get_got_offset (acfg, TRUE, ji);
10026
10027         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10028         ji->type = MONO_PATCH_INFO_AOT_MODULE;
10029         get_got_offset (acfg, FALSE, ji);
10030         get_got_offset (acfg, TRUE, ji);
10031
10032         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10033         ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10034         get_got_offset (acfg, FALSE, ji);
10035         get_got_offset (acfg, TRUE, ji);
10036
10037         for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10038                 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10039                 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10040                 ji->data.name = preinited_jit_icalls [i];
10041                 get_got_offset (acfg, FALSE, ji);
10042                 get_got_offset (acfg, TRUE, ji);
10043         }
10044
10045         acfg->nshared_got_entries = acfg->got_offset;
10046 }
10047
10048 int
10049 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10050 {
10051         MonoImage *image = ass->image;
10052         int i, res;
10053         gint64 all_sizes;
10054         MonoAotCompile *acfg;
10055         char *outfile_name, *tmp_outfile_name, *p;
10056         char llvm_stats_msg [256];
10057         TV_DECLARE (atv);
10058         TV_DECLARE (btv);
10059
10060         acfg = acfg_create (ass, opts);
10061
10062         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10063         acfg->aot_opts.write_symbols = TRUE;
10064         acfg->aot_opts.ntrampolines = 1024;
10065         acfg->aot_opts.nrgctx_trampolines = 1024;
10066         acfg->aot_opts.nimt_trampolines = 128;
10067         acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10068         acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
10069         acfg->aot_opts.llvm_path = g_strdup ("");
10070         acfg->aot_opts.temp_path = g_strdup ("");
10071 #ifdef MONOTOUCH
10072         acfg->aot_opts.use_trampolines_page = TRUE;
10073 #endif
10074
10075         mono_aot_parse_options (aot_options, &acfg->aot_opts);
10076
10077         if (acfg->aot_opts.logfile) {
10078                 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10079         }
10080
10081         if (acfg->aot_opts.data_outfile) {
10082                 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10083                 if (!acfg->data_outfile) {
10084                         aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10085                         return 1;
10086                 }
10087                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10088         }
10089
10090         //acfg->aot_opts.print_skipped_methods = TRUE;
10091
10092 #if !defined(ENABLE_GSHAREDVT)
10093         if (opts & MONO_OPT_GSHAREDVT) {
10094                 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10095                 return 1;
10096         }
10097 #endif
10098
10099 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10100         if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10101                 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10102                 return 1;
10103         }
10104 #endif
10105
10106         if (acfg->aot_opts.llvm_only) {
10107 #ifndef ENABLE_GSHAREDVT
10108                 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with --enable-gsharedvt.\n");
10109                 return 1;
10110 #endif
10111         }
10112
10113 #if defined(ENABLE_GSHAREDVT) && defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10114         acfg->opts |= MONO_OPT_GSHAREDVT;
10115         opts |= MONO_OPT_GSHAREDVT;
10116 #endif
10117
10118         if (opts & MONO_OPT_GSHAREDVT)
10119                 mono_set_generic_sharing_vt_supported (TRUE);
10120
10121         aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10122
10123 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10124         if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10125                 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10126                 return 1;
10127         }
10128 #endif
10129
10130         if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10131                 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10132                 return 1;
10133         }
10134
10135         if (acfg->aot_opts.static_link)
10136                 acfg->aot_opts.asm_writer = TRUE;
10137
10138         if (acfg->aot_opts.soft_debug) {
10139                 MonoDebugOptions *opt = mini_get_debug_options ();
10140
10141                 opt->mdb_optimizations = TRUE;
10142                 opt->gen_sdb_seq_points = TRUE;
10143
10144                 if (!mono_debug_enabled ()) {
10145                         aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10146                         return 1;
10147                 }
10148                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10149         }
10150
10151         if (mono_use_llvm || acfg->aot_opts.llvm) {
10152                 acfg->llvm = TRUE;
10153                 acfg->aot_opts.asm_writer = TRUE;
10154                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10155
10156                 if (acfg->aot_opts.soft_debug) {
10157                         aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10158                         return 1;
10159                 }
10160
10161                 mini_llvm_init ();
10162
10163                 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10164                         aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10165                         return 1;
10166                 }
10167
10168                 /*
10169                  * Emit all LLVM code into a separate assembly/object file and link with it
10170                  * normally.
10171                  */
10172                 if (!acfg->aot_opts.asm_only) {
10173                         acfg->llvm_owriter = TRUE;
10174                 } else if (acfg->aot_opts.llvm_outfile) {
10175                         int len = strlen (acfg->aot_opts.llvm_outfile);
10176
10177                         if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10178                                 acfg->llvm_owriter = TRUE;
10179                 }
10180         }
10181
10182         if (mono_aot_mode_is_full (&acfg->aot_opts))
10183                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10184
10185         if (mono_threads_is_coop_enabled ())
10186                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10187
10188         if (acfg->aot_opts.instances_logfile_path) {
10189                 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10190                 if (!acfg->instances_logfile) {
10191                         aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10192                         return 1;
10193                 }
10194         }
10195
10196         load_profile_files (acfg);
10197
10198         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10199 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10200         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10201 #endif
10202         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10203 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10204         if (acfg->opts & MONO_OPT_GSHAREDVT)
10205                 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10206 #endif
10207
10208         acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10209
10210         arch_init (acfg);
10211
10212         if (acfg->llvm && acfg->thumb_mixed)
10213                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10214         if (acfg->aot_opts.llvm_only)
10215                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10216
10217         acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10218         /* Get rid of characters which cannot occur in symbols */
10219         for (p = acfg->assembly_name_sym; *p; ++p) {
10220                 if (!(isalnum (*p) || *p == '_'))
10221                         *p = '_';
10222         }
10223
10224         acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10225         acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10226         acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10227         if (acfg->llvm) {
10228                 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10229                 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10230         }
10231
10232         acfg->method_index = 1;
10233
10234         if (mono_aot_mode_is_full (&acfg->aot_opts))
10235                 mono_set_partial_sharing_supported (TRUE);
10236
10237         res = collect_methods (acfg);
10238         if (!res)
10239                 return 1;
10240
10241         acfg->cfgs_size = acfg->methods->len + 32;
10242         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10243
10244         /* PLT offset 0 is reserved for the PLT trampoline */
10245         acfg->plt_offset = 1;
10246         add_preinit_got_slots (acfg);
10247
10248 #ifdef ENABLE_LLVM
10249         if (acfg->llvm) {
10250                 llvm_acfg = acfg;
10251                 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10252         }
10253 #endif
10254
10255         TV_GETTIME (atv);
10256
10257         compile_methods (acfg);
10258
10259         TV_GETTIME (btv);
10260
10261         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10262
10263         TV_GETTIME (atv);
10264
10265 #ifdef ENABLE_LLVM
10266         if (acfg->llvm) {
10267                 if (acfg->aot_opts.asm_only) {
10268                         if (acfg->aot_opts.outfile) {
10269                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10270                                 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10271                         } else {
10272                                 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10273                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10274                         }
10275                         g_assert (acfg->aot_opts.llvm_outfile);
10276                         acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10277                         if (acfg->llvm_owriter)
10278                                 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10279                         else
10280                                 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10281                 } else {
10282                         acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10283                                 g_strdup_printf ("%s", "temp") :
10284                                 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10285                                 
10286                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10287                         acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10288                         acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10289                 }
10290         }
10291 #endif
10292
10293         if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10294                 if (acfg->aot_opts.outfile)
10295                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10296                 else
10297                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10298                         acfg->fp = fopen (acfg->tmpfname, "w+");
10299         } else {
10300                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10301                 acfg->fp = fdopen (i, "w+");
10302         }
10303         if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10304                 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10305                 return 1;
10306         }
10307         if (acfg->fp)
10308                 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10309
10310         tmp_outfile_name = NULL;
10311         outfile_name = NULL;
10312
10313         /* Compute symbols for methods */
10314         for (i = 0; i < acfg->nmethods; ++i) {
10315                 if (acfg->cfgs [i]) {
10316                         MonoCompile *cfg = acfg->cfgs [i];
10317                         int method_index = get_method_index (acfg, cfg->orig_method);
10318
10319                         if (COMPILE_LLVM (cfg))
10320                                 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10321                         else if (acfg->global_symbols || acfg->llvm)
10322                                 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10323                         else
10324                                 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10325                         cfg->asm_debug_symbol = cfg->asm_symbol;
10326                 }
10327         }
10328
10329         if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
10330                 /*
10331                  * CLANG supports GAS .file/.loc directives, so emit line number information this way
10332                  * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
10333                  * .byte directives.
10334                  */
10335                 //acfg->gas_line_numbers = TRUE;
10336         }
10337
10338         if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10339                 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10340                         aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10341                         return 1;
10342                 }
10343                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
10344         }
10345
10346         if (acfg->w)
10347                 mono_img_writer_emit_start (acfg->w);
10348
10349         if (acfg->dwarf)
10350                 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10351
10352         emit_code (acfg);
10353
10354         emit_info (acfg);
10355
10356         emit_extra_methods (acfg);
10357
10358         emit_trampolines (acfg);
10359
10360         emit_class_name_table (acfg);
10361
10362         emit_got_info (acfg, FALSE);
10363         if (acfg->llvm)
10364                 emit_got_info (acfg, TRUE);
10365
10366         emit_exception_info (acfg);
10367
10368         emit_unwind_info (acfg);
10369
10370         emit_class_info (acfg);
10371
10372         emit_plt (acfg);
10373
10374         emit_image_table (acfg);
10375
10376         emit_got (acfg);
10377
10378         {
10379                 /*
10380                  * The managed allocators are GC specific, so can't use an AOT image created by one GC
10381                  * in another.
10382                  */
10383                 const char *gc_name = mono_gc_get_gc_name ();
10384                 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10385         }
10386
10387         emit_blob (acfg);
10388
10389         emit_objc_selectors (acfg);
10390
10391         emit_globals (acfg);
10392
10393         emit_file_info (acfg);
10394
10395         if (acfg->dwarf) {
10396                 emit_dwarf_info (acfg);
10397                 mono_dwarf_writer_close (acfg->dwarf);
10398         }
10399
10400         emit_mem_end (acfg);
10401
10402         if (acfg->need_pt_gnu_stack) {
10403                 /* This is required so the .so doesn't have an executable stack */
10404                 /* The bin writer already emits this */
10405                 fprintf (acfg->fp, "\n.section  .note.GNU-stack,\"\",@progbits\n");
10406         }
10407
10408         if (acfg->aot_opts.data_outfile)
10409                 fclose (acfg->data_outfile);
10410
10411 #ifdef ENABLE_LLVM
10412         if (acfg->llvm) {
10413                 gboolean res;
10414
10415                 res = emit_llvm_file (acfg);
10416                 if (!res)
10417                         return 1;
10418         }
10419 #endif
10420
10421         TV_GETTIME (btv);
10422
10423         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10424
10425         if (acfg->llvm)
10426                 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10427         else
10428                 strcpy (llvm_stats_msg, "");
10429
10430         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;
10431
10432         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",
10433                                 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10434                                 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10435                                 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10436                                 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10437                                 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10438                                 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,
10439                                 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10440                                 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10441                         (int)(acfg->got_offset * sizeof (gpointer)));
10442         aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n", 
10443                         acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10444                         llvm_stats_msg,
10445                         acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10446                         acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10447         if (acfg->stats.genericcount)
10448                 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10449         if (acfg->stats.abscount)
10450                 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10451         if (acfg->stats.lmfcount)
10452                 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10453         if (acfg->stats.ocount)
10454                 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10455
10456         TV_GETTIME (atv);
10457         if (acfg->w) {
10458                 res = mono_img_writer_emit_writeout (acfg->w);
10459                 if (res != 0) {
10460                         acfg_free (acfg);
10461                         return res;
10462                 }
10463                 res = compile_asm (acfg);
10464                 if (res != 0) {
10465                         acfg_free (acfg);
10466                         return res;
10467                 }
10468         }
10469         TV_GETTIME (btv);
10470         acfg->stats.link_time = TV_ELAPSED (atv, btv);
10471
10472         if (acfg->aot_opts.stats) {
10473                 int i;
10474
10475                 aot_printf (acfg, "GOT slot distribution:\n");
10476                 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
10477                         if (acfg->stats.got_slot_types [i])
10478                                 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]);
10479                 aot_printf (acfg, "\nMethod stats:\n");
10480                 aot_printf (acfg, "\tNormal:    %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10481                 aot_printf (acfg, "\tInstance:  %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10482                 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10483                 aot_printf (acfg, "\tWrapper:   %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10484         }
10485
10486         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);
10487
10488         if (acfg->aot_opts.dump_json)
10489                 aot_dump (acfg);
10490
10491         acfg_free (acfg);
10492         
10493         return 0;
10494 }
10495
10496 #else
10497
10498 /* AOT disabled */
10499
10500 void*
10501 mono_aot_readonly_field_override (MonoClassField *field)
10502 {
10503         return NULL;
10504 }
10505
10506 int
10507 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10508 {
10509         return 0;
10510 }
10511
10512 gboolean
10513 mono_aot_is_shared_got_offset (int offset)
10514 {
10515         return FALSE;
10516 }
10517
10518 #endif