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