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