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