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