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