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