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