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