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