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