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