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