Increase the number of trampoline entries reserved for trampolines.
[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->thumb_mixed)
4773                         emit_label (acfg, plt_entry->llvm_symbol);
4774
4775                 if (debug_sym) {
4776                         if (acfg->need_no_dead_strip)
4777                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
4778                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4779                         emit_label (acfg, debug_sym);
4780                 }
4781
4782                 emit_label (acfg, plt_entry->symbol);
4783
4784                 arch_emit_plt_entry (acfg, i);
4785
4786                 if (debug_sym)
4787                         emit_symbol_size (acfg, debug_sym, ".");
4788         }
4789
4790         if (acfg->thumb_mixed) {
4791                 /* Make sure the ARM symbols don't alias the thumb ones */
4792                 emit_zero_bytes (acfg, 16);
4793
4794                 /* 
4795                  * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4796                  * code.
4797                  */
4798                 for (i = 0; i < acfg->plt_offset; ++i) {
4799                         char *debug_sym = NULL;
4800                         MonoPltEntry *plt_entry = NULL;
4801                         MonoJumpInfo *ji;
4802
4803                         if (i == 0)
4804                                 continue;
4805
4806                         plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4807                         ji = plt_entry->ji;
4808
4809                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4810                                 continue;
4811
4812                         /* Skip plt entries not actually called by LLVM code */
4813                         if (!plt_entry->llvm_used)
4814                                 continue;
4815
4816                         if (acfg->aot_opts.write_symbols) {
4817                                 if (plt_entry->debug_sym)
4818                                         debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4819                         }
4820
4821                         if (debug_sym) {
4822 #if defined(TARGET_MACH)
4823                                 fprintf (acfg->fp, "    .thumb_func %s\n", debug_sym);
4824                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
4825 #endif
4826                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4827                                 emit_label (acfg, debug_sym);
4828                         }
4829                         fprintf (acfg->fp, "\n.thumb_func\n");
4830
4831                         emit_label (acfg, plt_entry->llvm_symbol);
4832
4833                         arch_emit_llvm_plt_entry (acfg, i);
4834
4835                         if (debug_sym) {
4836                                 emit_symbol_size (acfg, debug_sym, ".");
4837                                 g_free (debug_sym);
4838                         }
4839                 }
4840         }
4841
4842         emit_symbol_size (acfg, acfg->plt_symbol, ".");
4843
4844         sprintf (symbol, "plt_end");
4845         emit_label (acfg, symbol);
4846 }
4847
4848 static G_GNUC_UNUSED void
4849 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4850 {
4851         char start_symbol [256];
4852         char symbol [256];
4853         guint32 buf_size, info_offset;
4854         MonoJumpInfo *patch_info;
4855         guint8 *buf, *p;
4856         GPtrArray *patches;
4857         char *name;
4858         guint8 *code;
4859         guint32 code_size;
4860         MonoJumpInfo *ji;
4861         GSList *unwind_ops;
4862
4863         name = info->name;
4864         code = info->code;
4865         code_size = info->code_size;
4866         ji = info->ji;
4867         unwind_ops = info->unwind_ops;
4868
4869 #ifdef __native_client_codegen__
4870         mono_nacl_fix_patches (code, ji);
4871 #endif
4872
4873         /* Emit code */
4874
4875         sprintf (start_symbol, "%s", name);
4876
4877         emit_section_change (acfg, ".text", 0);
4878         emit_global (acfg, start_symbol, TRUE);
4879         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4880         emit_label (acfg, start_symbol);
4881
4882         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4883         emit_label (acfg, symbol);
4884
4885         /* 
4886          * The code should access everything through the GOT, so we pass
4887          * TRUE here.
4888          */
4889         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4890
4891         emit_symbol_size (acfg, start_symbol, ".");
4892
4893         /* Emit info */
4894
4895         /* Sort relocations */
4896         patches = g_ptr_array_new ();
4897         for (patch_info = ji; patch_info; patch_info = patch_info->next)
4898                 if (patch_info->type != MONO_PATCH_INFO_NONE)
4899                         g_ptr_array_add (patches, patch_info);
4900         g_ptr_array_sort (patches, compare_patches);
4901
4902         buf_size = patches->len * 128 + 128;
4903         buf = g_malloc (buf_size);
4904         p = buf;
4905
4906         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4907         g_assert (p - buf < buf_size);
4908
4909         sprintf (symbol, "%s_p", name);
4910
4911         info_offset = add_to_blob (acfg, buf, p - buf);
4912
4913         emit_section_change (acfg, RODATA_SECT, 0);
4914         emit_global (acfg, symbol, FALSE);
4915         emit_label (acfg, symbol);
4916
4917         emit_int32 (acfg, info_offset);
4918
4919         /* Emit debug info */
4920         if (unwind_ops) {
4921                 char symbol2 [256];
4922
4923                 sprintf (symbol, "%s", name);
4924                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4925
4926                 if (acfg->dwarf)
4927                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4928         }
4929 }
4930
4931 static void
4932 emit_trampolines (MonoAotCompile *acfg)
4933 {
4934         char symbol [256];
4935         char end_symbol [256];
4936         int i, tramp_got_offset;
4937         MonoAotTrampoline ntype;
4938 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4939         int tramp_type;
4940 #endif
4941
4942         if (!acfg->aot_opts.full_aot)
4943                 return;
4944         
4945         g_assert (acfg->image->assembly);
4946
4947         /* Currently, we emit most trampolines into the mscorlib AOT image. */
4948         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4949 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4950                 MonoTrampInfo *info;
4951
4952                 /*
4953                  * Emit the generic trampolines.
4954                  *
4955                  * We could save some code by treating the generic trampolines as a wrapper
4956                  * method, but that approach has its own complexities, so we choose the simpler
4957                  * method.
4958                  */
4959                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4960                         mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4961                         emit_trampoline (acfg, acfg->got_offset, info);
4962                 }
4963
4964                 mono_arch_get_nullified_class_init_trampoline (&info);
4965                 emit_trampoline (acfg, acfg->got_offset, info);
4966 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4967                 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4968                 emit_trampoline (acfg, acfg->got_offset, info);
4969                 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4970                 emit_trampoline (acfg, acfg->got_offset, info);
4971 #endif
4972
4973                 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4974                 emit_trampoline (acfg, acfg->got_offset, info);
4975
4976                 /* Emit the exception related code pieces */
4977                 mono_arch_get_restore_context (&info, TRUE);
4978                 emit_trampoline (acfg, acfg->got_offset, info);
4979                 mono_arch_get_call_filter (&info, TRUE);
4980                 emit_trampoline (acfg, acfg->got_offset, info);
4981                 mono_arch_get_throw_exception (&info, TRUE);
4982                 emit_trampoline (acfg, acfg->got_offset, info);
4983                 mono_arch_get_rethrow_exception (&info, TRUE);
4984                 emit_trampoline (acfg, acfg->got_offset, info);
4985                 mono_arch_get_throw_corlib_exception (&info, TRUE);
4986                 emit_trampoline (acfg, acfg->got_offset, info);
4987
4988 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4989                 {
4990                         GSList *l = mono_arch_get_trampolines (TRUE);
4991
4992                         while (l) {
4993                                 MonoTrampInfo *info = l->data;
4994
4995                                 emit_trampoline (acfg, acfg->got_offset, info);
4996                                 l = l->next;
4997                         }
4998                 }
4999 #endif
5000
5001                 for (i = 0; i < 128; ++i) {
5002                         int offset;
5003
5004                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5005                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5006                         emit_trampoline (acfg, acfg->got_offset, info);
5007
5008                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5009                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5010                         emit_trampoline (acfg, acfg->got_offset, info);
5011                 }
5012
5013                 {
5014                         GSList *l;
5015
5016                         /* delegate_invoke_impl trampolines */
5017                         l = mono_arch_get_delegate_invoke_impls ();
5018                         while (l) {
5019                                 MonoTrampInfo *info = l->data;
5020
5021                                 emit_trampoline (acfg, acfg->got_offset, info);
5022                                 l = l->next;
5023                         }
5024                 }
5025
5026 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5027
5028                 /* Emit trampolines which are numerous */
5029
5030                 /*
5031                  * These include the following:
5032                  * - specific trampolines
5033                  * - static rgctx invoke trampolines
5034                  * - imt thunks
5035                  * These trampolines have the same code, they are parameterized by GOT 
5036                  * slots. 
5037                  * They are defined in this file, in the arch_... routines instead of
5038                  * in tramp-<ARCH>.c, since it is easier to do it this way.
5039                  */
5040
5041                 /*
5042                  * When running in aot-only mode, we can't create specific trampolines at 
5043                  * runtime, so we create a few, and save them in the AOT file. 
5044                  * Normal trampolines embed their argument as a literal inside the 
5045                  * trampoline code, we can't do that here, so instead we embed an offset
5046                  * which needs to be added to the trampoline address to get the address of
5047                  * the GOT slot which contains the argument value.
5048                  * The generated trampolines jump to the generic trampolines using another
5049                  * GOT slot, which will be setup by the AOT loader to point to the 
5050                  * generic trampoline code of the given type.
5051                  */
5052
5053                 /*
5054                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5055                  * each class).
5056                  */
5057
5058                 emit_section_change (acfg, ".text", 0);
5059
5060                 tramp_got_offset = acfg->got_offset;
5061
5062                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5063                         switch (ntype) {
5064                         case MONO_AOT_TRAMP_SPECIFIC:
5065                                 sprintf (symbol, "specific_trampolines");
5066                                 break;
5067                         case MONO_AOT_TRAMP_STATIC_RGCTX:
5068                                 sprintf (symbol, "static_rgctx_trampolines");
5069                                 break;
5070                         case MONO_AOT_TRAMP_IMT_THUNK:
5071                                 sprintf (symbol, "imt_thunks");
5072                                 break;
5073                         default:
5074                                 g_assert_not_reached ();
5075                         }
5076
5077                         sprintf (end_symbol, "%s_e", symbol);
5078
5079                         if (acfg->aot_opts.write_symbols)
5080                                 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5081
5082                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5083                         emit_label (acfg, symbol);
5084
5085                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5086
5087                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5088                                 int tramp_size = 0;
5089
5090                                 switch (ntype) {
5091                                 case MONO_AOT_TRAMP_SPECIFIC:
5092                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5093                                         tramp_got_offset += 2;
5094                                 break;
5095                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
5096                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
5097                                         tramp_got_offset += 2;
5098                                         break;
5099                                 case MONO_AOT_TRAMP_IMT_THUNK:
5100                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5101                                         tramp_got_offset += 1;
5102                                         break;
5103                                 default:
5104                                         g_assert_not_reached ();
5105                                 }
5106 #ifdef __native_client_codegen__
5107                                 /* align to avoid 32-byte boundary crossings */
5108                                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5109 #endif
5110
5111                                 if (!acfg->trampoline_size [ntype]) {
5112                                         g_assert (tramp_size);
5113                                         acfg->trampoline_size [ntype] = tramp_size;
5114                                 }
5115                         }
5116
5117                         emit_label (acfg, end_symbol);
5118                 }
5119
5120                 /* Reserve some entries at the end of the GOT for our use */
5121                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5122         }
5123
5124         acfg->got_offset += acfg->num_trampoline_got_entries;
5125 }
5126
5127 static gboolean
5128 str_begins_with (const char *str1, const char *str2)
5129 {
5130         int len = strlen (str2);
5131         return strncmp (str1, str2, len) == 0;
5132 }
5133
5134 void*
5135 mono_aot_readonly_field_override (MonoClassField *field)
5136 {
5137         ReadOnlyValue *rdv;
5138         for (rdv = readonly_values; rdv; rdv = rdv->next) {
5139                 char *p = rdv->name;
5140                 int len;
5141                 len = strlen (field->parent->name_space);
5142                 if (strncmp (p, field->parent->name_space, len))
5143                         continue;
5144                 p += len;
5145                 if (*p++ != '.')
5146                         continue;
5147                 len = strlen (field->parent->name);
5148                 if (strncmp (p, field->parent->name, len))
5149                         continue;
5150                 p += len;
5151                 if (*p++ != '.')
5152                         continue;
5153                 if (strcmp (p, field->name))
5154                         continue;
5155                 switch (rdv->type) {
5156                 case MONO_TYPE_I1:
5157                         return &rdv->value.i1;
5158                 case MONO_TYPE_I2:
5159                         return &rdv->value.i2;
5160                 case MONO_TYPE_I4:
5161                         return &rdv->value.i4;
5162                 default:
5163                         break;
5164                 }
5165         }
5166         return NULL;
5167 }
5168
5169 static void
5170 add_readonly_value (MonoAotOptions *opts, const char *val)
5171 {
5172         ReadOnlyValue *rdv;
5173         const char *fval;
5174         const char *tval;
5175         /* the format of val is:
5176          * namespace.typename.fieldname=type/value
5177          * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5178          */
5179         fval = strrchr (val, '/');
5180         if (!fval) {
5181                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5182                 exit (1);
5183         }
5184         tval = strrchr (val, '=');
5185         if (!tval) {
5186                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5187                 exit (1);
5188         }
5189         rdv = g_new0 (ReadOnlyValue, 1);
5190         rdv->name = g_malloc0 (tval - val + 1);
5191         memcpy (rdv->name, val, tval - val);
5192         tval++;
5193         fval++;
5194         if (strncmp (tval, "i1", 2) == 0) {
5195                 rdv->value.i1 = atoi (fval);
5196                 rdv->type = MONO_TYPE_I1;
5197         } else if (strncmp (tval, "i2", 2) == 0) {
5198                 rdv->value.i2 = atoi (fval);
5199                 rdv->type = MONO_TYPE_I2;
5200         } else if (strncmp (tval, "i4", 2) == 0) {
5201                 rdv->value.i4 = atoi (fval);
5202                 rdv->type = MONO_TYPE_I4;
5203         } else {
5204                 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5205                 exit (1);
5206         }
5207         rdv->next = readonly_values;
5208         readonly_values = rdv;
5209 }
5210
5211 static void
5212 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5213 {
5214         gchar **args, **ptr;
5215
5216         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5217         for (ptr = args; ptr && *ptr; ptr ++) {
5218                 const char *arg = *ptr;
5219
5220                 if (str_begins_with (arg, "outfile=")) {
5221                         opts->outfile = g_strdup (arg + strlen ("outfile="));
5222                 } else if (str_begins_with (arg, "save-temps")) {
5223                         opts->save_temps = TRUE;
5224                 } else if (str_begins_with (arg, "keep-temps")) {
5225                         opts->save_temps = TRUE;
5226                 } else if (str_begins_with (arg, "write-symbols")) {
5227                         opts->write_symbols = TRUE;
5228                 } else if (str_begins_with (arg, "no-write-symbols")) {
5229                         opts->write_symbols = FALSE;
5230                 } else if (str_begins_with (arg, "metadata-only")) {
5231                         opts->metadata_only = TRUE;
5232                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5233                         opts->bind_to_runtime_version = TRUE;
5234                 } else if (str_begins_with (arg, "full")) {
5235                         opts->full_aot = TRUE;
5236                 } else if (str_begins_with (arg, "threads=")) {
5237                         opts->nthreads = atoi (arg + strlen ("threads="));
5238                 } else if (str_begins_with (arg, "static")) {
5239                         opts->static_link = TRUE;
5240                         opts->no_dlsym = TRUE;
5241                 } else if (str_begins_with (arg, "asmonly")) {
5242                         opts->asm_only = TRUE;
5243                 } else if (str_begins_with (arg, "asmwriter")) {
5244                         opts->asm_writer = TRUE;
5245                 } else if (str_begins_with (arg, "nodebug")) {
5246                         opts->nodebug = TRUE;
5247                 } else if (str_begins_with (arg, "ntrampolines=")) {
5248                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5249                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5250                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5251                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5252                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5253                 } else if (str_begins_with (arg, "autoreg")) {
5254                         opts->autoreg = TRUE;
5255                 } else if (str_begins_with (arg, "tool-prefix=")) {
5256                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5257                 } else if (str_begins_with (arg, "soft-debug")) {
5258                         opts->soft_debug = TRUE;
5259                 } else if (str_begins_with (arg, "direct-pinvoke")) {
5260                         opts->direct_pinvoke = TRUE;
5261                 } else if (str_begins_with (arg, "direct-icalls")) {
5262                         opts->direct_icalls = TRUE;
5263 #if defined(TARGET_ARM)
5264                 } else if (str_begins_with (arg, "iphone-abi")) {
5265                         // older full-aot users did depend on this.
5266 #endif
5267                 } else if (str_begins_with (arg, "no-direct-calls")) {
5268                         opts->no_direct_calls = TRUE;
5269                 } else if (str_begins_with (arg, "print-skipped")) {
5270                         opts->print_skipped_methods = TRUE;
5271                 } else if (str_begins_with (arg, "stats")) {
5272                         opts->stats = TRUE;
5273                 } else if (str_begins_with (arg, "log-generics")) {
5274                         opts->log_generics = TRUE;
5275                 } else if (str_begins_with (arg, "mtriple=")) {
5276                         opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5277                 } else if (str_begins_with (arg, "llvm-path=")) {
5278                         opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5279                 } else if (str_begins_with (arg, "readonly-value=")) {
5280                         add_readonly_value (opts, arg + strlen ("readonly-value="));
5281                 } else if (str_begins_with (arg, "info")) {
5282                         printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5283                         exit (0);
5284                 } else if (str_begins_with (arg, "gc-maps")) {
5285                         mini_gc_enable_gc_maps_for_aot ();
5286                 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5287                         printf ("Supported options for --aot:\n");
5288                         printf ("    outfile=\n");
5289                         printf ("    save-temps\n");
5290                         printf ("    keep-temps\n");
5291                         printf ("    write-symbols\n");
5292                         printf ("    metadata-only\n");
5293                         printf ("    bind-to-runtime-version\n");
5294                         printf ("    full\n");
5295                         printf ("    threads=\n");
5296                         printf ("    static\n");
5297                         printf ("    asmonly\n");
5298                         printf ("    asmwriter\n");
5299                         printf ("    nodebug\n");
5300                         printf ("    ntrampolines=\n");
5301                         printf ("    nrgctx-trampolines=\n");
5302                         printf ("    nimt-trampolines=\n");
5303                         printf ("    autoreg\n");
5304                         printf ("    tool-prefix=\n");
5305                         printf ("    readonly-value=\n");
5306                         printf ("    soft-debug\n");
5307                         printf ("    gc-maps\n");
5308                         printf ("    print-skipped\n");
5309                         printf ("    stats\n");
5310                         printf ("    info\n");
5311                         printf ("    help/?\n");
5312                         exit (0);
5313                 } else {
5314                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5315                         exit (1);
5316                 }
5317         }
5318
5319         g_strfreev (args);
5320 }
5321
5322 static void
5323 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5324 {
5325         MonoMethod *method = (MonoMethod*)key;
5326         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5327         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5328         MonoAotCompile *acfg = user_data;
5329
5330         new_ji->image = ji->image;
5331         new_ji->token = ji->token;
5332         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5333 }
5334
5335 static gboolean
5336 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5337 {
5338         if (klass->type_token)
5339                 return TRUE;
5340         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5341                 return TRUE;
5342         if (klass->rank)
5343                 return can_encode_class (acfg, klass->element_class);
5344         return FALSE;
5345 }
5346
5347 static gboolean
5348 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5349 {
5350         switch (patch_info->type) {
5351         case MONO_PATCH_INFO_METHOD:
5352         case MONO_PATCH_INFO_METHODCONST: {
5353                 MonoMethod *method = patch_info->data.method;
5354
5355                 if (method->wrapper_type) {
5356                         switch (method->wrapper_type) {
5357                         case MONO_WRAPPER_NONE:
5358                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5359                         case MONO_WRAPPER_XDOMAIN_INVOKE:
5360                         case MONO_WRAPPER_STFLD:
5361                         case MONO_WRAPPER_LDFLD:
5362                         case MONO_WRAPPER_LDFLDA:
5363                         case MONO_WRAPPER_LDFLD_REMOTE:
5364                         case MONO_WRAPPER_STFLD_REMOTE:
5365                         case MONO_WRAPPER_STELEMREF:
5366                         case MONO_WRAPPER_ISINST:
5367                         case MONO_WRAPPER_PROXY_ISINST:
5368                         case MONO_WRAPPER_ALLOC:
5369                         case MONO_WRAPPER_REMOTING_INVOKE:
5370                         case MONO_WRAPPER_UNKNOWN:
5371                         case MONO_WRAPPER_WRITE_BARRIER:
5372                                 break;
5373                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
5374                         case MONO_WRAPPER_CASTCLASS: {
5375                                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5376
5377                                 if (info)
5378                                         return TRUE;
5379                                 else
5380                                         return FALSE;
5381                                 break;
5382                         }
5383                         default:
5384                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5385                                 return FALSE;
5386                         }
5387                 } else {
5388                         if (!method->token) {
5389                                 /* The method is part of a constructed type like Int[,].Set (). */
5390                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5391                                         if (method->klass->rank)
5392                                                 return TRUE;
5393                                         return FALSE;
5394                                 }
5395                         }
5396                 }
5397                 break;
5398         }
5399         case MONO_PATCH_INFO_VTABLE:
5400         case MONO_PATCH_INFO_CLASS_INIT:
5401         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5402         case MONO_PATCH_INFO_CLASS:
5403         case MONO_PATCH_INFO_IID:
5404         case MONO_PATCH_INFO_ADJUSTED_IID:
5405                 if (!can_encode_class (acfg, patch_info->data.klass)) {
5406                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5407                         return FALSE;
5408                 }
5409                 break;
5410         case MONO_PATCH_INFO_RGCTX_FETCH: {
5411                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5412
5413                 if (!can_encode_patch (acfg, entry->data))
5414                         return FALSE;
5415                 break;
5416         }
5417         default:
5418                 break;
5419         }
5420
5421         return TRUE;
5422 }
5423
5424 /*
5425  * compile_method:
5426  *
5427  *   AOT compile a given method.
5428  * This function might be called by multiple threads, so it must be thread-safe.
5429  */
5430 static void
5431 compile_method (MonoAotCompile *acfg, MonoMethod *method)
5432 {
5433         MonoCompile *cfg;
5434         MonoJumpInfo *patch_info;
5435         gboolean skip;
5436         int index, depth;
5437         MonoMethod *wrapped;
5438
5439         if (acfg->aot_opts.metadata_only)
5440                 return;
5441
5442         mono_acfg_lock (acfg);
5443         index = get_method_index (acfg, method);
5444         mono_acfg_unlock (acfg);
5445
5446         /* fixme: maybe we can also precompile wrapper methods */
5447         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5448                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5449                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
5450                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
5451                 return;
5452         }
5453
5454         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5455                 return;
5456
5457         wrapped = mono_marshal_method_from_wrapper (method);
5458         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
5459                 // FIXME: The wrapper should be generic too, but it is not
5460                 return;
5461
5462         if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
5463                 return;
5464
5465         InterlockedIncrement (&acfg->stats.mcount);
5466
5467 #if 0
5468         if (method->is_generic || method->klass->generic_container) {
5469                 InterlockedIncrement (&acfg->stats.genericcount);
5470                 return;
5471         }
5472 #endif
5473
5474         //acfg->aot_opts.print_skipped_methods = TRUE;
5475
5476         /*
5477          * Since these methods are the only ones which are compiled with
5478          * AOT support, and they are not used by runtime startup/shutdown code,
5479          * the runtime will not see AOT methods during AOT compilation,so it
5480          * does not need to support them by creating a fake GOT etc.
5481          */
5482         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
5483         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
5484                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
5485                 InterlockedIncrement (&acfg->stats.genericcount);
5486                 return;
5487         }
5488         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
5489                 if (acfg->aot_opts.print_skipped_methods)
5490                         printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
5491                 /* Let the exception happen at runtime */
5492                 return;
5493         }
5494
5495         if (cfg->disable_aot) {
5496                 if (acfg->aot_opts.print_skipped_methods)
5497                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
5498                 InterlockedIncrement (&acfg->stats.ocount);
5499                 mono_destroy_compile (cfg);
5500                 return;
5501         }
5502
5503         /* Nullify patches which need no aot processing */
5504         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5505                 switch (patch_info->type) {
5506                 case MONO_PATCH_INFO_LABEL:
5507                 case MONO_PATCH_INFO_BB:
5508                         patch_info->type = MONO_PATCH_INFO_NONE;
5509                         break;
5510                 default:
5511                         break;
5512                 }
5513         }
5514
5515         /* Collect method->token associations from the cfg */
5516         mono_acfg_lock (acfg);
5517         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
5518         mono_acfg_unlock (acfg);
5519
5520         /*
5521          * Check for absolute addresses.
5522          */
5523         skip = FALSE;
5524         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5525                 switch (patch_info->type) {
5526                 case MONO_PATCH_INFO_ABS:
5527                         /* unable to handle this */
5528                         skip = TRUE;    
5529                         break;
5530                 default:
5531                         break;
5532                 }
5533         }
5534
5535         if (skip) {
5536                 if (acfg->aot_opts.print_skipped_methods)
5537                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
5538                 InterlockedIncrement (&acfg->stats.abscount);
5539                 mono_destroy_compile (cfg);
5540                 return;
5541         }
5542
5543         /* Lock for the rest of the code */
5544         mono_acfg_lock (acfg);
5545
5546         /*
5547          * Check for methods/klasses we can't encode.
5548          */
5549         skip = FALSE;
5550         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5551                 if (!can_encode_patch (acfg, patch_info))
5552                         skip = TRUE;
5553         }
5554
5555         if (skip) {
5556                 if (acfg->aot_opts.print_skipped_methods)
5557                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
5558                 acfg->stats.ocount++;
5559                 mono_destroy_compile (cfg);
5560                 mono_acfg_unlock (acfg);
5561                 return;
5562         }
5563
5564         /* Adds generic instances referenced by this method */
5565         /* 
5566          * The depth is used to avoid infinite loops when generic virtual recursion is 
5567          * encountered.
5568          */
5569         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5570         if (depth < 32) {
5571                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5572                         switch (patch_info->type) {
5573                         case MONO_PATCH_INFO_METHOD: {
5574                                 MonoMethod *m = patch_info->data.method;
5575                                 if (m->is_inflated) {
5576                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
5577                                                   mono_method_is_generic_sharable_impl (m, FALSE)) &&
5578                                                 !method_has_type_vars (m)) {
5579                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5580                                                         if (acfg->aot_opts.full_aot)
5581                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
5582                                                 } else {
5583                                                         add_extra_method_with_depth (acfg, m, depth + 1);
5584                                                         add_types_from_method_header (acfg, m);
5585                                                 }
5586                                         }
5587                                         add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
5588                                 }
5589                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
5590                                         add_extra_method_with_depth (acfg, m, depth + 1);
5591                                 break;
5592                         }
5593                         case MONO_PATCH_INFO_VTABLE: {
5594                                 MonoClass *klass = patch_info->data.klass;
5595
5596                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
5597                                         add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
5598                                 break;
5599                         }
5600                         case MONO_PATCH_INFO_SFLDA: {
5601                                 MonoClass *klass = patch_info->data.field->parent;
5602
5603                                 /* The .cctor needs to run at runtime. */
5604                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
5605                                         add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
5606                                 break;
5607                         }
5608                         default:
5609                                 break;
5610                         }
5611                 }
5612         }
5613
5614         /* Determine whenever the method has GOT slots */
5615         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5616                 switch (patch_info->type) {
5617                 case MONO_PATCH_INFO_GOT_OFFSET:
5618                 case MONO_PATCH_INFO_NONE:
5619                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5620                         break;
5621                 case MONO_PATCH_INFO_IMAGE:
5622                         /* The assembly is stored in GOT slot 0 */
5623                         if (patch_info->data.image != acfg->image)
5624                                 cfg->has_got_slots = TRUE;
5625                         break;
5626                 default:
5627                         if (!is_plt_patch (patch_info))
5628                                 cfg->has_got_slots = TRUE;
5629                         break;
5630                 }
5631         }
5632
5633         if (!cfg->has_got_slots)
5634                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5635
5636         /* 
5637          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5638          */
5639         /* Make a copy of the patch info which is in the mempool */
5640         {
5641                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5642
5643                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5644                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5645
5646                         if (!patches)
5647                                 patches = new_patch_info;
5648                         else
5649                                 patches_end->next = new_patch_info;
5650                         patches_end = new_patch_info;
5651                 }
5652                 cfg->patch_info = patches;
5653         }
5654         /* Make a copy of the unwind info */
5655         {
5656                 GSList *l, *unwind_ops;
5657                 MonoUnwindOp *op;
5658
5659                 unwind_ops = NULL;
5660                 for (l = cfg->unwind_ops; l; l = l->next) {
5661                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5662                         memcpy (op, l->data, sizeof (MonoUnwindOp));
5663                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5664                 }
5665                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5666         }
5667         /* Make a copy of the argument/local info */
5668         {
5669                 MonoInst **args, **locals;
5670                 MonoMethodSignature *sig;
5671                 MonoMethodHeader *header;
5672                 int i;
5673                 
5674                 sig = mono_method_signature (method);
5675                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5676                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5677                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5678                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5679                 }
5680                 cfg->args = args;
5681
5682                 header = mono_method_get_header (method);
5683                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5684                 for (i = 0; i < header->num_locals; ++i) {
5685                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5686                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5687                 }
5688                 cfg->locals = locals;
5689         }
5690
5691         /* Free some fields used by cfg to conserve memory */
5692         mono_mempool_destroy (cfg->mempool);
5693         cfg->mempool = NULL;
5694         g_free (cfg->varinfo);
5695         cfg->varinfo = NULL;
5696         g_free (cfg->vars);
5697         cfg->vars = NULL;
5698         if (cfg->rs) {
5699                 mono_regstate_free (cfg->rs);
5700                 cfg->rs = NULL;
5701         }
5702
5703         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
5704
5705         while (index >= acfg->cfgs_size) {
5706                 MonoCompile **new_cfgs;
5707                 int new_size;
5708
5709                 new_size = acfg->cfgs_size * 2;
5710                 new_cfgs = g_new0 (MonoCompile*, new_size);
5711                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5712                 g_free (acfg->cfgs);
5713                 acfg->cfgs = new_cfgs;
5714                 acfg->cfgs_size = new_size;
5715         }
5716         acfg->cfgs [index] = cfg;
5717
5718         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5719
5720         /*
5721         if (cfg->orig_method->wrapper_type)
5722                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5723         */
5724
5725         mono_acfg_unlock (acfg);
5726
5727         InterlockedIncrement (&acfg->stats.ccount);
5728 }
5729  
5730 static void
5731 compile_thread_main (gpointer *user_data)
5732 {
5733         MonoDomain *domain = user_data [0];
5734         MonoAotCompile *acfg = user_data [1];
5735         GPtrArray *methods = user_data [2];
5736         int i;
5737
5738         mono_thread_attach (domain);
5739
5740         for (i = 0; i < methods->len; ++i)
5741                 compile_method (acfg, g_ptr_array_index (methods, i));
5742 }
5743
5744 static void
5745 load_profile_files (MonoAotCompile *acfg)
5746 {
5747         FILE *infile;
5748         char *tmp;
5749         int file_index, res, method_index, i;
5750         char ver [256];
5751         guint32 token;
5752         GList *unordered, *l;
5753         gboolean found;
5754
5755         file_index = 0;
5756         while (TRUE) {
5757                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5758
5759                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5760                         g_free (tmp);
5761                         break;
5762                 }
5763
5764                 infile = fopen (tmp, "r");
5765                 g_assert (infile);
5766
5767                 printf ("Using profile data file '%s'\n", tmp);
5768                 g_free (tmp);
5769
5770                 file_index ++;
5771
5772                 res = fscanf (infile, "%32s\n", ver);
5773                 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5774                         printf ("Profile file has wrong version or invalid.\n");
5775                         fclose (infile);
5776                         continue;
5777                 }
5778
5779                 while (TRUE) {
5780                         char name [1024];
5781                         MonoMethodDesc *desc;
5782                         MonoMethod *method;
5783
5784                         if (fgets (name, 1023, infile) == NULL)
5785                                 break;
5786
5787                         /* Kill the newline */
5788                         if (strlen (name) > 0)
5789                                 name [strlen (name) - 1] = '\0';
5790
5791                         desc = mono_method_desc_new (name, TRUE);
5792
5793                         method = mono_method_desc_search_in_image (desc, acfg->image);
5794
5795                         if (method && mono_method_get_token (method)) {
5796                                 token = mono_method_get_token (method);
5797                                 method_index = mono_metadata_token_index (token) - 1;
5798
5799                                 found = FALSE;
5800                                 for (i = 0; i < acfg->method_order->len; ++i) {
5801                                         if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5802                                                 found = TRUE;
5803                                                 break;
5804                                         }
5805                                 }
5806                                 if (!found)
5807                                         g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5808                         } else {
5809                                 //printf ("No method found matching '%s'.\n", name);
5810                         }
5811                 }
5812                 fclose (infile);
5813         }
5814
5815         /* Add missing methods */
5816         unordered = NULL;
5817         for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5818                 found = FALSE;
5819                 for (i = 0; i < acfg->method_order->len; ++i) {
5820                         if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5821                                 found = TRUE;
5822                                 break;
5823                         }
5824                 }
5825                 if (!found)
5826                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5827         }
5828         unordered = g_list_reverse (unordered);
5829         for (l = unordered; l; l = l->next)
5830                 g_ptr_array_add (acfg->method_order, l->data);
5831 }
5832  
5833 /* Used by the LLVM backend */
5834 guint32
5835 mono_aot_get_got_offset (MonoJumpInfo *ji)
5836 {
5837         return get_got_offset (llvm_acfg, ji);
5838 }
5839
5840 char*
5841 mono_aot_get_method_name (MonoCompile *cfg)
5842 {
5843         if (llvm_acfg->aot_opts.static_link)
5844                 /* Include the assembly name too to avoid duplicate symbol errors */
5845                 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5846         else
5847                 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5848 }
5849
5850 char*
5851 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5852 {
5853         MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5854         MonoPltEntry *plt_entry;
5855
5856         ji->type = type;
5857         ji->data.target = data;
5858
5859         if (!can_encode_patch (llvm_acfg, ji))
5860                 return NULL;
5861
5862         plt_entry = get_plt_entry (llvm_acfg, ji);
5863         plt_entry->llvm_used = TRUE;
5864
5865 #if defined(TARGET_MACH)
5866         return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5867 #else
5868         return g_strdup_printf (plt_entry->llvm_symbol);
5869 #endif
5870 }
5871
5872 MonoJumpInfo*
5873 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5874 {
5875         MonoJumpInfo *res;
5876
5877         mono_acfg_lock (llvm_acfg);
5878         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5879         mono_acfg_unlock (llvm_acfg);
5880
5881         return res;
5882 }
5883
5884 #ifdef ENABLE_LLVM
5885
5886 /*
5887  * emit_llvm_file:
5888  *
5889  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5890  * tools.
5891  */
5892 static void
5893 emit_llvm_file (MonoAotCompile *acfg)
5894 {
5895         char *command, *opts, *tempbc;
5896         int i;
5897         MonoJumpInfo *patch_info;
5898
5899         /*
5900          * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5901          * to it.
5902          */
5903
5904         /* Compute the final size of the got */
5905         for (i = 0; i < acfg->nmethods; ++i) {
5906                 if (acfg->cfgs [i]) {
5907                         for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5908                                 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5909                                         if (!is_plt_patch (patch_info))
5910                                                 get_got_offset (acfg, patch_info);
5911                                         else
5912                                                 get_plt_entry (acfg, patch_info);
5913                                 }
5914                         }
5915                 }
5916         }
5917
5918         acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5919
5920         if (acfg->aot_opts.full_aot) {
5921                 int ntype;
5922
5923                 /* 
5924                  * Need to add the got entries used by the trampolines.
5925                  * This is only a conservative approximation.
5926                  */
5927                 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5928                         /* For the generic + rgctx trampolines */
5929                         acfg->final_got_size += 400;
5930                         /* For the specific trampolines */
5931                         for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5932                                 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5933                 }
5934         }
5935
5936
5937         tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
5938         mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
5939         g_free (tempbc);
5940
5941         /*
5942          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5943          * a lot of time, and doesn't seem to save much space.
5944          * The following optimizations cannot be enabled:
5945          * - 'tailcallelim'
5946          * - 'jump-threading' changes our blockaddress references to int constants.
5947          * - 'basiccg' fails because it contains:
5948          * if (CS && !isa<IntrinsicInst>(II)) {
5949          * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
5950          * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
5951          * The opt list below was produced by taking the output of:
5952          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5953          * then removing tailcallelim + the global opts, and adding a second gvn.
5954          */
5955         opts = g_strdup ("-instcombine -simplifycfg");
5956         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");
5957 #if 1
5958         command = g_strdup_printf ("%sopt -f %s -o %s.opt.bc %s.bc", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
5959         printf ("Executing opt: %s\n", command);
5960         if (system (command) != 0) {
5961                 exit (1);
5962         }
5963 #endif
5964         g_free (opts);
5965
5966         if (!acfg->llc_args)
5967                 acfg->llc_args = g_string_new ("");
5968
5969         /* Verbose asm slows down llc greatly */
5970         g_string_append (acfg->llc_args, " -asm-verbose=false");
5971
5972         if (acfg->aot_opts.mtriple)
5973                 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5974
5975         if (llvm_acfg->aot_opts.static_link)
5976                 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5977         else
5978                 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5979         unlink (acfg->tmpfname);
5980
5981         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);
5982
5983         printf ("Executing llc: %s\n", command);
5984
5985         if (system (command) != 0) {
5986                 exit (1);
5987         }
5988 }
5989 #endif
5990
5991 static void
5992 emit_code (MonoAotCompile *acfg)
5993 {
5994         int oindex, i, prev_index;
5995         char symbol [256];
5996         char end_symbol [256];
5997
5998 #if defined(TARGET_POWERPC64)
5999         sprintf (symbol, ".Lgot_addr");
6000         emit_section_change (acfg, ".text", 0);
6001         emit_alignment (acfg, 8);
6002         emit_label (acfg, symbol);
6003         emit_pointer (acfg, acfg->got_symbol);
6004 #endif
6005
6006         /* 
6007          * This global symbol is used to compute the address of each method using the
6008          * code_offsets array. It is also used to compute the memory ranges occupied by
6009          * AOT code, so it must be equal to the address of the first emitted method.
6010          */
6011         sprintf (symbol, "methods");
6012         emit_section_change (acfg, ".text", 0);
6013         emit_alignment (acfg, 8);
6014         if (acfg->llvm) {
6015                 for (i = 0; i < acfg->nmethods; ++i) {
6016                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
6017                                 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
6018                                 break;
6019                         }
6020                 }
6021                 if (i == acfg->nmethods)
6022                         /* No LLVM compiled methods */
6023                         emit_label (acfg, symbol);
6024         } else {
6025                 emit_label (acfg, symbol);
6026         }
6027
6028         /* 
6029          * Emit some padding so the local symbol for the first method doesn't have the
6030          * same address as 'methods'.
6031          */
6032 #if defined(__default_codegen__)
6033         emit_zero_bytes (acfg, 16);
6034 #elif defined(__native_client_codegen__)
6035         {
6036                 const int kPaddingSize = 16;
6037                 guint8 pad_buffer[kPaddingSize];
6038                 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
6039                 emit_bytes (acfg, pad_buffer, kPaddingSize);
6040         }
6041 #endif
6042
6043         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6044                 MonoCompile *cfg;
6045                 MonoMethod *method;
6046
6047                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6048
6049                 cfg = acfg->cfgs [i];
6050
6051                 if (!cfg)
6052                         continue;
6053
6054                 method = cfg->orig_method;
6055
6056                 /* Emit unbox trampoline */
6057                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6058                         sprintf (symbol, "ut_%d", get_method_index (acfg, method));
6059
6060                         emit_section_change (acfg, ".text", 0);
6061 #ifdef __native_client_codegen__
6062                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6063 #endif
6064
6065                         if (acfg->thumb_mixed && cfg->compile_llvm)
6066                                 fprintf (acfg->fp, "\n.thumb_func\n");
6067
6068                         emit_label (acfg, symbol);
6069
6070                         arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
6071                 }
6072
6073                 if (cfg->compile_llvm)
6074                         acfg->stats.llvm_count ++;
6075                 else
6076                         emit_method_code (acfg, cfg);
6077         }
6078
6079         sprintf (symbol, "methods_end");
6080         emit_section_change (acfg, ".text", 0);
6081         emit_alignment (acfg, 8);
6082         emit_label (acfg, symbol);
6083
6084         /* 
6085          * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6086          * from optimizing them away, since it doesn't see that code_offsets references them.
6087          * JITted methods don't need this since they are referenced using assembler local
6088          * symbols.
6089          * FIXME: This is why write-symbols doesn't work on OSX ?
6090          */
6091         if (acfg->llvm && acfg->need_no_dead_strip) {
6092                 fprintf (acfg->fp, "\n");
6093                 for (i = 0; i < acfg->nmethods; ++i) {
6094                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6095                                 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6096                 }
6097         }
6098
6099 #ifdef MONOTOUCH
6100         if (acfg->direct_method_addresses) {
6101                 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
6102
6103                 sprintf (symbol, "method_addresses");
6104                 emit_section_change (acfg, RODATA_SECT, 1);
6105                 emit_alignment (acfg, 8);
6106                 emit_label (acfg, symbol);
6107
6108                 for (i = 0; i < acfg->nmethods; ++i) {
6109                         if (acfg->cfgs [i]) {
6110                                 emit_pointer (acfg, acfg->cfgs [i]->asm_symbol);
6111                         } else {
6112                                 emit_pointer (acfg, NULL);
6113                         }
6114                 }
6115
6116                 /* Empty */
6117                 sprintf (symbol, "code_offsets");
6118                 emit_section_change (acfg, RODATA_SECT, 1);
6119                 emit_alignment (acfg, 8);
6120                 emit_label (acfg, symbol);
6121         } else {
6122                 sprintf (symbol, "code_offsets");
6123                 emit_section_change (acfg, RODATA_SECT, 1);
6124                 emit_alignment (acfg, 8);
6125                 emit_label (acfg, symbol);
6126
6127                 acfg->stats.offsets_size += acfg->nmethods * 4;
6128
6129                 sprintf (end_symbol, "methods");
6130                 for (i = 0; i < acfg->nmethods; ++i) {
6131                         if (acfg->cfgs [i]) {
6132                                 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6133                         } else {
6134                                 emit_int32 (acfg, 0xffffffff);
6135                         }
6136                 }
6137         }
6138 #else
6139         sprintf (symbol, "code_offsets");
6140         emit_section_change (acfg, RODATA_SECT, 1);
6141         emit_alignment (acfg, 8);
6142         emit_label (acfg, symbol);
6143
6144         acfg->stats.offsets_size += acfg->nmethods * 4;
6145
6146         sprintf (end_symbol, "methods");
6147         for (i = 0; i < acfg->nmethods; ++i) {
6148                 if (acfg->cfgs [i]) {
6149                         emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6150                 } else {
6151                         emit_int32 (acfg, 0xffffffff);
6152                 }
6153         }
6154 #endif
6155         emit_line (acfg);
6156
6157         /* Emit a sorted table mapping methods to their unbox trampolines */
6158         sprintf (symbol, "unbox_trampolines");
6159         emit_section_change (acfg, RODATA_SECT, 1);
6160         emit_alignment (acfg, 8);
6161         emit_label (acfg, symbol);
6162
6163         sprintf (end_symbol, "methods");
6164         prev_index = -1;
6165         for (i = 0; i < acfg->nmethods; ++i) {
6166                 MonoCompile *cfg;
6167                 MonoMethod *method;
6168                 int index;
6169
6170                 cfg = acfg->cfgs [i];
6171                 if (!cfg)
6172                         continue;
6173
6174                 method = cfg->orig_method;
6175
6176                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6177                         index = get_method_index (acfg, method);
6178                         sprintf (symbol, "ut_%d", index);
6179
6180                         emit_int32 (acfg, index);
6181                         emit_symbol_diff (acfg, symbol, end_symbol, 0);
6182                         /* Make sure the table is sorted by index */
6183                         g_assert (index > prev_index);
6184                         prev_index = index;
6185                 }
6186         }
6187         sprintf (symbol, "unbox_trampolines_end");
6188         emit_label (acfg, symbol);
6189 }
6190
6191 static void
6192 emit_info (MonoAotCompile *acfg)
6193 {
6194         int oindex, i;
6195         char symbol [256];
6196         gint32 *offsets;
6197
6198         offsets = g_new0 (gint32, acfg->nmethods);
6199
6200         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6201                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6202
6203                 if (acfg->cfgs [i]) {
6204                         emit_method_info (acfg, acfg->cfgs [i]);
6205                         offsets [i] = acfg->cfgs [i]->method_info_offset;
6206                 } else {
6207                         offsets [i] = 0;
6208                 }
6209         }
6210
6211         sprintf (symbol, "method_info_offsets");
6212         emit_section_change (acfg, RODATA_SECT, 1);
6213         emit_alignment (acfg, 8);
6214         emit_label (acfg, symbol);
6215
6216         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6217
6218         g_free (offsets);
6219 }
6220
6221 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6222
6223 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6224 #define mix(a,b,c) { \
6225         a -= c;  a ^= rot(c, 4);  c += b; \
6226         b -= a;  b ^= rot(a, 6);  a += c; \
6227         c -= b;  c ^= rot(b, 8);  b += a; \
6228         a -= c;  a ^= rot(c,16);  c += b; \
6229         b -= a;  b ^= rot(a,19);  a += c; \
6230         c -= b;  c ^= rot(b, 4);  b += a; \
6231 }
6232 #define final(a,b,c) { \
6233         c ^= b; c -= rot(b,14); \
6234         a ^= c; a -= rot(c,11); \
6235         b ^= a; b -= rot(a,25); \
6236         c ^= b; c -= rot(b,16); \
6237         a ^= c; a -= rot(c,4);  \
6238         b ^= a; b -= rot(a,14); \
6239         c ^= b; c -= rot(b,24); \
6240 }
6241
6242 static guint
6243 mono_aot_type_hash (MonoType *t1)
6244 {
6245         guint hash = t1->type;
6246
6247         hash |= t1->byref << 6; /* do not collide with t1->type values */
6248         switch (t1->type) {
6249         case MONO_TYPE_VALUETYPE:
6250         case MONO_TYPE_CLASS:
6251         case MONO_TYPE_SZARRAY:
6252                 /* check if the distribution is good enough */
6253                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6254         case MONO_TYPE_PTR:
6255                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6256         case MONO_TYPE_ARRAY:
6257                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6258         case MONO_TYPE_GENERICINST:
6259                 return ((hash << 5) - hash) ^ 0;
6260         default:
6261                 return hash;
6262         }
6263 }
6264
6265 /*
6266  * mono_aot_method_hash:
6267  *
6268  *   Return a hash code for methods which only depends on metadata.
6269  */
6270 guint32
6271 mono_aot_method_hash (MonoMethod *method)
6272 {
6273         MonoMethodSignature *sig;
6274         MonoClass *klass;
6275         int i, hindex;
6276         int hashes_count;
6277         guint32 *hashes_start, *hashes;
6278         guint32 a, b, c;
6279         MonoGenericInst *ginst = NULL;
6280
6281         /* Similar to the hash in mono_method_get_imt_slot () */
6282
6283         sig = mono_method_signature (method);
6284
6285         if (method->is_inflated)
6286                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6287
6288         hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6289         hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6290         hashes = hashes_start;
6291
6292         /* Some wrappers are assigned to random classes */
6293         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6294                 klass = method->klass;
6295         else
6296                 klass = mono_defaults.object_class;
6297
6298         if (!method->wrapper_type) {
6299                 char *full_name = mono_type_full_name (&klass->byval_arg);
6300
6301                 hashes [0] = mono_metadata_str_hash (full_name);
6302                 hashes [1] = 0;
6303                 g_free (full_name);
6304         } else {
6305                 hashes [0] = mono_metadata_str_hash (klass->name);
6306                 hashes [1] = mono_metadata_str_hash (klass->name_space);
6307         }
6308         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6309                 /* The method name includes a stringified pointer */
6310                 hashes [2] = 0;
6311         else
6312                 hashes [2] = mono_metadata_str_hash (method->name);
6313         hashes [3] = method->wrapper_type;
6314         hashes [4] = mono_aot_type_hash (sig->ret);
6315         hindex = 5;
6316         for (i = 0; i < sig->param_count; i++) {
6317                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6318         }
6319         if (ginst) {
6320                 for (i = 0; i < ginst->type_argc; ++i)
6321                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6322         }               
6323         g_assert (hindex == hashes_count);
6324
6325         /* Setup internal state */
6326         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6327
6328         /* Handle most of the hashes */
6329         while (hashes_count > 3) {
6330                 a += hashes [0];
6331                 b += hashes [1];
6332                 c += hashes [2];
6333                 mix (a,b,c);
6334                 hashes_count -= 3;
6335                 hashes += 3;
6336         }
6337
6338         /* Handle the last 3 hashes (all the case statements fall through) */
6339         switch (hashes_count) { 
6340         case 3 : c += hashes [2];
6341         case 2 : b += hashes [1];
6342         case 1 : a += hashes [0];
6343                 final (a,b,c);
6344         case 0: /* nothing left to add */
6345                 break;
6346         }
6347         
6348         free (hashes_start);
6349         
6350         return c;
6351 }
6352 #undef rot
6353 #undef mix
6354 #undef final
6355
6356 /*
6357  * mono_aot_wrapper_name:
6358  *
6359  *   Return a string which uniqely identifies the given wrapper method.
6360  */
6361 char*
6362 mono_aot_wrapper_name (MonoMethod *method)
6363 {
6364         char *name, *tmpsig, *klass_desc;
6365
6366         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6367
6368         switch (method->wrapper_type) {
6369         case MONO_WRAPPER_RUNTIME_INVOKE:
6370                 if (!strcmp (method->name, "runtime_invoke_dynamic"))
6371                         name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
6372                 else
6373                         name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
6374                 break;
6375         default:
6376                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
6377                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
6378                 g_free (klass_desc);
6379                 break;
6380         }
6381
6382         g_free (tmpsig);
6383
6384         return name;
6385 }
6386
6387 /*
6388  * mono_aot_get_array_helper_from_wrapper;
6389  *
6390  * Get the helper method in Array called by an array wrapper method.
6391  */
6392 MonoMethod*
6393 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6394 {
6395         MonoMethod *m;
6396         const char *prefix;
6397         MonoGenericContext ctx;
6398         MonoType *args [16];
6399         char *mname, *iname, *s, *s2, *helper_name = NULL;
6400
6401         prefix = "System.Collections.Generic";
6402         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6403         s2 = strstr (s, "`1.");
6404         g_assert (s2);
6405         s2 [0] = '\0';
6406         iname = s;
6407         mname = s2 + 3;
6408
6409         //printf ("X: %s %s\n", iname, mname);
6410
6411         if (!strcmp (iname, "IList"))
6412                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6413         else
6414                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6415         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6416         g_assert (m);
6417         g_free (helper_name);
6418         g_free (s);
6419
6420         if (m->is_generic) {
6421                 memset (&ctx, 0, sizeof (ctx));
6422                 args [0] = &method->klass->element_class->byval_arg;
6423                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6424                 m = mono_class_inflate_generic_method (m, &ctx);
6425         }
6426
6427         return m;
6428 }
6429
6430 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6431
6432 typedef struct HashEntry {
6433     guint32 key, value, index;
6434         struct HashEntry *next;
6435 } HashEntry;
6436
6437 /*
6438  * emit_extra_methods:
6439  *
6440  * Emit methods which are not in the METHOD table, like wrappers.
6441  */
6442 static void
6443 emit_extra_methods (MonoAotCompile *acfg)
6444 {
6445         int i, table_size, buf_size;
6446         char symbol [256];
6447         guint8 *p, *buf;
6448         guint32 *info_offsets;
6449         guint32 hash;
6450         GPtrArray *table;
6451         HashEntry *entry, *new_entry;
6452         int nmethods, max_chain_length;
6453         int *chain_lengths;
6454
6455         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
6456
6457         /* Emit method info */
6458         nmethods = 0;
6459         for (i = 0; i < acfg->extra_methods->len; ++i) {
6460                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6461                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6462
6463                 if (!cfg)
6464                         continue;
6465
6466                 buf_size = 10240;
6467                 p = buf = g_malloc (buf_size);
6468
6469                 nmethods ++;
6470
6471                 method = cfg->method_to_register;
6472
6473                 encode_method_ref (acfg, method, p, &p);
6474
6475                 g_assert ((p - buf) < buf_size);
6476
6477                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6478                 g_free (buf);
6479         }
6480
6481         /*
6482          * Construct a chained hash table for mapping indexes in extra_method_info to
6483          * method indexes.
6484          */
6485         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
6486         table = g_ptr_array_sized_new (table_size);
6487         for (i = 0; i < table_size; ++i)
6488                 g_ptr_array_add (table, NULL);
6489         chain_lengths = g_new0 (int, table_size);
6490         max_chain_length = 0;
6491         for (i = 0; i < acfg->extra_methods->len; ++i) {
6492                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6493                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6494                 guint32 key, value;
6495
6496                 if (!cfg)
6497                         continue;
6498
6499                 key = info_offsets [i];
6500                 value = get_method_index (acfg, method);
6501
6502                 hash = mono_aot_method_hash (method) % table_size;
6503
6504                 chain_lengths [hash] ++;
6505                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
6506
6507                 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
6508                 new_entry->key = key;
6509                 new_entry->value = value;
6510
6511                 entry = g_ptr_array_index (table, hash);
6512                 if (entry == NULL) {
6513                         new_entry->index = hash;
6514                         g_ptr_array_index (table, hash) = new_entry;
6515                 } else {
6516                         while (entry->next)
6517                                 entry = entry->next;
6518                         
6519                         entry->next = new_entry;
6520                         new_entry->index = table->len;
6521                         g_ptr_array_add (table, new_entry);
6522                 }
6523         }
6524
6525         //printf ("MAX: %d\n", max_chain_length);
6526
6527         /* Emit the table */
6528         sprintf (symbol, "extra_method_table");
6529         emit_section_change (acfg, RODATA_SECT, 0);
6530         emit_alignment (acfg, 8);
6531         emit_label (acfg, symbol);
6532
6533         emit_int32 (acfg, table_size);
6534         for (i = 0; i < table->len; ++i) {
6535                 HashEntry *entry = g_ptr_array_index (table, i);
6536
6537                 if (entry == NULL) {
6538                         emit_int32 (acfg, 0);
6539                         emit_int32 (acfg, 0);
6540                         emit_int32 (acfg, 0);
6541                 } else {
6542                         //g_assert (entry->key > 0);
6543                         emit_int32 (acfg, entry->key);
6544                         emit_int32 (acfg, entry->value);
6545                         if (entry->next)
6546                                 emit_int32 (acfg, entry->next->index);
6547                         else
6548                                 emit_int32 (acfg, 0);
6549                 }
6550         }
6551
6552         /* 
6553          * Emit a table reverse mapping method indexes to their index in extra_method_info.
6554          * This is used by mono_aot_find_jit_info ().
6555          */
6556         sprintf (symbol, "extra_method_info_offsets");
6557         emit_section_change (acfg, RODATA_SECT, 0);
6558         emit_alignment (acfg, 8);
6559         emit_label (acfg, symbol);
6560
6561         emit_int32 (acfg, acfg->extra_methods->len);
6562         for (i = 0; i < acfg->extra_methods->len; ++i) {
6563                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6564
6565                 emit_int32 (acfg, get_method_index (acfg, method));
6566                 emit_int32 (acfg, info_offsets [i]);
6567         }
6568 }       
6569
6570 static void
6571 emit_exception_info (MonoAotCompile *acfg)
6572 {
6573         int i;
6574         char symbol [256];
6575         gint32 *offsets;
6576
6577         offsets = g_new0 (gint32, acfg->nmethods);
6578         for (i = 0; i < acfg->nmethods; ++i) {
6579                 if (acfg->cfgs [i]) {
6580                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
6581                         offsets [i] = acfg->cfgs [i]->ex_info_offset;
6582                 } else {
6583                         offsets [i] = 0;
6584                 }
6585         }
6586
6587         sprintf (symbol, "ex_info_offsets");
6588         emit_section_change (acfg, RODATA_SECT, 1);
6589         emit_alignment (acfg, 8);
6590         emit_label (acfg, symbol);
6591
6592         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6593         g_free (offsets);
6594 }
6595
6596 static void
6597 emit_unwind_info (MonoAotCompile *acfg)
6598 {
6599         int i;
6600         char symbol [128];
6601
6602         /* 
6603          * The unwind info contains a lot of duplicates so we emit each unique
6604          * entry once, and only store the offset from the start of the table in the
6605          * exception info.
6606          */
6607
6608         sprintf (symbol, "unwind_info");
6609         emit_section_change (acfg, RODATA_SECT, 1);
6610         emit_alignment (acfg, 8);
6611         emit_label (acfg, symbol);
6612
6613         for (i = 0; i < acfg->unwind_ops->len; ++i) {
6614                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
6615                 guint8 *unwind_info;
6616                 guint32 unwind_info_len;
6617                 guint8 buf [16];
6618                 guint8 *p;
6619
6620                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
6621
6622                 p = buf;
6623                 encode_value (unwind_info_len, p, &p);
6624                 emit_bytes (acfg, buf, p - buf);
6625                 emit_bytes (acfg, unwind_info, unwind_info_len);
6626
6627                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
6628         }
6629 }
6630
6631 static void
6632 emit_class_info (MonoAotCompile *acfg)
6633 {
6634         int i;
6635         char symbol [256];
6636         gint32 *offsets;
6637
6638         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6639         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6640                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6641
6642         sprintf (symbol, "class_info_offsets");
6643         emit_section_change (acfg, RODATA_SECT, 1);
6644         emit_alignment (acfg, 8);
6645         emit_label (acfg, symbol);
6646
6647         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6648         g_free (offsets);
6649 }
6650
6651 typedef struct ClassNameTableEntry {
6652         guint32 token, index;
6653         struct ClassNameTableEntry *next;
6654 } ClassNameTableEntry;
6655
6656 static void
6657 emit_class_name_table (MonoAotCompile *acfg)
6658 {
6659         int i, table_size;
6660         guint32 token, hash;
6661         MonoClass *klass;
6662         GPtrArray *table;
6663         char *full_name;
6664         char symbol [256];
6665         ClassNameTableEntry *entry, *new_entry;
6666
6667         /*
6668          * Construct a chained hash table for mapping class names to typedef tokens.
6669          */
6670         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6671         table = g_ptr_array_sized_new (table_size);
6672         for (i = 0; i < table_size; ++i)
6673                 g_ptr_array_add (table, NULL);
6674         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6675                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6676                 klass = mono_class_get (acfg->image, token);
6677                 if (!klass) {
6678                         mono_loader_clear_error ();
6679                         continue;
6680                 }
6681                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6682                 hash = mono_metadata_str_hash (full_name) % table_size;
6683                 g_free (full_name);
6684
6685                 /* FIXME: Allocate from the mempool */
6686                 new_entry = g_new0 (ClassNameTableEntry, 1);
6687                 new_entry->token = token;
6688
6689                 entry = g_ptr_array_index (table, hash);
6690                 if (entry == NULL) {
6691                         new_entry->index = hash;
6692                         g_ptr_array_index (table, hash) = new_entry;
6693                 } else {
6694                         while (entry->next)
6695                                 entry = entry->next;
6696                         
6697                         entry->next = new_entry;
6698                         new_entry->index = table->len;
6699                         g_ptr_array_add (table, new_entry);
6700                 }
6701         }
6702
6703         /* Emit the table */
6704         sprintf (symbol, "class_name_table");
6705         emit_section_change (acfg, RODATA_SECT, 0);
6706         emit_alignment (acfg, 8);
6707         emit_label (acfg, symbol);
6708
6709         /* FIXME: Optimize memory usage */
6710         g_assert (table_size < 65000);
6711         emit_int16 (acfg, table_size);
6712         g_assert (table->len < 65000);
6713         for (i = 0; i < table->len; ++i) {
6714                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6715
6716                 if (entry == NULL) {
6717                         emit_int16 (acfg, 0);
6718                         emit_int16 (acfg, 0);
6719                 } else {
6720                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
6721                         if (entry->next)
6722                                 emit_int16 (acfg, entry->next->index);
6723                         else
6724                                 emit_int16 (acfg, 0);
6725                 }
6726         }
6727 }
6728
6729 static void
6730 emit_image_table (MonoAotCompile *acfg)
6731 {
6732         int i;
6733         char symbol [256];
6734
6735         /*
6736          * The image table is small but referenced in a lot of places.
6737          * So we emit it at once, and reference its elements by an index.
6738          */
6739
6740         sprintf (symbol, "image_table");
6741         emit_section_change (acfg, RODATA_SECT, 1);
6742         emit_alignment (acfg, 8);
6743         emit_label (acfg, symbol);
6744
6745         emit_int32 (acfg, acfg->image_table->len);
6746         for (i = 0; i < acfg->image_table->len; i++) {
6747                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6748                 MonoAssemblyName *aname = &image->assembly->aname;
6749
6750                 /* FIXME: Support multi-module assemblies */
6751                 g_assert (image->assembly->image == image);
6752
6753                 emit_string (acfg, image->assembly_name);
6754                 emit_string (acfg, image->guid);
6755                 emit_string (acfg, aname->culture ? aname->culture : "");
6756                 emit_string (acfg, (const char*)aname->public_key_token);
6757
6758                 emit_alignment (acfg, 8);
6759                 emit_int32 (acfg, aname->flags);
6760                 emit_int32 (acfg, aname->major);
6761                 emit_int32 (acfg, aname->minor);
6762                 emit_int32 (acfg, aname->build);
6763                 emit_int32 (acfg, aname->revision);
6764         }
6765 }
6766
6767 static void
6768 emit_got_info (MonoAotCompile *acfg)
6769 {
6770         char symbol [256];
6771         int i, first_plt_got_patch, buf_size;
6772         guint8 *p, *buf;
6773         guint32 *got_info_offsets;
6774
6775         /* Add the patches needed by the PLT to the GOT */
6776         acfg->plt_got_offset_base = acfg->got_offset;
6777         first_plt_got_patch = acfg->got_patches->len;
6778         for (i = 1; i < acfg->plt_offset; ++i) {
6779                 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6780
6781                 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6782
6783                 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
6784         }
6785
6786         acfg->got_offset += acfg->plt_offset;
6787
6788         /**
6789          * FIXME: 
6790          * - optimize offsets table.
6791          * - reduce number of exported symbols.
6792          * - emit info for a klass only once.
6793          * - determine when a method uses a GOT slot which is guaranteed to be already 
6794          *   initialized.
6795          * - clean up and document the code.
6796          * - use String.Empty in class libs.
6797          */
6798
6799         /* Encode info required to decode shared GOT entries */
6800         buf_size = acfg->got_patches->len * 128;
6801         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6802         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6803         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6804         /* Unused */
6805         if (acfg->plt_offset)
6806                 acfg->plt_got_info_offsets [0] = 0;
6807         for (i = 0; i < acfg->got_patches->len; ++i) {
6808                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6809                 guint8 *p2;
6810
6811                 p = buf;
6812
6813                 encode_value (ji->type, p, &p);
6814                 p2 = p;
6815                 encode_patch (acfg, ji, p, &p);
6816                 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
6817                 g_assert (p - buf <= buf_size);
6818                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6819
6820                 if (i >= first_plt_got_patch)
6821                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6822                 acfg->stats.got_info_size += p - buf;
6823         }
6824
6825         /* Emit got_info_offsets table */
6826         sprintf (symbol, "got_info_offsets");
6827         emit_section_change (acfg, RODATA_SECT, 1);
6828         emit_alignment (acfg, 8);
6829         emit_label (acfg, symbol);
6830
6831         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6832         acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6833 }
6834
6835 static void
6836 emit_got (MonoAotCompile *acfg)
6837 {
6838         char symbol [256];
6839
6840         if (!acfg->llvm) {
6841                 /* Don't make GOT global so accesses to it don't need relocations */
6842                 sprintf (symbol, "%s", acfg->got_symbol);
6843                 emit_section_change (acfg, ".bss", 0);
6844                 emit_alignment (acfg, 8);
6845                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6846                 emit_label (acfg, symbol);
6847                 if (acfg->got_offset > 0)
6848                         emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6849
6850                 sprintf (symbol, "got_end");
6851                 emit_label (acfg, symbol);
6852         }
6853 }
6854
6855 typedef struct GlobalsTableEntry {
6856         guint32 value, index;
6857         struct GlobalsTableEntry *next;
6858 } GlobalsTableEntry;
6859
6860 static void
6861 emit_globals (MonoAotCompile *acfg)
6862 {
6863         int i, table_size;
6864         guint32 hash;
6865         GPtrArray *table;
6866         char symbol [256];
6867         GlobalsTableEntry *entry, *new_entry;
6868
6869         if (!acfg->aot_opts.static_link)
6870                 return;
6871
6872         /* 
6873          * When static linking, we emit a table containing our globals.
6874          */
6875
6876         /*
6877          * Construct a chained hash table for mapping global names to their index in
6878          * the globals table.
6879          */
6880         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6881         table = g_ptr_array_sized_new (table_size);
6882         for (i = 0; i < table_size; ++i)
6883                 g_ptr_array_add (table, NULL);
6884         for (i = 0; i < acfg->globals->len; ++i) {
6885                 char *name = g_ptr_array_index (acfg->globals, i);
6886
6887                 hash = mono_metadata_str_hash (name) % table_size;
6888
6889                 /* FIXME: Allocate from the mempool */
6890                 new_entry = g_new0 (GlobalsTableEntry, 1);
6891                 new_entry->value = i;
6892
6893                 entry = g_ptr_array_index (table, hash);
6894                 if (entry == NULL) {
6895                         new_entry->index = hash;
6896                         g_ptr_array_index (table, hash) = new_entry;
6897                 } else {
6898                         while (entry->next)
6899                                 entry = entry->next;
6900                         
6901                         entry->next = new_entry;
6902                         new_entry->index = table->len;
6903                         g_ptr_array_add (table, new_entry);
6904                 }
6905         }
6906
6907         /* Emit the table */
6908         sprintf (symbol, ".Lglobals_hash");
6909         emit_section_change (acfg, RODATA_SECT, 0);
6910         emit_alignment (acfg, 8);
6911         emit_label (acfg, symbol);
6912
6913         /* FIXME: Optimize memory usage */
6914         g_assert (table_size < 65000);
6915         emit_int16 (acfg, table_size);
6916         for (i = 0; i < table->len; ++i) {
6917                 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6918
6919                 if (entry == NULL) {
6920                         emit_int16 (acfg, 0);
6921                         emit_int16 (acfg, 0);
6922                 } else {
6923                         emit_int16 (acfg, entry->value + 1);
6924                         if (entry->next)
6925                                 emit_int16 (acfg, entry->next->index);
6926                         else
6927                                 emit_int16 (acfg, 0);
6928                 }
6929         }
6930
6931         /* Emit the names */
6932         for (i = 0; i < acfg->globals->len; ++i) {
6933                 char *name = g_ptr_array_index (acfg->globals, i);
6934
6935                 sprintf (symbol, "name_%d", i);
6936                 emit_section_change (acfg, RODATA_SECT, 1);
6937 #ifdef TARGET_MACH
6938                 emit_alignment (acfg, 4);
6939 #endif
6940                 emit_label (acfg, symbol);
6941                 emit_string (acfg, name);
6942         }
6943
6944         /* Emit the globals table */
6945         sprintf (symbol, "globals");
6946         emit_section_change (acfg, ".data", 0);
6947         /* This is not a global, since it is accessed by the init function */
6948         emit_alignment (acfg, 8);
6949         emit_label (acfg, symbol);
6950
6951         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6952         emit_pointer (acfg, symbol);
6953
6954         for (i = 0; i < acfg->globals->len; ++i) {
6955                 char *name = g_ptr_array_index (acfg->globals, i);
6956
6957                 sprintf (symbol, "name_%d", i);
6958                 emit_pointer (acfg, symbol);
6959
6960                 sprintf (symbol, "%s", name);
6961                 emit_pointer (acfg, symbol);
6962         }
6963         /* Null terminate the table */
6964         emit_int32 (acfg, 0);
6965         emit_int32 (acfg, 0);
6966 }
6967
6968 static void
6969 emit_autoreg (MonoAotCompile *acfg)
6970 {
6971         char *symbol;
6972
6973         /*
6974          * Emit a function into the .ctor section which will be called by the ELF
6975          * loader to register this module with the runtime.
6976          */
6977         if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6978                 return;
6979
6980         symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6981
6982         arch_emit_autoreg (acfg, symbol);
6983
6984         g_free (symbol);
6985 }       
6986
6987 static void
6988 emit_mem_end (MonoAotCompile *acfg)
6989 {
6990         char symbol [128];
6991
6992         sprintf (symbol, "mem_end");
6993         emit_section_change (acfg, ".text", 1);
6994         emit_alignment (acfg, 8);
6995         emit_label (acfg, symbol);
6996 }
6997
6998 /*
6999  * Emit a structure containing all the information not stored elsewhere.
7000  */
7001 static void
7002 emit_file_info (MonoAotCompile *acfg)
7003 {
7004         char symbol [256];
7005         int i;
7006         int gc_name_offset;
7007         const char *gc_name;
7008         char *build_info;
7009
7010         emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
7011
7012         if (acfg->aot_opts.bind_to_runtime_version) {
7013                 build_info = mono_get_runtime_build_info ();
7014                 emit_string_symbol (acfg, "runtime_version", build_info);
7015                 g_free (build_info);
7016         } else {
7017                 emit_string_symbol (acfg, "runtime_version", "");
7018         }
7019
7020         /* Emit a string holding the assembly name */
7021         emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
7022
7023         /*
7024          * The managed allocators are GC specific, so can't use an AOT image created by one GC
7025          * in another.
7026          */
7027         gc_name = mono_gc_get_gc_name ();
7028         gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
7029
7030         sprintf (symbol, "mono_aot_file_info");
7031         emit_section_change (acfg, ".data", 0);
7032         emit_alignment (acfg, 8);
7033         emit_label (acfg, symbol);
7034         if (!acfg->aot_opts.static_link)
7035                 emit_global (acfg, symbol, FALSE);
7036
7037         /* The data emitted here must match MonoAotFileInfo. */
7038
7039         emit_int32 (acfg, MONO_AOT_FILE_VERSION);
7040         emit_int32 (acfg, 0);
7041
7042         /* 
7043          * We emit pointers to our data structures instead of emitting global symbols which
7044          * point to them, to reduce the number of globals, and because using globals leads to
7045          * various problems (i.e. arm/thumb).
7046          */
7047         emit_pointer (acfg, acfg->got_symbol);
7048         emit_pointer (acfg, "methods");
7049         if (acfg->llvm) {
7050                 /*
7051                  * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
7052                  */
7053                 emit_pointer (acfg, "mono_eh_frame");
7054         } else {
7055                 emit_pointer (acfg, NULL);
7056         }
7057         emit_pointer (acfg, "blob");
7058         emit_pointer (acfg, "class_name_table");
7059         emit_pointer (acfg, "class_info_offsets");
7060         emit_pointer (acfg, "method_info_offsets");
7061         emit_pointer (acfg, "ex_info_offsets");
7062         emit_pointer (acfg, "code_offsets");
7063 #ifdef MONOTOUCH
7064         emit_pointer (acfg, "method_addresses");
7065 #endif
7066         emit_pointer (acfg, "extra_method_info_offsets");
7067         emit_pointer (acfg, "extra_method_table");
7068         emit_pointer (acfg, "got_info_offsets");
7069         emit_pointer (acfg, "methods_end");
7070         emit_pointer (acfg, "unwind_info");
7071         emit_pointer (acfg, "mem_end");
7072         emit_pointer (acfg, "image_table");
7073         emit_pointer (acfg, "plt");
7074         emit_pointer (acfg, "plt_end");
7075         emit_pointer (acfg, "assembly_guid");
7076         emit_pointer (acfg, "runtime_version");
7077         if (acfg->num_trampoline_got_entries) {
7078                 emit_pointer (acfg, "specific_trampolines");
7079                 emit_pointer (acfg, "static_rgctx_trampolines");
7080                 emit_pointer (acfg, "imt_thunks");
7081         } else {
7082                 emit_pointer (acfg, NULL);
7083                 emit_pointer (acfg, NULL);
7084                 emit_pointer (acfg, NULL);
7085         }
7086         if (acfg->thumb_mixed) {
7087                 emit_pointer (acfg, "thumb_end");
7088         } else {
7089                 emit_pointer (acfg, NULL);
7090         }
7091         if (acfg->aot_opts.static_link) {
7092                 emit_pointer (acfg, "globals");
7093         } else {
7094                 emit_pointer (acfg, NULL);
7095         }
7096         emit_pointer (acfg, "assembly_name");
7097         emit_pointer (acfg, "unbox_trampolines");
7098         emit_pointer (acfg, "unbox_trampolines_end");
7099
7100         emit_int32 (acfg, acfg->plt_got_offset_base);
7101         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7102         emit_int32 (acfg, acfg->plt_offset);
7103         emit_int32 (acfg, acfg->nmethods);
7104         emit_int32 (acfg, acfg->flags);
7105         emit_int32 (acfg, acfg->opts);
7106         emit_int32 (acfg, acfg->simd_opts);
7107         emit_int32 (acfg, gc_name_offset);
7108
7109         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7110                 emit_int32 (acfg, acfg->num_trampolines [i]);
7111         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7112                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
7113         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7114                 emit_int32 (acfg, acfg->trampoline_size [i]);
7115
7116 #if defined (TARGET_ARM) && defined (TARGET_MACH)
7117         {
7118                 MonoType t;
7119                 int align = 0;
7120
7121                 memset (&t, 0, sizeof (MonoType));
7122                 t.type = MONO_TYPE_R8;
7123                 mono_type_size (&t, &align);
7124
7125                 emit_int32 (acfg, align);
7126
7127                 memset (&t, 0, sizeof (MonoType));
7128                 t.type = MONO_TYPE_I8;
7129                 mono_type_size (&t, &align);
7130
7131                 emit_int32 (acfg, align);
7132         }
7133 #else
7134         emit_int32 (acfg, __alignof__ (double));
7135         emit_int32 (acfg, __alignof__ (gint64));
7136 #endif
7137
7138         if (acfg->aot_opts.static_link) {
7139                 char *p;
7140
7141                 /* 
7142                  * Emit a global symbol which can be passed by an embedding app to
7143                  * mono_aot_register_module (). The symbol points to a pointer to the the file info
7144                  * structure.
7145                  */
7146 #if defined(TARGET_MACH) && !defined(__native_client_codegen__)
7147                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7148 #else
7149                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7150 #endif
7151
7152                 /* Get rid of characters which cannot occur in symbols */
7153                 p = symbol;
7154                 for (p = symbol; *p; ++p) {
7155                         if (!(isalnum (*p) || *p == '_'))
7156                                 *p = '_';
7157                 }
7158                 acfg->static_linking_symbol = g_strdup (symbol);
7159                 emit_global_inner (acfg, symbol, FALSE);
7160                 emit_label (acfg, symbol);
7161                 emit_pointer (acfg, "mono_aot_file_info");
7162         }
7163 }
7164
7165 static void
7166 emit_blob (MonoAotCompile *acfg)
7167 {
7168         char symbol [128];
7169
7170         sprintf (symbol, "blob");
7171         emit_section_change (acfg, RODATA_SECT, 1);
7172         emit_alignment (acfg, 8);
7173         emit_label (acfg, symbol);
7174
7175         emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7176 }
7177
7178 static void
7179 emit_dwarf_info (MonoAotCompile *acfg)
7180 {
7181 #ifdef EMIT_DWARF_INFO
7182         int i;
7183         char symbol2 [128];
7184
7185         /* DIEs for methods */
7186         for (i = 0; i < acfg->nmethods; ++i) {
7187                 MonoCompile *cfg = acfg->cfgs [i];
7188
7189                 if (!cfg)
7190                         continue;
7191
7192                 // FIXME: LLVM doesn't define .Lme_...
7193                 if (cfg->compile_llvm)
7194                         continue;
7195
7196                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7197
7198                 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 ()));
7199         }
7200 #endif
7201 }
7202
7203 static void
7204 collect_methods (MonoAotCompile *acfg)
7205 {
7206         int i;
7207         MonoImage *image = acfg->image;
7208
7209         /* Collect methods */
7210         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7211                 MonoMethod *method;
7212                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7213
7214                 method = mono_get_method (acfg->image, token, NULL);
7215
7216                 if (!method) {
7217                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7218                         exit (1);
7219                 }
7220                         
7221                 /* Load all methods eagerly to skip the slower lazy loading code */
7222                 mono_class_setup_methods (method->klass);
7223
7224                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7225                         /* Compile the wrapper instead */
7226                         /* We do this here instead of add_wrappers () because it is easy to do it here */
7227                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7228                         method = wrapper;
7229                 }
7230
7231                 /* FIXME: Some mscorlib methods don't have debug info */
7232                 /*
7233                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7234                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7235                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7236                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7237                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7238                                 if (!mono_debug_lookup_method (method)) {
7239                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7240                                         exit (1);
7241                                 }
7242                         }
7243                 }
7244                 */
7245
7246                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7247                 add_method_with_index (acfg, method, i, FALSE);
7248                 acfg->method_index ++;
7249         }
7250
7251         add_generic_instances (acfg);
7252
7253         if (acfg->aot_opts.full_aot)
7254                 add_wrappers (acfg);
7255 }
7256
7257 static void
7258 compile_methods (MonoAotCompile *acfg)
7259 {
7260         int i, methods_len;
7261
7262         if (acfg->aot_opts.nthreads > 0) {
7263                 GPtrArray *frag;
7264                 int len, j;
7265                 GPtrArray *threads;
7266                 HANDLE handle;
7267                 gpointer *user_data;
7268                 MonoMethod **methods;
7269
7270                 methods_len = acfg->methods->len;
7271
7272                 len = acfg->methods->len / acfg->aot_opts.nthreads;
7273                 g_assert (len > 0);
7274                 /* 
7275                  * Partition the list of methods into fragments, and hand it to threads to
7276                  * process.
7277                  */
7278                 threads = g_ptr_array_new ();
7279                 /* Make a copy since acfg->methods is modified by compile_method () */
7280                 methods = g_new0 (MonoMethod*, methods_len);
7281                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7282                 for (i = 0; i < methods_len; ++i)
7283                         methods [i] = g_ptr_array_index (acfg->methods, i);
7284                 i = 0;
7285                 while (i < methods_len) {
7286                         frag = g_ptr_array_new ();
7287                         for (j = 0; j < len; ++j) {
7288                                 if (i < methods_len) {
7289                                         g_ptr_array_add (frag, methods [i]);
7290                                         i ++;
7291                                 }
7292                         }
7293
7294                         user_data = g_new0 (gpointer, 3);
7295                         user_data [0] = mono_domain_get ();
7296                         user_data [1] = acfg;
7297                         user_data [2] = frag;
7298                         
7299                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7300                         g_ptr_array_add (threads, handle);
7301                 }
7302                 g_free (methods);
7303
7304                 for (i = 0; i < threads->len; ++i) {
7305                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7306                 }
7307         } else {
7308                 methods_len = 0;
7309         }
7310
7311         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7312         for (i = methods_len; i < acfg->methods->len; ++i) {
7313                 /* This can new methods to acfg->methods */
7314                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7315         }
7316 }
7317
7318 static int
7319 compile_asm (MonoAotCompile *acfg)
7320 {
7321         char *command, *objfile;
7322         char *outfile_name, *tmp_outfile_name;
7323         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7324
7325 #if defined(TARGET_AMD64)
7326 #define AS_OPTIONS "--64"
7327 #elif defined(TARGET_POWERPC64)
7328 #define AS_OPTIONS "-a64 -mppc64"
7329 #define LD_OPTIONS "-m elf64ppc"
7330 #elif defined(sparc) && SIZEOF_VOID_P == 8
7331 #define AS_OPTIONS "-xarch=v9"
7332 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7333 #define AS_OPTIONS "-arch i386 -W"
7334 #else
7335 #define AS_OPTIONS ""
7336 #endif
7337
7338 #ifdef __native_client_codegen__
7339 #if defined(TARGET_AMD64)
7340 #define AS_NAME "nacl64-as"
7341 #else
7342 #define AS_NAME "nacl-as"
7343 #endif
7344 #else
7345 #define AS_NAME "as"
7346 #endif
7347
7348 #ifndef LD_OPTIONS
7349 #define LD_OPTIONS ""
7350 #endif
7351
7352 #define EH_LD_OPTIONS ""
7353
7354         if (acfg->aot_opts.asm_only) {
7355                 printf ("Output file: '%s'.\n", acfg->tmpfname);
7356                 if (acfg->aot_opts.static_link)
7357                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7358                 return 0;
7359         }
7360
7361         if (acfg->aot_opts.static_link) {
7362                 if (acfg->aot_opts.outfile)
7363                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7364                 else
7365                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
7366         } else {
7367                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7368         }
7369         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);
7370         printf ("Executing the native assembler: %s\n", command);
7371         if (system (command) != 0) {
7372                 g_free (command);
7373                 g_free (objfile);
7374                 return 1;
7375         }
7376
7377         g_free (command);
7378
7379         if (acfg->aot_opts.static_link) {
7380                 printf ("Output file: '%s'.\n", objfile);
7381                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7382                 g_free (objfile);
7383                 return 0;
7384         }
7385
7386         if (acfg->aot_opts.outfile)
7387                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7388         else
7389                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7390
7391         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7392
7393 #if defined(sparc)
7394         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7395 #elif defined(__ppc__) && defined(TARGET_MACH)
7396         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7397 #elif defined(HOST_WIN32)
7398         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7399 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7400         command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7401 #else
7402         command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7403 #endif
7404         printf ("Executing the native linker: %s\n", command);
7405         if (system (command) != 0) {
7406                 g_free (tmp_outfile_name);
7407                 g_free (outfile_name);
7408                 g_free (command);
7409                 g_free (objfile);
7410                 return 1;
7411         }
7412
7413         g_free (command);
7414
7415         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7416         printf ("Stripping the binary: %s\n", com);
7417         system (com);
7418         g_free (com);*/
7419
7420 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
7421         /* 
7422          * gas generates 'mapping symbols' each time code and data is mixed, which 
7423          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7424          */
7425         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7426         printf ("Stripping the binary: %s\n", command);
7427         if (system (command) != 0) {
7428                 g_free (tmp_outfile_name);
7429                 g_free (outfile_name);
7430                 g_free (command);
7431                 g_free (objfile);
7432                 return 1;
7433         }
7434 #endif
7435
7436         rename (tmp_outfile_name, outfile_name);
7437
7438 #if defined(TARGET_MACH)
7439         command = g_strdup_printf ("dsymutil %s", outfile_name);
7440         printf ("Generating debug symbols: %s\n", command);
7441         if (system (command) != 0) {
7442                 return 1;
7443         }
7444 #endif
7445
7446         if (!acfg->aot_opts.save_temps)
7447                 unlink (objfile);
7448
7449         g_free (tmp_outfile_name);
7450         g_free (outfile_name);
7451         g_free (objfile);
7452
7453         if (acfg->aot_opts.save_temps)
7454                 printf ("Retained input file.\n");
7455         else
7456                 unlink (acfg->tmpfname);
7457
7458         return 0;
7459 }
7460
7461 static MonoAotCompile*
7462 acfg_create (MonoAssembly *ass, guint32 opts)
7463 {
7464         MonoImage *image = ass->image;
7465         MonoAotCompile *acfg;
7466         int i;
7467
7468         acfg = g_new0 (MonoAotCompile, 1);
7469         acfg->methods = g_ptr_array_new ();
7470         acfg->method_indexes = g_hash_table_new (NULL, NULL);
7471         acfg->method_depth = g_hash_table_new (NULL, NULL);
7472         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
7473         acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7474         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7475         acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
7476         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7477                 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7478         acfg->got_patches = g_ptr_array_new ();
7479         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
7480         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7481         acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7482         acfg->image_hash = g_hash_table_new (NULL, NULL);
7483         acfg->image_table = g_ptr_array_new ();
7484         acfg->globals = g_ptr_array_new ();
7485         acfg->image = image;
7486         acfg->opts = opts;
7487         /* TODO: Write out set of SIMD instructions used, rather than just those available */
7488         acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
7489         acfg->mempool = mono_mempool_new ();
7490         acfg->extra_methods = g_ptr_array_new ();
7491         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
7492         acfg->unwind_ops = g_ptr_array_new ();
7493         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7494         acfg->method_order = g_ptr_array_new ();
7495         acfg->export_names = g_hash_table_new (NULL, NULL);
7496         acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
7497         acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
7498         acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
7499         InitializeCriticalSection (&acfg->mutex);
7500
7501         return acfg;
7502 }
7503
7504 static void
7505 acfg_free (MonoAotCompile *acfg)
7506 {
7507         int i;
7508
7509         img_writer_destroy (acfg->w);
7510         for (i = 0; i < acfg->nmethods; ++i)
7511                 if (acfg->cfgs [i])
7512                         g_free (acfg->cfgs [i]);
7513         g_free (acfg->cfgs);
7514         g_free (acfg->static_linking_symbol);
7515         g_free (acfg->got_symbol);
7516         g_free (acfg->plt_symbol);
7517         g_ptr_array_free (acfg->methods, TRUE);
7518         g_ptr_array_free (acfg->got_patches, TRUE);
7519         g_ptr_array_free (acfg->image_table, TRUE);
7520         g_ptr_array_free (acfg->globals, TRUE);
7521         g_ptr_array_free (acfg->unwind_ops, TRUE);
7522         g_hash_table_destroy (acfg->method_indexes);
7523         g_hash_table_destroy (acfg->method_depth);
7524         g_hash_table_destroy (acfg->plt_offset_to_entry);
7525         g_hash_table_destroy (acfg->patch_to_plt_entry);
7526         g_hash_table_destroy (acfg->patch_to_got_offset);
7527         g_hash_table_destroy (acfg->method_to_cfg);
7528         g_hash_table_destroy (acfg->token_info_hash);
7529         g_hash_table_destroy (acfg->method_to_pinvoke_import);
7530         g_hash_table_destroy (acfg->image_hash);
7531         g_hash_table_destroy (acfg->unwind_info_offsets);
7532         g_hash_table_destroy (acfg->method_label_hash);
7533         g_hash_table_destroy (acfg->export_names);
7534         g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
7535         g_hash_table_destroy (acfg->klass_blob_hash);
7536         g_hash_table_destroy (acfg->method_blob_hash);
7537         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7538                 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
7539         g_free (acfg->patch_to_got_offset_by_type);
7540         mono_mempool_destroy (acfg->mempool);
7541         g_free (acfg);
7542 }
7543
7544 int
7545 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7546 {
7547         MonoImage *image = ass->image;
7548         int i, res;
7549         MonoAotCompile *acfg;
7550         char *outfile_name, *tmp_outfile_name, *p;
7551         TV_DECLARE (atv);
7552         TV_DECLARE (btv);
7553
7554         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
7555
7556         acfg = acfg_create (ass, opts);
7557
7558         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
7559         acfg->aot_opts.write_symbols = TRUE;
7560         acfg->aot_opts.ntrampolines = 1024;
7561         acfg->aot_opts.nrgctx_trampolines = 1024;
7562         acfg->aot_opts.nimt_trampolines = 128;
7563         acfg->aot_opts.llvm_path = g_strdup ("");
7564
7565         mono_aot_parse_options (aot_options, &acfg->aot_opts);
7566
7567         if (acfg->aot_opts.static_link)
7568                 acfg->aot_opts.autoreg = TRUE;
7569
7570         //acfg->aot_opts.print_skipped_methods = TRUE;
7571
7572 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7573         if (acfg->aot_opts.full_aot) {
7574                 printf ("--aot=full is not supported on this platform.\n");
7575                 return 1;
7576         }
7577 #endif
7578
7579         if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
7580                 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
7581                 exit (1);
7582         }
7583
7584         if (acfg->aot_opts.static_link)
7585                 acfg->aot_opts.asm_writer = TRUE;
7586
7587         if (acfg->aot_opts.soft_debug) {
7588                 MonoDebugOptions *opt = mini_get_debug_options ();
7589
7590                 opt->mdb_optimizations = TRUE;
7591                 opt->gen_seq_points = TRUE;
7592
7593                 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
7594                         fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
7595                         return 1;
7596                 }
7597                 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
7598         }
7599
7600         if (mono_use_llvm) {
7601                 acfg->llvm = TRUE;
7602                 acfg->aot_opts.asm_writer = TRUE;
7603                 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
7604
7605                 if (acfg->aot_opts.soft_debug) {
7606                         fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
7607                         exit (1);
7608                 }
7609         }
7610
7611         if (acfg->aot_opts.full_aot)
7612                 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
7613
7614         load_profile_files (acfg);
7615
7616         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
7617 #ifdef MONO_ARCH_GSHARED_SUPPORTED
7618         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
7619 #endif
7620         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
7621
7622         acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
7623
7624         arch_init (acfg);
7625
7626         acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
7627         acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
7628         acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
7629
7630         /* Get rid of characters which cannot occur in symbols */
7631         for (p = acfg->got_symbol_base; *p; ++p) {
7632                 if (!(isalnum (*p) || *p == '_'))
7633                         *p = '_';
7634         }
7635         for (p = acfg->plt_symbol; *p; ++p) {
7636                 if (!(isalnum (*p) || *p == '_'))
7637                         *p = '_';
7638         }
7639         for (p = acfg->assembly_name_sym; *p; ++p) {
7640                 if (!(isalnum (*p) || *p == '_'))
7641                         *p = '_';
7642         }
7643
7644         acfg->method_index = 1;
7645
7646         collect_methods (acfg);
7647
7648         acfg->cfgs_size = acfg->methods->len + 32;
7649         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
7650
7651         /* PLT offset 0 is reserved for the PLT trampoline */
7652         acfg->plt_offset = 1;
7653
7654 #ifdef ENABLE_LLVM
7655         if (acfg->llvm) {
7656                 llvm_acfg = acfg;
7657                 mono_llvm_create_aot_module (acfg->got_symbol_base);
7658         }
7659 #endif
7660
7661         /* GOT offset 0 is reserved for the address of the current assembly */
7662         {
7663                 MonoJumpInfo *ji;
7664
7665                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7666                 ji->type = MONO_PATCH_INFO_IMAGE;
7667                 ji->data.image = acfg->image;
7668
7669                 get_got_offset (acfg, ji);
7670
7671                 /* Slot 1 is reserved for the mscorlib got addr */
7672                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7673                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
7674                 get_got_offset (acfg, ji);
7675
7676                 /* This is very common */
7677                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7678                 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
7679                 get_got_offset (acfg, ji);
7680         }
7681
7682         TV_GETTIME (atv);
7683
7684         compile_methods (acfg);
7685
7686         TV_GETTIME (btv);
7687
7688         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7689
7690         TV_GETTIME (atv);
7691
7692 #ifdef ENABLE_LLVM
7693         if (acfg->llvm) {
7694                 if (acfg->aot_opts.asm_only) {
7695                         if (acfg->aot_opts.outfile)
7696                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7697                         else
7698                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7699                 } else {
7700                         acfg->tmpfname = g_strdup ("temp.s");
7701                 }
7702
7703                 emit_llvm_file (acfg);
7704         }
7705 #endif
7706
7707         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7708                 if (acfg->aot_opts.outfile)
7709                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7710                 else
7711                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7712
7713                 /* 
7714                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
7715                  * it might be in another file system so the rename () won't work.
7716                  */
7717                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7718
7719                 acfg->fp = fopen (tmp_outfile_name, "w");
7720                 if (!acfg->fp) {
7721                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7722                         return 1;
7723                 }
7724
7725                 acfg->w = img_writer_create (acfg->fp, TRUE);
7726                 acfg->use_bin_writer = TRUE;
7727         } else {
7728                 if (acfg->llvm) {
7729                         /* Append to the .s file created by llvm */
7730                         /* FIXME: Use multiple files instead */
7731                         acfg->fp = fopen (acfg->tmpfname, "a+");
7732                 } else {
7733                         if (acfg->aot_opts.asm_only) {
7734                                 if (acfg->aot_opts.outfile)
7735                                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7736                                 else
7737                                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7738                                 acfg->fp = fopen (acfg->tmpfname, "w+");
7739                         } else {
7740                                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7741                                 acfg->fp = fdopen (i, "w+");
7742                         }
7743                         if (acfg->fp == 0) {
7744                                 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
7745                                 return 1;
7746                         }
7747                 }
7748                 acfg->w = img_writer_create (acfg->fp, FALSE);
7749                 
7750                 tmp_outfile_name = NULL;
7751                 outfile_name = NULL;
7752         }
7753
7754         acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7755
7756         /* Compute symbols for methods */
7757         for (i = 0; i < acfg->nmethods; ++i) {
7758                 if (acfg->cfgs [i]) {
7759                         MonoCompile *cfg = acfg->cfgs [i];
7760                         int method_index = get_method_index (acfg, cfg->orig_method);
7761
7762                         if (COMPILE_LLVM (cfg))
7763                                 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7764                         else if (acfg->global_symbols)
7765                                 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
7766                         else
7767                                 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7768                 }
7769         }
7770
7771         if (!acfg->aot_opts.nodebug)
7772                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7773
7774         img_writer_emit_start (acfg->w);
7775
7776         if (acfg->dwarf)
7777                 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7778
7779         if (acfg->thumb_mixed) {
7780                 char symbol [256];
7781                 /*
7782                  * This global symbol marks the end of THUMB code, and the beginning of ARM
7783                  * code generated by our JIT.
7784                  */
7785                 sprintf (symbol, "thumb_end");
7786                 emit_section_change (acfg, ".text", 0);
7787                 emit_alignment (acfg, 8);
7788                 emit_label (acfg, symbol);
7789                 emit_zero_bytes (acfg, 16);
7790
7791                 fprintf (acfg->fp, ".arm\n");
7792         }
7793
7794         emit_code (acfg);
7795
7796         emit_info (acfg);
7797
7798         emit_extra_methods (acfg);
7799
7800         emit_trampolines (acfg);
7801
7802         emit_class_name_table (acfg);
7803
7804         emit_got_info (acfg);
7805
7806         emit_exception_info (acfg);
7807
7808         emit_unwind_info (acfg);
7809
7810         emit_class_info (acfg);
7811
7812         emit_plt (acfg);
7813
7814         emit_image_table (acfg);
7815
7816         emit_got (acfg);
7817
7818         emit_file_info (acfg);
7819
7820         emit_blob (acfg);
7821
7822         emit_globals (acfg);
7823
7824         emit_autoreg (acfg);
7825
7826         if (acfg->dwarf) {
7827                 emit_dwarf_info (acfg);
7828                 mono_dwarf_writer_close (acfg->dwarf);
7829         }
7830
7831         emit_mem_end (acfg);
7832
7833         if (acfg->need_pt_gnu_stack) {
7834                 /* This is required so the .so doesn't have an executable stack */
7835                 /* The bin writer already emits this */
7836                 if (!acfg->use_bin_writer)
7837                         fprintf (acfg->fp, "\n.section  .note.GNU-stack,\"\",@progbits\n");
7838         }
7839
7840         TV_GETTIME (btv);
7841
7842         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7843
7844         if (acfg->llvm)
7845                 g_assert (acfg->got_offset <= acfg->final_got_size);
7846
7847         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);
7848         printf ("Compiled: %d/%d (%d%%), No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n", 
7849                         acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
7850                         acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
7851                         acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7852         if (acfg->stats.genericcount)
7853                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7854         if (acfg->stats.abscount)
7855                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7856         if (acfg->stats.lmfcount)
7857                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7858         if (acfg->stats.ocount)
7859                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7860         if (acfg->llvm)
7861                 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7862
7863         TV_GETTIME (atv);
7864         res = img_writer_emit_writeout (acfg->w);
7865         if (res != 0) {
7866                 acfg_free (acfg);
7867                 return res;
7868         }
7869         if (acfg->use_bin_writer) {
7870                 int err = rename (tmp_outfile_name, outfile_name);
7871
7872                 if (err) {
7873                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7874                         return 1;
7875                 }
7876         } else {
7877                 res = compile_asm (acfg);
7878                 if (res != 0) {
7879                         acfg_free (acfg);
7880                         return res;
7881                 }
7882         }
7883         TV_GETTIME (btv);
7884         acfg->stats.link_time = TV_ELAPSED (atv, btv);
7885
7886         if (acfg->aot_opts.stats) {
7887                 int i;
7888
7889                 printf ("GOT slot distribution:\n");
7890                 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7891                         if (acfg->stats.got_slot_types [i])
7892                                 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
7893         }
7894
7895         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);
7896
7897         acfg_free (acfg);
7898         
7899         return 0;
7900 }
7901
7902 #else
7903
7904 /* AOT disabled */
7905
7906 void*
7907 mono_aot_readonly_field_override (MonoClassField *field)
7908 {
7909         return NULL;
7910 }
7911
7912 int
7913 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7914 {
7915         return 0;
7916 }
7917
7918 #endif