2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 /* Remaining AOT-only work:
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
25 #include <sys/types.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger-internal.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
70 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
72 #if defined(__linux__) || defined(__native_client_codegen__)
73 #define RODATA_SECT ".rodata"
74 #elif defined(TARGET_MACH)
75 #define RODATA_SECT ".section __TEXT, __const"
77 #define RODATA_SECT ".text"
80 #define TV_DECLARE(name) gint64 name
81 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
82 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
85 #define SHARED_EXT ".dll"
86 #elif defined(__ppc__) && defined(TARGET_MACH)
87 #define SHARED_EXT ".dylib"
88 #elif defined(TARGET_MACH) && defined(TARGET_X86) && !defined(__native_client_codegen__)
89 #define SHARED_EXT ".dylib"
90 #elif defined(TARGET_MACH) && defined(TARGET_AMD64) && !defined(__native_client_codegen__)
91 #define SHARED_EXT ".dylib"
93 #define SHARED_EXT ".so"
96 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
97 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
98 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
100 /* predefined values for static readonly fields without needed to run the .cctor */
101 typedef struct _ReadOnlyValue ReadOnlyValue;
102 struct _ReadOnlyValue {
105 int type; /* to be used later for typechecking to prevent user errors */
114 static ReadOnlyValue *readonly_values = NULL;
116 typedef struct MonoAotOptions {
119 gboolean write_symbols;
120 gboolean metadata_only;
121 gboolean bind_to_runtime_version;
124 gboolean static_link;
128 gboolean dwarf_debug;
130 gboolean log_generics;
131 gboolean log_instances;
132 gboolean direct_pinvoke;
133 gboolean direct_icalls;
134 gboolean no_direct_calls;
135 gboolean use_trampolines_page;
136 gboolean no_instances;
140 int nrgctx_trampolines;
141 int nimt_trampolines;
142 int ngsharedvt_arg_trampolines;
143 int nrgctx_fetch_trampolines;
144 gboolean print_skipped_methods;
150 char *instances_logfile_path;
153 typedef struct MonoAotStats {
154 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
155 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
156 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
157 int got_slots, offsets_size;
158 int got_slot_types [MONO_PATCH_INFO_NONE];
159 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
160 int jit_time, gen_time, link_time;
163 typedef struct MonoAotCompile {
166 GHashTable *method_indexes;
167 GHashTable *method_depth;
170 GHashTable **patch_to_plt_entry;
171 GHashTable *plt_offset_to_entry;
172 GHashTable *patch_to_got_offset;
173 GHashTable **patch_to_got_offset_by_type;
174 GPtrArray *got_patches;
175 GHashTable *image_hash;
176 GHashTable *method_to_cfg;
177 GHashTable *token_info_hash;
178 GHashTable *method_to_pinvoke_import;
179 GPtrArray *extra_methods;
180 GPtrArray *image_table;
182 GPtrArray *method_order;
183 GHashTable *export_names;
184 /* Maps MonoClass* -> blob offset */
185 GHashTable *klass_blob_hash;
186 /* Maps MonoMethod* -> blob offset */
187 GHashTable *method_blob_hash;
188 guint32 *plt_got_info_offsets;
189 guint32 got_offset, plt_offset, plt_got_offset_base;
190 guint32 final_got_size;
191 /* Number of GOT entries reserved for trampolines */
192 guint32 num_trampoline_got_entries;
193 guint32 tramp_page_size;
195 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
196 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
197 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
198 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
200 MonoAotOptions aot_opts;
204 MonoMemPool *mempool;
207 char *static_linking_symbol;
208 CRITICAL_SECTION mutex;
209 gboolean use_bin_writer;
210 gboolean gas_line_numbers;
212 MonoDwarfWriter *dwarf;
217 GHashTable *unwind_info_offsets;
218 GPtrArray *unwind_ops;
219 guint32 unwind_info_offset;
220 char *got_symbol_base;
223 char *methods_symbol;
224 GHashTable *method_label_hash;
225 const char *temp_prefix;
226 const char *user_symbol_prefix;
227 const char *llvm_label_prefix;
228 guint32 label_generator;
230 MonoAotFileFlags flags;
231 MonoDynamicStream blob;
232 MonoClass **typespec_classes;
235 char *assembly_name_sym;
236 GHashTable *plt_entry_debug_sym_cache;
237 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
238 GHashTable *ginst_hash;
239 GHashTable *dwarf_ln_filenames;
240 gboolean global_symbols;
241 gboolean direct_method_addresses;
242 int objc_selector_index, objc_selector_index_2;
243 GPtrArray *objc_selectors;
244 GHashTable *objc_selector_to_index;
245 FILE *instances_logfile;
250 char *symbol, *llvm_symbol, *debug_sym;
252 gboolean jit_used, llvm_used;
255 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
256 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
258 /* This points to the current acfg in LLVM mode */
259 static MonoAotCompile *llvm_acfg;
261 #ifdef HAVE_ARRAY_ELEM_INIT
262 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
263 #define MSGSTRFIELD1(line) str##line
264 static const struct msgstr_t {
265 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
266 #include "patch-info.h"
269 #define PATCH_INFO(a,b) b,
270 #include "patch-info.h"
273 static const gint16 opidx [] = {
274 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
275 #include "patch-info.h"
279 static G_GNUC_UNUSED const char*
280 get_patch_name (int info)
282 return (const char*)&opstr + opidx [info];
286 #define PATCH_INFO(a,b) b,
287 static const char* const
288 patch_types [MONO_PATCH_INFO_NUM + 1] = {
289 #include "patch-info.h"
293 static G_GNUC_UNUSED const char*
294 get_patch_name (int info)
296 return patch_types [info];
302 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
304 /* Wrappers around the image writer functions */
307 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
309 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
313 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
315 img_writer_emit_push_section (acfg->w, section_name, subsection);
319 emit_pop_section (MonoAotCompile *acfg)
321 img_writer_emit_pop_section (acfg->w);
325 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
327 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
331 emit_label (MonoAotCompile *acfg, const char *name)
333 img_writer_emit_label (acfg->w, name);
337 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
339 img_writer_emit_bytes (acfg->w, buf, size);
343 emit_string (MonoAotCompile *acfg, const char *value)
345 img_writer_emit_string (acfg->w, value);
349 emit_line (MonoAotCompile *acfg)
351 img_writer_emit_line (acfg->w);
355 emit_alignment (MonoAotCompile *acfg, int size)
357 img_writer_emit_alignment (acfg->w, size);
361 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
363 img_writer_emit_pointer_unaligned (acfg->w, target);
367 emit_pointer (MonoAotCompile *acfg, const char *target)
369 img_writer_emit_pointer (acfg->w, target);
373 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
375 if (prefix [0] != '\0') {
376 char *s = g_strdup_printf ("%s%s", prefix, target);
377 img_writer_emit_pointer (acfg->w, s);
380 img_writer_emit_pointer (acfg->w, target);
385 emit_int16 (MonoAotCompile *acfg, int value)
387 img_writer_emit_int16 (acfg->w, value);
391 emit_int32 (MonoAotCompile *acfg, int value)
393 img_writer_emit_int32 (acfg->w, value);
397 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
399 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
403 emit_zero_bytes (MonoAotCompile *acfg, int num)
405 img_writer_emit_zero_bytes (acfg->w, num);
409 emit_byte (MonoAotCompile *acfg, guint8 val)
411 img_writer_emit_byte (acfg->w, val);
414 #ifdef __native_client_codegen__
416 emit_nacl_call_alignment (MonoAotCompile *acfg)
418 img_writer_emit_nacl_call_alignment (acfg->w);
422 static G_GNUC_UNUSED void
423 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
425 img_writer_emit_global (acfg->w, name, func);
429 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
431 if (acfg->aot_opts.no_dlsym) {
432 g_ptr_array_add (acfg->globals, g_strdup (name));
433 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
435 img_writer_emit_global (acfg->w, name, func);
440 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
442 img_writer_emit_symbol_size (acfg->w, name, end_label);
446 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
448 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
450 /* On apple, all symbols need to be aligned to avoid warnings from ld */
451 emit_alignment (acfg, 4);
453 img_writer_emit_label (acfg->w, name);
454 img_writer_emit_string (acfg->w, value);
457 static G_GNUC_UNUSED void
458 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
461 guint8 b = value & 0x7f;
463 if (value != 0) /* more bytes to come */
469 static G_GNUC_UNUSED void
470 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
473 gboolean negative = (value < 0);
480 /* the following is unnecessary if the
481 * implementation of >>= uses an arithmetic rather
482 * than logical shift for a signed left operand
486 value |= - ((gint64)1 <<(size - 7));
487 /* sign bit of byte is second high order bit (0x40) */
488 if ((value == 0 && !(byte & 0x40)) ||
489 (value == -1 && (byte & 0x40)))
493 emit_byte (acfg, byte);
497 static G_GNUC_UNUSED void
498 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
503 guint8 b = value & 0x7f;
505 if (value != 0) /* more bytes to come */
513 static G_GNUC_UNUSED void
514 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
517 gboolean negative = (value < 0);
525 /* the following is unnecessary if the
526 * implementation of >>= uses an arithmetic rather
527 * than logical shift for a signed left operand
531 value |= - (1 <<(size - 7));
532 /* sign bit of byte is second high order bit (0x40) */
533 if ((value == 0 && !(byte & 0x40)) ||
534 (value == -1 && (byte & 0x40)))
545 emit_unset_mode (MonoAotCompile *acfg)
547 img_writer_emit_unset_mode (acfg->w);
550 static G_GNUC_UNUSED void
551 emit_set_thumb_mode (MonoAotCompile *acfg)
553 emit_unset_mode (acfg);
554 fprintf (acfg->fp, ".code 16\n");
557 static G_GNUC_UNUSED void
558 emit_set_arm_mode (MonoAotCompile *acfg)
560 emit_unset_mode (acfg);
561 fprintf (acfg->fp, ".code 32\n");
565 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
567 emit_bytes (acfg, buf, size);
570 /* ARCHITECTURE SPECIFIC CODE */
572 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
573 #define EMIT_DWARF_INFO 1
576 #if defined(TARGET_ARM)
577 #define AOT_FUNC_ALIGNMENT 4
579 #define AOT_FUNC_ALIGNMENT 16
581 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
582 #undef AOT_FUNC_ALIGNMENT
583 #define AOT_FUNC_ALIGNMENT 32
586 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
587 #define PPC_LD_OP "ld"
588 #define PPC_LDX_OP "ldx"
590 #define PPC_LD_OP "lwz"
591 #define PPC_LDX_OP "lwzx"
595 #define AOT_TARGET_STR "AMD64"
600 #define AOT_TARGET_STR "ARM (MACH)"
602 #define AOT_TARGET_STR "ARM (!MACH)"
606 #ifdef TARGET_POWERPC64
607 #ifdef __mono_ilp32__
608 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
610 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
613 #ifdef TARGET_POWERPC
614 #ifdef __mono_ilp32__
615 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
617 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
624 #define AOT_TARGET_STR "X86 (WIN32)"
625 #elif defined(__native_client_codegen__)
626 #define AOT_TARGET_STR "X86 (native client codegen)"
628 #define AOT_TARGET_STR "X86 (!native client codegen)"
632 #ifndef AOT_TARGET_STR
633 #define AOT_TARGET_STR ""
637 arch_init (MonoAotCompile *acfg)
639 acfg->llc_args = g_string_new ("");
640 acfg->as_args = g_string_new ("");
643 * The prefix LLVM likes to put in front of symbol names on darwin.
644 * The mach-os specs require this for globals, but LLVM puts them in front of all
645 * symbols. We need to handle this, since we need to refer to LLVM generated
648 acfg->llvm_label_prefix = "";
649 acfg->user_symbol_prefix = "";
651 #if defined(TARGET_AMD64)
652 g_string_append (acfg->llc_args, " -march=x86-64");
656 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
657 g_string_append (acfg->llc_args, "-mattr=+v6");
660 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
661 g_string_append (acfg->as_args, " -mfpu=vfp3");
663 g_string_append (acfg->llc_args, " -soft-float");
666 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
667 acfg->thumb_mixed = TRUE;
669 if (acfg->aot_opts.mtriple)
670 mono_arch_set_target (acfg->aot_opts.mtriple);
674 acfg->user_symbol_prefix = "_";
675 acfg->llvm_label_prefix = "_";
676 acfg->need_no_dead_strip = TRUE;
677 acfg->aot_opts.gnu_asm = TRUE;
680 #if defined(__linux__) && !defined(TARGET_ARM)
681 acfg->need_pt_gnu_stack = TRUE;
685 acfg->direct_method_addresses = TRUE;
686 acfg->global_symbols = TRUE;
690 #ifdef MONO_ARCH_AOT_SUPPORTED
692 * arch_emit_direct_call:
694 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
698 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
700 #if defined(TARGET_X86) || defined(TARGET_AMD64)
701 /* Need to make sure this is exactly 5 bytes long */
702 if (external && !acfg->use_bin_writer) {
703 emit_unset_mode (acfg);
704 fprintf (acfg->fp, "call %s\n", target);
706 emit_byte (acfg, '\xe8');
707 emit_symbol_diff (acfg, target, ".", -4);
710 #elif defined(TARGET_ARM)
711 if (acfg->use_bin_writer) {
718 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
719 emit_bytes (acfg, buf, 4);
721 emit_unset_mode (acfg);
723 fprintf (acfg->fp, "blx %s\n", target);
725 fprintf (acfg->fp, "bl %s\n", target);
728 #elif defined(TARGET_POWERPC)
729 if (acfg->use_bin_writer) {
730 g_assert_not_reached ();
732 emit_unset_mode (acfg);
733 fprintf (acfg->fp, "bl %s\n", target);
737 g_assert_not_reached ();
744 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
746 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
747 * in in the 2. slot of every GOT, and require every method to place the GOT
748 * address in r30, even when it doesn't access the GOT otherwise. This way,
749 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
754 * PPC64 uses function descriptors which greatly complicate all code, since
755 * these are used very inconsistently in the runtime. Some functions like
756 * mono_compile_method () return ftn descriptors, while others like the
757 * trampoline creation functions do not.
758 * We assume that all GOT slots contain function descriptors, and create
759 * descriptors in aot-runtime.c when needed.
760 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
761 * from function descriptors, we could do the same, but it would require
762 * rewriting all the ppc/aot code to handle function descriptors properly.
763 * So instead, we use the same approach as on PPC32.
764 * This is a horrible mess, but fixing it would probably lead to an even bigger
770 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
773 #ifdef MONO_ARCH_AOT_SUPPORTED
775 * arch_emit_got_offset:
777 * The memory pointed to by CODE should hold native code for computing the GOT
778 * address. Emit this code while patching it with the offset between code and
779 * the GOT. CODE_SIZE is set to the number of bytes emitted.
782 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
784 #if defined(TARGET_POWERPC64)
785 g_assert (!acfg->use_bin_writer);
786 emit_unset_mode (acfg);
788 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
789 * unsupported relocations. So we store the got address into the .Lgot_addr
790 * symbol which is in the text segment, compute its address, and load it.
792 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
793 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
794 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
795 fprintf (acfg->fp, "add 30, 30, 0\n");
796 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
797 acfg->label_generator ++;
799 #elif defined(TARGET_POWERPC)
800 g_assert (!acfg->use_bin_writer);
801 emit_unset_mode (acfg);
802 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
803 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
804 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
805 acfg->label_generator ++;
808 guint32 offset = mono_arch_get_patch_offset (code);
809 emit_bytes (acfg, code, offset);
810 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
812 *code_size = offset + 4;
817 * arch_emit_got_access:
819 * The memory pointed to by CODE should hold native code for loading a GOT
820 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
821 * CODE_SIZE is set to the number of bytes emitted.
824 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
826 /* Emit beginning of instruction */
827 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
829 /* Emit the offset */
831 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
832 *code_size = mono_arch_get_patch_offset (code) + 4;
833 #elif defined(TARGET_X86)
834 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
835 *code_size = mono_arch_get_patch_offset (code) + 4;
836 #elif defined(TARGET_ARM)
837 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
838 *code_size = mono_arch_get_patch_offset (code) + 4;
839 #elif defined(TARGET_POWERPC)
845 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
846 g_assert (code - buf == 8);
847 emit_bytes (acfg, buf, code - buf);
848 *code_size = code - buf;
851 g_assert_not_reached ();
857 #ifdef MONO_ARCH_AOT_SUPPORTED
859 * arch_emit_objc_selector_ref:
861 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
864 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
866 #if defined(TARGET_ARM)
869 int lindex = acfg->objc_selector_index_2 ++;
872 emit_bytes (acfg, code, 8);
874 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
875 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
877 emit_label (acfg, symbol1);
878 img_writer_emit_unset_mode (acfg->w);
879 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
883 g_assert_not_reached ();
889 * arch_emit_plt_entry:
891 * Emit code for the PLT entry with index INDEX.
894 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
896 #if defined(TARGET_X86)
897 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
898 #if defined(__default_codegen__)
899 /* jmp *<offset>(%ebx) */
900 emit_byte (acfg, 0xff);
901 emit_byte (acfg, 0xa3);
902 emit_int32 (acfg, offset);
903 /* Used by mono_aot_get_plt_info_offset */
904 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
905 #elif defined(__native_client_codegen__)
906 const guint8 kSizeOfNaClJmp = 11;
907 guint8 bytes[kSizeOfNaClJmp];
908 guint8 *pbytes = &bytes[0];
910 x86_jump_membase32 (pbytes, X86_EBX, offset);
911 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
912 /* four bytes of data, used by mono_arch_patch_plt_entry */
913 /* For Native Client, make this work with data embedded in push. */
914 emit_byte (acfg, 0x68); /* hide data in a push */
915 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
916 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
917 #endif /*__native_client_codegen__*/
918 #elif defined(TARGET_AMD64)
919 #if defined(__default_codegen__)
921 * We can't emit jumps because they are 32 bits only so they can't be patched.
922 * So we make indirect calls through GOT entries which are patched by the AOT
923 * loader to point to .Lpd entries.
925 /* jmpq *<offset>(%rip) */
926 emit_byte (acfg, '\xff');
927 emit_byte (acfg, '\x25');
928 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
929 /* Used by mono_aot_get_plt_info_offset */
930 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
931 acfg->stats.plt_size += 10;
932 #elif defined(__native_client_codegen__)
934 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
935 guint8 *code = buf_aligned;
937 /* mov <OFFSET>(%rip), %r11d */
938 emit_byte (acfg, '\x45');
939 emit_byte (acfg, '\x8b');
940 emit_byte (acfg, '\x1d');
941 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
943 amd64_jump_reg (code, AMD64_R11);
944 /* This should be constant for the plt patch */
945 g_assert ((size_t)(code-buf_aligned) == 10);
946 emit_bytes (acfg, buf_aligned, code - buf_aligned);
948 /* Hide data in a push imm32 so it passes validation */
949 emit_byte (acfg, 0x68); /* push */
950 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
951 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
952 #endif /*__native_client_codegen__*/
953 #elif defined(TARGET_ARM)
958 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
959 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
960 emit_bytes (acfg, buf, code - buf);
961 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
962 /* Used by mono_aot_get_plt_info_offset */
963 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
964 #elif defined(TARGET_POWERPC)
965 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
967 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
968 g_assert (!acfg->use_bin_writer);
969 emit_unset_mode (acfg);
970 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
971 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
972 fprintf (acfg->fp, "add 11, 11, 30\n");
973 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
974 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
975 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
976 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
978 fprintf (acfg->fp, "mtctr 11\n");
979 fprintf (acfg->fp, "bctr\n");
980 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
982 g_assert_not_reached ();
987 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
989 #if defined(TARGET_ARM)
991 /* LLVM calls the PLT entries using bl, so emit a stub */
992 /* FIXME: Too much overhead on every call */
993 fprintf (acfg->fp, ".thumb_func\n");
994 fprintf (acfg->fp, "bx pc\n");
995 fprintf (acfg->fp, "nop\n");
996 fprintf (acfg->fp, ".arm\n");
998 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
999 /* The caller already transitioned to thumb */
1000 /* The code below should be 12 bytes long */
1001 /* clang has trouble encoding these instructions, so emit the binary */
1003 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1004 /* thumb can't encode ld pc, [pc, ip] */
1005 fprintf (acfg->fp, "add ip, pc, ip\n");
1006 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1007 fprintf (acfg->fp, "bx ip\n");
1009 emit_set_thumb_mode (acfg);
1010 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1011 fprintf (acfg->fp, ".2byte 0x44fc\n");
1012 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1013 fprintf (acfg->fp, ".2byte 0x4760\n");
1014 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1015 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1016 emit_unset_mode (acfg);
1017 emit_set_arm_mode (acfg);
1019 g_assert_not_reached ();
1024 * arch_emit_specific_trampoline_pages:
1026 * Emits a page full of trampolines: each trampoline uses its own address to
1027 * lookup both the generic trampoline code and the data argument.
1028 * This page can be remapped in process multiple times so we can get an
1029 * unlimited number of trampolines.
1030 * Specifically this implementation uses the following trick: two memory pages
1031 * are allocated, with the first containing the data and the second containing the trampolines.
1032 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1033 * implementation does all the lifting.
1034 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1035 * on the arm 32 bit system.
1038 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1040 #if defined(TARGET_ARM)
1043 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1045 #define COMMON_TRAMP_SIZE 16
1046 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1047 int imm8, rot_amount;
1050 if (!acfg->aot_opts.use_trampolines_page)
1053 acfg->tramp_page_size = mono_pagesize ();
1055 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1056 emit_alignment (acfg, mono_pagesize ());
1057 emit_global (acfg, symbol, TRUE);
1058 emit_label (acfg, symbol);
1060 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1062 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1063 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1064 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1065 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1067 g_assert (code - buf == COMMON_TRAMP_SIZE);
1070 emit_bytes (acfg, buf, code - buf);
1072 for (i = 0; i < count; ++i) {
1074 ARM_PUSH (code, 0x5fff);
1076 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1077 g_assert (code - buf == 8);
1078 emit_bytes (acfg, buf, code - buf);
1081 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1082 * the instruction pointer address, so the generic trampoline at the start of the page
1083 * subtracts 4096 to get to the data page and loads the values
1084 * We again fit the generic trampiline in 16 bytes.
1086 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1087 emit_global (acfg, symbol, TRUE);
1088 emit_label (acfg, symbol);
1090 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1091 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1092 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1093 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1095 g_assert (code - buf == COMMON_TRAMP_SIZE);
1098 emit_bytes (acfg, buf, code - buf);
1100 for (i = 0; i < count; ++i) {
1102 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1104 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1105 g_assert (code - buf == 8);
1106 emit_bytes (acfg, buf, code - buf);
1110 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1112 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1113 emit_global (acfg, symbol, TRUE);
1114 emit_label (acfg, symbol);
1116 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1117 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1118 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1119 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1120 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1121 g_assert (code - buf == COMMON_TRAMP_SIZE);
1123 emit_bytes (acfg, buf, code - buf);
1125 for (i = 0; i < count; ++i) {
1127 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1129 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1130 g_assert (code - buf == 8);
1131 emit_bytes (acfg, buf, code - buf);
1134 /* now the imt trampolines: each specific trampolines puts in the ip register
1135 * the instruction pointer address, so the generic trampoline at the start of the page
1136 * subtracts 4096 to get to the data page and loads the values
1137 * We again fit the generic trampiline in 16 bytes.
1139 #define IMT_TRAMP_SIZE 72
1140 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1141 emit_global (acfg, symbol, TRUE);
1142 emit_label (acfg, symbol);
1144 /* Need at least two free registers, plus a slot for storing the pc */
1145 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1147 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1148 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1149 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1151 /* The IMT method is in v5, r0 has the imt array address */
1154 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1155 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1156 imt_found_check = code;
1157 ARM_B_COND (code, ARMCOND_EQ, 0);
1159 /* End-of-loop check */
1160 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1161 loop_end_check = code;
1162 ARM_B_COND (code, ARMCOND_EQ, 0);
1165 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1166 loop_branch_back = code;
1168 arm_patch (loop_branch_back, loop_start);
1171 arm_patch (imt_found_check, code);
1172 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1173 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1174 /* Save it to the third stack slot */
1175 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1176 /* Restore the registers and branch */
1177 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1180 arm_patch (loop_end_check, code);
1181 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1182 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1183 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1187 g_assert (code - buf == IMT_TRAMP_SIZE);
1188 emit_bytes (acfg, buf, code - buf);
1190 for (i = 0; i < count; ++i) {
1192 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1194 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1195 g_assert (code - buf == 8);
1196 emit_bytes (acfg, buf, code - buf);
1202 * arch_emit_specific_trampoline:
1204 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1205 * two GOT slots which contain the generic trampoline address and the trampoline
1206 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1209 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1212 * The trampolines created here are variations of the specific
1213 * trampolines created in mono_arch_create_specific_trampoline (). The
1215 * - the generic trampoline address is taken from a got slot.
1216 * - the offset of the got slot where the trampoline argument is stored
1217 * is embedded in the instruction stream, and the generic trampoline
1218 * can load the argument by loading the offset, adding it to the
1219 * address of the trampoline to get the address of the got slot, and
1220 * loading the argument from there.
1221 * - all the trampolines should be of the same length.
1223 #if defined(TARGET_AMD64)
1224 #if defined(__default_codegen__)
1225 /* This should be exactly 16 bytes long */
1227 /* call *<offset>(%rip) */
1228 emit_byte (acfg, '\x41');
1229 emit_byte (acfg, '\xff');
1230 emit_byte (acfg, '\x15');
1231 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1232 /* This should be relative to the start of the trampoline */
1233 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1234 emit_zero_bytes (acfg, 5);
1235 #elif defined(__native_client_codegen__)
1237 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1238 guint8 *code = buf_aligned;
1243 /* Emit this call in 'code' so we can find out how long it is. */
1244 amd64_call_reg (code, AMD64_R11);
1245 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1246 call_len = code - call_start;
1248 /* The tramp_size is twice the NaCl alignment because it starts with */
1249 /* a call which needs to be aligned to the end of the boundary. */
1250 *tramp_size = kNaClAlignment*2;
1252 /* Emit nops to align call site below which is 7 bytes plus */
1253 /* the length of the call sequence emitted above. */
1254 /* Note: this requires the specific trampoline starts on a */
1255 /* kNaclAlignedment aligned address, which it does because */
1256 /* it's its own function that is aligned. */
1257 guint8 nop_buf[256];
1258 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1259 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1260 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1262 /* The trampoline is stored at the offset'th pointer, the -4 is */
1263 /* present because RIP relative addressing starts at the end of */
1264 /* the current instruction, while the label "." is relative to */
1265 /* the beginning of the current asm location, which in this case */
1266 /* is not the mov instruction, but the offset itself, due to the */
1267 /* way the bytes and ints are emitted here. */
1268 got_offset = (offset * sizeof(gpointer)) - 4;
1270 /* mov <OFFSET>(%rip), %r11d */
1271 emit_byte (acfg, '\x45');
1272 emit_byte (acfg, '\x8b');
1273 emit_byte (acfg, '\x1d');
1274 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1277 emit_bytes (acfg, call_start, call_len);
1279 /* The arg is stored at the offset+1 pointer, relative to beginning */
1280 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1281 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1283 /* We can't emit this data directly, hide in a "push imm32" */
1284 emit_byte (acfg, '\x68'); /* push */
1285 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1286 emit_alignment (acfg, kNaClAlignment);
1287 #endif /*__native_client_codegen__*/
1288 #elif defined(TARGET_ARM)
1292 /* This should be exactly 20 bytes long */
1295 ARM_PUSH (code, 0x5fff);
1296 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1297 /* Load the value from the GOT */
1298 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1300 ARM_BLX_REG (code, ARMREG_R1);
1302 g_assert (code - buf == 16);
1305 emit_bytes (acfg, buf, code - buf);
1307 * Only one offset is needed, since the second one would be equal to the
1310 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1311 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1312 #elif defined(TARGET_POWERPC)
1319 g_assert (!acfg->use_bin_writer);
1322 * PPC has no ip relative addressing, so we need to compute the address
1323 * of the mscorlib got. That is slow and complex, so instead, we store it
1324 * in the second got slot of every aot image. The caller already computed
1325 * the address of its got and placed it into r30.
1327 emit_unset_mode (acfg);
1328 /* Load mscorlib got address */
1329 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1330 /* Load generic trampoline address */
1331 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1332 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1333 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1334 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1335 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1337 fprintf (acfg->fp, "mtctr 11\n");
1338 /* Load trampoline argument */
1339 /* On ppc, we pass it normally to the generic trampoline */
1340 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1341 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1342 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1343 /* Branch to generic trampoline */
1344 fprintf (acfg->fp, "bctr\n");
1346 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1347 *tramp_size = 10 * 4;
1349 *tramp_size = 9 * 4;
1351 #elif defined(TARGET_X86)
1355 /* Similar to the PPC code above */
1357 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1359 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1360 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1361 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1365 /* Load mscorlib got address */
1366 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1367 /* Push trampoline argument */
1368 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1369 /* Load generic trampoline address */
1370 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1371 /* Branch to generic trampoline */
1372 x86_jump_reg (code, X86_ECX);
1374 #ifdef __native_client_codegen__
1376 /* emit nops to next 32 byte alignment */
1377 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1378 while (code < (buf + a)) x86_nop(code);
1381 emit_bytes (acfg, buf, code - buf);
1383 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1384 g_assert (code - buf == *tramp_size);
1386 g_assert_not_reached ();
1391 * arch_emit_unbox_trampoline:
1393 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1394 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1397 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1399 #if defined(TARGET_AMD64)
1404 this_reg = mono_arch_get_this_arg_reg (NULL);
1406 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1408 emit_bytes (acfg, buf, code - buf);
1410 emit_byte (acfg, '\xe9');
1411 emit_symbol_diff (acfg, call_target, ".", -4);
1412 #elif defined(TARGET_X86)
1419 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1421 emit_bytes (acfg, buf, code - buf);
1424 emit_byte (acfg, '\xe9');
1425 emit_symbol_diff (acfg, call_target, ".", -4);
1426 #elif defined(TARGET_ARM)
1430 if (acfg->thumb_mixed && cfg->compile_llvm) {
1431 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1432 fprintf (acfg->fp, "b %s\n", call_target);
1433 fprintf (acfg->fp, ".arm\n");
1434 fprintf (acfg->fp, ".align 2\n");
1440 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1442 emit_bytes (acfg, buf, code - buf);
1443 /* jump to method */
1444 if (acfg->use_bin_writer) {
1451 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1452 emit_bytes (acfg, buf, 4);
1454 if (acfg->thumb_mixed && cfg->compile_llvm)
1455 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1457 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1459 #elif defined(TARGET_POWERPC)
1462 g_assert (!acfg->use_bin_writer);
1464 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1465 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1467 g_assert_not_reached ();
1472 * arch_emit_static_rgctx_trampoline:
1474 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1475 * two GOT slots which contain the rgctx argument, and the method to jump to.
1476 * TRAMP_SIZE is set to the size of the emitted trampoline.
1477 * These kinds of trampolines cannot be enumerated statically, since there could
1478 * be one trampoline per method instantiation, so we emit the same code for all
1479 * trampolines, and parameterize them using two GOT slots.
1482 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1484 #if defined(TARGET_AMD64)
1485 #if defined(__default_codegen__)
1486 /* This should be exactly 13 bytes long */
1489 /* mov <OFFSET>(%rip), %r10 */
1490 emit_byte (acfg, '\x4d');
1491 emit_byte (acfg, '\x8b');
1492 emit_byte (acfg, '\x15');
1493 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1495 /* jmp *<offset>(%rip) */
1496 emit_byte (acfg, '\xff');
1497 emit_byte (acfg, '\x25');
1498 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1499 #elif defined(__native_client_codegen__)
1501 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1502 guint8 *code = buf_aligned;
1504 /* mov <OFFSET>(%rip), %r10d */
1505 emit_byte (acfg, '\x45');
1506 emit_byte (acfg, '\x8b');
1507 emit_byte (acfg, '\x15');
1508 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1510 /* mov <OFFSET>(%rip), %r11d */
1511 emit_byte (acfg, '\x45');
1512 emit_byte (acfg, '\x8b');
1513 emit_byte (acfg, '\x1d');
1514 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1517 amd64_jump_reg (code, AMD64_R11);
1518 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1520 emit_alignment (acfg, kNaClAlignment);
1521 *tramp_size = kNaClAlignment;
1522 #endif /*__native_client_codegen__*/
1524 #elif defined(TARGET_ARM)
1528 /* This should be exactly 24 bytes long */
1531 /* Load rgctx value */
1532 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1533 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1534 /* Load branch addr + branch */
1535 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1536 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1538 g_assert (code - buf == 16);
1541 emit_bytes (acfg, buf, code - buf);
1542 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1543 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1544 #elif defined(TARGET_POWERPC)
1551 g_assert (!acfg->use_bin_writer);
1554 * PPC has no ip relative addressing, so we need to compute the address
1555 * of the mscorlib got. That is slow and complex, so instead, we store it
1556 * in the second got slot of every aot image. The caller already computed
1557 * the address of its got and placed it into r30.
1559 emit_unset_mode (acfg);
1560 /* Load mscorlib got address */
1561 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1563 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1564 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1565 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1566 /* Load target address */
1567 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1568 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1569 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1570 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1571 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1572 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1574 fprintf (acfg->fp, "mtctr 11\n");
1575 /* Branch to the target address */
1576 fprintf (acfg->fp, "bctr\n");
1578 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1579 *tramp_size = 11 * 4;
1581 *tramp_size = 9 * 4;
1584 #elif defined(TARGET_X86)
1588 /* Similar to the PPC code above */
1590 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1593 /* Load mscorlib got address */
1594 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1596 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1597 /* Branch to the target address */
1598 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1600 #ifdef __native_client_codegen__
1602 /* emit nops to next 32 byte alignment */
1603 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1604 while (code < (buf + a)) x86_nop(code);
1608 emit_bytes (acfg, buf, code - buf);
1610 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1611 g_assert (code - buf == *tramp_size);
1613 g_assert_not_reached ();
1618 * arch_emit_imt_thunk:
1620 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1621 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1622 * key is the IMT key, and ptr holds the address of a memory location holding
1623 * the address to branch to if the IMT arg matches the key. The array is
1624 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1626 * TRAMP_SIZE is set to the size of the emitted trampoline.
1629 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1631 #if defined(TARGET_AMD64)
1633 #if defined(__native_client_codegen__)
1636 guint8 *labels [16];
1638 guint8 *mov_buf_ptr = mov_buf;
1640 const int kSizeOfMove = 7;
1641 #if defined(__default_codegen__)
1642 code = buf = g_malloc (256);
1643 #elif defined(__native_client_codegen__)
1644 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1645 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1646 /* The RIP relative move below is emitted first */
1651 /* FIXME: Optimize this, i.e. use binary search etc. */
1652 /* Maybe move the body into a separate function (slower, but much smaller) */
1654 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1657 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1659 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1662 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1664 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1667 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1668 amd64_jump_code (code, labels [0]);
1671 mono_amd64_patch (labels [2], code);
1672 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1673 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1676 mono_amd64_patch (labels [1], code);
1677 /* Load fail tramp */
1678 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1679 /* Check if there is a fail tramp */
1680 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1682 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1683 /* Jump to fail tramp */
1684 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1687 mono_amd64_patch (labels [3], code);
1688 x86_breakpoint (code);
1690 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1691 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1692 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1693 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1694 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1695 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1697 emit_bytes (acfg, buf, code - buf);
1699 *tramp_size = code - buf + kSizeOfMove;
1700 #if defined(__native_client_codegen__)
1701 /* The tramp will be padded to the next kNaClAlignment bundle. */
1702 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1705 #if defined(__default_codegen__)
1707 #elif defined(__native_client_codegen__)
1711 #elif defined(TARGET_X86)
1713 #ifdef __native_client_codegen__
1716 guint8 *labels [16];
1718 #if defined(__default_codegen__)
1719 code = buf = g_malloc (256);
1720 #elif defined(__native_client_codegen__)
1721 buf_alloc = g_malloc (256 + kNaClAlignment);
1722 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1725 /* Allocate a temporary stack slot */
1726 x86_push_reg (code, X86_EAX);
1728 x86_push_reg (code, X86_EAX);
1730 /* Load mscorlib got address */
1731 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1733 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1736 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1738 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1741 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1743 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1746 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1747 x86_jump_code (code, labels [0]);
1750 mono_x86_patch (labels [2], code);
1751 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1752 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1753 /* Save the target address to the temporary stack location */
1754 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1756 x86_pop_reg (code, X86_EAX);
1757 /* Jump to the target address */
1761 mono_x86_patch (labels [1], code);
1762 /* Load fail tramp */
1763 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1764 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1766 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1767 /* Jump to fail tramp */
1768 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1769 x86_pop_reg (code, X86_EAX);
1773 mono_x86_patch (labels [3], code);
1774 x86_breakpoint (code);
1776 #ifdef __native_client_codegen__
1778 /* emit nops to next 32 byte alignment */
1779 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1780 while (code < (buf + a)) x86_nop(code);
1783 emit_bytes (acfg, buf, code - buf);
1785 *tramp_size = code - buf;
1787 #if defined(__default_codegen__)
1789 #elif defined(__native_client_codegen__)
1793 #elif defined(TARGET_ARM)
1795 guint8 *code, *code2, *labels [16];
1799 /* The IMT method is in v5 */
1801 /* Need at least two free registers, plus a slot for storing the pc */
1802 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1804 /* Load the parameter from the GOT */
1805 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1806 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1809 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1810 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1812 ARM_B_COND (code, ARMCOND_EQ, 0);
1814 /* End-of-loop check */
1815 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1817 ARM_B_COND (code, ARMCOND_EQ, 0);
1820 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1823 arm_patch (labels [4], labels [1]);
1826 arm_patch (labels [2], code);
1827 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1828 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1829 /* Save it to the third stack slot */
1830 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1831 /* Restore the registers and branch */
1832 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1835 arm_patch (labels [3], code);
1836 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1837 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1838 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1842 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1844 emit_bytes (acfg, buf, code - buf);
1845 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1847 *tramp_size = code - buf + 4;
1848 #elif defined(TARGET_POWERPC)
1850 guint8 *code, *labels [16];
1854 /* Load the mscorlib got address */
1855 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1856 /* Load the parameter from the GOT */
1857 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1858 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1860 /* Load and check key */
1862 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1863 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1865 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1867 /* End-of-loop check */
1868 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1870 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1873 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1876 mono_ppc_patch (labels [4], labels [1]);
1879 mono_ppc_patch (labels [2], code);
1880 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1881 /* r11 now contains the value of the vtable slot */
1882 /* this is not a function descriptor on ppc64 */
1883 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1884 ppc_mtctr (code, ppc_r11);
1885 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1888 mono_ppc_patch (labels [3], code);
1892 *tramp_size = code - buf;
1894 emit_bytes (acfg, buf, code - buf);
1896 g_assert_not_reached ();
1901 * arch_emit_gsharedvt_arg_trampoline:
1903 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1904 * two GOT slots which contain the argument, and the code to jump to.
1905 * TRAMP_SIZE is set to the size of the emitted trampoline.
1906 * These kinds of trampolines cannot be enumerated statically, since there could
1907 * be one trampoline per method instantiation, so we emit the same code for all
1908 * trampolines, and parameterize them using two GOT slots.
1911 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1913 #if defined(TARGET_X86)
1917 /* Similar to the PPC code above */
1919 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1922 /* Load mscorlib got address */
1923 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1925 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1926 /* Branch to the target address */
1927 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1929 #ifdef __native_client_codegen__
1931 /* emit nops to next 32 byte alignment */
1932 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1933 while (code < (buf + a)) x86_nop(code);
1937 emit_bytes (acfg, buf, code - buf);
1939 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1940 g_assert (code - buf == *tramp_size);
1941 #elif defined(TARGET_ARM)
1945 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1946 /* Similar to arch_emit_specific_trampoline () */
1949 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1950 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1951 /* Load the arg value from the GOT */
1952 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1953 /* Load the addr from the GOT */
1954 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1956 ARM_BX (code, ARMREG_R1);
1958 g_assert (code - buf == 20);
1961 emit_bytes (acfg, buf, code - buf);
1962 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1964 g_assert_not_reached ();
1969 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1971 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1972 /* Based on code generated by gcc */
1973 emit_unset_mode (acfg);
1976 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1977 ".section .ctors,\"aw\",@progbits\n"
1981 ".section .opd,\"aw\"\n"
1984 ".long .%s,.TOC.@tocbase32\n"
1987 ".type .%s,@function\n"
1989 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1991 ".section .ctors,\"aw\",@progbits\n"
1995 ".section .opd,\"aw\"\n"
1998 ".long .%1$s,.TOC.@tocbase32\n"
1999 ".size %1$s,.-%1$s\n"
2001 ".type .%1$s,@function\n"
2003 ".%1$s:\n", symbol);
2014 "lis 3, .Lglobals@h\n"
2015 "ori 3, 3, .Lglobals@l\n"
2016 "bl .mono_aot_register_module\n"
2024 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2026 ".size .%s,.-.%s\n", symbol, symbol);
2029 ".size .%1$s,.-.%1$s\n", symbol);
2035 /* END OF ARCH SPECIFIC CODE */
2038 mono_get_field_token (MonoClassField *field)
2040 MonoClass *klass = field->parent;
2043 for (i = 0; i < klass->field.count; ++i) {
2044 if (field == &klass->fields [i])
2045 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2048 g_assert_not_reached ();
2053 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2057 //printf ("ENCODE: %d 0x%x.\n", value, value);
2060 * Same encoding as the one used in the metadata, extended to handle values
2061 * greater than 0x1fffffff.
2063 if ((value >= 0) && (value <= 127))
2065 else if ((value >= 0) && (value <= 16383)) {
2066 p [0] = 0x80 | (value >> 8);
2067 p [1] = value & 0xff;
2069 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2070 p [0] = (value >> 24) | 0xc0;
2071 p [1] = (value >> 16) & 0xff;
2072 p [2] = (value >> 8) & 0xff;
2073 p [3] = value & 0xff;
2078 p [1] = (value >> 24) & 0xff;
2079 p [2] = (value >> 16) & 0xff;
2080 p [3] = (value >> 8) & 0xff;
2081 p [4] = value & 0xff;
2089 stream_init (MonoDynamicStream *sh)
2092 sh->alloc_size = 4096;
2093 sh->data = g_malloc (4096);
2095 /* So offsets are > 0 */
2101 make_room_in_stream (MonoDynamicStream *stream, int size)
2103 if (size <= stream->alloc_size)
2106 while (stream->alloc_size <= size) {
2107 if (stream->alloc_size < 4096)
2108 stream->alloc_size = 4096;
2110 stream->alloc_size *= 2;
2113 stream->data = g_realloc (stream->data, stream->alloc_size);
2117 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2121 make_room_in_stream (stream, stream->index + len);
2122 memcpy (stream->data + stream->index, data, len);
2123 idx = stream->index;
2124 stream->index += len;
2131 * Add data to the binary blob inside the aot image. Returns the offset inside the
2132 * blob where the data was stored.
2135 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2137 if (acfg->blob.alloc_size == 0)
2138 stream_init (&acfg->blob);
2140 return add_stream_data (&acfg->blob, (char*)data, data_len);
2144 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2149 if (acfg->blob.alloc_size == 0)
2150 stream_init (&acfg->blob);
2152 count = acfg->blob.index % align;
2154 /* we assume the stream data will be aligned */
2156 add_stream_data (&acfg->blob, buf, 4 - count);
2158 return add_stream_data (&acfg->blob, (char*)data, data_len);
2162 * emit_offset_table:
2164 * Emit a table of increasing offsets in a compact form using differential encoding.
2165 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2166 * group size, the more compact the table becomes, but the slower it becomes to compute
2167 * a given entry. Returns the size of the table.
2170 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2172 gint32 current_offset;
2173 int i, buf_size, ngroups, index_entry_size;
2175 guint32 *index_offsets;
2177 ngroups = (noffsets + (group_size - 1)) / group_size;
2179 index_offsets = g_new0 (guint32, ngroups);
2181 buf_size = noffsets * 4;
2182 p = buf = g_malloc0 (buf_size);
2185 for (i = 0; i < noffsets; ++i) {
2186 //printf ("D: %d -> %d\n", i, offsets [i]);
2187 if ((i % group_size) == 0) {
2188 index_offsets [i / group_size] = p - buf;
2189 /* Emit the full value for these entries */
2190 encode_value (offsets [i], p, &p);
2192 /* The offsets are allowed to be non-increasing */
2193 //g_assert (offsets [i] >= current_offset);
2194 encode_value (offsets [i] - current_offset, p, &p);
2196 current_offset = offsets [i];
2199 if (ngroups && index_offsets [ngroups - 1] < 65000)
2200 index_entry_size = 2;
2202 index_entry_size = 4;
2204 /* Emit the header */
2205 emit_int32 (acfg, noffsets);
2206 emit_int32 (acfg, group_size);
2207 emit_int32 (acfg, ngroups);
2208 emit_int32 (acfg, index_entry_size);
2210 /* Emit the index */
2211 for (i = 0; i < ngroups; ++i) {
2212 if (index_entry_size == 2)
2213 emit_int16 (acfg, index_offsets [i]);
2215 emit_int32 (acfg, index_offsets [i]);
2219 emit_bytes (acfg, buf, p - buf);
2221 return (int)(p - buf) + (ngroups * 4);
2225 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2229 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2233 index = g_hash_table_size (cfg->image_hash);
2234 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2235 g_ptr_array_add (cfg->image_table, image);
2241 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2244 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2246 /* FIXME: Search referenced images as well */
2247 if (!acfg->typespec_classes) {
2248 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2249 for (i = 0; i < len; ++i) {
2250 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2253 for (i = 0; i < len; ++i) {
2254 if (acfg->typespec_classes [i] == klass)
2259 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2265 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2268 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2271 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2274 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2277 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2282 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2286 if (klass->generic_class) {
2288 g_assert (klass->type_token);
2290 /* Find a typespec for a class if possible */
2291 token = find_typespec_for_class (acfg, klass);
2293 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2294 encode_value (token, p, &p);
2296 MonoClass *gclass = klass->generic_class->container_class;
2297 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2298 static int count = 0;
2301 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2302 encode_klass_ref (acfg, gclass, p, &p);
2303 encode_ginst (acfg, inst, p, &p);
2307 } else if (klass->type_token) {
2308 int iindex = get_image_index (acfg, klass->image);
2310 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2312 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2313 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2315 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2316 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2317 encode_value (get_image_index (acfg, klass->image), p, &p);
2319 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2320 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2321 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2323 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2324 encode_value (klass->byval_arg.type, p, &p);
2325 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2327 encode_value (container ? 1 : 0, p, &p);
2329 encode_value (container->is_method, p, &p);
2330 g_assert (par->serial == 0);
2331 if (container->is_method)
2332 encode_method_ref (acfg, container->owner.method, p, &p);
2334 encode_klass_ref (acfg, container->owner.klass, p, &p);
2336 encode_value (par->serial, p, &p);
2338 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2339 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2340 encode_type (acfg, &klass->byval_arg, p, &p);
2343 g_assert (klass->rank > 0);
2344 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2345 encode_value (klass->rank, p, &p);
2346 encode_klass_ref (acfg, klass->element_class, p, &p);
2354 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2355 * standard metadata encoding.
2358 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2360 gboolean shared = FALSE;
2363 * The encoding of generic instances is large so emit them only once.
2365 if (klass->generic_class) {
2367 g_assert (klass->type_token);
2369 /* Find a typespec for a class if possible */
2370 token = find_typespec_for_class (acfg, klass);
2373 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2378 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2382 buf2 = g_malloc (1024);
2385 encode_klass_ref_inner (acfg, klass, p, &p);
2386 g_assert (p - buf2 < 1024);
2388 offset = add_to_blob (acfg, buf2, p - buf2);
2391 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2397 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2398 encode_value (offset, p, &p);
2403 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2407 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2409 guint32 token = mono_get_field_token (field);
2412 encode_klass_ref (cfg, field->parent, p, &p);
2413 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2414 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2419 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2424 encode_value (inst->type_argc, p, &p);
2425 for (i = 0; i < inst->type_argc; ++i)
2426 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2431 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2434 MonoGenericInst *inst;
2436 inst = context->class_inst;
2438 g_assert (inst->type_argc);
2439 encode_ginst (acfg, inst, p, &p);
2441 encode_value (0, p, &p);
2443 inst = context->method_inst;
2445 g_assert (inst->type_argc);
2446 encode_ginst (acfg, inst, p, &p);
2448 encode_value (0, p, &p);
2454 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2458 g_assert (t->num_mods == 0);
2459 /* t->attrs can be ignored */
2460 //g_assert (t->attrs == 0);
2463 *p = MONO_TYPE_PINNED;
2467 *p = MONO_TYPE_BYREF;
2475 case MONO_TYPE_VOID:
2476 case MONO_TYPE_BOOLEAN:
2477 case MONO_TYPE_CHAR:
2490 case MONO_TYPE_STRING:
2491 case MONO_TYPE_OBJECT:
2492 case MONO_TYPE_TYPEDBYREF:
2494 case MONO_TYPE_VALUETYPE:
2495 case MONO_TYPE_CLASS:
2496 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2498 case MONO_TYPE_SZARRAY:
2499 encode_klass_ref (acfg, t->data.klass, p, &p);
2502 encode_type (acfg, t->data.type, p, &p);
2504 case MONO_TYPE_GENERICINST: {
2505 MonoClass *gclass = t->data.generic_class->container_class;
2506 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2508 encode_klass_ref (acfg, gclass, p, &p);
2509 encode_ginst (acfg, inst, p, &p);
2512 case MONO_TYPE_ARRAY: {
2513 MonoArrayType *array = t->data.array;
2516 encode_klass_ref (acfg, array->eklass, p, &p);
2517 encode_value (array->rank, p, &p);
2518 encode_value (array->numsizes, p, &p);
2519 for (i = 0; i < array->numsizes; ++i)
2520 encode_value (array->sizes [i], p, &p);
2521 encode_value (array->numlobounds, p, &p);
2522 for (i = 0; i < array->numlobounds; ++i)
2523 encode_value (array->lobounds [i], p, &p);
2527 case MONO_TYPE_MVAR:
2528 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2531 g_assert_not_reached ();
2538 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2544 /* Similar to the metadata encoding */
2545 if (sig->generic_param_count)
2549 if (sig->explicit_this)
2551 flags |= (sig->call_convention & 0x0F);
2555 if (sig->generic_param_count)
2556 encode_value (sig->generic_param_count, p, &p);
2557 encode_value (sig->param_count, p, &p);
2559 encode_type (acfg, sig->ret, p, &p);
2560 for (i = 0; i < sig->param_count; ++i) {
2561 if (sig->sentinelpos == i) {
2562 *p = MONO_TYPE_SENTINEL;
2565 encode_type (acfg, sig->params [i], p, &p);
2571 #define MAX_IMAGE_INDEX 250
2574 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2576 guint32 image_index = get_image_index (acfg, method->klass->image);
2577 guint32 token = method->token;
2578 MonoJumpInfoToken *ji;
2582 * The encoding for most methods is as follows:
2583 * - image index encoded as a leb128
2584 * - token index encoded as a leb128
2585 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2586 * types of method encodings.
2589 /* Mark methods which can't use aot trampolines because they need the further
2590 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2592 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2593 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2594 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2596 if (method->wrapper_type) {
2597 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2599 encode_value (method->wrapper_type, p, &p);
2601 switch (method->wrapper_type) {
2602 case MONO_WRAPPER_REMOTING_INVOKE:
2603 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2604 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2607 m = mono_marshal_method_from_wrapper (method);
2609 encode_method_ref (acfg, m, p, &p);
2612 case MONO_WRAPPER_PROXY_ISINST:
2613 case MONO_WRAPPER_LDFLD:
2614 case MONO_WRAPPER_LDFLDA:
2615 case MONO_WRAPPER_STFLD:
2616 case MONO_WRAPPER_ISINST: {
2617 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2618 encode_klass_ref (acfg, proxy_class, p, &p);
2621 case MONO_WRAPPER_LDFLD_REMOTE:
2622 case MONO_WRAPPER_STFLD_REMOTE:
2624 case MONO_WRAPPER_ALLOC: {
2625 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2627 /* The GC name is saved once in MonoAotFileInfo */
2628 g_assert (info->alloc_type != -1);
2629 encode_value (info->alloc_type, p, &p);
2632 case MONO_WRAPPER_WRITE_BARRIER:
2634 case MONO_WRAPPER_STELEMREF: {
2635 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2638 encode_value (info->subtype, p, &p);
2639 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2640 encode_value (info->d.virtual_stelemref.kind, p, &p);
2643 case MONO_WRAPPER_UNKNOWN: {
2644 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2647 encode_value (info->subtype, p, &p);
2648 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2649 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2650 encode_klass_ref (acfg, method->klass, p, &p);
2651 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2652 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2653 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2654 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2657 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2658 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2661 encode_value (info->subtype, p, &p);
2662 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2663 strcpy ((char*)p, method->name);
2664 p += strlen (method->name) + 1;
2665 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2666 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2668 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2669 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2673 case MONO_WRAPPER_SYNCHRONIZED: {
2676 m = mono_marshal_method_from_wrapper (method);
2678 g_assert (m != method);
2679 encode_method_ref (acfg, m, p, &p);
2682 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2683 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2686 encode_value (info->subtype, p, &p);
2688 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2689 encode_value (info->d.element_addr.rank, p, &p);
2690 encode_value (info->d.element_addr.elem_size, p, &p);
2691 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2692 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2694 g_assert_not_reached ();
2698 case MONO_WRAPPER_CASTCLASS: {
2699 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2702 encode_value (info->subtype, p, &p);
2705 case MONO_WRAPPER_RUNTIME_INVOKE: {
2706 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2709 encode_value (info->subtype, p, &p);
2710 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2711 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2712 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2713 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2716 case MONO_WRAPPER_DELEGATE_INVOKE:
2717 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2718 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2719 if (method->is_inflated) {
2720 /* These wrappers are identified by their class */
2721 encode_value (1, p, &p);
2722 encode_klass_ref (acfg, method->klass, p, &p);
2724 MonoMethodSignature *sig = mono_method_signature (method);
2725 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2727 encode_value (0, p, &p);
2728 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2729 encode_value (info ? info->subtype : 0, p, &p);
2730 encode_signature (acfg, sig, p, &p);
2734 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2735 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2738 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2739 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2743 g_assert_not_reached ();
2745 } else if (mono_method_signature (method)->is_inflated) {
2747 * This is a generic method, find the original token which referenced it and
2749 * Obtain the token from information recorded by the JIT.
2751 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2753 image_index = get_image_index (acfg, ji->image);
2754 g_assert (image_index < MAX_IMAGE_INDEX);
2757 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2758 encode_value (image_index, p, &p);
2759 encode_value (token, p, &p);
2761 MonoMethod *declaring;
2762 MonoGenericContext *context = mono_method_get_context (method);
2764 g_assert (method->is_inflated);
2765 declaring = ((MonoMethodInflated*)method)->declaring;
2768 * This might be a non-generic method of a generic instance, which
2769 * doesn't have a token since the reference is generated by the JIT
2770 * like Nullable:Box/Unbox, or by generic sharing.
2772 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2773 /* Encode the klass */
2774 encode_klass_ref (acfg, method->klass, p, &p);
2775 /* Encode the method */
2776 image_index = get_image_index (acfg, method->klass->image);
2777 g_assert (image_index < MAX_IMAGE_INDEX);
2778 g_assert (declaring->token);
2779 token = declaring->token;
2780 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2781 encode_value (image_index, p, &p);
2782 encode_value (token, p, &p);
2783 encode_generic_context (acfg, context, p, &p);
2785 } else if (token == 0) {
2786 /* This might be a method of a constructed type like int[,].Set */
2787 /* Obtain the token from information recorded by the JIT */
2788 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2790 image_index = get_image_index (acfg, ji->image);
2791 g_assert (image_index < MAX_IMAGE_INDEX);
2794 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2795 encode_value (image_index, p, &p);
2796 encode_value (token, p, &p);
2799 g_assert (method->klass->rank);
2801 /* Encode directly */
2802 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2803 encode_klass_ref (acfg, method->klass, p, &p);
2804 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2805 encode_value (0, p, &p);
2806 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2807 encode_value (1, p, &p);
2808 else if (!strcmp (method->name, "Get"))
2809 encode_value (2, p, &p);
2810 else if (!strcmp (method->name, "Address"))
2811 encode_value (3, p, &p);
2812 else if (!strcmp (method->name, "Set"))
2813 encode_value (4, p, &p);
2815 g_assert_not_reached ();
2818 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2820 if (image_index >= MONO_AOT_METHODREF_MIN) {
2821 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2822 encode_value (image_index, p, &p);
2823 encode_value (mono_metadata_token_index (token), p, &p);
2825 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2832 compare_patches (gconstpointer a, gconstpointer b)
2836 i = (*(MonoJumpInfo**)a)->ip.i;
2837 j = (*(MonoJumpInfo**)b)->ip.i;
2848 static G_GNUC_UNUSED char*
2849 patch_to_string (MonoJumpInfo *patch_info)
2853 str = g_string_new ("");
2855 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2857 switch (patch_info->type) {
2858 case MONO_PATCH_INFO_VTABLE:
2859 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2864 g_string_append_printf (str, ")");
2865 return g_string_free (str, FALSE);
2871 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2874 static inline gboolean
2875 is_plt_patch (MonoJumpInfo *patch_info)
2877 switch (patch_info->type) {
2878 case MONO_PATCH_INFO_METHOD:
2879 case MONO_PATCH_INFO_INTERNAL_METHOD:
2880 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2881 case MONO_PATCH_INFO_ICALL_ADDR:
2882 case MONO_PATCH_INFO_CLASS_INIT:
2883 case MONO_PATCH_INFO_RGCTX_FETCH:
2884 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2885 case MONO_PATCH_INFO_MONITOR_ENTER:
2886 case MONO_PATCH_INFO_MONITOR_EXIT:
2887 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2897 * Return the symbol identifying the plt entry PLT_OFFSET.
2900 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2904 * The Apple linker reorganizes object files, so it doesn't like branches to local
2905 * labels, since those have no relocations.
2907 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2909 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2916 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2918 static MonoPltEntry*
2919 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2923 if (!is_plt_patch (patch_info))
2926 if (!acfg->patch_to_plt_entry [patch_info->type])
2927 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
2928 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
2930 // FIXME: This breaks the calculation of final_got_size
2931 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2933 * Allocate a separate PLT slot for each such patch, since some plt
2934 * entries will refer to the method itself, and some will refer to the
2941 MonoJumpInfo *new_ji;
2943 g_assert (!acfg->final_got_size);
2945 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2947 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2948 res->plt_offset = acfg->plt_offset;
2950 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2951 if (acfg->aot_opts.write_symbols)
2952 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2954 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2956 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2958 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
2960 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2962 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2963 //mono_print_ji (patch_info); printf ("\n");
2964 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2966 acfg->plt_offset ++;
2975 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2976 * JI could be found if it exists, otherwise allocates a new one.
2979 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2983 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2985 return got_offset - 1;
2987 got_offset = acfg->got_offset;
2988 acfg->got_offset ++;
2990 if (acfg->final_got_size)
2991 g_assert (got_offset < acfg->final_got_size);
2993 acfg->stats.got_slots ++;
2994 acfg->stats.got_slot_types [ji->type] ++;
2996 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2997 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2998 g_ptr_array_add (acfg->got_patches, ji);
3003 /* Add a method to the list of methods which need to be emitted */
3005 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3008 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3009 g_ptr_array_add (acfg->methods, method);
3010 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3011 acfg->nmethods = acfg->methods->len + 1;
3014 if (method->wrapper_type || extra)
3015 g_ptr_array_add (acfg->extra_methods, method);
3019 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3021 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3029 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3033 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3037 index = acfg->method_index;
3038 add_method_with_index (acfg, method, index, extra);
3040 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3042 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3044 acfg->method_index ++;
3050 add_method (MonoAotCompile *acfg, MonoMethod *method)
3052 return add_method_full (acfg, method, FALSE, 0);
3056 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3058 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3059 method = mini_get_shared_method (method);
3061 if (acfg->aot_opts.log_generics)
3062 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3064 add_method_full (acfg, method, TRUE, depth);
3068 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3070 add_extra_method_with_depth (acfg, method, 0);
3074 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3076 MonoAotCompile *acfg = user_data;
3077 MonoJitICallInfo *callinfo = value;
3078 MonoMethod *wrapper;
3084 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3085 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3088 add_method (acfg, wrapper);
3092 get_runtime_invoke_sig (MonoMethodSignature *sig)
3094 MonoMethodBuilder *mb;
3097 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3098 m = mono_mb_create_method (mb, sig, 16);
3099 return mono_marshal_get_runtime_invoke (m, FALSE);
3103 can_marshal_struct (MonoClass *klass)
3105 MonoClassField *field;
3106 gboolean can_marshal = TRUE;
3107 gpointer iter = NULL;
3108 MonoMarshalType *info;
3111 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3114 info = mono_marshal_load_type_info (klass);
3116 /* Only allow a few field types to avoid asserts in the marshalling code */
3117 while ((field = mono_class_get_fields (klass, &iter))) {
3118 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3121 switch (field->type->type) {
3126 case MONO_TYPE_BOOLEAN:
3129 case MONO_TYPE_CHAR:
3137 case MONO_TYPE_STRING:
3139 case MONO_TYPE_VALUETYPE:
3140 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3141 can_marshal = FALSE;
3143 case MONO_TYPE_SZARRAY: {
3144 gboolean has_mspec = FALSE;
3147 for (i = 0; i < info->num_fields; ++i) {
3148 if (info->fields [i].field == field && info->fields [i].mspec)
3153 can_marshal = FALSE;
3157 can_marshal = FALSE;
3163 /* Its hard to compute whenever these can be marshalled or not */
3164 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3171 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3173 /* Create a vtype instantiation */
3174 MonoGenericContext shared_context;
3176 MonoGenericInst *inst;
3177 MonoGenericContainer *container;
3178 MonoClass **constraints;
3181 memset (ctx, 0, sizeof (MonoGenericContext));
3183 if (method->klass->generic_container) {
3184 shared_context = method->klass->generic_container->context;
3185 inst = shared_context.class_inst;
3187 args = g_new0 (MonoType*, inst->type_argc);
3188 for (i = 0; i < inst->type_argc; ++i) {
3189 args [i] = &mono_defaults.int_class->byval_arg;
3191 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3193 if (method->is_generic) {
3194 container = mono_method_get_generic_container (method);
3195 shared_context = container->context;
3196 inst = shared_context.method_inst;
3198 args = g_new0 (MonoType*, inst->type_argc);
3199 for (i = 0; i < container->type_argc; ++i) {
3200 MonoGenericParamInfo *info = &container->type_params [i].info;
3201 gboolean ref_only = FALSE;
3203 if (info && info->constraints) {
3204 constraints = info->constraints;
3206 while (*constraints) {
3207 MonoClass *cklass = *constraints;
3208 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3209 /* Inflaring the method with our vtype would not be valid */
3216 args [i] = &mono_defaults.object_class->byval_arg;
3218 args [i] = &mono_defaults.int_class->byval_arg;
3220 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3225 add_wrappers (MonoAotCompile *acfg)
3227 MonoMethod *method, *m;
3229 MonoMethodSignature *sig, *csig;
3233 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3234 * so there is only one wrapper of a given type, or inlining their contents into their
3237 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3239 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3240 gboolean skip = FALSE;
3242 method = mono_get_method (acfg->image, token, NULL);
3244 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3245 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3246 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3249 /* Skip methods which can not be handled by get_runtime_invoke () */
3250 sig = mono_method_signature (method);
3253 if ((sig->ret->type == MONO_TYPE_PTR) ||
3254 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3256 if (mono_class_is_open_constructed_type (sig->ret))
3259 for (j = 0; j < sig->param_count; j++) {
3260 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3262 if (mono_class_is_open_constructed_type (sig->params [j]))
3266 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3267 if (!mono_class_is_contextbound (method->klass)) {
3268 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3269 gboolean has_nullable = FALSE;
3271 for (j = 0; j < sig->param_count; j++) {
3272 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3273 has_nullable = TRUE;
3276 if (info && !has_nullable) {
3277 /* Supported by the dynamic runtime-invoke wrapper */
3285 //printf ("%s\n", mono_method_full_name (method, TRUE));
3286 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3290 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3291 MonoMethodDesc *desc;
3292 MonoMethod *orig_method;
3295 /* Runtime invoke wrappers */
3297 /* void runtime-invoke () [.cctor] */
3298 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3299 csig->ret = &mono_defaults.void_class->byval_arg;
3300 add_method (acfg, get_runtime_invoke_sig (csig));
3302 /* void runtime-invoke () [Finalize] */
3303 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3305 csig->ret = &mono_defaults.void_class->byval_arg;
3306 add_method (acfg, get_runtime_invoke_sig (csig));
3308 /* void runtime-invoke (string) [exception ctor] */
3309 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3311 csig->ret = &mono_defaults.void_class->byval_arg;
3312 csig->params [0] = &mono_defaults.string_class->byval_arg;
3313 add_method (acfg, get_runtime_invoke_sig (csig));
3315 /* void runtime-invoke (string, string) [exception ctor] */
3316 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3318 csig->ret = &mono_defaults.void_class->byval_arg;
3319 csig->params [0] = &mono_defaults.string_class->byval_arg;
3320 csig->params [1] = &mono_defaults.string_class->byval_arg;
3321 add_method (acfg, get_runtime_invoke_sig (csig));
3323 /* string runtime-invoke () [Exception.ToString ()] */
3324 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3326 csig->ret = &mono_defaults.string_class->byval_arg;
3327 add_method (acfg, get_runtime_invoke_sig (csig));
3329 /* void runtime-invoke (string, Exception) [exception ctor] */
3330 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3332 csig->ret = &mono_defaults.void_class->byval_arg;
3333 csig->params [0] = &mono_defaults.string_class->byval_arg;
3334 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3335 add_method (acfg, get_runtime_invoke_sig (csig));
3337 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3338 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3340 csig->ret = &(mono_class_from_name (
3341 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3342 csig->params [0] = &mono_defaults.string_class->byval_arg;
3343 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3344 add_method (acfg, get_runtime_invoke_sig (csig));
3346 /* runtime-invoke used by finalizers */
3347 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3349 /* This is used by mono_runtime_capture_context () */
3350 method = mono_get_context_capture_method ();
3352 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3354 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3355 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3359 add_method (acfg, mono_marshal_get_stelemref ());
3361 if (MONO_ARCH_HAVE_TLS_GET) {
3362 /* Managed Allocators */
3363 nallocators = mono_gc_get_managed_allocator_types ();
3364 for (i = 0; i < nallocators; ++i) {
3365 m = mono_gc_get_managed_allocator_by_type (i);
3367 add_method (acfg, m);
3370 /* Monitor Enter/Exit */
3371 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3372 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3373 /* This is a v4 method */
3375 method = mono_monitor_get_fast_path (orig_method);
3377 add_method (acfg, method);
3379 mono_method_desc_free (desc);
3381 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3382 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3383 g_assert (orig_method);
3384 mono_method_desc_free (desc);
3385 method = mono_monitor_get_fast_path (orig_method);
3387 add_method (acfg, method);
3390 /* Stelemref wrappers */
3392 MonoMethod **wrappers;
3395 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3396 for (i = 0; i < nwrappers; ++i)
3397 add_method (acfg, wrappers [i]);
3401 /* castclass_with_check wrapper */
3402 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3403 /* isinst_with_check wrapper */
3404 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3406 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3408 MonoMethodDesc *desc;
3411 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3412 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3413 mono_method_desc_free (desc);
3415 m = mono_monitor_get_fast_path (m);
3417 add_method (acfg, m);
3422 /* JIT icall wrappers */
3423 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3424 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3428 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3429 * we use the original method instead at runtime.
3430 * Since full-aot doesn't support remoting, this is not a problem.
3433 /* remoting-invoke wrappers */
3434 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3435 MonoMethodSignature *sig;
3437 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3438 method = mono_get_method (acfg->image, token, NULL);
3440 sig = mono_method_signature (method);
3442 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3443 m = mono_marshal_get_remoting_invoke_with_check (method);
3445 add_method (acfg, m);
3450 /* delegate-invoke wrappers */
3451 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3453 MonoCustomAttrInfo *cattr;
3455 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3456 klass = mono_class_get (acfg->image, token);
3459 mono_loader_clear_error ();
3463 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3466 if (!klass->generic_container) {
3467 method = mono_get_delegate_invoke (klass);
3469 m = mono_marshal_get_delegate_invoke (method, NULL);
3471 add_method (acfg, m);
3473 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3475 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3477 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3479 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3481 cattr = mono_custom_attrs_from_class (klass);
3486 for (j = 0; j < cattr->num_attrs; ++j)
3487 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3489 if (j < cattr->num_attrs)
3490 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3492 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3493 MonoGenericContext ctx;
3494 MonoMethod *inst, *gshared;
3497 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3500 method = mono_get_delegate_invoke (klass);
3501 create_gsharedvt_inst (acfg, method, &ctx);
3503 inst = mono_class_inflate_generic_method (method, &ctx);
3505 m = mono_marshal_get_delegate_invoke (inst, NULL);
3506 g_assert (m->is_inflated);
3508 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3509 add_extra_method (acfg, gshared);
3512 method = mono_get_delegate_begin_invoke (klass);
3513 create_gsharedvt_inst (acfg, method, &ctx);
3515 inst = mono_class_inflate_generic_method (method, &ctx);
3517 m = mono_marshal_get_delegate_begin_invoke (inst);
3518 g_assert (m->is_inflated);
3520 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3521 add_extra_method (acfg, gshared);
3524 method = mono_get_delegate_end_invoke (klass);
3525 create_gsharedvt_inst (acfg, method, &ctx);
3527 inst = mono_class_inflate_generic_method (method, &ctx);
3529 m = mono_marshal_get_delegate_end_invoke (inst);
3530 g_assert (m->is_inflated);
3532 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3533 add_extra_method (acfg, gshared);
3538 /* array access wrappers */
3539 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3542 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3543 klass = mono_class_get (acfg->image, token);
3546 mono_loader_clear_error ();
3550 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3551 MonoMethod *m, *wrapper;
3553 /* Add runtime-invoke wrappers too */
3555 m = mono_class_get_method_from_name (klass, "Get", -1);
3557 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3558 add_extra_method (acfg, wrapper);
3559 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3561 m = mono_class_get_method_from_name (klass, "Set", -1);
3563 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3564 add_extra_method (acfg, wrapper);
3565 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3569 /* Synchronized wrappers */
3570 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3571 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3572 method = mono_get_method (acfg->image, token, NULL);
3574 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3575 if (method->is_generic) {
3577 } else if (method->klass->generic_container) {
3578 MonoGenericContext ctx;
3579 MonoMethod *inst, *gshared, *m;
3582 * Create a generic wrapper for a generic instance, and AOT that.
3584 create_gsharedvt_inst (acfg, method, &ctx);
3585 inst = mono_class_inflate_generic_method (method, &ctx);
3586 m = mono_marshal_get_synchronized_wrapper (inst);
3587 g_assert (m->is_inflated);
3588 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3589 add_method (acfg, gshared);
3591 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3596 /* pinvoke wrappers */
3597 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3599 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3601 method = mono_get_method (acfg->image, token, NULL);
3603 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3604 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3605 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3609 /* native-to-managed wrappers */
3610 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3612 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3613 MonoCustomAttrInfo *cattr;
3616 method = mono_get_method (acfg->image, token, NULL);
3619 * Only generate native-to-managed wrappers for methods which have an
3620 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3621 * name to avoid defining a new assembly to contain it.
3623 cattr = mono_custom_attrs_from_method (method);
3626 for (j = 0; j < cattr->num_attrs; ++j)
3627 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3629 if (j < cattr->num_attrs) {
3630 MonoCustomAttrEntry *e = &cattr->attrs [j];
3631 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3632 const char *p = (const char*)e->data;
3634 int slen, num_named, named_type, data_type;
3638 char *export_name = NULL;
3639 MonoMethod *wrapper;
3641 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3642 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3643 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3644 mono_method_full_name (method, TRUE));
3648 g_assert (sig->param_count == 1);
3649 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3652 * Decode the cattr manually since we can't create objects
3653 * during aot compilation.
3659 /* From load_cattr_value () in reflection.c */
3660 slen = mono_metadata_decode_value (p, &p);
3661 n = g_memdup (p, slen + 1);
3663 t = mono_reflection_type_from_name (n, acfg->image);
3667 klass = mono_class_from_mono_type (t);
3668 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3672 num_named = read16 (p);
3675 g_assert (num_named < 2);
3676 if (num_named == 1) {
3679 MonoType *prop_type;
3681 /* parse ExportSymbol attribute */
3683 named_type = *named;
3688 name_len = mono_metadata_decode_blob_size (named, &named);
3689 name = g_malloc (name_len + 1);
3690 memcpy (name, named, name_len);
3691 name [name_len] = 0;
3694 g_assert (named_type == 0x54);
3695 g_assert (!strcmp (name, "ExportSymbol"));
3697 prop_type = &mono_defaults.string_class->byval_arg;
3699 /* load_cattr_value (), string case */
3700 g_assert (*named != (char)0xff);
3701 slen = mono_metadata_decode_value (named, &named);
3702 export_name = g_malloc (slen + 1);
3703 memcpy (export_name, named, slen);
3704 export_name [slen] = 0;
3708 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3709 add_method (acfg, wrapper);
3711 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3715 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3716 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3717 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3721 /* StructureToPtr/PtrToStructure wrappers */
3722 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3725 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3726 klass = mono_class_get (acfg->image, token);
3729 mono_loader_clear_error ();
3733 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3734 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3735 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3736 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3742 has_type_vars (MonoClass *klass)
3744 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3747 return has_type_vars (klass->element_class);
3748 if (klass->generic_class) {
3749 MonoGenericContext *context = &klass->generic_class->context;
3750 if (context->class_inst) {
3753 for (i = 0; i < context->class_inst->type_argc; ++i)
3754 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3758 if (klass->generic_container)
3764 is_vt_inst (MonoGenericInst *inst)
3768 for (i = 0; i < inst->type_argc; ++i) {
3769 MonoType *t = inst->type_argv [i];
3770 if (t->type == MONO_TYPE_VALUETYPE)
3777 method_has_type_vars (MonoMethod *method)
3779 if (has_type_vars (method->klass))
3782 if (method->is_inflated) {
3783 MonoGenericContext *context = mono_method_get_context (method);
3784 if (context->method_inst) {
3787 for (i = 0; i < context->method_inst->type_argc; ++i)
3788 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3795 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3798 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3800 /* This might lead to a huge code blowup so only do it if neccesary */
3801 if (!acfg->aot_opts.full_aot && !force)
3804 add_generic_class_with_depth (acfg, klass, 0, ref);
3808 check_type_depth (MonoType *t, int depth)
3816 case MONO_TYPE_GENERICINST: {
3817 MonoGenericClass *gklass = t->data.generic_class;
3818 MonoGenericInst *ginst = gklass->context.class_inst;
3821 for (i = 0; i < ginst->type_argc; ++i) {
3822 if (check_type_depth (ginst->type_argv [i], depth + 1))
3836 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3839 * add_generic_class:
3841 * Add all methods of a generic class.
3844 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3847 MonoClassField *field;
3849 gboolean use_gsharedvt = FALSE;
3851 if (!acfg->ginst_hash)
3852 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3854 mono_class_init (klass);
3856 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3859 if (has_type_vars (klass))
3862 if (!klass->generic_class && !klass->rank)
3865 if (klass->exception_type)
3868 if (!acfg->ginst_hash)
3869 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3871 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3874 if (check_type_depth (&klass->byval_arg, 0))
3877 if (acfg->aot_opts.log_generics)
3878 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3880 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3883 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3884 * Enable this only for some classes since gsharedvt might not support all methods.
3886 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) &&
3887 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
3888 use_gsharedvt = TRUE;
3891 while ((method = mono_class_get_methods (klass, &iter))) {
3892 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3894 * This is partial sharing, and we can't handle it yet
3899 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
3901 add_types_from_method_header (acfg, method);
3905 if (method->is_generic)
3910 * FIXME: Instances which are referenced by these methods are not added,
3911 * for example Array.Resize<int> for List<int>.Add ().
3913 add_extra_method_with_depth (acfg, method, depth + 1);
3917 while ((field = mono_class_get_fields (klass, &iter))) {
3918 if (field->type->type == MONO_TYPE_GENERICINST)
3919 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3922 if (klass->delegate) {
3923 method = mono_get_delegate_invoke (klass);
3925 method = mono_marshal_get_delegate_invoke (method, NULL);
3927 if (acfg->aot_opts.log_generics)
3928 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3930 add_method (acfg, method);
3933 /* Add superclasses */
3935 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3938 * For ICollection<T>, add instances of the helper methods
3939 * in Array, since a T[] could be cast to ICollection<T>.
3941 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3942 (!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"))) {
3943 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3944 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3948 if (!strcmp (klass->name, "IEnumerator`1"))
3949 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3951 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3953 /* Add the T[]/InternalEnumerator class */
3954 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3958 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3959 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3963 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3964 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3968 while ((method = mono_class_get_methods (array_class, &iter))) {
3969 if (strstr (method->name, name_prefix)) {
3970 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3972 add_extra_method_with_depth (acfg, m, depth);
3976 g_free (name_prefix);
3979 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3980 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3981 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3982 MonoClass *icomparable, *gcomparer;
3983 MonoGenericContext ctx;
3984 MonoType *args [16];
3986 memset (&ctx, 0, sizeof (ctx));
3988 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3989 g_assert (icomparable);
3990 args [0] = &tclass->byval_arg;
3991 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3993 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3994 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3995 g_assert (gcomparer);
3996 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4000 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4001 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4002 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4003 MonoClass *iface, *gcomparer;
4004 MonoGenericContext ctx;
4005 MonoType *args [16];
4007 memset (&ctx, 0, sizeof (ctx));
4009 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4011 args [0] = &tclass->byval_arg;
4012 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4014 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4015 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4016 g_assert (gcomparer);
4017 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4023 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4026 MonoGenericContext ctx;
4027 MonoType *args [16];
4029 if (acfg->aot_opts.no_instances)
4032 memset (&ctx, 0, sizeof (ctx));
4034 for (i = 0; i < ninsts; ++i) {
4035 args [0] = insts [i];
4036 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4037 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4042 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4044 MonoMethodHeader *header;
4045 MonoMethodSignature *sig;
4048 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4050 sig = mono_method_signature (method);
4053 for (j = 0; j < sig->param_count; ++j)
4054 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4055 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4058 header = mono_method_get_header (method);
4061 for (j = 0; j < header->num_locals; ++j)
4062 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4063 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4065 mono_loader_clear_error ();
4070 * add_generic_instances:
4072 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4075 add_generic_instances (MonoAotCompile *acfg)
4080 MonoGenericContext *context;
4082 if (acfg->aot_opts.no_instances)
4085 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4086 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4087 method = mono_get_method (acfg->image, token, NULL);
4092 if (method->klass->image != acfg->image)
4095 context = mono_method_get_context (method);
4097 if (context && ((context->class_inst && context->class_inst->is_open)))
4101 * For open methods, create an instantiation which can be passed to the JIT.
4102 * FIXME: Handle class_inst as well.
4104 if (context && context->method_inst && context->method_inst->is_open) {
4105 MonoGenericContext shared_context;
4106 MonoGenericInst *inst;
4107 MonoType **type_argv;
4109 MonoMethod *declaring_method;
4110 gboolean supported = TRUE;
4112 /* Check that the context doesn't contain open constructed types */
4113 if (context->class_inst) {
4114 inst = context->class_inst;
4115 for (i = 0; i < inst->type_argc; ++i) {
4116 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)
4118 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4122 if (context->method_inst) {
4123 inst = context->method_inst;
4124 for (i = 0; i < inst->type_argc; ++i) {
4125 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)
4127 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4135 memset (&shared_context, 0, sizeof (MonoGenericContext));
4137 inst = context->class_inst;
4139 type_argv = g_new0 (MonoType*, inst->type_argc);
4140 for (i = 0; i < inst->type_argc; ++i) {
4141 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)
4142 type_argv [i] = &mono_defaults.object_class->byval_arg;
4144 type_argv [i] = inst->type_argv [i];
4147 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4151 inst = context->method_inst;
4153 type_argv = g_new0 (MonoType*, inst->type_argc);
4154 for (i = 0; i < inst->type_argc; ++i) {
4155 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)
4156 type_argv [i] = &mono_defaults.object_class->byval_arg;
4158 type_argv [i] = inst->type_argv [i];
4161 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4165 if (method->is_generic || method->klass->generic_container)
4166 declaring_method = method;
4168 declaring_method = mono_method_get_declaring_generic_method (method);
4170 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4174 * If the method is fully sharable, it was already added in place of its
4175 * generic definition.
4177 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4181 * FIXME: Partially shared methods are not shared here, so we end up with
4182 * many identical methods.
4184 add_extra_method (acfg, method);
4187 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4190 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4192 klass = mono_class_get (acfg->image, token);
4193 if (!klass || klass->rank) {
4194 mono_loader_clear_error ();
4198 add_generic_class (acfg, klass, FALSE, "typespec");
4201 /* Add types of args/locals */
4202 for (i = 0; i < acfg->methods->len; ++i) {
4203 method = g_ptr_array_index (acfg->methods, i);
4204 add_types_from_method_header (acfg, method);
4207 if (acfg->image == mono_defaults.corlib) {
4209 MonoType *insts [256];
4212 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4213 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4214 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4215 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4216 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4217 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4218 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4219 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4220 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4221 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4222 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4223 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4225 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4226 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4228 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4229 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4231 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4233 /* Add instances of the array generic interfaces for primitive types */
4234 /* This will add instances of the InternalArray_ helper methods in Array too */
4235 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4237 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4238 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4240 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4241 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4243 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4246 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4247 * used for all instances of GetGenericValueImpl by the AOT runtime.
4250 MonoGenericContext ctx;
4251 MonoType *args [16];
4252 MonoMethod *get_method;
4253 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4255 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4258 memset (&ctx, 0, sizeof (ctx));
4259 args [0] = &mono_defaults.object_class->byval_arg;
4260 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4261 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4265 /* Same for CompareExchange<T>/Exchange<T> */
4267 MonoGenericContext ctx;
4268 MonoType *args [16];
4270 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4271 gpointer iter = NULL;
4273 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4274 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4275 memset (&ctx, 0, sizeof (ctx));
4276 args [0] = &mono_defaults.object_class->byval_arg;
4277 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4278 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4283 /* Same for Volatile.Read/Write<T> */
4285 MonoGenericContext ctx;
4286 MonoType *args [16];
4288 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4289 gpointer iter = NULL;
4291 if (volatile_klass) {
4292 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4293 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4294 memset (&ctx, 0, sizeof (ctx));
4295 args [0] = &mono_defaults.object_class->byval_arg;
4296 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4297 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4306 * is_direct_callable:
4308 * Return whenever the method identified by JI is directly callable without
4309 * going through the PLT.
4312 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4314 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4315 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4317 gboolean direct_callable = TRUE;
4319 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4320 direct_callable = FALSE;
4321 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4322 // FIXME: Maybe call the wrapper directly ?
4323 direct_callable = FALSE;
4325 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4326 /* Disable this so all calls go through load_method (), see the
4327 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4328 * mono_debugger_agent_init ().
4330 direct_callable = FALSE;
4333 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4334 /* sgen does some initialization when the allocator method is created */
4335 direct_callable = FALSE;
4337 if (direct_callable)
4340 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4341 if (acfg->aot_opts.direct_pinvoke)
4343 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4344 if (acfg->aot_opts.direct_icalls)
4352 #ifdef MONO_ARCH_AOT_SUPPORTED
4354 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4356 MonoImage *image = method->klass->image;
4357 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4358 MonoTableInfo *tables = image->tables;
4359 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4360 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4361 guint32 im_cols [MONO_IMPLMAP_SIZE];
4364 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4368 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4371 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4373 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4376 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4378 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4385 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4387 if (a->native_offset == b->native_offset)
4388 return a->il_offset - b->il_offset;
4390 return a->native_offset - b->native_offset;
4394 * compute_line_numbers:
4396 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4399 static MonoDebugSourceLocation**
4400 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4402 MonoDebugMethodInfo *minfo;
4403 MonoDebugLineNumberEntry *ln_array;
4404 MonoDebugSourceLocation *loc;
4405 int i, prev_line, prev_il_offset;
4406 int *native_to_il_offset = NULL;
4407 MonoDebugSourceLocation **res;
4410 minfo = mono_debug_lookup_method (method);
4413 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4414 if (debug_info->code_size != code_size)
4417 g_assert (code_size);
4419 /* Compute the native->IL offset mapping */
4421 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4422 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4424 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4426 native_to_il_offset = g_new0 (int, code_size + 1);
4428 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4430 MonoDebugLineNumberEntry *lne = &ln_array [i];
4433 for (j = 0; j < lne->native_offset; ++j)
4434 native_to_il_offset [j] = -1;
4437 if (i < debug_info->num_line_numbers - 1) {
4438 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4440 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4441 native_to_il_offset [j] = lne->il_offset;
4443 for (j = lne->native_offset; j < code_size; ++j)
4444 native_to_il_offset [j] = lne->il_offset;
4449 /* Compute the native->line number mapping */
4450 res = g_new0 (MonoDebugSourceLocation*, code_size);
4451 prev_il_offset = -1;
4454 for (i = 0; i < code_size; ++i) {
4455 int il_offset = native_to_il_offset [i];
4457 if (il_offset == -1 || il_offset == prev_il_offset)
4459 prev_il_offset = il_offset;
4460 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4461 if (!(loc && loc->source_file))
4463 if (loc->row == prev_line) {
4464 mono_debug_symfile_free_location (loc);
4467 prev_line = loc->row;
4468 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4470 /* This will cover the prolog too */
4480 get_file_index (MonoAotCompile *acfg, const char *source_file)
4484 // FIXME: Free these
4485 if (!acfg->dwarf_ln_filenames)
4486 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4487 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4489 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4490 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4491 emit_unset_mode (acfg);
4492 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4500 * emit_and_reloc_code:
4502 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4503 * is true, calls are made through the GOT too. This is used for emitting trampolines
4504 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4505 * since trampolines are needed to make PTL work.
4508 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4510 int i, pindex, start_index, method_index;
4512 MonoJumpInfo *patch_info;
4513 MonoMethodHeader *header;
4514 MonoDebugSourceLocation **locs = NULL;
4516 #ifdef MONO_ARCH_AOT_SUPPORTED
4517 gboolean direct_call, external_call;
4519 const char *direct_call_target = 0;
4520 const char *direct_pinvoke;
4524 header = mono_method_get_header (method);
4526 method_index = get_method_index (acfg, method);
4529 if (acfg->gas_line_numbers && method && debug_info) {
4530 locs = compute_line_numbers (method, code_len, debug_info);
4532 int findex = get_file_index (acfg, "<unknown>");
4533 emit_unset_mode (acfg);
4534 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4538 /* Collect and sort relocations */
4539 patches = g_ptr_array_new ();
4540 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4541 g_ptr_array_add (patches, patch_info);
4542 g_ptr_array_sort (patches, compare_patches);
4545 for (i = 0; i < code_len; i += INST_LEN) {
4547 for (pindex = start_index; pindex < patches->len; ++pindex) {
4548 patch_info = g_ptr_array_index (patches, pindex);
4549 if (patch_info->ip.i >= i)
4553 if (locs && locs [i]) {
4554 MonoDebugSourceLocation *loc = locs [i];
4557 findex = get_file_index (acfg, loc->source_file);
4558 emit_unset_mode (acfg);
4559 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4560 mono_debug_symfile_free_location (loc);
4564 #ifdef MONO_ARCH_AOT_SUPPORTED
4565 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4566 start_index = pindex;
4568 switch (patch_info->type) {
4569 case MONO_PATCH_INFO_NONE:
4571 case MONO_PATCH_INFO_GOT_OFFSET: {
4574 arch_emit_got_offset (acfg, code + i, &code_size);
4575 i += code_size - INST_LEN;
4577 patch_info->type = MONO_PATCH_INFO_NONE;
4580 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4581 int code_size, index;
4582 char *selector = (void*)patch_info->data.target;
4584 if (!acfg->objc_selector_to_index)
4585 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4586 if (!acfg->objc_selectors)
4587 acfg->objc_selectors = g_ptr_array_new ();
4588 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4592 index = acfg->objc_selector_index;
4593 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4594 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4595 acfg->objc_selector_index ++;
4598 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4599 i += code_size - INST_LEN;
4601 patch_info->type = MONO_PATCH_INFO_NONE;
4606 * If this patch is a call, try emitting a direct call instead of
4607 * through a PLT entry. This is possible if the called method is in
4608 * the same assembly and requires no initialization.
4610 direct_call = FALSE;
4611 external_call = FALSE;
4612 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4613 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4614 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4615 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4617 direct_call_target = callee_cfg->asm_symbol;
4618 patch_info->type = MONO_PATCH_INFO_NONE;
4619 acfg->stats.direct_calls ++;
4622 acfg->stats.all_calls ++;
4623 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4624 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4625 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4626 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4628 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4629 if (direct_pinvoke) {
4631 g_assert (strlen (direct_pinvoke) < 1000);
4632 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4635 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4636 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4637 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4638 /* Call to a C function implementing a jit icall */
4640 external_call = TRUE;
4641 g_assert (strlen (sym) < 1000);
4642 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4644 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4645 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4646 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4647 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4648 /* Call to a jit icall without a wrapper */
4650 external_call = TRUE;
4651 g_assert (strlen (sym) < 1000);
4652 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4657 patch_info->type = MONO_PATCH_INFO_NONE;
4658 acfg->stats.direct_calls ++;
4661 if (!got_only && !direct_call) {
4662 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4664 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4666 direct_call_target = plt_entry->symbol;
4668 /* Nullify the patch */
4669 patch_info->type = MONO_PATCH_INFO_NONE;
4670 plt_entry->jit_used = TRUE;
4677 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4678 i += call_size - INST_LEN;
4682 got_slot = get_got_offset (acfg, patch_info);
4684 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4685 i += code_size - INST_LEN;
4691 #endif /* MONO_ARCH_AOT_SUPPORTED */
4694 /* Find next patch */
4696 for (pindex = start_index; pindex < patches->len; ++pindex) {
4697 patch_info = g_ptr_array_index (patches, pindex);
4698 if (patch_info->ip.i >= i)
4702 /* Try to emit multiple bytes at once */
4703 if (pindex < patches->len && patch_info->ip.i > i) {
4706 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4707 if (locs && locs [limit])
4711 emit_code_bytes (acfg, code + i, limit - i);
4712 i = limit - INST_LEN;
4714 emit_code_bytes (acfg, code + i, INST_LEN);
4725 * Return a modified version of S which only includes characters permissible in symbols.
4728 sanitize_symbol (MonoAotCompile *acfg, char *s)
4730 gboolean process = FALSE;
4739 for (i = 0; i < len; ++i)
4740 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4745 gs = g_string_sized_new (len);
4746 for (i = 0; i < len; ++i) {
4748 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4749 g_string_append_c (gs, c);
4750 } else if (c > 0x7f) {
4751 /* multi-byte utf8 */
4752 g_string_append_printf (gs, "_0x%x", c);
4755 while (c >> 6 == 0x2) {
4756 g_string_append_printf (gs, "%x", c);
4760 g_string_append_printf (gs, "_");
4763 g_string_append_c (gs, '_');
4767 res = mono_mempool_strdup (acfg->mempool, gs->str);
4768 g_string_free (gs, TRUE);
4773 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4775 char *name1, *name2, *cached;
4776 int i, j, len, count;
4779 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4780 if (!prefix || !*prefix)
4784 name1 = mono_method_full_name (method, TRUE);
4785 len = strlen (name1);
4786 name2 = malloc (strlen (prefix) + len + 16);
4787 memcpy (name2, prefix, strlen (prefix));
4788 j = strlen (prefix);
4789 for (i = 0; i < len; ++i) {
4790 if (isalnum (name1 [i])) {
4791 name2 [j ++] = name1 [i];
4792 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4794 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4797 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4806 while (g_hash_table_lookup (cache, name2)) {
4807 sprintf (name2 + j, "_%d", count);
4811 cached = g_strdup (name2);
4812 g_hash_table_insert (cache, cached, cached);
4818 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4823 char *debug_sym = NULL;
4824 char *symbol = NULL;
4825 int func_alignment = AOT_FUNC_ALIGNMENT;
4826 MonoMethodHeader *header;
4829 method = cfg->orig_method;
4830 code = cfg->native_code;
4831 header = cfg->header;
4833 method_index = get_method_index (acfg, method);
4834 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4837 /* Make the labels local */
4838 emit_section_change (acfg, ".text", 0);
4839 emit_alignment (acfg, func_alignment);
4841 if (acfg->global_symbols && acfg->need_no_dead_strip)
4842 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4844 emit_label (acfg, cfg->asm_symbol);
4846 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4848 * Write a C style symbol for every method, this has two uses:
4849 * - it works on platforms where the dwarf debugging info is not
4851 * - it allows the setting of breakpoints of aot-ed methods.
4853 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4855 if (acfg->need_no_dead_strip)
4856 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4857 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4858 emit_label (acfg, debug_sym);
4861 export_name = g_hash_table_lookup (acfg->export_names, method);
4863 /* Emit a global symbol for the method */
4864 emit_global_inner (acfg, export_name, TRUE);
4865 emit_label (acfg, export_name);
4868 if (cfg->verbose_level > 0)
4869 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4871 acfg->stats.code_size += cfg->code_len;
4873 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4875 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 ()));
4879 if (acfg->aot_opts.write_symbols) {
4880 emit_symbol_size (acfg, debug_sym, ".");
4884 emit_label (acfg, symbol);
4891 * Encode PATCH_INFO into its disk representation.
4894 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4898 switch (patch_info->type) {
4899 case MONO_PATCH_INFO_NONE:
4901 case MONO_PATCH_INFO_IMAGE:
4902 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4904 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4905 case MONO_PATCH_INFO_JIT_TLS_ID:
4906 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4907 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4909 case MONO_PATCH_INFO_METHOD_REL:
4910 encode_value ((gint)patch_info->data.offset, p, &p);
4912 case MONO_PATCH_INFO_SWITCH: {
4913 gpointer *table = (gpointer *)patch_info->data.table->table;
4916 encode_value (patch_info->data.table->table_size, p, &p);
4917 for (k = 0; k < patch_info->data.table->table_size; k++)
4918 encode_value ((int)(gssize)table [k], p, &p);
4921 case MONO_PATCH_INFO_METHODCONST:
4922 case MONO_PATCH_INFO_METHOD:
4923 case MONO_PATCH_INFO_METHOD_JUMP:
4924 case MONO_PATCH_INFO_ICALL_ADDR:
4925 case MONO_PATCH_INFO_METHOD_RGCTX:
4926 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
4927 encode_method_ref (acfg, patch_info->data.method, p, &p);
4929 case MONO_PATCH_INFO_INTERNAL_METHOD:
4930 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4931 guint32 len = strlen (patch_info->data.name);
4933 encode_value (len, p, &p);
4935 memcpy (p, patch_info->data.name, len);
4940 case MONO_PATCH_INFO_LDSTR: {
4941 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4942 guint32 token = patch_info->data.token->token;
4943 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4944 encode_value (image_index, p, &p);
4945 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4948 case MONO_PATCH_INFO_RVA:
4949 case MONO_PATCH_INFO_DECLSEC:
4950 case MONO_PATCH_INFO_LDTOKEN:
4951 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4952 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4953 encode_value (patch_info->data.token->token, p, &p);
4954 encode_value (patch_info->data.token->has_context, p, &p);
4955 if (patch_info->data.token->has_context)
4956 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4958 case MONO_PATCH_INFO_EXC_NAME: {
4959 MonoClass *ex_class;
4962 mono_class_from_name (mono_defaults.exception_class->image,
4963 "System", patch_info->data.target);
4964 g_assert (ex_class);
4965 encode_klass_ref (acfg, ex_class, p, &p);
4968 case MONO_PATCH_INFO_R4:
4969 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4971 case MONO_PATCH_INFO_R8:
4972 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4973 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4975 case MONO_PATCH_INFO_VTABLE:
4976 case MONO_PATCH_INFO_CLASS:
4977 case MONO_PATCH_INFO_IID:
4978 case MONO_PATCH_INFO_ADJUSTED_IID:
4979 case MONO_PATCH_INFO_CLASS_INIT:
4980 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4982 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4983 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
4984 if (patch_info->data.del_tramp->method) {
4985 encode_value (1, p, &p);
4986 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
4988 encode_value (0, p, &p);
4991 case MONO_PATCH_INFO_FIELD:
4992 case MONO_PATCH_INFO_SFLDA:
4993 encode_field_info (acfg, patch_info->data.field, p, &p);
4995 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4997 case MONO_PATCH_INFO_RGCTX_FETCH: {
4998 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5003 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5004 * reference the same method, so encode the method only once.
5006 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5008 buf2 = g_malloc (1024);
5011 encode_method_ref (acfg, entry->method, p2, &p2);
5012 g_assert (p2 - buf2 < 1024);
5014 offset = add_to_blob (acfg, buf2, p2 - buf2);
5017 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5022 encode_value (offset, p, &p);
5023 g_assert ((int)entry->info_type < 256);
5024 g_assert (entry->data->type < 256);
5025 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5026 encode_patch (acfg, entry->data, p, &p);
5029 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5030 case MONO_PATCH_INFO_MONITOR_ENTER:
5031 case MONO_PATCH_INFO_MONITOR_EXIT:
5032 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5034 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5035 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5036 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5038 case MONO_PATCH_INFO_SIGNATURE:
5039 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5041 case MONO_PATCH_INFO_TLS_OFFSET:
5042 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5044 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5045 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5046 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5048 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5049 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5052 encode_method_ref (acfg, info->method, p, &p);
5053 encode_value (info->num_entries, p, &p);
5054 for (i = 0; i < info->num_entries; ++i) {
5055 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5057 encode_value (template->info_type, p, &p);
5058 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5059 case MONO_PATCH_INFO_CLASS:
5060 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5062 case MONO_PATCH_INFO_FIELD:
5063 encode_field_info (acfg, template->data, p, &p);
5066 g_assert_not_reached ();
5073 g_warning ("unable to handle jump info %d", patch_info->type);
5074 g_assert_not_reached ();
5081 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5084 guint32 pindex, offset;
5085 MonoJumpInfo *patch_info;
5087 encode_value (n_patches, p, &p);
5089 for (pindex = 0; pindex < patches->len; ++pindex) {
5090 patch_info = g_ptr_array_index (patches, pindex);
5092 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5096 offset = get_got_offset (acfg, patch_info);
5097 encode_value (offset, p, &p);
5104 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5108 int pindex, buf_size, n_patches;
5110 MonoJumpInfo *patch_info;
5111 MonoMethodHeader *header;
5112 guint32 method_index;
5114 guint32 first_got_offset;
5116 method = cfg->orig_method;
5117 header = mono_method_get_header (method);
5119 method_index = get_method_index (acfg, method);
5121 /* Sort relocations */
5122 patches = g_ptr_array_new ();
5123 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5124 g_ptr_array_add (patches, patch_info);
5125 g_ptr_array_sort (patches, compare_patches);
5127 first_got_offset = acfg->cfgs [method_index]->got_offset;
5129 /**********************/
5130 /* Encode method info */
5131 /**********************/
5133 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5134 p = buf = g_malloc (buf_size);
5136 if (mono_class_get_cctor (method->klass))
5137 encode_klass_ref (acfg, method->klass, p, &p);
5139 /* Not needed when loading the method */
5140 encode_value (0, p, &p);
5143 if (cfg->opt & MONO_OPT_SHARED) {
5144 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5145 for (l = cfg->ldstr_list; l; l = l->next) {
5146 encode_value ((long)l->data, p, &p);
5150 /* Used only in shared mode */
5151 g_assert (!cfg->ldstr_list);
5154 for (pindex = 0; pindex < patches->len; ++pindex) {
5155 patch_info = g_ptr_array_index (patches, pindex);
5157 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5158 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5159 patch_info->type = MONO_PATCH_INFO_NONE;
5164 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5165 /* Stored in a GOT slot initialized at module load time */
5166 patch_info->type = MONO_PATCH_INFO_NONE;
5170 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5171 /* Stored in a GOT slot initialized at module load time */
5172 patch_info->type = MONO_PATCH_INFO_NONE;
5176 if (is_plt_patch (patch_info)) {
5177 /* Calls are made through the PLT */
5178 patch_info->type = MONO_PATCH_INFO_NONE;
5186 g_assert (cfg->has_got_slots);
5188 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5190 acfg->stats.info_size += p - buf;
5192 g_assert (p - buf < buf_size);
5194 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5199 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5201 guint32 cache_index;
5204 /* Reuse the unwind module to canonize and store unwind info entries */
5205 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5207 /* Use +/- 1 to distinguish 0s from missing entries */
5208 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5216 * It would be easier to use assembler symbols, but the caller needs an
5219 offset = acfg->unwind_info_offset;
5220 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5221 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5224 encode_value (encoded_len, p, &p);
5226 acfg->unwind_info_offset += encoded_len + (p - buf);
5232 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5235 int i, k, buf_size, method_index;
5236 guint32 debug_info_size;
5238 MonoMethodHeader *header;
5239 guint8 *p, *buf, *debug_info;
5240 MonoJitInfo *jinfo = cfg->jit_info;
5242 gboolean use_unwind_ops = FALSE;
5243 MonoSeqPointInfo *seq_points;
5245 method = cfg->orig_method;
5246 code = cfg->native_code;
5247 header = cfg->header;
5249 method_index = get_method_index (acfg, method);
5251 if (!acfg->aot_opts.nodebug) {
5252 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5255 debug_info_size = 0;
5258 seq_points = cfg->seq_point_info;
5260 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 128) : 0) + cfg->gc_map_size;
5261 p = buf = g_malloc (buf_size);
5263 use_unwind_ops = cfg->unwind_ops != NULL;
5265 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 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);
5267 encode_value (flags, p, &p);
5269 if (use_unwind_ops) {
5270 guint32 encoded_len;
5274 * This is a duplicate of the data in the .debug_frame section, but that
5275 * section cannot be accessed using the dl interface.
5277 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5278 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5281 encode_value (jinfo->used_regs, p, &p);
5284 /*Encode the number of holes before the number of clauses to make decoding easier*/
5285 if (jinfo->has_try_block_holes) {
5286 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5287 encode_value (table->num_holes, p, &p);
5290 /* Exception table */
5291 if (cfg->compile_llvm) {
5293 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5294 * since the information is only available to llc. Instead, we let llc save the data
5295 * into the LSDA, and read it from there at runtime.
5297 /* The assembly might be CIL stripped so emit the data ourselves */
5298 if (header->num_clauses)
5299 encode_value (header->num_clauses, p, &p);
5301 for (k = 0; k < header->num_clauses; ++k) {
5302 MonoExceptionClause *clause;
5304 clause = &header->clauses [k];
5306 encode_value (clause->flags, p, &p);
5307 if (clause->data.catch_class) {
5308 encode_value (1, p, &p);
5309 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5311 encode_value (0, p, &p);
5314 /* Emit a list of nesting clauses */
5315 for (i = 0; i < header->num_clauses; ++i) {
5317 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5319 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5321 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5322 encode_value (i, p, &p);
5324 encode_value (-1, p, &p);
5327 if (jinfo->num_clauses)
5328 encode_value (jinfo->num_clauses, p, &p);
5330 for (k = 0; k < jinfo->num_clauses; ++k) {
5331 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5333 encode_value (ei->flags, p, &p);
5334 encode_value (ei->exvar_offset, p, &p);
5336 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5337 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5339 if (ei->data.catch_class) {
5343 buf2 = g_malloc (4096);
5345 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5347 g_assert (len < 4096);
5348 encode_value (len, p, &p);
5349 memcpy (p, buf2, len);
5353 encode_value (0, p, &p);
5357 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5358 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5359 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5363 if (jinfo->has_try_block_holes) {
5364 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5365 for (i = 0; i < table->num_holes; ++i) {
5366 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5367 encode_value (hole->clause, p, &p);
5368 encode_value (hole->length, p, &p);
5369 encode_value (hole->offset, p, &p);
5373 if (jinfo->has_arch_eh_info) {
5374 MonoArchEHJitInfo *eh_info;
5376 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5377 encode_value (eh_info->stack_size, p, &p);
5380 if (jinfo->has_generic_jit_info) {
5381 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5382 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5388 encode_value (gi->nlocs, p, &p);
5390 for (i = 0; i < gi->nlocs; ++i) {
5391 MonoDwarfLocListEntry *entry = &gi->locations [i];
5393 encode_value (entry->is_reg ? 1 : 0, p, &p);
5394 encode_value (entry->reg, p, &p);
5396 encode_value (entry->offset, p, &p);
5398 g_assert (entry->from == 0);
5400 encode_value (entry->from, p, &p);
5401 encode_value (entry->to, p, &p);
5404 if (!cfg->compile_llvm) {
5405 encode_value (gi->has_this ? 1 : 0, p, &p);
5406 encode_value (gi->this_reg, p, &p);
5407 encode_value (gi->this_offset, p, &p);
5412 * Need to encode jinfo->method too, since it is not equal to 'method'
5413 * when using generic sharing.
5415 buf2 = g_malloc (4096);
5417 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5419 g_assert (len < 4096);
5420 encode_value (len, p, &p);
5421 memcpy (p, buf2, len);
5425 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5426 MonoMethodInflated *inflated;
5427 MonoGenericContext *context;
5428 MonoGenericInst *inst;
5430 g_assert (jinfo->d.method->is_inflated);
5431 inflated = (MonoMethodInflated*)jinfo->d.method;
5432 context = &inflated->context;
5434 encode_value (1, p, &p);
5435 if (context->class_inst) {
5436 inst = context->class_inst;
5438 encode_value (inst->type_argc, p, &p);
5439 for (i = 0; i < inst->type_argc; ++i)
5440 encode_value (gsctx->var_is_vt [i], p, &p);
5442 encode_value (0, p, &p);
5444 if (context->method_inst) {
5445 inst = context->method_inst;
5447 encode_value (inst->type_argc, p, &p);
5448 for (i = 0; i < inst->type_argc; ++i)
5449 encode_value (gsctx->mvar_is_vt [i], p, &p);
5451 encode_value (0, p, &p);
5454 encode_value (0, p, &p);
5459 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5461 encode_value (seq_points->len, p, &p);
5462 last_il_offset = last_native_offset = 0;
5463 for (i = 0; i < seq_points->len; ++i) {
5464 SeqPoint *sp = &seq_points->seq_points [i];
5465 il_offset = sp->il_offset;
5466 native_offset = sp->native_offset;
5467 encode_value (il_offset - last_il_offset, p, &p);
5468 encode_value (native_offset - last_native_offset, p, &p);
5469 last_il_offset = il_offset;
5470 last_native_offset = native_offset;
5472 encode_value (sp->flags, p, &p);
5473 encode_value (sp->next_len, p, &p);
5474 for (j = 0; j < sp->next_len; ++j)
5475 encode_value (sp->next [j], p, &p);
5479 g_assert (debug_info_size < buf_size);
5481 encode_value (debug_info_size, p, &p);
5482 if (debug_info_size) {
5483 memcpy (p, debug_info, debug_info_size);
5484 p += debug_info_size;
5485 g_free (debug_info);
5490 encode_value (cfg->gc_map_size, p, &p);
5491 /* The GC map requires 4 bytes of alignment */
5492 while ((gsize)p % 4)
5494 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5495 p += cfg->gc_map_size;
5498 acfg->stats.ex_info_size += p - buf;
5500 g_assert (p - buf < buf_size);
5503 /* The GC Map requires 4 byte alignment */
5504 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5509 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5511 MonoClass *klass = mono_class_get (acfg->image, token);
5513 int i, buf_size, res;
5514 gboolean no_special_static, cant_encode;
5515 gpointer iter = NULL;
5518 mono_loader_clear_error ();
5522 p = buf = g_malloc (buf_size);
5524 /* Mark as unusable */
5525 encode_value (-1, p, &p);
5527 res = add_to_blob (acfg, buf, p - buf);
5533 buf_size = 10240 + (klass->vtable_size * 16);
5534 p = buf = g_malloc (buf_size);
5538 mono_class_init (klass);
5540 mono_class_get_nested_types (klass, &iter);
5541 g_assert (klass->nested_classes_inited);
5543 mono_class_setup_vtable (klass);
5546 * Emit all the information which is required for creating vtables so
5547 * the runtime does not need to create the MonoMethod structures which
5548 * take up a lot of space.
5551 no_special_static = !mono_class_has_special_static_fields (klass);
5553 /* Check whenever we have enough info to encode the vtable */
5554 cant_encode = FALSE;
5555 for (i = 0; i < klass->vtable_size; ++i) {
5556 MonoMethod *cm = klass->vtable [i];
5558 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5562 mono_class_has_finalizer (klass);
5564 if (klass->generic_container || cant_encode) {
5565 encode_value (-1, p, &p);
5567 encode_value (klass->vtable_size, p, &p);
5568 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);
5569 if (klass->has_cctor)
5570 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5571 if (klass->has_finalize)
5572 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5574 encode_value (klass->instance_size, p, &p);
5575 encode_value (mono_class_data_size (klass), p, &p);
5576 encode_value (klass->packing_size, p, &p);
5577 encode_value (klass->min_align, p, &p);
5579 for (i = 0; i < klass->vtable_size; ++i) {
5580 MonoMethod *cm = klass->vtable [i];
5583 encode_method_ref (acfg, cm, p, &p);
5585 encode_value (0, p, &p);
5589 acfg->stats.class_info_size += p - buf;
5591 g_assert (p - buf < buf_size);
5592 res = add_to_blob (acfg, buf, p - buf);
5599 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5601 char *debug_sym = NULL;
5605 case MONO_PATCH_INFO_METHOD:
5606 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5608 case MONO_PATCH_INFO_INTERNAL_METHOD:
5609 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5611 case MONO_PATCH_INFO_CLASS_INIT:
5612 s = mono_type_get_name (&ji->data.klass->byval_arg);
5613 debug_sym = g_strdup_printf ("plt__class_init_%s", s);
5616 case MONO_PATCH_INFO_RGCTX_FETCH:
5617 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5619 case MONO_PATCH_INFO_ICALL_ADDR: {
5620 char *s = get_debug_sym (ji->data.method, "", cache);
5622 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5626 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5627 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5629 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5630 debug_sym = g_strdup_printf ("plt__generic_class_init");
5636 return sanitize_symbol (acfg, debug_sym);
5640 * Calls made from AOTed code are routed through a table of jumps similar to the
5641 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5642 * control to the AOT runtime through a trampoline.
5645 emit_plt (MonoAotCompile *acfg)
5651 sprintf (symbol, "plt");
5653 emit_section_change (acfg, ".text", 0);
5654 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5655 emit_label (acfg, symbol);
5656 emit_label (acfg, acfg->plt_symbol);
5658 for (i = 0; i < acfg->plt_offset; ++i) {
5659 char *debug_sym = NULL;
5660 MonoPltEntry *plt_entry = NULL;
5665 * The first plt entry is unused.
5669 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5674 * If the target is directly callable, alias the plt symbol to point to
5676 * FIXME: Use this to simplify emit_and_reloc_code ().
5677 * FIXME: Avoid the got slot.
5678 * FIXME: Add support to the binary writer.
5680 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5681 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5684 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5685 /* LLVM calls the PLT entries using bl, so emit a stub */
5686 emit_set_thumb_mode (acfg);
5687 fprintf (acfg->fp, "\n.thumb_func\n");
5688 emit_label (acfg, plt_entry->llvm_symbol);
5689 fprintf (acfg->fp, "bx pc\n");
5690 fprintf (acfg->fp, "nop\n");
5691 emit_set_arm_mode (acfg);
5692 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5694 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5701 debug_sym = plt_entry->debug_sym;
5703 if (acfg->thumb_mixed && !plt_entry->jit_used)
5704 /* Emit only a thumb version */
5707 if (acfg->llvm && !acfg->thumb_mixed)
5708 emit_label (acfg, plt_entry->llvm_symbol);
5711 if (acfg->need_no_dead_strip) {
5712 emit_unset_mode (acfg);
5713 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5715 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5716 emit_label (acfg, debug_sym);
5719 emit_label (acfg, plt_entry->symbol);
5721 arch_emit_plt_entry (acfg, i);
5724 emit_symbol_size (acfg, debug_sym, ".");
5727 if (acfg->thumb_mixed) {
5728 /* Make sure the ARM symbols don't alias the thumb ones */
5729 emit_zero_bytes (acfg, 16);
5732 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5735 for (i = 0; i < acfg->plt_offset; ++i) {
5736 char *debug_sym = NULL;
5737 MonoPltEntry *plt_entry = NULL;
5743 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5746 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5749 /* Skip plt entries not actually called by LLVM code */
5750 if (!plt_entry->llvm_used)
5753 if (acfg->aot_opts.write_symbols) {
5754 if (plt_entry->debug_sym)
5755 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5759 #if defined(TARGET_MACH)
5760 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5761 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5763 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5764 emit_label (acfg, debug_sym);
5766 fprintf (acfg->fp, "\n.thumb_func\n");
5768 emit_label (acfg, plt_entry->llvm_symbol);
5770 arch_emit_llvm_plt_entry (acfg, i);
5773 emit_symbol_size (acfg, debug_sym, ".");
5779 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5781 sprintf (symbol, "plt_end");
5782 emit_label (acfg, symbol);
5786 * emit_trampoline_full:
5788 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5789 * create_jit_info_for_trampoline ().
5791 static G_GNUC_UNUSED void
5792 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5794 char start_symbol [256];
5795 char end_symbol [256];
5797 guint32 buf_size, info_offset;
5798 MonoJumpInfo *patch_info;
5811 code_size = info->code_size;
5813 unwind_ops = info->unwind_ops;
5815 #ifdef __native_client_codegen__
5816 mono_nacl_fix_patches (code, ji);
5821 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5823 emit_section_change (acfg, ".text", 0);
5824 emit_global (acfg, start_symbol, TRUE);
5825 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5826 emit_label (acfg, start_symbol);
5828 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5829 emit_label (acfg, symbol);
5832 * The code should access everything through the GOT, so we pass
5835 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5837 emit_symbol_size (acfg, start_symbol, ".");
5840 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5841 emit_label (acfg, end_symbol);
5846 /* Sort relocations */
5847 patches = g_ptr_array_new ();
5848 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5849 if (patch_info->type != MONO_PATCH_INFO_NONE)
5850 g_ptr_array_add (patches, patch_info);
5851 g_ptr_array_sort (patches, compare_patches);
5853 buf_size = patches->len * 128 + 128;
5854 buf = g_malloc (buf_size);
5857 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5858 g_assert (p - buf < buf_size);
5860 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5862 info_offset = add_to_blob (acfg, buf, p - buf);
5864 emit_section_change (acfg, RODATA_SECT, 0);
5865 emit_global (acfg, symbol, FALSE);
5866 emit_label (acfg, symbol);
5868 emit_int32 (acfg, info_offset);
5872 guint32 encoded_len;
5876 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5878 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5879 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5882 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5883 emit_int32 (acfg, uw_offset);
5886 /* Emit debug info */
5890 sprintf (symbol, "%s", name);
5891 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5894 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5898 static G_GNUC_UNUSED void
5899 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5901 emit_trampoline_full (acfg, got_offset, info, FALSE);
5905 emit_trampolines (MonoAotCompile *acfg)
5908 char end_symbol [256];
5909 int i, tramp_got_offset;
5910 MonoAotTrampoline ntype;
5911 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5915 if (!acfg->aot_opts.full_aot)
5918 g_assert (acfg->image->assembly);
5920 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5921 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5922 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5923 MonoTrampInfo *info;
5926 * Emit the generic trampolines.
5928 * We could save some code by treating the generic trampolines as a wrapper
5929 * method, but that approach has its own complexities, so we choose the simpler
5932 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5933 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5934 #ifdef DISABLE_REMOTING
5935 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5938 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5939 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5942 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5943 emit_trampoline (acfg, acfg->got_offset, info);
5946 mono_arch_get_nullified_class_init_trampoline (&info);
5947 emit_trampoline (acfg, acfg->got_offset, info);
5948 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5949 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5950 emit_trampoline (acfg, acfg->got_offset, info);
5951 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5952 emit_trampoline (acfg, acfg->got_offset, info);
5955 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5956 emit_trampoline (acfg, acfg->got_offset, info);
5958 /* Emit the exception related code pieces */
5959 mono_arch_get_restore_context (&info, TRUE);
5960 emit_trampoline (acfg, acfg->got_offset, info);
5961 mono_arch_get_call_filter (&info, TRUE);
5962 emit_trampoline (acfg, acfg->got_offset, info);
5963 mono_arch_get_throw_exception (&info, TRUE);
5964 emit_trampoline (acfg, acfg->got_offset, info);
5965 mono_arch_get_rethrow_exception (&info, TRUE);
5966 emit_trampoline (acfg, acfg->got_offset, info);
5967 mono_arch_get_throw_corlib_exception (&info, TRUE);
5968 emit_trampoline (acfg, acfg->got_offset, info);
5970 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5971 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5973 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5975 /* Create a separate out trampoline for more information in stack traces */
5976 info->name = g_strdup ("gsharedvt_out_trampoline");
5977 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5981 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5983 GSList *l = mono_arch_get_trampolines (TRUE);
5986 MonoTrampInfo *info = l->data;
5988 emit_trampoline (acfg, acfg->got_offset, info);
5994 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5997 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5998 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5999 emit_trampoline (acfg, acfg->got_offset, info);
6001 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6002 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6003 emit_trampoline (acfg, acfg->got_offset, info);
6006 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6007 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6008 emit_trampoline (acfg, acfg->got_offset, info);
6014 /* delegate_invoke_impl trampolines */
6015 l = mono_arch_get_delegate_invoke_impls ();
6017 MonoTrampInfo *info = l->data;
6019 emit_trampoline (acfg, acfg->got_offset, info);
6024 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6026 /* Emit trampolines which are numerous */
6029 * These include the following:
6030 * - specific trampolines
6031 * - static rgctx invoke trampolines
6033 * These trampolines have the same code, they are parameterized by GOT
6035 * They are defined in this file, in the arch_... routines instead of
6036 * in tramp-<ARCH>.c, since it is easier to do it this way.
6040 * When running in aot-only mode, we can't create specific trampolines at
6041 * runtime, so we create a few, and save them in the AOT file.
6042 * Normal trampolines embed their argument as a literal inside the
6043 * trampoline code, we can't do that here, so instead we embed an offset
6044 * which needs to be added to the trampoline address to get the address of
6045 * the GOT slot which contains the argument value.
6046 * The generated trampolines jump to the generic trampolines using another
6047 * GOT slot, which will be setup by the AOT loader to point to the
6048 * generic trampoline code of the given type.
6052 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6056 emit_section_change (acfg, ".text", 0);
6058 tramp_got_offset = acfg->got_offset;
6060 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6062 case MONO_AOT_TRAMP_SPECIFIC:
6063 sprintf (symbol, "specific_trampolines");
6065 case MONO_AOT_TRAMP_STATIC_RGCTX:
6066 sprintf (symbol, "static_rgctx_trampolines");
6068 case MONO_AOT_TRAMP_IMT_THUNK:
6069 sprintf (symbol, "imt_thunks");
6071 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6072 sprintf (symbol, "gsharedvt_arg_trampolines");
6075 g_assert_not_reached ();
6078 sprintf (end_symbol, "%s_e", symbol);
6080 if (acfg->aot_opts.write_symbols)
6081 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6083 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6084 emit_label (acfg, symbol);
6086 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6088 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6092 case MONO_AOT_TRAMP_SPECIFIC:
6093 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6094 tramp_got_offset += 2;
6096 case MONO_AOT_TRAMP_STATIC_RGCTX:
6097 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6098 tramp_got_offset += 2;
6100 case MONO_AOT_TRAMP_IMT_THUNK:
6101 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6102 tramp_got_offset += 1;
6104 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6105 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6106 tramp_got_offset += 2;
6109 g_assert_not_reached ();
6111 #ifdef __native_client_codegen__
6112 /* align to avoid 32-byte boundary crossings */
6113 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6116 if (!acfg->trampoline_size [ntype]) {
6117 g_assert (tramp_size);
6118 acfg->trampoline_size [ntype] = tramp_size;
6122 emit_label (acfg, end_symbol);
6123 emit_int32 (acfg, 0);
6126 arch_emit_specific_trampoline_pages (acfg);
6128 /* Reserve some entries at the end of the GOT for our use */
6129 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6132 acfg->got_offset += acfg->num_trampoline_got_entries;
6136 str_begins_with (const char *str1, const char *str2)
6138 int len = strlen (str2);
6139 return strncmp (str1, str2, len) == 0;
6143 mono_aot_readonly_field_override (MonoClassField *field)
6146 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6147 char *p = rdv->name;
6149 len = strlen (field->parent->name_space);
6150 if (strncmp (p, field->parent->name_space, len))
6155 len = strlen (field->parent->name);
6156 if (strncmp (p, field->parent->name, len))
6161 if (strcmp (p, field->name))
6163 switch (rdv->type) {
6165 return &rdv->value.i1;
6167 return &rdv->value.i2;
6169 return &rdv->value.i4;
6178 add_readonly_value (MonoAotOptions *opts, const char *val)
6183 /* the format of val is:
6184 * namespace.typename.fieldname=type/value
6185 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6187 fval = strrchr (val, '/');
6189 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6192 tval = strrchr (val, '=');
6194 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6197 rdv = g_new0 (ReadOnlyValue, 1);
6198 rdv->name = g_malloc0 (tval - val + 1);
6199 memcpy (rdv->name, val, tval - val);
6202 if (strncmp (tval, "i1", 2) == 0) {
6203 rdv->value.i1 = atoi (fval);
6204 rdv->type = MONO_TYPE_I1;
6205 } else if (strncmp (tval, "i2", 2) == 0) {
6206 rdv->value.i2 = atoi (fval);
6207 rdv->type = MONO_TYPE_I2;
6208 } else if (strncmp (tval, "i4", 2) == 0) {
6209 rdv->value.i4 = atoi (fval);
6210 rdv->type = MONO_TYPE_I4;
6212 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6215 rdv->next = readonly_values;
6216 readonly_values = rdv;
6220 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6222 gchar **args, **ptr;
6224 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6225 for (ptr = args; ptr && *ptr; ptr ++) {
6226 const char *arg = *ptr;
6228 if (str_begins_with (arg, "outfile=")) {
6229 opts->outfile = g_strdup (arg + strlen ("outfile="));
6230 } else if (str_begins_with (arg, "save-temps")) {
6231 opts->save_temps = TRUE;
6232 } else if (str_begins_with (arg, "keep-temps")) {
6233 opts->save_temps = TRUE;
6234 } else if (str_begins_with (arg, "write-symbols")) {
6235 opts->write_symbols = TRUE;
6236 } else if (str_begins_with (arg, "no-write-symbols")) {
6237 opts->write_symbols = FALSE;
6238 } else if (str_begins_with (arg, "metadata-only")) {
6239 opts->metadata_only = TRUE;
6240 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6241 opts->bind_to_runtime_version = TRUE;
6242 } else if (str_begins_with (arg, "full")) {
6243 opts->full_aot = TRUE;
6244 } else if (str_begins_with (arg, "threads=")) {
6245 opts->nthreads = atoi (arg + strlen ("threads="));
6246 } else if (str_begins_with (arg, "static")) {
6247 opts->static_link = TRUE;
6248 opts->no_dlsym = TRUE;
6249 } else if (str_begins_with (arg, "asmonly")) {
6250 opts->asm_only = TRUE;
6251 } else if (str_begins_with (arg, "asmwriter")) {
6252 opts->asm_writer = TRUE;
6253 } else if (str_begins_with (arg, "nodebug")) {
6254 opts->nodebug = TRUE;
6255 } else if (str_begins_with (arg, "dwarfdebug")) {
6256 opts->dwarf_debug = TRUE;
6257 } else if (str_begins_with (arg, "nopagetrampolines")) {
6258 opts->use_trampolines_page = FALSE;
6259 } else if (str_begins_with (arg, "ntrampolines=")) {
6260 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6261 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6262 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6263 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6264 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6265 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6266 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6267 } else if (str_begins_with (arg, "autoreg")) {
6268 opts->autoreg = TRUE;
6269 } else if (str_begins_with (arg, "tool-prefix=")) {
6270 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6271 } else if (str_begins_with (arg, "soft-debug")) {
6272 opts->soft_debug = TRUE;
6273 } else if (str_begins_with (arg, "direct-pinvoke")) {
6274 opts->direct_pinvoke = TRUE;
6275 } else if (str_begins_with (arg, "direct-icalls")) {
6276 opts->direct_icalls = TRUE;
6277 #if defined(TARGET_ARM)
6278 } else if (str_begins_with (arg, "iphone-abi")) {
6279 // older full-aot users did depend on this.
6281 } else if (str_begins_with (arg, "no-direct-calls")) {
6282 opts->no_direct_calls = TRUE;
6283 } else if (str_begins_with (arg, "print-skipped")) {
6284 opts->print_skipped_methods = TRUE;
6285 } else if (str_begins_with (arg, "stats")) {
6287 } else if (str_begins_with (arg, "no-instances")) {
6288 opts->no_instances = TRUE;
6289 } else if (str_begins_with (arg, "log-generics")) {
6290 opts->log_generics = TRUE;
6291 } else if (str_begins_with (arg, "log-instances=")) {
6292 opts->log_instances = TRUE;
6293 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6294 } else if (str_begins_with (arg, "log-instances")) {
6295 opts->log_instances = TRUE;
6296 } else if (str_begins_with (arg, "mtriple=")) {
6297 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6298 } else if (str_begins_with (arg, "llvm-path=")) {
6299 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6300 } else if (str_begins_with (arg, "readonly-value=")) {
6301 add_readonly_value (opts, arg + strlen ("readonly-value="));
6302 } else if (str_begins_with (arg, "info")) {
6303 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6305 } else if (str_begins_with (arg, "gc-maps")) {
6306 mini_gc_enable_gc_maps_for_aot ();
6307 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6308 printf ("Supported options for --aot:\n");
6309 printf (" outfile=\n");
6310 printf (" save-temps\n");
6311 printf (" keep-temps\n");
6312 printf (" write-symbols\n");
6313 printf (" metadata-only\n");
6314 printf (" bind-to-runtime-version\n");
6316 printf (" threads=\n");
6317 printf (" static\n");
6318 printf (" asmonly\n");
6319 printf (" asmwriter\n");
6320 printf (" nodebug\n");
6321 printf (" dwarfdebug\n");
6322 printf (" ntrampolines=\n");
6323 printf (" nrgctx-trampolines=\n");
6324 printf (" nimt-trampolines=\n");
6325 printf (" ngsharedvt-trampolines=\n");
6326 printf (" autoreg\n");
6327 printf (" tool-prefix=\n");
6328 printf (" readonly-value=\n");
6329 printf (" soft-debug\n");
6330 printf (" gc-maps\n");
6331 printf (" print-skipped\n");
6332 printf (" no-instances\n");
6333 printf (" stats\n");
6335 printf (" help/?\n");
6338 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6343 if (opts->use_trampolines_page) {
6344 opts->ntrampolines = 0;
6345 opts->nrgctx_trampolines = 0;
6346 opts->nimt_trampolines = 0;
6347 opts->ngsharedvt_arg_trampolines = 0;
6353 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6355 MonoMethod *method = (MonoMethod*)key;
6356 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6357 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6358 MonoAotCompile *acfg = user_data;
6360 new_ji->image = ji->image;
6361 new_ji->token = ji->token;
6362 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6366 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6368 if (klass->type_token)
6370 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6373 return can_encode_class (acfg, klass->element_class);
6378 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6380 if (method->wrapper_type) {
6381 switch (method->wrapper_type) {
6382 case MONO_WRAPPER_NONE:
6383 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6384 case MONO_WRAPPER_XDOMAIN_INVOKE:
6385 case MONO_WRAPPER_STFLD:
6386 case MONO_WRAPPER_LDFLD:
6387 case MONO_WRAPPER_LDFLDA:
6388 case MONO_WRAPPER_LDFLD_REMOTE:
6389 case MONO_WRAPPER_STFLD_REMOTE:
6390 case MONO_WRAPPER_STELEMREF:
6391 case MONO_WRAPPER_ISINST:
6392 case MONO_WRAPPER_PROXY_ISINST:
6393 case MONO_WRAPPER_ALLOC:
6394 case MONO_WRAPPER_REMOTING_INVOKE:
6395 case MONO_WRAPPER_UNKNOWN:
6396 case MONO_WRAPPER_WRITE_BARRIER:
6397 case MONO_WRAPPER_DELEGATE_INVOKE:
6398 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6399 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6400 case MONO_WRAPPER_SYNCHRONIZED:
6402 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6403 case MONO_WRAPPER_CASTCLASS: {
6404 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6413 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6417 if (!method->token) {
6418 /* The method is part of a constructed type like Int[,].Set (). */
6419 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6420 if (method->klass->rank)
6430 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6432 switch (patch_info->type) {
6433 case MONO_PATCH_INFO_METHOD:
6434 case MONO_PATCH_INFO_METHODCONST:
6435 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6436 MonoMethod *method = patch_info->data.method;
6438 return can_encode_method (acfg, method);
6440 case MONO_PATCH_INFO_VTABLE:
6441 case MONO_PATCH_INFO_CLASS_INIT:
6442 case MONO_PATCH_INFO_CLASS:
6443 case MONO_PATCH_INFO_IID:
6444 case MONO_PATCH_INFO_ADJUSTED_IID:
6445 if (!can_encode_class (acfg, patch_info->data.klass)) {
6446 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6450 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6451 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6452 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6457 case MONO_PATCH_INFO_RGCTX_FETCH: {
6458 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6460 if (!can_encode_method (acfg, entry->method))
6462 if (!can_encode_patch (acfg, entry->data))
6476 * AOT compile a given method.
6477 * This function might be called by multiple threads, so it must be thread-safe.
6480 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6483 MonoJumpInfo *patch_info;
6486 MonoMethod *wrapped;
6488 if (acfg->aot_opts.metadata_only)
6491 mono_acfg_lock (acfg);
6492 index = get_method_index (acfg, method);
6493 mono_acfg_unlock (acfg);
6495 /* fixme: maybe we can also precompile wrapper methods */
6496 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6497 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6498 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6499 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6503 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6506 wrapped = mono_marshal_method_from_wrapper (method);
6507 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6508 // FIXME: The wrapper should be generic too, but it is not
6511 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6514 InterlockedIncrement (&acfg->stats.mcount);
6517 if (method->is_generic || method->klass->generic_container) {
6518 InterlockedIncrement (&acfg->stats.genericcount);
6523 //acfg->aot_opts.print_skipped_methods = TRUE;
6526 * Since these methods are the only ones which are compiled with
6527 * AOT support, and they are not used by runtime startup/shutdown code,
6528 * the runtime will not see AOT methods during AOT compilation,so it
6529 * does not need to support them by creating a fake GOT etc.
6531 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), acfg->aot_opts.full_aot ? (JIT_FLAG_AOT|JIT_FLAG_FULL_AOT) : (JIT_FLAG_AOT), 0);
6532 mono_loader_clear_error ();
6534 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6535 if (acfg->aot_opts.print_skipped_methods)
6536 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6537 InterlockedIncrement (&acfg->stats.genericcount);
6540 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6541 if (acfg->aot_opts.print_skipped_methods)
6542 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6543 /* Let the exception happen at runtime */
6547 if (cfg->disable_aot) {
6548 if (acfg->aot_opts.print_skipped_methods)
6549 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6550 InterlockedIncrement (&acfg->stats.ocount);
6551 mono_destroy_compile (cfg);
6554 cfg->method_index = index;
6556 /* Nullify patches which need no aot processing */
6557 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6558 switch (patch_info->type) {
6559 case MONO_PATCH_INFO_LABEL:
6560 case MONO_PATCH_INFO_BB:
6561 patch_info->type = MONO_PATCH_INFO_NONE;
6568 /* Collect method->token associations from the cfg */
6569 mono_acfg_lock (acfg);
6570 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6571 mono_acfg_unlock (acfg);
6574 * Check for absolute addresses.
6577 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6578 switch (patch_info->type) {
6579 case MONO_PATCH_INFO_ABS:
6580 /* unable to handle this */
6589 if (acfg->aot_opts.print_skipped_methods)
6590 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6591 InterlockedIncrement (&acfg->stats.abscount);
6592 mono_destroy_compile (cfg);
6596 /* Lock for the rest of the code */
6597 mono_acfg_lock (acfg);
6600 * Check for methods/klasses we can't encode.
6603 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6604 if (!can_encode_patch (acfg, patch_info))
6609 if (acfg->aot_opts.print_skipped_methods)
6610 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6611 acfg->stats.ocount++;
6612 mono_destroy_compile (cfg);
6613 mono_acfg_unlock (acfg);
6617 if (method->is_inflated && acfg->aot_opts.log_instances) {
6618 if (acfg->instances_logfile)
6619 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6621 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6624 /* Adds generic instances referenced by this method */
6626 * The depth is used to avoid infinite loops when generic virtual recursion is
6629 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6630 if (!acfg->aot_opts.no_instances && depth < 32) {
6631 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6632 switch (patch_info->type) {
6633 case MONO_PATCH_INFO_METHOD: {
6634 MonoMethod *m = patch_info->data.method;
6635 if (m->is_inflated) {
6636 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6637 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6638 !method_has_type_vars (m)) {
6639 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6640 if (acfg->aot_opts.full_aot)
6641 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6643 add_extra_method_with_depth (acfg, m, depth + 1);
6644 add_types_from_method_header (acfg, m);
6647 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6649 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6650 add_extra_method_with_depth (acfg, m, depth + 1);
6653 case MONO_PATCH_INFO_VTABLE: {
6654 MonoClass *klass = patch_info->data.klass;
6656 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6657 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6660 case MONO_PATCH_INFO_SFLDA: {
6661 MonoClass *klass = patch_info->data.field->parent;
6663 /* The .cctor needs to run at runtime. */
6664 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6665 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6674 /* Determine whenever the method has GOT slots */
6675 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6676 switch (patch_info->type) {
6677 case MONO_PATCH_INFO_GOT_OFFSET:
6678 case MONO_PATCH_INFO_NONE:
6679 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6681 case MONO_PATCH_INFO_IMAGE:
6682 /* The assembly is stored in GOT slot 0 */
6683 if (patch_info->data.image != acfg->image)
6684 cfg->has_got_slots = TRUE;
6687 if (!is_plt_patch (patch_info))
6688 cfg->has_got_slots = TRUE;
6693 if (!cfg->has_got_slots)
6694 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6697 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6699 /* Make a copy of the patch info which is in the mempool */
6701 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6703 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6704 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6707 patches = new_patch_info;
6709 patches_end->next = new_patch_info;
6710 patches_end = new_patch_info;
6712 cfg->patch_info = patches;
6714 /* Make a copy of the unwind info */
6716 GSList *l, *unwind_ops;
6720 for (l = cfg->unwind_ops; l; l = l->next) {
6721 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6722 memcpy (op, l->data, sizeof (MonoUnwindOp));
6723 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6725 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6727 /* Make a copy of the argument/local info */
6729 MonoInst **args, **locals;
6730 MonoMethodSignature *sig;
6731 MonoMethodHeader *header;
6734 sig = mono_method_signature (method);
6735 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6736 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6737 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6738 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6742 header = mono_method_get_header (method);
6743 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6744 for (i = 0; i < header->num_locals; ++i) {
6745 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6746 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6748 cfg->locals = locals;
6751 /* Free some fields used by cfg to conserve memory */
6752 mono_mempool_destroy (cfg->mempool);
6753 cfg->mempool = NULL;
6754 g_free (cfg->varinfo);
6755 cfg->varinfo = NULL;
6759 mono_regstate_free (cfg->rs);
6763 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6765 while (index >= acfg->cfgs_size) {
6766 MonoCompile **new_cfgs;
6769 new_size = acfg->cfgs_size * 2;
6770 new_cfgs = g_new0 (MonoCompile*, new_size);
6771 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6772 g_free (acfg->cfgs);
6773 acfg->cfgs = new_cfgs;
6774 acfg->cfgs_size = new_size;
6776 acfg->cfgs [index] = cfg;
6778 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6781 if (cfg->orig_method->wrapper_type)
6782 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6785 mono_acfg_unlock (acfg);
6787 InterlockedIncrement (&acfg->stats.ccount);
6791 compile_thread_main (gpointer *user_data)
6793 MonoDomain *domain = user_data [0];
6794 MonoAotCompile *acfg = user_data [1];
6795 GPtrArray *methods = user_data [2];
6798 mono_thread_attach (domain);
6800 for (i = 0; i < methods->len; ++i)
6801 compile_method (acfg, g_ptr_array_index (methods, i));
6805 load_profile_files (MonoAotCompile *acfg)
6809 int file_index, res, method_index, i;
6812 GList *unordered, *l;
6817 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6819 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6824 infile = fopen (tmp, "r");
6827 printf ("Using profile data file '%s'\n", tmp);
6832 res = fscanf (infile, "%32s\n", ver);
6833 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6834 printf ("Profile file has wrong version or invalid.\n");
6841 MonoMethodDesc *desc;
6844 if (fgets (name, 1023, infile) == NULL)
6847 /* Kill the newline */
6848 if (strlen (name) > 0)
6849 name [strlen (name) - 1] = '\0';
6851 desc = mono_method_desc_new (name, TRUE);
6853 method = mono_method_desc_search_in_image (desc, acfg->image);
6855 if (method && mono_method_get_token (method)) {
6856 token = mono_method_get_token (method);
6857 method_index = mono_metadata_token_index (token) - 1;
6860 for (i = 0; i < acfg->method_order->len; ++i) {
6861 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6867 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6869 //printf ("No method found matching '%s'.\n", name);
6875 /* Add missing methods */
6877 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6879 for (i = 0; i < acfg->method_order->len; ++i) {
6880 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6886 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6888 unordered = g_list_reverse (unordered);
6889 for (l = unordered; l; l = l->next)
6890 g_ptr_array_add (acfg->method_order, l->data);
6893 /* Used by the LLVM backend */
6895 mono_aot_get_got_offset (MonoJumpInfo *ji)
6897 return get_got_offset (llvm_acfg, ji);
6901 mono_aot_get_method_name (MonoCompile *cfg)
6903 if (llvm_acfg->aot_opts.static_link)
6904 /* Include the assembly name too to avoid duplicate symbol errors */
6905 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6907 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6911 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6913 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6914 MonoPltEntry *plt_entry;
6917 ji->data.target = data;
6919 if (!can_encode_patch (llvm_acfg, ji))
6922 plt_entry = get_plt_entry (llvm_acfg, ji);
6923 plt_entry->llvm_used = TRUE;
6925 #if defined(TARGET_MACH)
6926 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6928 return g_strdup_printf (plt_entry->llvm_symbol);
6933 mono_aot_get_method_index (MonoMethod *method)
6935 g_assert (llvm_acfg);
6936 return get_method_index (llvm_acfg, method);
6940 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6944 mono_acfg_lock (llvm_acfg);
6945 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6946 mono_acfg_unlock (llvm_acfg);
6956 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6960 emit_llvm_file (MonoAotCompile *acfg)
6962 char *command, *opts, *tempbc;
6964 MonoJumpInfo *patch_info;
6967 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6971 /* Compute the final size of the got */
6972 for (i = 0; i < acfg->nmethods; ++i) {
6973 if (acfg->cfgs [i]) {
6974 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6975 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6976 if (!is_plt_patch (patch_info))
6977 get_got_offset (acfg, patch_info);
6979 get_plt_entry (acfg, patch_info);
6985 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6987 if (acfg->aot_opts.full_aot) {
6991 * Need to add the got entries used by the trampolines.
6992 * This is only a conservative approximation.
6994 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6995 /* For the generic + rgctx trampolines */
6996 acfg->final_got_size += 400;
6997 /* For the specific trampolines */
6998 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6999 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
7004 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7005 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
7009 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7010 * a lot of time, and doesn't seem to save much space.
7011 * The following optimizations cannot be enabled:
7013 * - 'jump-threading' changes our blockaddress references to int constants.
7014 * - 'basiccg' fails because it contains:
7015 * if (CS && !isa<IntrinsicInst>(II)) {
7016 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7017 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7018 * The opt list below was produced by taking the output of:
7019 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7020 * then removing tailcallelim + the global opts.
7021 * strip-dead-prototypes deletes unused intrinsics definitions.
7023 opts = g_strdup ("-instcombine -simplifycfg");
7024 //opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -domtree -verify");
7025 /* The dse pass is disabled because of #13734 and #17616 */
7027 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7028 * // If we have no DataLayout information around, then the size of the store
7029 * // is inferrable from the pointee type. If they are the same type, then
7030 * // we know that the store is safe.
7031 * if (AA.getDataLayout() == 0 &&
7032 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7033 * return OverwriteComplete;
7034 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7036 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -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");
7038 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7039 printf ("Executing opt: %s\n", command);
7040 if (system (command) != 0) {
7046 if (!acfg->llc_args)
7047 acfg->llc_args = g_string_new ("");
7049 /* Verbose asm slows down llc greatly */
7050 g_string_append (acfg->llc_args, " -asm-verbose=false");
7052 if (acfg->aot_opts.mtriple)
7053 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7055 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7056 /* ios requires PIC code now */
7057 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7059 if (llvm_acfg->aot_opts.static_link)
7060 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7062 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7064 unlink (acfg->tmpfname);
7066 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpbasename);
7068 printf ("Executing llc: %s\n", command);
7070 if (system (command) != 0) {
7077 emit_code (MonoAotCompile *acfg)
7079 int oindex, i, prev_index;
7082 #if defined(TARGET_POWERPC64)
7083 sprintf (symbol, ".Lgot_addr");
7084 emit_section_change (acfg, ".text", 0);
7085 emit_alignment (acfg, 8);
7086 emit_label (acfg, symbol);
7087 emit_pointer (acfg, acfg->got_symbol);
7091 * This global symbol is used to compute the address of each method using the
7092 * code_offsets array. It is also used to compute the memory ranges occupied by
7093 * AOT code, so it must be equal to the address of the first emitted method.
7095 emit_section_change (acfg, ".text", 0);
7096 emit_alignment (acfg, 8);
7098 for (i = 0; i < acfg->nmethods; ++i) {
7099 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7100 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7105 if (!acfg->methods_symbol) {
7106 sprintf (symbol, "methods");
7107 emit_label (acfg, symbol);
7108 acfg->methods_symbol = g_strdup (symbol);
7112 * Emit some padding so the local symbol for the first method doesn't have the
7113 * same address as 'methods'.
7115 #if defined(__default_codegen__)
7116 emit_zero_bytes (acfg, 16);
7117 #elif defined(__native_client_codegen__)
7119 const int kPaddingSize = 16;
7120 guint8 pad_buffer[kPaddingSize];
7121 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7122 emit_bytes (acfg, pad_buffer, kPaddingSize);
7126 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7130 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7132 cfg = acfg->cfgs [i];
7137 method = cfg->orig_method;
7139 /* Emit unbox trampoline */
7140 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7141 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7143 emit_section_change (acfg, ".text", 0);
7144 #ifdef __native_client_codegen__
7145 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7148 if (acfg->thumb_mixed && cfg->compile_llvm) {
7149 emit_set_thumb_mode (acfg);
7150 fprintf (acfg->fp, "\n.thumb_func\n");
7153 emit_label (acfg, symbol);
7155 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7157 if (acfg->thumb_mixed && cfg->compile_llvm) {
7158 emit_set_arm_mode (acfg);
7162 if (cfg->compile_llvm)
7163 acfg->stats.llvm_count ++;
7165 emit_method_code (acfg, cfg);
7168 sprintf (symbol, "methods_end");
7169 emit_section_change (acfg, ".text", 0);
7170 emit_alignment (acfg, 8);
7171 emit_label (acfg, symbol);
7172 /* To distinguish it from the next symbol */
7173 emit_int32 (acfg, 0);
7176 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7177 * from optimizing them away, since it doesn't see that code_offsets references them.
7178 * JITted methods don't need this since they are referenced using assembler local
7180 * FIXME: This is why write-symbols doesn't work on OSX ?
7182 if (acfg->llvm && acfg->need_no_dead_strip) {
7183 fprintf (acfg->fp, "\n");
7184 for (i = 0; i < acfg->nmethods; ++i) {
7185 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7186 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7190 if (acfg->direct_method_addresses) {
7191 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7194 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7195 * This is PIE code, and the linker can update it if needed.
7197 sprintf (symbol, "method_addresses");
7198 emit_section_change (acfg, ".text", 1);
7199 emit_alignment (acfg, 8);
7200 emit_label (acfg, symbol);
7201 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7202 emit_unset_mode (acfg);
7203 if (acfg->need_no_dead_strip)
7204 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7206 for (i = 0; i < acfg->nmethods; ++i) {
7209 #ifdef MONO_ARCH_AOT_SUPPORTED
7211 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7213 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7217 sprintf (symbol, "method_addresses_end");
7218 emit_label (acfg, symbol);
7221 sprintf (symbol, "code_offsets");
7222 emit_section_change (acfg, RODATA_SECT, 1);
7223 emit_alignment (acfg, 8);
7224 emit_label (acfg, symbol);
7225 emit_int32 (acfg, 0);
7227 sprintf (symbol, "code_offsets");
7228 emit_section_change (acfg, RODATA_SECT, 1);
7229 emit_alignment (acfg, 8);
7230 emit_label (acfg, symbol);
7232 acfg->stats.offsets_size += acfg->nmethods * 4;
7234 for (i = 0; i < acfg->nmethods; ++i) {
7235 if (acfg->cfgs [i]) {
7236 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7238 emit_int32 (acfg, 0xffffffff);
7244 /* Emit a sorted table mapping methods to their unbox trampolines */
7245 sprintf (symbol, "unbox_trampolines");
7246 if (acfg->direct_method_addresses)
7247 emit_section_change (acfg, ".text", 0);
7249 emit_section_change (acfg, RODATA_SECT, 0);
7250 emit_alignment (acfg, 8);
7251 emit_label (acfg, symbol);
7254 for (i = 0; i < acfg->nmethods; ++i) {
7259 cfg = acfg->cfgs [i];
7263 method = cfg->orig_method;
7265 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7268 index = get_method_index (acfg, method);
7269 sprintf (symbol, "ut_%d", index);
7271 emit_int32 (acfg, index);
7272 if (acfg->direct_method_addresses) {
7273 #ifdef MONO_ARCH_AOT_SUPPORTED
7274 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7277 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7279 /* Make sure the table is sorted by index */
7280 g_assert (index > prev_index);
7284 sprintf (symbol, "unbox_trampolines_end");
7285 emit_label (acfg, symbol);
7286 emit_int32 (acfg, 0);
7290 emit_info (MonoAotCompile *acfg)
7296 offsets = g_new0 (gint32, acfg->nmethods);
7298 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7299 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7301 if (acfg->cfgs [i]) {
7302 emit_method_info (acfg, acfg->cfgs [i]);
7303 offsets [i] = acfg->cfgs [i]->method_info_offset;
7309 sprintf (symbol, "method_info_offsets");
7310 emit_section_change (acfg, RODATA_SECT, 1);
7311 emit_alignment (acfg, 8);
7312 emit_label (acfg, symbol);
7314 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7319 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7321 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7322 #define mix(a,b,c) { \
7323 a -= c; a ^= rot(c, 4); c += b; \
7324 b -= a; b ^= rot(a, 6); a += c; \
7325 c -= b; c ^= rot(b, 8); b += a; \
7326 a -= c; a ^= rot(c,16); c += b; \
7327 b -= a; b ^= rot(a,19); a += c; \
7328 c -= b; c ^= rot(b, 4); b += a; \
7330 #define final(a,b,c) { \
7331 c ^= b; c -= rot(b,14); \
7332 a ^= c; a -= rot(c,11); \
7333 b ^= a; b -= rot(a,25); \
7334 c ^= b; c -= rot(b,16); \
7335 a ^= c; a -= rot(c,4); \
7336 b ^= a; b -= rot(a,14); \
7337 c ^= b; c -= rot(b,24); \
7341 mono_aot_type_hash (MonoType *t1)
7343 guint hash = t1->type;
7345 hash |= t1->byref << 6; /* do not collide with t1->type values */
7347 case MONO_TYPE_VALUETYPE:
7348 case MONO_TYPE_CLASS:
7349 case MONO_TYPE_SZARRAY:
7350 /* check if the distribution is good enough */
7351 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7353 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7354 case MONO_TYPE_ARRAY:
7355 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7356 case MONO_TYPE_GENERICINST:
7357 return ((hash << 5) - hash) ^ 0;
7364 * mono_aot_method_hash:
7366 * Return a hash code for methods which only depends on metadata.
7369 mono_aot_method_hash (MonoMethod *method)
7371 MonoMethodSignature *sig;
7375 guint32 *hashes_start, *hashes;
7377 MonoGenericInst *ginst = NULL;
7379 /* Similar to the hash in mono_method_get_imt_slot () */
7381 sig = mono_method_signature (method);
7383 if (method->is_inflated)
7384 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7386 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7387 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7388 hashes = hashes_start;
7390 /* Some wrappers are assigned to random classes */
7391 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7392 klass = method->klass;
7394 klass = mono_defaults.object_class;
7396 if (!method->wrapper_type) {
7397 char *full_name = mono_type_full_name (&klass->byval_arg);
7399 hashes [0] = mono_metadata_str_hash (full_name);
7403 hashes [0] = mono_metadata_str_hash (klass->name);
7404 hashes [1] = mono_metadata_str_hash (klass->name_space);
7406 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7407 /* The method name includes a stringified pointer */
7410 hashes [2] = mono_metadata_str_hash (method->name);
7411 hashes [3] = method->wrapper_type;
7412 hashes [4] = mono_aot_type_hash (sig->ret);
7414 for (i = 0; i < sig->param_count; i++) {
7415 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7418 for (i = 0; i < ginst->type_argc; ++i)
7419 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7421 g_assert (hindex == hashes_count);
7423 /* Setup internal state */
7424 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7426 /* Handle most of the hashes */
7427 while (hashes_count > 3) {
7436 /* Handle the last 3 hashes (all the case statements fall through) */
7437 switch (hashes_count) {
7438 case 3 : c += hashes [2];
7439 case 2 : b += hashes [1];
7440 case 1 : a += hashes [0];
7442 case 0: /* nothing left to add */
7446 free (hashes_start);
7455 * mono_aot_get_array_helper_from_wrapper;
7457 * Get the helper method in Array called by an array wrapper method.
7460 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7464 MonoGenericContext ctx;
7465 MonoType *args [16];
7466 char *mname, *iname, *s, *s2, *helper_name = NULL;
7468 prefix = "System.Collections.Generic";
7469 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7470 s2 = strstr (s, "`1.");
7476 //printf ("X: %s %s\n", iname, mname);
7478 if (!strcmp (iname, "IList"))
7479 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7481 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7482 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7484 g_free (helper_name);
7487 if (m->is_generic) {
7488 memset (&ctx, 0, sizeof (ctx));
7489 args [0] = &method->klass->element_class->byval_arg;
7490 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7491 m = mono_class_inflate_generic_method (m, &ctx);
7497 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7499 typedef struct HashEntry {
7500 guint32 key, value, index;
7501 struct HashEntry *next;
7505 * emit_extra_methods:
7507 * Emit methods which are not in the METHOD table, like wrappers.
7510 emit_extra_methods (MonoAotCompile *acfg)
7512 int i, table_size, buf_size;
7515 guint32 *info_offsets;
7518 HashEntry *entry, *new_entry;
7519 int nmethods, max_chain_length;
7522 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7524 /* Emit method info */
7526 for (i = 0; i < acfg->extra_methods->len; ++i) {
7527 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7528 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7534 p = buf = g_malloc (buf_size);
7538 method = cfg->method_to_register;
7540 encode_method_ref (acfg, method, p, &p);
7542 g_assert ((p - buf) < buf_size);
7544 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7549 * Construct a chained hash table for mapping indexes in extra_method_info to
7552 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7553 table = g_ptr_array_sized_new (table_size);
7554 for (i = 0; i < table_size; ++i)
7555 g_ptr_array_add (table, NULL);
7556 chain_lengths = g_new0 (int, table_size);
7557 max_chain_length = 0;
7558 for (i = 0; i < acfg->extra_methods->len; ++i) {
7559 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7560 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7566 key = info_offsets [i];
7567 value = get_method_index (acfg, method);
7569 hash = mono_aot_method_hash (method) % table_size;
7570 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7572 chain_lengths [hash] ++;
7573 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7575 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7576 new_entry->key = key;
7577 new_entry->value = value;
7579 entry = g_ptr_array_index (table, hash);
7580 if (entry == NULL) {
7581 new_entry->index = hash;
7582 g_ptr_array_index (table, hash) = new_entry;
7585 entry = entry->next;
7587 entry->next = new_entry;
7588 new_entry->index = table->len;
7589 g_ptr_array_add (table, new_entry);
7593 //printf ("MAX: %d\n", max_chain_length);
7595 /* Emit the table */
7596 sprintf (symbol, "extra_method_table");
7597 emit_section_change (acfg, RODATA_SECT, 0);
7598 emit_alignment (acfg, 8);
7599 emit_label (acfg, symbol);
7601 emit_int32 (acfg, table_size);
7602 for (i = 0; i < table->len; ++i) {
7603 HashEntry *entry = g_ptr_array_index (table, i);
7605 if (entry == NULL) {
7606 emit_int32 (acfg, 0);
7607 emit_int32 (acfg, 0);
7608 emit_int32 (acfg, 0);
7610 //g_assert (entry->key > 0);
7611 emit_int32 (acfg, entry->key);
7612 emit_int32 (acfg, entry->value);
7614 emit_int32 (acfg, entry->next->index);
7616 emit_int32 (acfg, 0);
7621 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7622 * This is used by mono_aot_find_jit_info ().
7624 sprintf (symbol, "extra_method_info_offsets");
7625 emit_section_change (acfg, RODATA_SECT, 0);
7626 emit_alignment (acfg, 8);
7627 emit_label (acfg, symbol);
7629 emit_int32 (acfg, acfg->extra_methods->len);
7630 for (i = 0; i < acfg->extra_methods->len; ++i) {
7631 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7633 emit_int32 (acfg, get_method_index (acfg, method));
7634 emit_int32 (acfg, info_offsets [i]);
7639 emit_exception_info (MonoAotCompile *acfg)
7645 offsets = g_new0 (gint32, acfg->nmethods);
7646 for (i = 0; i < acfg->nmethods; ++i) {
7647 if (acfg->cfgs [i]) {
7648 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7649 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7655 sprintf (symbol, "ex_info_offsets");
7656 emit_section_change (acfg, RODATA_SECT, 1);
7657 emit_alignment (acfg, 8);
7658 emit_label (acfg, symbol);
7660 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7665 emit_unwind_info (MonoAotCompile *acfg)
7671 * The unwind info contains a lot of duplicates so we emit each unique
7672 * entry once, and only store the offset from the start of the table in the
7676 sprintf (symbol, "unwind_info");
7677 emit_section_change (acfg, RODATA_SECT, 1);
7678 emit_alignment (acfg, 8);
7679 emit_label (acfg, symbol);
7681 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7682 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7683 guint8 *unwind_info;
7684 guint32 unwind_info_len;
7688 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7691 encode_value (unwind_info_len, p, &p);
7692 emit_bytes (acfg, buf, p - buf);
7693 emit_bytes (acfg, unwind_info, unwind_info_len);
7695 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7700 emit_class_info (MonoAotCompile *acfg)
7706 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7707 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7708 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7710 sprintf (symbol, "class_info_offsets");
7711 emit_section_change (acfg, RODATA_SECT, 1);
7712 emit_alignment (acfg, 8);
7713 emit_label (acfg, symbol);
7715 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7719 typedef struct ClassNameTableEntry {
7720 guint32 token, index;
7721 struct ClassNameTableEntry *next;
7722 } ClassNameTableEntry;
7725 emit_class_name_table (MonoAotCompile *acfg)
7728 guint32 token, hash;
7733 ClassNameTableEntry *entry, *new_entry;
7736 * Construct a chained hash table for mapping class names to typedef tokens.
7738 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7739 table = g_ptr_array_sized_new (table_size);
7740 for (i = 0; i < table_size; ++i)
7741 g_ptr_array_add (table, NULL);
7742 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7743 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7744 klass = mono_class_get (acfg->image, token);
7746 mono_loader_clear_error ();
7749 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7750 hash = mono_metadata_str_hash (full_name) % table_size;
7753 /* FIXME: Allocate from the mempool */
7754 new_entry = g_new0 (ClassNameTableEntry, 1);
7755 new_entry->token = token;
7757 entry = g_ptr_array_index (table, hash);
7758 if (entry == NULL) {
7759 new_entry->index = hash;
7760 g_ptr_array_index (table, hash) = new_entry;
7763 entry = entry->next;
7765 entry->next = new_entry;
7766 new_entry->index = table->len;
7767 g_ptr_array_add (table, new_entry);
7771 /* Emit the table */
7772 sprintf (symbol, "class_name_table");
7773 emit_section_change (acfg, RODATA_SECT, 0);
7774 emit_alignment (acfg, 8);
7775 emit_label (acfg, symbol);
7777 /* FIXME: Optimize memory usage */
7778 g_assert (table_size < 65000);
7779 emit_int16 (acfg, table_size);
7780 g_assert (table->len < 65000);
7781 for (i = 0; i < table->len; ++i) {
7782 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7784 if (entry == NULL) {
7785 emit_int16 (acfg, 0);
7786 emit_int16 (acfg, 0);
7788 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7790 emit_int16 (acfg, entry->next->index);
7792 emit_int16 (acfg, 0);
7798 emit_image_table (MonoAotCompile *acfg)
7804 * The image table is small but referenced in a lot of places.
7805 * So we emit it at once, and reference its elements by an index.
7808 sprintf (symbol, "image_table");
7809 emit_section_change (acfg, RODATA_SECT, 1);
7810 emit_alignment (acfg, 8);
7811 emit_label (acfg, symbol);
7813 emit_int32 (acfg, acfg->image_table->len);
7814 for (i = 0; i < acfg->image_table->len; i++) {
7815 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7816 MonoAssemblyName *aname = &image->assembly->aname;
7818 /* FIXME: Support multi-module assemblies */
7819 g_assert (image->assembly->image == image);
7821 emit_string (acfg, image->assembly_name);
7822 emit_string (acfg, image->guid);
7823 emit_string (acfg, aname->culture ? aname->culture : "");
7824 emit_string (acfg, (const char*)aname->public_key_token);
7826 emit_alignment (acfg, 8);
7827 emit_int32 (acfg, aname->flags);
7828 emit_int32 (acfg, aname->major);
7829 emit_int32 (acfg, aname->minor);
7830 emit_int32 (acfg, aname->build);
7831 emit_int32 (acfg, aname->revision);
7836 emit_got_info (MonoAotCompile *acfg)
7839 int i, first_plt_got_patch, buf_size;
7841 guint32 *got_info_offsets;
7843 /* Add the patches needed by the PLT to the GOT */
7844 acfg->plt_got_offset_base = acfg->got_offset;
7845 first_plt_got_patch = acfg->got_patches->len;
7846 for (i = 1; i < acfg->plt_offset; ++i) {
7847 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7849 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7851 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7854 acfg->got_offset += acfg->plt_offset;
7858 * - optimize offsets table.
7859 * - reduce number of exported symbols.
7860 * - emit info for a klass only once.
7861 * - determine when a method uses a GOT slot which is guaranteed to be already
7863 * - clean up and document the code.
7864 * - use String.Empty in class libs.
7867 /* Encode info required to decode shared GOT entries */
7868 buf_size = acfg->got_patches->len * 128;
7869 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7870 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7871 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7873 if (acfg->plt_offset)
7874 acfg->plt_got_info_offsets [0] = 0;
7875 for (i = 0; i < acfg->got_patches->len; ++i) {
7876 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7881 encode_value (ji->type, p, &p);
7883 encode_patch (acfg, ji, p, &p);
7884 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7885 g_assert (p - buf <= buf_size);
7886 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7888 if (i >= first_plt_got_patch)
7889 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7890 acfg->stats.got_info_size += p - buf;
7893 /* Emit got_info_offsets table */
7894 sprintf (symbol, "got_info_offsets");
7895 emit_section_change (acfg, RODATA_SECT, 1);
7896 emit_alignment (acfg, 8);
7897 emit_label (acfg, symbol);
7899 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7900 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7904 emit_got (MonoAotCompile *acfg)
7909 /* Don't make GOT global so accesses to it don't need relocations */
7910 sprintf (symbol, "%s", acfg->got_symbol);
7911 emit_section_change (acfg, ".bss", 0);
7912 emit_alignment (acfg, 8);
7913 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7914 emit_label (acfg, symbol);
7915 if (acfg->got_offset > 0)
7916 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7918 sprintf (symbol, "got_end");
7919 emit_label (acfg, symbol);
7923 typedef struct GlobalsTableEntry {
7924 guint32 value, index;
7925 struct GlobalsTableEntry *next;
7926 } GlobalsTableEntry;
7929 emit_globals (MonoAotCompile *acfg)
7935 GlobalsTableEntry *entry, *new_entry;
7937 if (!acfg->aot_opts.static_link)
7941 * When static linking, we emit a table containing our globals.
7945 * Construct a chained hash table for mapping global names to their index in
7946 * the globals table.
7948 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7949 table = g_ptr_array_sized_new (table_size);
7950 for (i = 0; i < table_size; ++i)
7951 g_ptr_array_add (table, NULL);
7952 for (i = 0; i < acfg->globals->len; ++i) {
7953 char *name = g_ptr_array_index (acfg->globals, i);
7955 hash = mono_metadata_str_hash (name) % table_size;
7957 /* FIXME: Allocate from the mempool */
7958 new_entry = g_new0 (GlobalsTableEntry, 1);
7959 new_entry->value = i;
7961 entry = g_ptr_array_index (table, hash);
7962 if (entry == NULL) {
7963 new_entry->index = hash;
7964 g_ptr_array_index (table, hash) = new_entry;
7967 entry = entry->next;
7969 entry->next = new_entry;
7970 new_entry->index = table->len;
7971 g_ptr_array_add (table, new_entry);
7975 /* Emit the table */
7976 sprintf (symbol, ".Lglobals_hash");
7977 emit_section_change (acfg, RODATA_SECT, 0);
7978 emit_alignment (acfg, 8);
7979 emit_label (acfg, symbol);
7981 /* FIXME: Optimize memory usage */
7982 g_assert (table_size < 65000);
7983 emit_int16 (acfg, table_size);
7984 for (i = 0; i < table->len; ++i) {
7985 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7987 if (entry == NULL) {
7988 emit_int16 (acfg, 0);
7989 emit_int16 (acfg, 0);
7991 emit_int16 (acfg, entry->value + 1);
7993 emit_int16 (acfg, entry->next->index);
7995 emit_int16 (acfg, 0);
7999 /* Emit the names */
8000 for (i = 0; i < acfg->globals->len; ++i) {
8001 char *name = g_ptr_array_index (acfg->globals, i);
8003 sprintf (symbol, "name_%d", i);
8004 emit_section_change (acfg, RODATA_SECT, 1);
8006 emit_alignment (acfg, 4);
8008 emit_label (acfg, symbol);
8009 emit_string (acfg, name);
8012 /* Emit the globals table */
8013 sprintf (symbol, "globals");
8014 emit_section_change (acfg, ".data", 0);
8015 /* This is not a global, since it is accessed by the init function */
8016 emit_alignment (acfg, 8);
8017 emit_label (acfg, symbol);
8019 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8020 emit_pointer (acfg, symbol);
8022 for (i = 0; i < acfg->globals->len; ++i) {
8023 char *name = g_ptr_array_index (acfg->globals, i);
8025 sprintf (symbol, "name_%d", i);
8026 emit_pointer (acfg, symbol);
8028 sprintf (symbol, "%s", name);
8029 emit_pointer (acfg, symbol);
8031 /* Null terminate the table */
8032 emit_int32 (acfg, 0);
8033 emit_int32 (acfg, 0);
8037 emit_autoreg (MonoAotCompile *acfg)
8042 * Emit a function into the .ctor section which will be called by the ELF
8043 * loader to register this module with the runtime.
8045 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8048 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8050 arch_emit_autoreg (acfg, symbol);
8056 emit_mem_end (MonoAotCompile *acfg)
8060 sprintf (symbol, "mem_end");
8061 emit_section_change (acfg, ".text", 1);
8062 emit_alignment (acfg, 8);
8063 emit_label (acfg, symbol);
8067 * Emit a structure containing all the information not stored elsewhere.
8070 emit_file_info (MonoAotCompile *acfg)
8075 const char *gc_name;
8078 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8080 if (acfg->aot_opts.bind_to_runtime_version) {
8081 build_info = mono_get_runtime_build_info ();
8082 emit_string_symbol (acfg, "runtime_version", build_info);
8083 g_free (build_info);
8085 emit_string_symbol (acfg, "runtime_version", "");
8088 /* Emit a string holding the assembly name */
8089 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8092 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8095 gc_name = mono_gc_get_gc_name ();
8096 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8098 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8099 emit_section_change (acfg, ".data", 0);
8100 emit_alignment (acfg, 8);
8101 emit_label (acfg, symbol);
8102 if (!acfg->aot_opts.static_link)
8103 emit_global (acfg, symbol, FALSE);
8105 /* The data emitted here must match MonoAotFileInfo. */
8107 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8108 emit_int32 (acfg, 0);
8111 * We emit pointers to our data structures instead of emitting global symbols which
8112 * point to them, to reduce the number of globals, and because using globals leads to
8113 * various problems (i.e. arm/thumb).
8115 emit_pointer (acfg, acfg->got_symbol);
8116 emit_pointer (acfg, acfg->methods_symbol);
8119 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8121 emit_pointer (acfg, "mono_eh_frame");
8123 emit_pointer (acfg, NULL);
8125 emit_pointer (acfg, "blob");
8126 emit_pointer (acfg, "class_name_table");
8127 emit_pointer (acfg, "class_info_offsets");
8128 emit_pointer (acfg, "method_info_offsets");
8129 emit_pointer (acfg, "ex_info_offsets");
8130 emit_pointer (acfg, "code_offsets");
8131 if (acfg->direct_method_addresses)
8132 emit_pointer (acfg, "method_addresses");
8134 emit_pointer (acfg, NULL);
8135 emit_pointer (acfg, "extra_method_info_offsets");
8136 emit_pointer (acfg, "extra_method_table");
8137 emit_pointer (acfg, "got_info_offsets");
8138 emit_pointer (acfg, "methods_end");
8139 emit_pointer (acfg, "unwind_info");
8140 emit_pointer (acfg, "mem_end");
8141 emit_pointer (acfg, "image_table");
8142 emit_pointer (acfg, "plt");
8143 emit_pointer (acfg, "plt_end");
8144 emit_pointer (acfg, "assembly_guid");
8145 emit_pointer (acfg, "runtime_version");
8146 if (acfg->num_trampoline_got_entries) {
8147 emit_pointer (acfg, "specific_trampolines");
8148 emit_pointer (acfg, "static_rgctx_trampolines");
8149 emit_pointer (acfg, "imt_thunks");
8150 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8152 emit_pointer (acfg, NULL);
8153 emit_pointer (acfg, NULL);
8154 emit_pointer (acfg, NULL);
8155 emit_pointer (acfg, NULL);
8157 if (acfg->thumb_mixed) {
8158 emit_pointer (acfg, "thumb_end");
8160 emit_pointer (acfg, NULL);
8162 if (acfg->aot_opts.static_link) {
8163 emit_pointer (acfg, "globals");
8165 emit_pointer (acfg, NULL);
8167 emit_pointer (acfg, "assembly_name");
8168 emit_pointer (acfg, "unbox_trampolines");
8169 emit_pointer (acfg, "unbox_trampolines_end");
8171 emit_int32 (acfg, acfg->plt_got_offset_base);
8172 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8173 emit_int32 (acfg, acfg->plt_offset);
8174 emit_int32 (acfg, acfg->nmethods);
8175 emit_int32 (acfg, acfg->flags);
8176 emit_int32 (acfg, acfg->opts);
8177 emit_int32 (acfg, acfg->simd_opts);
8178 emit_int32 (acfg, gc_name_offset);
8180 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8181 emit_int32 (acfg, acfg->num_trampolines [i]);
8182 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8183 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8184 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8185 emit_int32 (acfg, acfg->trampoline_size [i]);
8186 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8188 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8193 memset (&t, 0, sizeof (MonoType));
8194 t.type = MONO_TYPE_R8;
8195 mono_type_size (&t, &align);
8196 emit_int32 (acfg, align);
8198 memset (&t, 0, sizeof (MonoType));
8199 t.type = MONO_TYPE_I8;
8200 mono_type_size (&t, &align);
8202 emit_int32 (acfg, align);
8205 emit_int32 (acfg, __alignof__ (double));
8206 emit_int32 (acfg, __alignof__ (gint64));
8208 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8209 emit_int32 (acfg, acfg->tramp_page_size);
8210 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8211 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8213 if (acfg->aot_opts.static_link) {
8217 * Emit a global symbol which can be passed by an embedding app to
8218 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8221 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8223 /* Get rid of characters which cannot occur in symbols */
8225 for (p = symbol; *p; ++p) {
8226 if (!(isalnum (*p) || *p == '_'))
8229 acfg->static_linking_symbol = g_strdup (symbol);
8230 emit_global_inner (acfg, symbol, FALSE);
8231 emit_alignment (acfg, sizeof (gpointer));
8232 emit_label (acfg, symbol);
8233 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8238 emit_blob (MonoAotCompile *acfg)
8242 sprintf (symbol, "blob");
8243 emit_section_change (acfg, RODATA_SECT, 1);
8244 emit_alignment (acfg, 8);
8245 emit_label (acfg, symbol);
8247 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8251 emit_objc_selectors (MonoAotCompile *acfg)
8255 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8260 * cat > foo.m << EOF
8263 * return @selector(print:);
8268 img_writer_emit_unset_mode (acfg->w);
8269 g_assert (acfg->fp);
8270 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8271 fprintf (acfg->fp, ".align 2\n");
8272 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8273 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8274 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8276 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8277 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8278 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8279 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8282 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8283 fprintf (acfg->fp, ".align 2\n");
8284 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8285 fprintf (acfg->fp, ".long 0\n");
8286 fprintf (acfg->fp, ".long 16\n");
8290 emit_dwarf_info (MonoAotCompile *acfg)
8292 #ifdef EMIT_DWARF_INFO
8296 /* DIEs for methods */
8297 for (i = 0; i < acfg->nmethods; ++i) {
8298 MonoCompile *cfg = acfg->cfgs [i];
8303 // FIXME: LLVM doesn't define .Lme_...
8304 if (cfg->compile_llvm)
8307 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8309 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, 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 ()));
8315 collect_methods (MonoAotCompile *acfg)
8318 MonoImage *image = acfg->image;
8320 /* Collect methods */
8321 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8323 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8325 method = mono_get_method (acfg->image, token, NULL);
8328 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8329 printf ("Run with MONO_LOG_LEVEL=debug for more information.\n");
8333 /* Load all methods eagerly to skip the slower lazy loading code */
8334 mono_class_setup_methods (method->klass);
8336 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8337 /* Compile the wrapper instead */
8338 /* We do this here instead of add_wrappers () because it is easy to do it here */
8339 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8343 /* FIXME: Some mscorlib methods don't have debug info */
8345 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8346 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8347 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8348 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8349 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8350 if (!mono_debug_lookup_method (method)) {
8351 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8358 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8359 add_method_with_index (acfg, method, i, FALSE);
8360 acfg->method_index ++;
8363 /* gsharedvt methods */
8364 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8366 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8368 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8371 method = mono_get_method (acfg->image, token, NULL);
8375 if (strcmp (method->name, "gshared2"))
8379 if (!strstr (method->klass->image->name, "mini"))
8382 if (method->is_generic || method->klass->generic_container) {
8383 MonoMethod *gshared;
8385 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8386 add_extra_method (acfg, gshared);
8390 add_generic_instances (acfg);
8392 if (acfg->aot_opts.full_aot)
8393 add_wrappers (acfg);
8397 compile_methods (MonoAotCompile *acfg)
8401 if (acfg->aot_opts.nthreads > 0) {
8406 gpointer *user_data;
8407 MonoMethod **methods;
8409 methods_len = acfg->methods->len;
8411 len = acfg->methods->len / acfg->aot_opts.nthreads;
8414 * Partition the list of methods into fragments, and hand it to threads to
8417 threads = g_ptr_array_new ();
8418 /* Make a copy since acfg->methods is modified by compile_method () */
8419 methods = g_new0 (MonoMethod*, methods_len);
8420 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8421 for (i = 0; i < methods_len; ++i)
8422 methods [i] = g_ptr_array_index (acfg->methods, i);
8424 while (i < methods_len) {
8425 frag = g_ptr_array_new ();
8426 for (j = 0; j < len; ++j) {
8427 if (i < methods_len) {
8428 g_ptr_array_add (frag, methods [i]);
8433 user_data = g_new0 (gpointer, 3);
8434 user_data [0] = mono_domain_get ();
8435 user_data [1] = acfg;
8436 user_data [2] = frag;
8438 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8439 g_ptr_array_add (threads, handle);
8443 for (i = 0; i < threads->len; ++i) {
8444 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8450 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8451 for (i = methods_len; i < acfg->methods->len; ++i) {
8452 /* This can new methods to acfg->methods */
8453 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8458 compile_asm (MonoAotCompile *acfg)
8460 char *command, *objfile;
8461 char *outfile_name, *tmp_outfile_name;
8462 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8464 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8465 #define AS_OPTIONS "--64"
8466 #elif defined(TARGET_POWERPC64)
8467 #define AS_OPTIONS "-a64 -mppc64"
8468 #define LD_OPTIONS "-m elf64ppc"
8469 #elif defined(sparc) && SIZEOF_VOID_P == 8
8470 #define AS_OPTIONS "-xarch=v9"
8471 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8472 #define AS_OPTIONS "-arch i386"
8474 #define AS_OPTIONS ""
8477 #ifdef __native_client_codegen__
8478 #if defined(TARGET_AMD64)
8479 #define AS_NAME "nacl64-as"
8481 #define AS_NAME "nacl-as"
8483 #elif defined(TARGET_OSX)
8484 #define AS_NAME "clang -c -x assembler"
8486 #define AS_NAME "as"
8490 #define LD_OPTIONS ""
8494 #define LD_NAME "ld -shared -G"
8495 #elif defined(__ppc__) && defined(TARGET_MACH)
8496 #define LD_NAME "gcc -dynamiclib"
8497 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8498 #define LD_NAME "clang --shared"
8499 #elif defined(HOST_WIN32)
8500 #define LD_NAME "gcc -shared --dll"
8501 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8502 #define LD_NAME "clang -m32 -dynamiclib"
8505 if (acfg->aot_opts.asm_only) {
8506 printf ("Output file: '%s'.\n", acfg->tmpfname);
8507 if (acfg->aot_opts.static_link)
8508 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8512 if (acfg->aot_opts.static_link) {
8513 if (acfg->aot_opts.outfile)
8514 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8516 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8518 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8520 command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
8521 printf ("Executing the native assembler: %s\n", command);
8522 if (system (command) != 0) {
8530 if (acfg->aot_opts.static_link) {
8531 printf ("Output file: '%s'.\n", objfile);
8532 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8537 if (acfg->aot_opts.outfile)
8538 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8540 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8542 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8545 command = g_strdup_printf ("%s -o %s %s.o", LD_NAME, tmp_outfile_name, acfg->tmpfname);
8547 command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8549 printf ("Executing the native linker: %s\n", command);
8550 if (system (command) != 0) {
8551 g_free (tmp_outfile_name);
8552 g_free (outfile_name);
8560 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8561 printf ("Stripping the binary: %s\n", com);
8565 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8567 * gas generates 'mapping symbols' each time code and data is mixed, which
8568 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8570 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8571 printf ("Stripping the binary: %s\n", command);
8572 if (system (command) != 0) {
8573 g_free (tmp_outfile_name);
8574 g_free (outfile_name);
8581 rename (tmp_outfile_name, outfile_name);
8583 #if defined(TARGET_MACH)
8584 command = g_strdup_printf ("dsymutil %s", outfile_name);
8585 printf ("Executing dsymutil: %s\n", command);
8586 if (system (command) != 0) {
8591 if (!acfg->aot_opts.save_temps)
8594 g_free (tmp_outfile_name);
8595 g_free (outfile_name);
8598 if (acfg->aot_opts.save_temps)
8599 printf ("Retained input file.\n");
8601 unlink (acfg->tmpfname);
8606 static MonoAotCompile*
8607 acfg_create (MonoAssembly *ass, guint32 opts)
8609 MonoImage *image = ass->image;
8610 MonoAotCompile *acfg;
8613 acfg = g_new0 (MonoAotCompile, 1);
8614 acfg->methods = g_ptr_array_new ();
8615 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8616 acfg->method_depth = g_hash_table_new (NULL, NULL);
8617 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8618 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8619 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8620 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8621 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8622 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8623 acfg->got_patches = g_ptr_array_new ();
8624 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8625 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8626 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8627 acfg->image_hash = g_hash_table_new (NULL, NULL);
8628 acfg->image_table = g_ptr_array_new ();
8629 acfg->globals = g_ptr_array_new ();
8630 acfg->image = image;
8632 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8633 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8634 acfg->mempool = mono_mempool_new ();
8635 acfg->extra_methods = g_ptr_array_new ();
8636 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8637 acfg->unwind_ops = g_ptr_array_new ();
8638 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8639 acfg->method_order = g_ptr_array_new ();
8640 acfg->export_names = g_hash_table_new (NULL, NULL);
8641 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8642 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8643 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8644 InitializeCriticalSection (&acfg->mutex);
8650 acfg_free (MonoAotCompile *acfg)
8654 img_writer_destroy (acfg->w);
8655 for (i = 0; i < acfg->nmethods; ++i)
8657 g_free (acfg->cfgs [i]);
8658 g_free (acfg->cfgs);
8659 g_free (acfg->static_linking_symbol);
8660 g_free (acfg->got_symbol);
8661 g_free (acfg->plt_symbol);
8662 g_ptr_array_free (acfg->methods, TRUE);
8663 g_ptr_array_free (acfg->got_patches, TRUE);
8664 g_ptr_array_free (acfg->image_table, TRUE);
8665 g_ptr_array_free (acfg->globals, TRUE);
8666 g_ptr_array_free (acfg->unwind_ops, TRUE);
8667 g_hash_table_destroy (acfg->method_indexes);
8668 g_hash_table_destroy (acfg->method_depth);
8669 g_hash_table_destroy (acfg->plt_offset_to_entry);
8670 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8671 if (acfg->patch_to_plt_entry [i])
8672 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8674 g_free (acfg->patch_to_plt_entry);
8675 g_hash_table_destroy (acfg->patch_to_got_offset);
8676 g_hash_table_destroy (acfg->method_to_cfg);
8677 g_hash_table_destroy (acfg->token_info_hash);
8678 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8679 g_hash_table_destroy (acfg->image_hash);
8680 g_hash_table_destroy (acfg->unwind_info_offsets);
8681 g_hash_table_destroy (acfg->method_label_hash);
8682 g_hash_table_destroy (acfg->export_names);
8683 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8684 g_hash_table_destroy (acfg->klass_blob_hash);
8685 g_hash_table_destroy (acfg->method_blob_hash);
8686 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8687 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8688 g_free (acfg->patch_to_got_offset_by_type);
8689 mono_mempool_destroy (acfg->mempool);
8694 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8696 MonoImage *image = ass->image;
8697 int i, res, all_sizes;
8698 MonoAotCompile *acfg;
8699 char *outfile_name, *tmp_outfile_name, *p;
8700 char llvm_stats_msg [256];
8704 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8705 if (opts & MONO_OPT_GSHAREDVT) {
8706 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8711 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8713 acfg = acfg_create (ass, opts);
8715 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8716 acfg->aot_opts.write_symbols = TRUE;
8717 acfg->aot_opts.ntrampolines = 1024;
8718 acfg->aot_opts.nrgctx_trampolines = 1024;
8719 acfg->aot_opts.nimt_trampolines = 128;
8720 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8721 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8722 acfg->aot_opts.llvm_path = g_strdup ("");
8724 acfg->aot_opts.use_trampolines_page = TRUE;
8727 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8729 if (acfg->aot_opts.static_link)
8730 acfg->aot_opts.autoreg = TRUE;
8732 //acfg->aot_opts.print_skipped_methods = TRUE;
8734 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8735 if (acfg->aot_opts.full_aot) {
8736 printf ("--aot=full is not supported on this platform.\n");
8741 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8742 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8746 if (acfg->aot_opts.static_link)
8747 acfg->aot_opts.asm_writer = TRUE;
8749 if (acfg->aot_opts.soft_debug) {
8750 MonoDebugOptions *opt = mini_get_debug_options ();
8752 opt->mdb_optimizations = TRUE;
8753 opt->gen_seq_points = TRUE;
8755 if (!mono_debug_enabled ()) {
8756 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8759 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8762 if (mono_use_llvm) {
8764 acfg->aot_opts.asm_writer = TRUE;
8765 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8767 if (acfg->aot_opts.soft_debug) {
8768 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8773 if (acfg->aot_opts.full_aot)
8774 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8776 if (acfg->aot_opts.instances_logfile_path) {
8777 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
8778 if (!acfg->instances_logfile) {
8779 fprintf (stderr, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
8784 load_profile_files (acfg);
8786 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8787 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8788 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8790 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8791 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8792 if (acfg->opts & MONO_OPT_GSHAREDVT)
8793 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8796 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8800 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8801 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8802 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8804 /* Get rid of characters which cannot occur in symbols */
8805 for (p = acfg->got_symbol_base; *p; ++p) {
8806 if (!(isalnum (*p) || *p == '_'))
8809 for (p = acfg->plt_symbol; *p; ++p) {
8810 if (!(isalnum (*p) || *p == '_'))
8813 for (p = acfg->assembly_name_sym; *p; ++p) {
8814 if (!(isalnum (*p) || *p == '_'))
8818 acfg->method_index = 1;
8822 if (acfg->aot_opts.full_aot)
8823 mono_set_partial_sharing_supported (TRUE);
8826 collect_methods (acfg);
8828 acfg->cfgs_size = acfg->methods->len + 32;
8829 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8831 /* PLT offset 0 is reserved for the PLT trampoline */
8832 acfg->plt_offset = 1;
8837 mono_llvm_create_aot_module (acfg->got_symbol_base);
8841 /* GOT offset 0 is reserved for the address of the current assembly */
8845 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8846 ji->type = MONO_PATCH_INFO_IMAGE;
8847 ji->data.image = acfg->image;
8849 get_got_offset (acfg, ji);
8851 /* Slot 1 is reserved for the mscorlib got addr */
8852 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8853 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8854 get_got_offset (acfg, ji);
8856 /* This is very common */
8857 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8858 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8859 get_got_offset (acfg, ji);
8861 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8862 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8863 get_got_offset (acfg, ji);
8868 compile_methods (acfg);
8872 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8878 if (acfg->aot_opts.asm_only) {
8879 if (acfg->aot_opts.outfile) {
8880 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8881 acfg->tmpbasename = g_strdup (acfg->tmpfname);
8883 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
8884 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8887 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
8888 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8891 emit_llvm_file (acfg);
8895 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8896 if (acfg->aot_opts.outfile)
8897 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8899 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8902 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8903 * it might be in another file system so the rename () won't work.
8905 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8907 acfg->fp = fopen (tmp_outfile_name, "w");
8909 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8913 acfg->w = img_writer_create (acfg->fp, TRUE);
8914 acfg->use_bin_writer = TRUE;
8917 /* Append to the .s file created by llvm */
8918 /* FIXME: Use multiple files instead */
8919 acfg->fp = fopen (acfg->tmpfname, "a+");
8921 if (acfg->aot_opts.asm_only) {
8922 if (acfg->aot_opts.outfile)
8923 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8925 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8926 acfg->fp = fopen (acfg->tmpfname, "w+");
8928 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8929 acfg->fp = fdopen (i, "w+");
8932 if (acfg->fp == 0) {
8933 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8936 acfg->w = img_writer_create (acfg->fp, FALSE);
8938 tmp_outfile_name = NULL;
8939 outfile_name = NULL;
8942 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8944 /* Compute symbols for methods */
8945 for (i = 0; i < acfg->nmethods; ++i) {
8946 if (acfg->cfgs [i]) {
8947 MonoCompile *cfg = acfg->cfgs [i];
8948 int method_index = get_method_index (acfg, cfg->orig_method);
8950 if (COMPILE_LLVM (cfg))
8951 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8952 else if (acfg->global_symbols)
8953 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8955 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8959 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
8961 * CLANG supports GAS .file/.loc directives, so emit line number information this way
8962 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
8965 //acfg->gas_line_numbers = TRUE;
8968 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8969 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
8970 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8973 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
8976 img_writer_emit_start (acfg->w);
8979 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
8981 if (acfg->thumb_mixed) {
8984 * This global symbol marks the end of THUMB code, and the beginning of ARM
8985 * code generated by our JIT.
8987 sprintf (symbol, "thumb_end");
8988 emit_section_change (acfg, ".text", 0);
8989 emit_alignment (acfg, 8);
8990 emit_label (acfg, symbol);
8991 emit_zero_bytes (acfg, 16);
8993 fprintf (acfg->fp, ".arm\n");
9000 emit_extra_methods (acfg);
9002 emit_trampolines (acfg);
9004 emit_class_name_table (acfg);
9006 emit_got_info (acfg);
9008 emit_exception_info (acfg);
9010 emit_unwind_info (acfg);
9012 emit_class_info (acfg);
9016 emit_image_table (acfg);
9020 emit_file_info (acfg);
9024 emit_objc_selectors (acfg);
9026 emit_globals (acfg);
9028 emit_autoreg (acfg);
9031 emit_dwarf_info (acfg);
9032 mono_dwarf_writer_close (acfg->dwarf);
9035 emit_mem_end (acfg);
9037 if (acfg->need_pt_gnu_stack) {
9038 /* This is required so the .so doesn't have an executable stack */
9039 /* The bin writer already emits this */
9040 if (!acfg->use_bin_writer)
9041 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9046 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9049 g_assert (acfg->got_offset <= acfg->final_got_size);
9052 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9054 strcpy (llvm_stats_msg, "");
9056 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;
9058 printf ("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",
9059 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9060 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9061 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9062 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9063 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9064 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9065 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9066 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9067 (int)(acfg->got_offset * sizeof (gpointer)));
9068 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9069 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9071 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9072 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9073 if (acfg->stats.genericcount)
9074 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9075 if (acfg->stats.abscount)
9076 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9077 if (acfg->stats.lmfcount)
9078 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9079 if (acfg->stats.ocount)
9080 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9083 res = img_writer_emit_writeout (acfg->w);
9088 if (acfg->use_bin_writer) {
9089 int err = rename (tmp_outfile_name, outfile_name);
9092 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9096 res = compile_asm (acfg);
9103 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9105 if (acfg->aot_opts.stats) {
9108 printf ("GOT slot distribution:\n");
9109 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9110 if (acfg->stats.got_slot_types [i])
9111 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9114 printf ("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);
9126 mono_aot_readonly_field_override (MonoClassField *field)
9132 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)