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