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