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