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