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