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