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