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