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