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