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