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