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