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 direct_pinvoke;
132 gboolean direct_icalls;
133 gboolean no_direct_calls;
134 gboolean use_trampolines_page;
135 gboolean no_instances;
139 int nrgctx_trampolines;
140 int nimt_trampolines;
141 int ngsharedvt_arg_trampolines;
142 int nrgctx_fetch_trampolines;
143 gboolean print_skipped_methods;
151 typedef struct MonoAotStats {
152 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
153 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
154 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
155 int got_slots, offsets_size;
156 int got_slot_types [MONO_PATCH_INFO_NONE];
157 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
158 int jit_time, gen_time, link_time;
161 typedef struct MonoAotCompile {
164 GHashTable *method_indexes;
165 GHashTable *method_depth;
168 GHashTable **patch_to_plt_entry;
169 GHashTable *plt_offset_to_entry;
170 GHashTable *patch_to_got_offset;
171 GHashTable **patch_to_got_offset_by_type;
172 GPtrArray *got_patches;
173 GHashTable *image_hash;
174 GHashTable *method_to_cfg;
175 GHashTable *token_info_hash;
176 GHashTable *method_to_pinvoke_import;
177 GPtrArray *extra_methods;
178 GPtrArray *image_table;
180 GPtrArray *method_order;
181 GHashTable *export_names;
182 /* Maps MonoClass* -> blob offset */
183 GHashTable *klass_blob_hash;
184 /* Maps MonoMethod* -> blob offset */
185 GHashTable *method_blob_hash;
186 guint32 *plt_got_info_offsets;
187 guint32 got_offset, plt_offset, plt_got_offset_base;
188 guint32 final_got_size;
189 /* Number of GOT entries reserved for trampolines */
190 guint32 num_trampoline_got_entries;
191 guint32 tramp_page_size;
193 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
194 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
195 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
196 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
198 MonoAotOptions aot_opts;
202 MonoMemPool *mempool;
205 char *static_linking_symbol;
206 CRITICAL_SECTION mutex;
207 gboolean use_bin_writer;
208 gboolean gas_line_numbers;
210 MonoDwarfWriter *dwarf;
215 GHashTable *unwind_info_offsets;
216 GPtrArray *unwind_ops;
217 guint32 unwind_info_offset;
218 char *got_symbol_base;
221 char *methods_symbol;
222 GHashTable *method_label_hash;
223 const char *temp_prefix;
224 const char *user_symbol_prefix;
225 const char *llvm_label_prefix;
226 guint32 label_generator;
228 MonoAotFileFlags flags;
229 MonoDynamicStream blob;
230 MonoClass **typespec_classes;
233 char *assembly_name_sym;
234 GHashTable *plt_entry_debug_sym_cache;
235 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
236 GHashTable *ginst_hash;
237 GHashTable *dwarf_ln_filenames;
238 gboolean global_symbols;
239 gboolean direct_method_addresses;
240 int objc_selector_index, objc_selector_index_2;
241 GPtrArray *objc_selectors;
242 GHashTable *objc_selector_to_index;
247 char *symbol, *llvm_symbol, *debug_sym;
249 gboolean jit_used, llvm_used;
252 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
253 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
255 /* This points to the current acfg in LLVM mode */
256 static MonoAotCompile *llvm_acfg;
258 #ifdef HAVE_ARRAY_ELEM_INIT
259 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
260 #define MSGSTRFIELD1(line) str##line
261 static const struct msgstr_t {
262 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
263 #include "patch-info.h"
266 #define PATCH_INFO(a,b) b,
267 #include "patch-info.h"
270 static const gint16 opidx [] = {
271 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
272 #include "patch-info.h"
276 static G_GNUC_UNUSED const char*
277 get_patch_name (int info)
279 return (const char*)&opstr + opidx [info];
283 #define PATCH_INFO(a,b) b,
284 static const char* const
285 patch_types [MONO_PATCH_INFO_NUM + 1] = {
286 #include "patch-info.h"
290 static G_GNUC_UNUSED const char*
291 get_patch_name (int info)
293 return patch_types [info];
299 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
301 /* Wrappers around the image writer functions */
304 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
306 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
310 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
312 img_writer_emit_push_section (acfg->w, section_name, subsection);
316 emit_pop_section (MonoAotCompile *acfg)
318 img_writer_emit_pop_section (acfg->w);
322 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
324 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
328 emit_label (MonoAotCompile *acfg, const char *name)
330 img_writer_emit_label (acfg->w, name);
334 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
336 img_writer_emit_bytes (acfg->w, buf, size);
340 emit_string (MonoAotCompile *acfg, const char *value)
342 img_writer_emit_string (acfg->w, value);
346 emit_line (MonoAotCompile *acfg)
348 img_writer_emit_line (acfg->w);
352 emit_alignment (MonoAotCompile *acfg, int size)
354 img_writer_emit_alignment (acfg->w, size);
358 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
360 img_writer_emit_pointer_unaligned (acfg->w, target);
364 emit_pointer (MonoAotCompile *acfg, const char *target)
366 img_writer_emit_pointer (acfg->w, target);
370 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
372 if (prefix [0] != '\0') {
373 char *s = g_strdup_printf ("%s%s", prefix, target);
374 img_writer_emit_pointer (acfg->w, s);
377 img_writer_emit_pointer (acfg->w, target);
382 emit_int16 (MonoAotCompile *acfg, int value)
384 img_writer_emit_int16 (acfg->w, value);
388 emit_int32 (MonoAotCompile *acfg, int value)
390 img_writer_emit_int32 (acfg->w, value);
394 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
396 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
400 emit_zero_bytes (MonoAotCompile *acfg, int num)
402 img_writer_emit_zero_bytes (acfg->w, num);
406 emit_byte (MonoAotCompile *acfg, guint8 val)
408 img_writer_emit_byte (acfg->w, val);
411 #ifdef __native_client_codegen__
413 emit_nacl_call_alignment (MonoAotCompile *acfg)
415 img_writer_emit_nacl_call_alignment (acfg->w);
419 static G_GNUC_UNUSED void
420 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
422 img_writer_emit_global (acfg->w, name, func);
426 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
428 if (acfg->aot_opts.no_dlsym) {
429 g_ptr_array_add (acfg->globals, g_strdup (name));
430 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
432 img_writer_emit_global (acfg->w, name, func);
437 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
439 img_writer_emit_symbol_size (acfg->w, name, end_label);
443 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
445 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
447 /* On apple, all symbols need to be aligned to avoid warnings from ld */
448 emit_alignment (acfg, 4);
450 img_writer_emit_label (acfg->w, name);
451 img_writer_emit_string (acfg->w, value);
454 static G_GNUC_UNUSED void
455 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
458 guint8 b = value & 0x7f;
460 if (value != 0) /* more bytes to come */
466 static G_GNUC_UNUSED void
467 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
470 gboolean negative = (value < 0);
477 /* the following is unnecessary if the
478 * implementation of >>= uses an arithmetic rather
479 * than logical shift for a signed left operand
483 value |= - ((gint64)1 <<(size - 7));
484 /* sign bit of byte is second high order bit (0x40) */
485 if ((value == 0 && !(byte & 0x40)) ||
486 (value == -1 && (byte & 0x40)))
490 emit_byte (acfg, byte);
494 static G_GNUC_UNUSED void
495 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
500 guint8 b = value & 0x7f;
502 if (value != 0) /* more bytes to come */
510 static G_GNUC_UNUSED void
511 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
514 gboolean negative = (value < 0);
522 /* the following is unnecessary if the
523 * implementation of >>= uses an arithmetic rather
524 * than logical shift for a signed left operand
528 value |= - (1 <<(size - 7));
529 /* sign bit of byte is second high order bit (0x40) */
530 if ((value == 0 && !(byte & 0x40)) ||
531 (value == -1 && (byte & 0x40)))
542 emit_unset_mode (MonoAotCompile *acfg)
544 img_writer_emit_unset_mode (acfg->w);
547 static G_GNUC_UNUSED void
548 emit_set_thumb_mode (MonoAotCompile *acfg)
550 emit_unset_mode (acfg);
551 fprintf (acfg->fp, ".code 16\n");
554 static G_GNUC_UNUSED void
555 emit_set_arm_mode (MonoAotCompile *acfg)
557 emit_unset_mode (acfg);
558 fprintf (acfg->fp, ".code 32\n");
562 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
564 emit_bytes (acfg, buf, size);
567 /* ARCHITECTURE SPECIFIC CODE */
569 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
570 #define EMIT_DWARF_INFO 1
573 #if defined(TARGET_ARM)
574 #define AOT_FUNC_ALIGNMENT 4
576 #define AOT_FUNC_ALIGNMENT 16
578 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
579 #undef AOT_FUNC_ALIGNMENT
580 #define AOT_FUNC_ALIGNMENT 32
583 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
584 #define PPC_LD_OP "ld"
585 #define PPC_LDX_OP "ldx"
587 #define PPC_LD_OP "lwz"
588 #define PPC_LDX_OP "lwzx"
592 #define AOT_TARGET_STR "AMD64"
597 #define AOT_TARGET_STR "ARM (MACH)"
599 #define AOT_TARGET_STR "ARM (!MACH)"
603 #ifdef TARGET_POWERPC64
604 #ifdef __mono_ilp32__
605 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
607 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
610 #ifdef TARGET_POWERPC
611 #ifdef __mono_ilp32__
612 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
614 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
621 #define AOT_TARGET_STR "X86 (WIN32)"
622 #elif defined(__native_client_codegen__)
623 #define AOT_TARGET_STR "X86 (native client codegen)"
625 #define AOT_TARGET_STR "X86 (!native client codegen)"
629 #ifndef AOT_TARGET_STR
630 #define AOT_TARGET_STR ""
634 arch_init (MonoAotCompile *acfg)
636 acfg->llc_args = g_string_new ("");
637 acfg->as_args = g_string_new ("");
640 * The prefix LLVM likes to put in front of symbol names on darwin.
641 * The mach-os specs require this for globals, but LLVM puts them in front of all
642 * symbols. We need to handle this, since we need to refer to LLVM generated
645 acfg->llvm_label_prefix = "";
646 acfg->user_symbol_prefix = "";
648 #if defined(TARGET_AMD64)
649 g_string_append (acfg->llc_args, " -march=x86-64");
653 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
654 g_string_append (acfg->llc_args, "-mattr=+v6");
657 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
658 g_string_append (acfg->as_args, " -mfpu=vfp3");
660 g_string_append (acfg->llc_args, " -soft-float");
663 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
664 acfg->thumb_mixed = TRUE;
666 if (acfg->aot_opts.mtriple)
667 mono_arch_set_target (acfg->aot_opts.mtriple);
671 acfg->user_symbol_prefix = "_";
672 acfg->llvm_label_prefix = "_";
673 acfg->need_no_dead_strip = TRUE;
674 acfg->aot_opts.gnu_asm = TRUE;
677 #if defined(__linux__) && !defined(TARGET_ARM)
678 acfg->need_pt_gnu_stack = TRUE;
682 acfg->direct_method_addresses = TRUE;
683 acfg->global_symbols = TRUE;
687 #ifdef MONO_ARCH_AOT_SUPPORTED
689 * arch_emit_direct_call:
691 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
695 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
697 #if defined(TARGET_X86) || defined(TARGET_AMD64)
698 /* Need to make sure this is exactly 5 bytes long */
699 if (external && !acfg->use_bin_writer) {
700 emit_unset_mode (acfg);
701 fprintf (acfg->fp, "call %s\n", target);
703 emit_byte (acfg, '\xe8');
704 emit_symbol_diff (acfg, target, ".", -4);
707 #elif defined(TARGET_ARM)
708 if (acfg->use_bin_writer) {
715 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
716 emit_bytes (acfg, buf, 4);
718 emit_unset_mode (acfg);
720 fprintf (acfg->fp, "blx %s\n", target);
722 fprintf (acfg->fp, "bl %s\n", target);
725 #elif defined(TARGET_POWERPC)
726 if (acfg->use_bin_writer) {
727 g_assert_not_reached ();
729 emit_unset_mode (acfg);
730 fprintf (acfg->fp, "bl %s\n", target);
734 g_assert_not_reached ();
741 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
743 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
744 * in in the 2. slot of every GOT, and require every method to place the GOT
745 * address in r30, even when it doesn't access the GOT otherwise. This way,
746 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
751 * PPC64 uses function descriptors which greatly complicate all code, since
752 * these are used very inconsistently in the runtime. Some functions like
753 * mono_compile_method () return ftn descriptors, while others like the
754 * trampoline creation functions do not.
755 * We assume that all GOT slots contain function descriptors, and create
756 * descriptors in aot-runtime.c when needed.
757 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
758 * from function descriptors, we could do the same, but it would require
759 * rewriting all the ppc/aot code to handle function descriptors properly.
760 * So instead, we use the same approach as on PPC32.
761 * This is a horrible mess, but fixing it would probably lead to an even bigger
767 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
770 #ifdef MONO_ARCH_AOT_SUPPORTED
772 * arch_emit_got_offset:
774 * The memory pointed to by CODE should hold native code for computing the GOT
775 * address. Emit this code while patching it with the offset between code and
776 * the GOT. CODE_SIZE is set to the number of bytes emitted.
779 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
781 #if defined(TARGET_POWERPC64)
782 g_assert (!acfg->use_bin_writer);
783 emit_unset_mode (acfg);
785 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
786 * unsupported relocations. So we store the got address into the .Lgot_addr
787 * symbol which is in the text segment, compute its address, and load it.
789 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
790 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
791 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
792 fprintf (acfg->fp, "add 30, 30, 0\n");
793 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
794 acfg->label_generator ++;
796 #elif defined(TARGET_POWERPC)
797 g_assert (!acfg->use_bin_writer);
798 emit_unset_mode (acfg);
799 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
800 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
801 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
802 acfg->label_generator ++;
805 guint32 offset = mono_arch_get_patch_offset (code);
806 emit_bytes (acfg, code, offset);
807 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
809 *code_size = offset + 4;
814 * arch_emit_got_access:
816 * The memory pointed to by CODE should hold native code for loading a GOT
817 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
818 * CODE_SIZE is set to the number of bytes emitted.
821 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
823 /* Emit beginning of instruction */
824 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
826 /* Emit the offset */
828 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
829 *code_size = mono_arch_get_patch_offset (code) + 4;
830 #elif defined(TARGET_X86)
831 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
832 *code_size = mono_arch_get_patch_offset (code) + 4;
833 #elif defined(TARGET_ARM)
834 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
835 *code_size = mono_arch_get_patch_offset (code) + 4;
836 #elif defined(TARGET_POWERPC)
842 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
843 g_assert (code - buf == 8);
844 emit_bytes (acfg, buf, code - buf);
845 *code_size = code - buf;
848 g_assert_not_reached ();
854 #ifdef MONO_ARCH_AOT_SUPPORTED
856 * arch_emit_objc_selector_ref:
858 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
861 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
863 #if defined(TARGET_ARM)
866 int lindex = acfg->objc_selector_index_2 ++;
869 emit_bytes (acfg, code, 8);
871 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
872 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
874 emit_label (acfg, symbol1);
875 img_writer_emit_unset_mode (acfg->w);
876 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
880 g_assert_not_reached ();
886 * arch_emit_plt_entry:
888 * Emit code for the PLT entry with index INDEX.
891 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
893 #if defined(TARGET_X86)
894 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
895 #if defined(__default_codegen__)
896 /* jmp *<offset>(%ebx) */
897 emit_byte (acfg, 0xff);
898 emit_byte (acfg, 0xa3);
899 emit_int32 (acfg, offset);
900 /* Used by mono_aot_get_plt_info_offset */
901 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
902 #elif defined(__native_client_codegen__)
903 const guint8 kSizeOfNaClJmp = 11;
904 guint8 bytes[kSizeOfNaClJmp];
905 guint8 *pbytes = &bytes[0];
907 x86_jump_membase32 (pbytes, X86_EBX, offset);
908 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
909 /* four bytes of data, used by mono_arch_patch_plt_entry */
910 /* For Native Client, make this work with data embedded in push. */
911 emit_byte (acfg, 0x68); /* hide data in a push */
912 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
913 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
914 #endif /*__native_client_codegen__*/
915 #elif defined(TARGET_AMD64)
916 #if defined(__default_codegen__)
918 * We can't emit jumps because they are 32 bits only so they can't be patched.
919 * So we make indirect calls through GOT entries which are patched by the AOT
920 * loader to point to .Lpd entries.
922 /* jmpq *<offset>(%rip) */
923 emit_byte (acfg, '\xff');
924 emit_byte (acfg, '\x25');
925 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
926 /* Used by mono_aot_get_plt_info_offset */
927 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
928 acfg->stats.plt_size += 10;
929 #elif defined(__native_client_codegen__)
931 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
932 guint8 *code = buf_aligned;
934 /* mov <OFFSET>(%rip), %r11d */
935 emit_byte (acfg, '\x45');
936 emit_byte (acfg, '\x8b');
937 emit_byte (acfg, '\x1d');
938 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
940 amd64_jump_reg (code, AMD64_R11);
941 /* This should be constant for the plt patch */
942 g_assert ((size_t)(code-buf_aligned) == 10);
943 emit_bytes (acfg, buf_aligned, code - buf_aligned);
945 /* Hide data in a push imm32 so it passes validation */
946 emit_byte (acfg, 0x68); /* push */
947 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
948 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
949 #endif /*__native_client_codegen__*/
950 #elif defined(TARGET_ARM)
955 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
956 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
957 emit_bytes (acfg, buf, code - buf);
958 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
959 /* Used by mono_aot_get_plt_info_offset */
960 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
961 #elif defined(TARGET_POWERPC)
962 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
964 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
965 g_assert (!acfg->use_bin_writer);
966 emit_unset_mode (acfg);
967 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
968 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
969 fprintf (acfg->fp, "add 11, 11, 30\n");
970 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
971 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
972 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
973 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
975 fprintf (acfg->fp, "mtctr 11\n");
976 fprintf (acfg->fp, "bctr\n");
977 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
979 g_assert_not_reached ();
984 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
986 #if defined(TARGET_ARM)
988 /* LLVM calls the PLT entries using bl, so emit a stub */
989 /* FIXME: Too much overhead on every call */
990 fprintf (acfg->fp, ".thumb_func\n");
991 fprintf (acfg->fp, "bx pc\n");
992 fprintf (acfg->fp, "nop\n");
993 fprintf (acfg->fp, ".arm\n");
995 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
996 /* The caller already transitioned to thumb */
997 /* The code below should be 12 bytes long */
998 /* clang has trouble encoding these instructions, so emit the binary */
1000 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1001 /* thumb can't encode ld pc, [pc, ip] */
1002 fprintf (acfg->fp, "add ip, pc, ip\n");
1003 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1004 fprintf (acfg->fp, "bx ip\n");
1006 emit_set_thumb_mode (acfg);
1007 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1008 fprintf (acfg->fp, ".2byte 0x44fc\n");
1009 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1010 fprintf (acfg->fp, ".2byte 0x4760\n");
1011 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1012 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1013 emit_unset_mode (acfg);
1014 emit_set_arm_mode (acfg);
1016 g_assert_not_reached ();
1021 * arch_emit_specific_trampoline_pages:
1023 * Emits a page full of trampolines: each trampoline uses its own address to
1024 * lookup both the generic trampoline code and the data argument.
1025 * This page can be remapped in process multiple times so we can get an
1026 * unlimited number of trampolines.
1027 * Specifically this implementation uses the following trick: two memory pages
1028 * are allocated, with the first containing the data and the second containing the trampolines.
1029 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1030 * implementation does all the lifting.
1031 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1032 * on the arm 32 bit system.
1035 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1037 #if defined(TARGET_ARM)
1040 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1042 #define COMMON_TRAMP_SIZE 16
1043 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1044 int imm8, rot_amount;
1047 if (!acfg->aot_opts.use_trampolines_page)
1050 acfg->tramp_page_size = mono_pagesize ();
1052 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1053 emit_alignment (acfg, mono_pagesize ());
1054 emit_global (acfg, symbol, TRUE);
1055 emit_label (acfg, symbol);
1057 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1059 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1060 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1061 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1062 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1064 g_assert (code - buf == COMMON_TRAMP_SIZE);
1067 emit_bytes (acfg, buf, code - buf);
1069 for (i = 0; i < count; ++i) {
1071 ARM_PUSH (code, 0x5fff);
1073 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1074 g_assert (code - buf == 8);
1075 emit_bytes (acfg, buf, code - buf);
1078 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1079 * the instruction pointer address, so the generic trampoline at the start of the page
1080 * subtracts 4096 to get to the data page and loads the values
1081 * We again fit the generic trampiline in 16 bytes.
1083 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1084 emit_global (acfg, symbol, TRUE);
1085 emit_label (acfg, symbol);
1087 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1088 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1089 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1090 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1092 g_assert (code - buf == COMMON_TRAMP_SIZE);
1095 emit_bytes (acfg, buf, code - buf);
1097 for (i = 0; i < count; ++i) {
1099 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1101 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1102 g_assert (code - buf == 8);
1103 emit_bytes (acfg, buf, code - buf);
1107 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1109 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1110 emit_global (acfg, symbol, TRUE);
1111 emit_label (acfg, symbol);
1113 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1114 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1115 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1116 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1117 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1118 g_assert (code - buf == COMMON_TRAMP_SIZE);
1120 emit_bytes (acfg, buf, code - buf);
1122 for (i = 0; i < count; ++i) {
1124 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1126 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1127 g_assert (code - buf == 8);
1128 emit_bytes (acfg, buf, code - buf);
1131 /* now the imt trampolines: each specific trampolines puts in the ip register
1132 * the instruction pointer address, so the generic trampoline at the start of the page
1133 * subtracts 4096 to get to the data page and loads the values
1134 * We again fit the generic trampiline in 16 bytes.
1136 #define IMT_TRAMP_SIZE 72
1137 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1138 emit_global (acfg, symbol, TRUE);
1139 emit_label (acfg, symbol);
1141 /* Need at least two free registers, plus a slot for storing the pc */
1142 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1144 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1145 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1146 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1148 /* The IMT method is in v5, r0 has the imt array address */
1151 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1152 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1153 imt_found_check = code;
1154 ARM_B_COND (code, ARMCOND_EQ, 0);
1156 /* End-of-loop check */
1157 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1158 loop_end_check = code;
1159 ARM_B_COND (code, ARMCOND_EQ, 0);
1162 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1163 loop_branch_back = code;
1165 arm_patch (loop_branch_back, loop_start);
1168 arm_patch (imt_found_check, code);
1169 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1170 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1171 /* Save it to the third stack slot */
1172 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1173 /* Restore the registers and branch */
1174 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1177 arm_patch (loop_end_check, code);
1178 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1179 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1180 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1184 g_assert (code - buf == IMT_TRAMP_SIZE);
1185 emit_bytes (acfg, buf, code - buf);
1187 for (i = 0; i < count; ++i) {
1189 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1191 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1192 g_assert (code - buf == 8);
1193 emit_bytes (acfg, buf, code - buf);
1199 * arch_emit_specific_trampoline:
1201 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1202 * two GOT slots which contain the generic trampoline address and the trampoline
1203 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1206 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1209 * The trampolines created here are variations of the specific
1210 * trampolines created in mono_arch_create_specific_trampoline (). The
1212 * - the generic trampoline address is taken from a got slot.
1213 * - the offset of the got slot where the trampoline argument is stored
1214 * is embedded in the instruction stream, and the generic trampoline
1215 * can load the argument by loading the offset, adding it to the
1216 * address of the trampoline to get the address of the got slot, and
1217 * loading the argument from there.
1218 * - all the trampolines should be of the same length.
1220 #if defined(TARGET_AMD64)
1221 #if defined(__default_codegen__)
1222 /* This should be exactly 16 bytes long */
1224 /* call *<offset>(%rip) */
1225 emit_byte (acfg, '\x41');
1226 emit_byte (acfg, '\xff');
1227 emit_byte (acfg, '\x15');
1228 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1229 /* This should be relative to the start of the trampoline */
1230 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1231 emit_zero_bytes (acfg, 5);
1232 #elif defined(__native_client_codegen__)
1234 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1235 guint8 *code = buf_aligned;
1240 /* Emit this call in 'code' so we can find out how long it is. */
1241 amd64_call_reg (code, AMD64_R11);
1242 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1243 call_len = code - call_start;
1245 /* The tramp_size is twice the NaCl alignment because it starts with */
1246 /* a call which needs to be aligned to the end of the boundary. */
1247 *tramp_size = kNaClAlignment*2;
1249 /* Emit nops to align call site below which is 7 bytes plus */
1250 /* the length of the call sequence emitted above. */
1251 /* Note: this requires the specific trampoline starts on a */
1252 /* kNaclAlignedment aligned address, which it does because */
1253 /* it's its own function that is aligned. */
1254 guint8 nop_buf[256];
1255 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1256 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1257 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1259 /* The trampoline is stored at the offset'th pointer, the -4 is */
1260 /* present because RIP relative addressing starts at the end of */
1261 /* the current instruction, while the label "." is relative to */
1262 /* the beginning of the current asm location, which in this case */
1263 /* is not the mov instruction, but the offset itself, due to the */
1264 /* way the bytes and ints are emitted here. */
1265 got_offset = (offset * sizeof(gpointer)) - 4;
1267 /* mov <OFFSET>(%rip), %r11d */
1268 emit_byte (acfg, '\x45');
1269 emit_byte (acfg, '\x8b');
1270 emit_byte (acfg, '\x1d');
1271 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1274 emit_bytes (acfg, call_start, call_len);
1276 /* The arg is stored at the offset+1 pointer, relative to beginning */
1277 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1278 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1280 /* We can't emit this data directly, hide in a "push imm32" */
1281 emit_byte (acfg, '\x68'); /* push */
1282 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1283 emit_alignment (acfg, kNaClAlignment);
1284 #endif /*__native_client_codegen__*/
1285 #elif defined(TARGET_ARM)
1289 /* This should be exactly 20 bytes long */
1292 ARM_PUSH (code, 0x5fff);
1293 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1294 /* Load the value from the GOT */
1295 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1297 ARM_BLX_REG (code, ARMREG_R1);
1299 g_assert (code - buf == 16);
1302 emit_bytes (acfg, buf, code - buf);
1304 * Only one offset is needed, since the second one would be equal to the
1307 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1308 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1309 #elif defined(TARGET_POWERPC)
1316 g_assert (!acfg->use_bin_writer);
1319 * PPC has no ip relative addressing, so we need to compute the address
1320 * of the mscorlib got. That is slow and complex, so instead, we store it
1321 * in the second got slot of every aot image. The caller already computed
1322 * the address of its got and placed it into r30.
1324 emit_unset_mode (acfg);
1325 /* Load mscorlib got address */
1326 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1327 /* Load generic trampoline address */
1328 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1329 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1330 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1331 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1332 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1334 fprintf (acfg->fp, "mtctr 11\n");
1335 /* Load trampoline argument */
1336 /* On ppc, we pass it normally to the generic trampoline */
1337 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1338 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1339 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1340 /* Branch to generic trampoline */
1341 fprintf (acfg->fp, "bctr\n");
1343 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1344 *tramp_size = 10 * 4;
1346 *tramp_size = 9 * 4;
1348 #elif defined(TARGET_X86)
1352 /* Similar to the PPC code above */
1354 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1356 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1357 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1358 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1362 /* Load mscorlib got address */
1363 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1364 /* Push trampoline argument */
1365 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1366 /* Load generic trampoline address */
1367 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1368 /* Branch to generic trampoline */
1369 x86_jump_reg (code, X86_ECX);
1371 #ifdef __native_client_codegen__
1373 /* emit nops to next 32 byte alignment */
1374 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1375 while (code < (buf + a)) x86_nop(code);
1378 emit_bytes (acfg, buf, code - buf);
1380 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1381 g_assert (code - buf == *tramp_size);
1383 g_assert_not_reached ();
1388 * arch_emit_unbox_trampoline:
1390 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1391 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1394 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1396 #if defined(TARGET_AMD64)
1401 this_reg = mono_arch_get_this_arg_reg (NULL);
1403 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1405 emit_bytes (acfg, buf, code - buf);
1407 emit_byte (acfg, '\xe9');
1408 emit_symbol_diff (acfg, call_target, ".", -4);
1409 #elif defined(TARGET_X86)
1416 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1418 emit_bytes (acfg, buf, code - buf);
1421 emit_byte (acfg, '\xe9');
1422 emit_symbol_diff (acfg, call_target, ".", -4);
1423 #elif defined(TARGET_ARM)
1427 if (acfg->thumb_mixed && cfg->compile_llvm) {
1428 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1429 fprintf (acfg->fp, "b %s\n", call_target);
1430 fprintf (acfg->fp, ".arm\n");
1431 fprintf (acfg->fp, ".align 2\n");
1437 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1439 emit_bytes (acfg, buf, code - buf);
1440 /* jump to method */
1441 if (acfg->use_bin_writer) {
1448 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1449 emit_bytes (acfg, buf, 4);
1451 if (acfg->thumb_mixed && cfg->compile_llvm)
1452 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1454 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1456 #elif defined(TARGET_POWERPC)
1459 g_assert (!acfg->use_bin_writer);
1461 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1462 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1464 g_assert_not_reached ();
1469 * arch_emit_static_rgctx_trampoline:
1471 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1472 * two GOT slots which contain the rgctx argument, and the method to jump to.
1473 * TRAMP_SIZE is set to the size of the emitted trampoline.
1474 * These kinds of trampolines cannot be enumerated statically, since there could
1475 * be one trampoline per method instantiation, so we emit the same code for all
1476 * trampolines, and parameterize them using two GOT slots.
1479 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1481 #if defined(TARGET_AMD64)
1482 #if defined(__default_codegen__)
1483 /* This should be exactly 13 bytes long */
1486 /* mov <OFFSET>(%rip), %r10 */
1487 emit_byte (acfg, '\x4d');
1488 emit_byte (acfg, '\x8b');
1489 emit_byte (acfg, '\x15');
1490 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1492 /* jmp *<offset>(%rip) */
1493 emit_byte (acfg, '\xff');
1494 emit_byte (acfg, '\x25');
1495 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1496 #elif defined(__native_client_codegen__)
1498 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1499 guint8 *code = buf_aligned;
1501 /* mov <OFFSET>(%rip), %r10d */
1502 emit_byte (acfg, '\x45');
1503 emit_byte (acfg, '\x8b');
1504 emit_byte (acfg, '\x15');
1505 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1507 /* mov <OFFSET>(%rip), %r11d */
1508 emit_byte (acfg, '\x45');
1509 emit_byte (acfg, '\x8b');
1510 emit_byte (acfg, '\x1d');
1511 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1514 amd64_jump_reg (code, AMD64_R11);
1515 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1517 emit_alignment (acfg, kNaClAlignment);
1518 *tramp_size = kNaClAlignment;
1519 #endif /*__native_client_codegen__*/
1521 #elif defined(TARGET_ARM)
1525 /* This should be exactly 24 bytes long */
1528 /* Load rgctx value */
1529 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1530 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1531 /* Load branch addr + branch */
1532 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1533 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1535 g_assert (code - buf == 16);
1538 emit_bytes (acfg, buf, code - buf);
1539 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1540 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1541 #elif defined(TARGET_POWERPC)
1548 g_assert (!acfg->use_bin_writer);
1551 * PPC has no ip relative addressing, so we need to compute the address
1552 * of the mscorlib got. That is slow and complex, so instead, we store it
1553 * in the second got slot of every aot image. The caller already computed
1554 * the address of its got and placed it into r30.
1556 emit_unset_mode (acfg);
1557 /* Load mscorlib got address */
1558 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1560 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1561 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1562 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1563 /* Load target address */
1564 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1565 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1566 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1567 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1568 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1569 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1571 fprintf (acfg->fp, "mtctr 11\n");
1572 /* Branch to the target address */
1573 fprintf (acfg->fp, "bctr\n");
1575 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1576 *tramp_size = 11 * 4;
1578 *tramp_size = 9 * 4;
1581 #elif defined(TARGET_X86)
1585 /* Similar to the PPC code above */
1587 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1590 /* Load mscorlib got address */
1591 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1593 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1594 /* Branch to the target address */
1595 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1597 #ifdef __native_client_codegen__
1599 /* emit nops to next 32 byte alignment */
1600 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1601 while (code < (buf + a)) x86_nop(code);
1605 emit_bytes (acfg, buf, code - buf);
1607 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1608 g_assert (code - buf == *tramp_size);
1610 g_assert_not_reached ();
1615 * arch_emit_imt_thunk:
1617 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1618 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1619 * key is the IMT key, and ptr holds the address of a memory location holding
1620 * the address to branch to if the IMT arg matches the key. The array is
1621 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1623 * TRAMP_SIZE is set to the size of the emitted trampoline.
1626 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1628 #if defined(TARGET_AMD64)
1630 #if defined(__native_client_codegen__)
1633 guint8 *labels [16];
1635 guint8 *mov_buf_ptr = mov_buf;
1637 const int kSizeOfMove = 7;
1638 #if defined(__default_codegen__)
1639 code = buf = g_malloc (256);
1640 #elif defined(__native_client_codegen__)
1641 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1642 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1643 /* The RIP relative move below is emitted first */
1648 /* FIXME: Optimize this, i.e. use binary search etc. */
1649 /* Maybe move the body into a separate function (slower, but much smaller) */
1651 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1654 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1656 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1659 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1661 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1664 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1665 amd64_jump_code (code, labels [0]);
1668 mono_amd64_patch (labels [2], code);
1669 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1670 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1673 mono_amd64_patch (labels [1], code);
1674 /* Load fail tramp */
1675 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1676 /* Check if there is a fail tramp */
1677 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1679 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1680 /* Jump to fail tramp */
1681 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1684 mono_amd64_patch (labels [3], code);
1685 x86_breakpoint (code);
1687 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1688 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1689 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1690 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1691 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1692 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1694 emit_bytes (acfg, buf, code - buf);
1696 *tramp_size = code - buf + kSizeOfMove;
1697 #if defined(__native_client_codegen__)
1698 /* The tramp will be padded to the next kNaClAlignment bundle. */
1699 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1702 #if defined(__default_codegen__)
1704 #elif defined(__native_client_codegen__)
1708 #elif defined(TARGET_X86)
1710 #ifdef __native_client_codegen__
1713 guint8 *labels [16];
1715 #if defined(__default_codegen__)
1716 code = buf = g_malloc (256);
1717 #elif defined(__native_client_codegen__)
1718 buf_alloc = g_malloc (256 + kNaClAlignment);
1719 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1722 /* Allocate a temporary stack slot */
1723 x86_push_reg (code, X86_EAX);
1725 x86_push_reg (code, X86_EAX);
1727 /* Load mscorlib got address */
1728 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1730 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1733 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1735 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1738 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1740 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1743 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1744 x86_jump_code (code, labels [0]);
1747 mono_x86_patch (labels [2], code);
1748 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1749 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1750 /* Save the target address to the temporary stack location */
1751 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1753 x86_pop_reg (code, X86_EAX);
1754 /* Jump to the target address */
1758 mono_x86_patch (labels [1], code);
1759 /* Load fail tramp */
1760 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1761 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1763 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1764 /* Jump to fail tramp */
1765 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1766 x86_pop_reg (code, X86_EAX);
1770 mono_x86_patch (labels [3], code);
1771 x86_breakpoint (code);
1773 #ifdef __native_client_codegen__
1775 /* emit nops to next 32 byte alignment */
1776 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1777 while (code < (buf + a)) x86_nop(code);
1780 emit_bytes (acfg, buf, code - buf);
1782 *tramp_size = code - buf;
1784 #if defined(__default_codegen__)
1786 #elif defined(__native_client_codegen__)
1790 #elif defined(TARGET_ARM)
1792 guint8 *code, *code2, *labels [16];
1796 /* The IMT method is in v5 */
1798 /* Need at least two free registers, plus a slot for storing the pc */
1799 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1801 /* Load the parameter from the GOT */
1802 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1803 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1806 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1807 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1809 ARM_B_COND (code, ARMCOND_EQ, 0);
1811 /* End-of-loop check */
1812 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1814 ARM_B_COND (code, ARMCOND_EQ, 0);
1817 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1820 arm_patch (labels [4], labels [1]);
1823 arm_patch (labels [2], code);
1824 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1825 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1826 /* Save it to the third stack slot */
1827 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1828 /* Restore the registers and branch */
1829 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1832 arm_patch (labels [3], code);
1833 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1834 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1835 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1839 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1841 emit_bytes (acfg, buf, code - buf);
1842 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1844 *tramp_size = code - buf + 4;
1845 #elif defined(TARGET_POWERPC)
1847 guint8 *code, *labels [16];
1851 /* Load the mscorlib got address */
1852 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1853 /* Load the parameter from the GOT */
1854 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1855 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1857 /* Load and check key */
1859 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1860 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1862 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1864 /* End-of-loop check */
1865 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1867 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1870 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1873 mono_ppc_patch (labels [4], labels [1]);
1876 mono_ppc_patch (labels [2], code);
1877 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1878 /* r11 now contains the value of the vtable slot */
1879 /* this is not a function descriptor on ppc64 */
1880 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1881 ppc_mtctr (code, ppc_r11);
1882 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1885 mono_ppc_patch (labels [3], code);
1889 *tramp_size = code - buf;
1891 emit_bytes (acfg, buf, code - buf);
1893 g_assert_not_reached ();
1898 * arch_emit_gsharedvt_arg_trampoline:
1900 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1901 * two GOT slots which contain the argument, and the code to jump to.
1902 * TRAMP_SIZE is set to the size of the emitted trampoline.
1903 * These kinds of trampolines cannot be enumerated statically, since there could
1904 * be one trampoline per method instantiation, so we emit the same code for all
1905 * trampolines, and parameterize them using two GOT slots.
1908 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1910 #if defined(TARGET_X86)
1914 /* Similar to the PPC code above */
1916 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1919 /* Load mscorlib got address */
1920 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1922 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1923 /* Branch to the target address */
1924 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1926 #ifdef __native_client_codegen__
1928 /* emit nops to next 32 byte alignment */
1929 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1930 while (code < (buf + a)) x86_nop(code);
1934 emit_bytes (acfg, buf, code - buf);
1936 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1937 g_assert (code - buf == *tramp_size);
1938 #elif defined(TARGET_ARM)
1942 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1943 /* Similar to arch_emit_specific_trampoline () */
1946 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1947 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1948 /* Load the arg value from the GOT */
1949 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1950 /* Load the addr from the GOT */
1951 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1953 ARM_BX (code, ARMREG_R1);
1955 g_assert (code - buf == 20);
1958 emit_bytes (acfg, buf, code - buf);
1959 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1961 g_assert_not_reached ();
1966 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1968 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1969 /* Based on code generated by gcc */
1970 emit_unset_mode (acfg);
1973 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1974 ".section .ctors,\"aw\",@progbits\n"
1978 ".section .opd,\"aw\"\n"
1981 ".long .%s,.TOC.@tocbase32\n"
1984 ".type .%s,@function\n"
1986 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1988 ".section .ctors,\"aw\",@progbits\n"
1992 ".section .opd,\"aw\"\n"
1995 ".long .%1$s,.TOC.@tocbase32\n"
1996 ".size %1$s,.-%1$s\n"
1998 ".type .%1$s,@function\n"
2000 ".%1$s:\n", symbol);
2011 "lis 3, .Lglobals@h\n"
2012 "ori 3, 3, .Lglobals@l\n"
2013 "bl .mono_aot_register_module\n"
2021 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2023 ".size .%s,.-.%s\n", symbol, symbol);
2026 ".size .%1$s,.-.%1$s\n", symbol);
2032 /* END OF ARCH SPECIFIC CODE */
2035 mono_get_field_token (MonoClassField *field)
2037 MonoClass *klass = field->parent;
2040 for (i = 0; i < klass->field.count; ++i) {
2041 if (field == &klass->fields [i])
2042 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2045 g_assert_not_reached ();
2050 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2054 //printf ("ENCODE: %d 0x%x.\n", value, value);
2057 * Same encoding as the one used in the metadata, extended to handle values
2058 * greater than 0x1fffffff.
2060 if ((value >= 0) && (value <= 127))
2062 else if ((value >= 0) && (value <= 16383)) {
2063 p [0] = 0x80 | (value >> 8);
2064 p [1] = value & 0xff;
2066 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2067 p [0] = (value >> 24) | 0xc0;
2068 p [1] = (value >> 16) & 0xff;
2069 p [2] = (value >> 8) & 0xff;
2070 p [3] = value & 0xff;
2075 p [1] = (value >> 24) & 0xff;
2076 p [2] = (value >> 16) & 0xff;
2077 p [3] = (value >> 8) & 0xff;
2078 p [4] = value & 0xff;
2086 stream_init (MonoDynamicStream *sh)
2089 sh->alloc_size = 4096;
2090 sh->data = g_malloc (4096);
2092 /* So offsets are > 0 */
2098 make_room_in_stream (MonoDynamicStream *stream, int size)
2100 if (size <= stream->alloc_size)
2103 while (stream->alloc_size <= size) {
2104 if (stream->alloc_size < 4096)
2105 stream->alloc_size = 4096;
2107 stream->alloc_size *= 2;
2110 stream->data = g_realloc (stream->data, stream->alloc_size);
2114 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2118 make_room_in_stream (stream, stream->index + len);
2119 memcpy (stream->data + stream->index, data, len);
2120 idx = stream->index;
2121 stream->index += len;
2128 * Add data to the binary blob inside the aot image. Returns the offset inside the
2129 * blob where the data was stored.
2132 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2134 if (acfg->blob.alloc_size == 0)
2135 stream_init (&acfg->blob);
2137 return add_stream_data (&acfg->blob, (char*)data, data_len);
2141 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2146 if (acfg->blob.alloc_size == 0)
2147 stream_init (&acfg->blob);
2149 count = acfg->blob.index % align;
2151 /* we assume the stream data will be aligned */
2153 add_stream_data (&acfg->blob, buf, 4 - count);
2155 return add_stream_data (&acfg->blob, (char*)data, data_len);
2159 * emit_offset_table:
2161 * Emit a table of increasing offsets in a compact form using differential encoding.
2162 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2163 * group size, the more compact the table becomes, but the slower it becomes to compute
2164 * a given entry. Returns the size of the table.
2167 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2169 gint32 current_offset;
2170 int i, buf_size, ngroups, index_entry_size;
2172 guint32 *index_offsets;
2174 ngroups = (noffsets + (group_size - 1)) / group_size;
2176 index_offsets = g_new0 (guint32, ngroups);
2178 buf_size = noffsets * 4;
2179 p = buf = g_malloc0 (buf_size);
2182 for (i = 0; i < noffsets; ++i) {
2183 //printf ("D: %d -> %d\n", i, offsets [i]);
2184 if ((i % group_size) == 0) {
2185 index_offsets [i / group_size] = p - buf;
2186 /* Emit the full value for these entries */
2187 encode_value (offsets [i], p, &p);
2189 /* The offsets are allowed to be non-increasing */
2190 //g_assert (offsets [i] >= current_offset);
2191 encode_value (offsets [i] - current_offset, p, &p);
2193 current_offset = offsets [i];
2196 if (ngroups && index_offsets [ngroups - 1] < 65000)
2197 index_entry_size = 2;
2199 index_entry_size = 4;
2201 /* Emit the header */
2202 emit_int32 (acfg, noffsets);
2203 emit_int32 (acfg, group_size);
2204 emit_int32 (acfg, ngroups);
2205 emit_int32 (acfg, index_entry_size);
2207 /* Emit the index */
2208 for (i = 0; i < ngroups; ++i) {
2209 if (index_entry_size == 2)
2210 emit_int16 (acfg, index_offsets [i]);
2212 emit_int32 (acfg, index_offsets [i]);
2216 emit_bytes (acfg, buf, p - buf);
2218 return (int)(p - buf) + (ngroups * 4);
2222 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2226 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2230 index = g_hash_table_size (cfg->image_hash);
2231 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2232 g_ptr_array_add (cfg->image_table, image);
2238 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2241 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2243 /* FIXME: Search referenced images as well */
2244 if (!acfg->typespec_classes) {
2245 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2246 for (i = 0; i < len; ++i) {
2247 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2250 for (i = 0; i < len; ++i) {
2251 if (acfg->typespec_classes [i] == klass)
2256 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2262 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2265 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2268 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2271 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2274 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2279 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2283 if (klass->generic_class) {
2285 g_assert (klass->type_token);
2287 /* Find a typespec for a class if possible */
2288 token = find_typespec_for_class (acfg, klass);
2290 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2291 encode_value (token, p, &p);
2293 MonoClass *gclass = klass->generic_class->container_class;
2294 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2295 static int count = 0;
2298 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2299 encode_klass_ref (acfg, gclass, p, &p);
2300 encode_ginst (acfg, inst, p, &p);
2304 } else if (klass->type_token) {
2305 int iindex = get_image_index (acfg, klass->image);
2307 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2309 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2310 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2312 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2313 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2314 encode_value (get_image_index (acfg, klass->image), p, &p);
2316 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2317 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2318 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2320 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2321 encode_value (klass->byval_arg.type, p, &p);
2322 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2324 encode_value (container ? 1 : 0, p, &p);
2326 encode_value (container->is_method, p, &p);
2327 g_assert (par->serial == 0);
2328 if (container->is_method)
2329 encode_method_ref (acfg, container->owner.method, p, &p);
2331 encode_klass_ref (acfg, container->owner.klass, p, &p);
2333 encode_value (par->serial, p, &p);
2335 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2336 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2337 encode_type (acfg, &klass->byval_arg, p, &p);
2340 g_assert (klass->rank > 0);
2341 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2342 encode_value (klass->rank, p, &p);
2343 encode_klass_ref (acfg, klass->element_class, p, &p);
2351 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2352 * standard metadata encoding.
2355 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2357 gboolean shared = FALSE;
2360 * The encoding of generic instances is large so emit them only once.
2362 if (klass->generic_class) {
2364 g_assert (klass->type_token);
2366 /* Find a typespec for a class if possible */
2367 token = find_typespec_for_class (acfg, klass);
2370 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2375 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2379 buf2 = g_malloc (1024);
2382 encode_klass_ref_inner (acfg, klass, p, &p);
2383 g_assert (p - buf2 < 1024);
2385 offset = add_to_blob (acfg, buf2, p - buf2);
2388 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2394 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2395 encode_value (offset, p, &p);
2400 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2404 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2406 guint32 token = mono_get_field_token (field);
2409 encode_klass_ref (cfg, field->parent, p, &p);
2410 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2411 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2416 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2421 encode_value (inst->type_argc, p, &p);
2422 for (i = 0; i < inst->type_argc; ++i)
2423 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2428 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2431 MonoGenericInst *inst;
2433 inst = context->class_inst;
2435 g_assert (inst->type_argc);
2436 encode_ginst (acfg, inst, p, &p);
2438 encode_value (0, p, &p);
2440 inst = context->method_inst;
2442 g_assert (inst->type_argc);
2443 encode_ginst (acfg, inst, p, &p);
2445 encode_value (0, p, &p);
2451 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2455 g_assert (t->num_mods == 0);
2456 /* t->attrs can be ignored */
2457 //g_assert (t->attrs == 0);
2460 *p = MONO_TYPE_PINNED;
2464 *p = MONO_TYPE_BYREF;
2472 case MONO_TYPE_VOID:
2473 case MONO_TYPE_BOOLEAN:
2474 case MONO_TYPE_CHAR:
2487 case MONO_TYPE_STRING:
2488 case MONO_TYPE_OBJECT:
2489 case MONO_TYPE_TYPEDBYREF:
2491 case MONO_TYPE_VALUETYPE:
2492 case MONO_TYPE_CLASS:
2493 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2495 case MONO_TYPE_SZARRAY:
2496 encode_klass_ref (acfg, t->data.klass, p, &p);
2499 encode_type (acfg, t->data.type, p, &p);
2501 case MONO_TYPE_GENERICINST: {
2502 MonoClass *gclass = t->data.generic_class->container_class;
2503 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2505 encode_klass_ref (acfg, gclass, p, &p);
2506 encode_ginst (acfg, inst, p, &p);
2509 case MONO_TYPE_ARRAY: {
2510 MonoArrayType *array = t->data.array;
2513 encode_klass_ref (acfg, array->eklass, p, &p);
2514 encode_value (array->rank, p, &p);
2515 encode_value (array->numsizes, p, &p);
2516 for (i = 0; i < array->numsizes; ++i)
2517 encode_value (array->sizes [i], p, &p);
2518 encode_value (array->numlobounds, p, &p);
2519 for (i = 0; i < array->numlobounds; ++i)
2520 encode_value (array->lobounds [i], p, &p);
2524 case MONO_TYPE_MVAR:
2525 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2528 g_assert_not_reached ();
2535 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2541 /* Similar to the metadata encoding */
2542 if (sig->generic_param_count)
2546 if (sig->explicit_this)
2548 flags |= (sig->call_convention & 0x0F);
2552 if (sig->generic_param_count)
2553 encode_value (sig->generic_param_count, p, &p);
2554 encode_value (sig->param_count, p, &p);
2556 encode_type (acfg, sig->ret, p, &p);
2557 for (i = 0; i < sig->param_count; ++i) {
2558 if (sig->sentinelpos == i) {
2559 *p = MONO_TYPE_SENTINEL;
2562 encode_type (acfg, sig->params [i], p, &p);
2568 #define MAX_IMAGE_INDEX 250
2571 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2573 guint32 image_index = get_image_index (acfg, method->klass->image);
2574 guint32 token = method->token;
2575 MonoJumpInfoToken *ji;
2579 * The encoding for most methods is as follows:
2580 * - image index encoded as a leb128
2581 * - token index encoded as a leb128
2582 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2583 * types of method encodings.
2586 /* Mark methods which can't use aot trampolines because they need the further
2587 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2589 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2590 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2591 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2593 if (method->wrapper_type) {
2594 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2596 encode_value (method->wrapper_type, p, &p);
2598 switch (method->wrapper_type) {
2599 case MONO_WRAPPER_REMOTING_INVOKE:
2600 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2601 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2604 m = mono_marshal_method_from_wrapper (method);
2606 encode_method_ref (acfg, m, p, &p);
2609 case MONO_WRAPPER_PROXY_ISINST:
2610 case MONO_WRAPPER_LDFLD:
2611 case MONO_WRAPPER_LDFLDA:
2612 case MONO_WRAPPER_STFLD:
2613 case MONO_WRAPPER_ISINST: {
2614 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2615 encode_klass_ref (acfg, proxy_class, p, &p);
2618 case MONO_WRAPPER_LDFLD_REMOTE:
2619 case MONO_WRAPPER_STFLD_REMOTE:
2621 case MONO_WRAPPER_ALLOC: {
2622 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2624 /* The GC name is saved once in MonoAotFileInfo */
2625 g_assert (info->alloc_type != -1);
2626 encode_value (info->alloc_type, p, &p);
2629 case MONO_WRAPPER_WRITE_BARRIER:
2631 case MONO_WRAPPER_STELEMREF: {
2632 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2635 encode_value (info->subtype, p, &p);
2636 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2637 encode_value (info->d.virtual_stelemref.kind, p, &p);
2640 case MONO_WRAPPER_UNKNOWN: {
2641 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2644 encode_value (info->subtype, p, &p);
2645 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2646 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2647 encode_klass_ref (acfg, method->klass, p, &p);
2648 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2649 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2650 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2651 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2654 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2655 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2658 encode_value (info->subtype, p, &p);
2659 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2660 strcpy ((char*)p, method->name);
2661 p += strlen (method->name) + 1;
2662 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2663 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2665 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2666 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2670 case MONO_WRAPPER_SYNCHRONIZED: {
2673 m = mono_marshal_method_from_wrapper (method);
2675 g_assert (m != method);
2676 encode_method_ref (acfg, m, p, &p);
2679 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2680 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2683 encode_value (info->subtype, p, &p);
2685 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2686 encode_value (info->d.element_addr.rank, p, &p);
2687 encode_value (info->d.element_addr.elem_size, p, &p);
2688 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2689 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2691 g_assert_not_reached ();
2695 case MONO_WRAPPER_CASTCLASS: {
2696 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2699 encode_value (info->subtype, p, &p);
2702 case MONO_WRAPPER_RUNTIME_INVOKE: {
2703 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2706 encode_value (info->subtype, p, &p);
2707 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2708 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2709 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2710 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2713 case MONO_WRAPPER_DELEGATE_INVOKE:
2714 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2715 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2716 if (method->is_inflated) {
2717 /* These wrappers are identified by their class */
2718 encode_value (1, p, &p);
2719 encode_klass_ref (acfg, method->klass, p, &p);
2721 MonoMethodSignature *sig = mono_method_signature (method);
2722 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2724 encode_value (0, p, &p);
2725 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2726 encode_value (info ? info->subtype : 0, p, &p);
2727 encode_signature (acfg, sig, p, &p);
2731 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2732 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2735 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2736 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2740 g_assert_not_reached ();
2742 } else if (mono_method_signature (method)->is_inflated) {
2744 * This is a generic method, find the original token which referenced it and
2746 * Obtain the token from information recorded by the JIT.
2748 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2750 image_index = get_image_index (acfg, ji->image);
2751 g_assert (image_index < MAX_IMAGE_INDEX);
2754 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2755 encode_value (image_index, p, &p);
2756 encode_value (token, p, &p);
2758 MonoMethod *declaring;
2759 MonoGenericContext *context = mono_method_get_context (method);
2761 g_assert (method->is_inflated);
2762 declaring = ((MonoMethodInflated*)method)->declaring;
2765 * This might be a non-generic method of a generic instance, which
2766 * doesn't have a token since the reference is generated by the JIT
2767 * like Nullable:Box/Unbox, or by generic sharing.
2769 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2770 /* Encode the klass */
2771 encode_klass_ref (acfg, method->klass, p, &p);
2772 /* Encode the method */
2773 image_index = get_image_index (acfg, method->klass->image);
2774 g_assert (image_index < MAX_IMAGE_INDEX);
2775 g_assert (declaring->token);
2776 token = declaring->token;
2777 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2778 encode_value (image_index, p, &p);
2779 encode_value (token, p, &p);
2780 encode_generic_context (acfg, context, p, &p);
2782 } else if (token == 0) {
2783 /* This might be a method of a constructed type like int[,].Set */
2784 /* Obtain the token from information recorded by the JIT */
2785 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2787 image_index = get_image_index (acfg, ji->image);
2788 g_assert (image_index < MAX_IMAGE_INDEX);
2791 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2792 encode_value (image_index, p, &p);
2793 encode_value (token, p, &p);
2796 g_assert (method->klass->rank);
2798 /* Encode directly */
2799 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2800 encode_klass_ref (acfg, method->klass, p, &p);
2801 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2802 encode_value (0, p, &p);
2803 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2804 encode_value (1, p, &p);
2805 else if (!strcmp (method->name, "Get"))
2806 encode_value (2, p, &p);
2807 else if (!strcmp (method->name, "Address"))
2808 encode_value (3, p, &p);
2809 else if (!strcmp (method->name, "Set"))
2810 encode_value (4, p, &p);
2812 g_assert_not_reached ();
2815 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2817 if (image_index >= MONO_AOT_METHODREF_MIN) {
2818 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2819 encode_value (image_index, p, &p);
2820 encode_value (mono_metadata_token_index (token), p, &p);
2822 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2829 compare_patches (gconstpointer a, gconstpointer b)
2833 i = (*(MonoJumpInfo**)a)->ip.i;
2834 j = (*(MonoJumpInfo**)b)->ip.i;
2845 static G_GNUC_UNUSED char*
2846 patch_to_string (MonoJumpInfo *patch_info)
2850 str = g_string_new ("");
2852 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2854 switch (patch_info->type) {
2855 case MONO_PATCH_INFO_VTABLE:
2856 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2861 g_string_append_printf (str, ")");
2862 return g_string_free (str, FALSE);
2868 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2871 static inline gboolean
2872 is_plt_patch (MonoJumpInfo *patch_info)
2874 switch (patch_info->type) {
2875 case MONO_PATCH_INFO_METHOD:
2876 case MONO_PATCH_INFO_INTERNAL_METHOD:
2877 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2878 case MONO_PATCH_INFO_ICALL_ADDR:
2879 case MONO_PATCH_INFO_CLASS_INIT:
2880 case MONO_PATCH_INFO_RGCTX_FETCH:
2881 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2882 case MONO_PATCH_INFO_MONITOR_ENTER:
2883 case MONO_PATCH_INFO_MONITOR_EXIT:
2884 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2894 * Return the symbol identifying the plt entry PLT_OFFSET.
2897 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2901 * The Apple linker reorganizes object files, so it doesn't like branches to local
2902 * labels, since those have no relocations.
2904 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2906 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2913 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2915 static MonoPltEntry*
2916 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2920 if (!is_plt_patch (patch_info))
2923 if (!acfg->patch_to_plt_entry [patch_info->type])
2924 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
2925 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
2927 // FIXME: This breaks the calculation of final_got_size
2928 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2930 * Allocate a separate PLT slot for each such patch, since some plt
2931 * entries will refer to the method itself, and some will refer to the
2938 MonoJumpInfo *new_ji;
2940 g_assert (!acfg->final_got_size);
2942 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2944 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2945 res->plt_offset = acfg->plt_offset;
2947 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2948 if (acfg->aot_opts.write_symbols)
2949 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2951 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2953 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2955 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
2957 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2959 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2960 //mono_print_ji (patch_info); printf ("\n");
2961 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2963 acfg->plt_offset ++;
2972 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2973 * JI could be found if it exists, otherwise allocates a new one.
2976 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2980 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2982 return got_offset - 1;
2984 got_offset = acfg->got_offset;
2985 acfg->got_offset ++;
2987 if (acfg->final_got_size)
2988 g_assert (got_offset < acfg->final_got_size);
2990 acfg->stats.got_slots ++;
2991 acfg->stats.got_slot_types [ji->type] ++;
2993 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2994 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2995 g_ptr_array_add (acfg->got_patches, ji);
3000 /* Add a method to the list of methods which need to be emitted */
3002 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3005 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3006 g_ptr_array_add (acfg->methods, method);
3007 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3008 acfg->nmethods = acfg->methods->len + 1;
3011 if (method->wrapper_type || extra)
3012 g_ptr_array_add (acfg->extra_methods, method);
3016 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3018 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3026 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3030 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3034 index = acfg->method_index;
3035 add_method_with_index (acfg, method, index, extra);
3037 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3039 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3041 acfg->method_index ++;
3047 add_method (MonoAotCompile *acfg, MonoMethod *method)
3049 return add_method_full (acfg, method, FALSE, 0);
3053 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3055 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3056 method = mini_get_shared_method (method);
3058 if (acfg->aot_opts.log_generics)
3059 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3061 add_method_full (acfg, method, TRUE, depth);
3065 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3067 add_extra_method_with_depth (acfg, method, 0);
3071 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3073 MonoAotCompile *acfg = user_data;
3074 MonoJitICallInfo *callinfo = value;
3075 MonoMethod *wrapper;
3081 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3082 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3085 add_method (acfg, wrapper);
3089 get_runtime_invoke_sig (MonoMethodSignature *sig)
3091 MonoMethodBuilder *mb;
3094 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3095 m = mono_mb_create_method (mb, sig, 16);
3096 return mono_marshal_get_runtime_invoke (m, FALSE);
3100 can_marshal_struct (MonoClass *klass)
3102 MonoClassField *field;
3103 gboolean can_marshal = TRUE;
3104 gpointer iter = NULL;
3105 MonoMarshalType *info;
3108 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3111 info = mono_marshal_load_type_info (klass);
3113 /* Only allow a few field types to avoid asserts in the marshalling code */
3114 while ((field = mono_class_get_fields (klass, &iter))) {
3115 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3118 switch (field->type->type) {
3123 case MONO_TYPE_BOOLEAN:
3126 case MONO_TYPE_CHAR:
3134 case MONO_TYPE_STRING:
3136 case MONO_TYPE_VALUETYPE:
3137 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3138 can_marshal = FALSE;
3140 case MONO_TYPE_SZARRAY: {
3141 gboolean has_mspec = FALSE;
3144 for (i = 0; i < info->num_fields; ++i) {
3145 if (info->fields [i].field == field && info->fields [i].mspec)
3150 can_marshal = FALSE;
3154 can_marshal = FALSE;
3160 /* Its hard to compute whenever these can be marshalled or not */
3161 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3168 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3170 /* Create a vtype instantiation */
3171 MonoGenericContext shared_context;
3173 MonoGenericInst *inst;
3174 MonoGenericContainer *container;
3175 MonoClass **constraints;
3178 memset (ctx, 0, sizeof (MonoGenericContext));
3180 if (method->klass->generic_container) {
3181 shared_context = method->klass->generic_container->context;
3182 inst = shared_context.class_inst;
3184 args = g_new0 (MonoType*, inst->type_argc);
3185 for (i = 0; i < inst->type_argc; ++i) {
3186 args [i] = &mono_defaults.int_class->byval_arg;
3188 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3190 if (method->is_generic) {
3191 container = mono_method_get_generic_container (method);
3192 shared_context = container->context;
3193 inst = shared_context.method_inst;
3195 args = g_new0 (MonoType*, inst->type_argc);
3196 for (i = 0; i < container->type_argc; ++i) {
3197 MonoGenericParamInfo *info = &container->type_params [i].info;
3198 gboolean ref_only = FALSE;
3200 if (info && info->constraints) {
3201 constraints = info->constraints;
3203 while (*constraints) {
3204 MonoClass *cklass = *constraints;
3205 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3206 /* Inflaring the method with our vtype would not be valid */
3213 args [i] = &mono_defaults.object_class->byval_arg;
3215 args [i] = &mono_defaults.int_class->byval_arg;
3217 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3222 add_wrappers (MonoAotCompile *acfg)
3224 MonoMethod *method, *m;
3226 MonoMethodSignature *sig, *csig;
3230 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3231 * so there is only one wrapper of a given type, or inlining their contents into their
3234 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3236 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3237 gboolean skip = FALSE;
3239 method = mono_get_method (acfg->image, token, NULL);
3241 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3242 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3243 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3246 /* Skip methods which can not be handled by get_runtime_invoke () */
3247 sig = mono_method_signature (method);
3250 if ((sig->ret->type == MONO_TYPE_PTR) ||
3251 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3253 if (mono_class_is_open_constructed_type (sig->ret))
3256 for (j = 0; j < sig->param_count; j++) {
3257 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3259 if (mono_class_is_open_constructed_type (sig->params [j]))
3263 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3264 if (!mono_class_is_contextbound (method->klass)) {
3265 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3266 gboolean has_nullable = FALSE;
3268 for (j = 0; j < sig->param_count; j++) {
3269 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3270 has_nullable = TRUE;
3273 if (info && !has_nullable) {
3274 /* Supported by the dynamic runtime-invoke wrapper */
3282 //printf ("%s\n", mono_method_full_name (method, TRUE));
3283 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3287 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3288 MonoMethodDesc *desc;
3289 MonoMethod *orig_method;
3292 /* Runtime invoke wrappers */
3294 /* void runtime-invoke () [.cctor] */
3295 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3296 csig->ret = &mono_defaults.void_class->byval_arg;
3297 add_method (acfg, get_runtime_invoke_sig (csig));
3299 /* void runtime-invoke () [Finalize] */
3300 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3302 csig->ret = &mono_defaults.void_class->byval_arg;
3303 add_method (acfg, get_runtime_invoke_sig (csig));
3305 /* void runtime-invoke (string) [exception ctor] */
3306 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3308 csig->ret = &mono_defaults.void_class->byval_arg;
3309 csig->params [0] = &mono_defaults.string_class->byval_arg;
3310 add_method (acfg, get_runtime_invoke_sig (csig));
3312 /* void runtime-invoke (string, string) [exception ctor] */
3313 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3315 csig->ret = &mono_defaults.void_class->byval_arg;
3316 csig->params [0] = &mono_defaults.string_class->byval_arg;
3317 csig->params [1] = &mono_defaults.string_class->byval_arg;
3318 add_method (acfg, get_runtime_invoke_sig (csig));
3320 /* string runtime-invoke () [Exception.ToString ()] */
3321 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3323 csig->ret = &mono_defaults.string_class->byval_arg;
3324 add_method (acfg, get_runtime_invoke_sig (csig));
3326 /* void runtime-invoke (string, Exception) [exception ctor] */
3327 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3329 csig->ret = &mono_defaults.void_class->byval_arg;
3330 csig->params [0] = &mono_defaults.string_class->byval_arg;
3331 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3332 add_method (acfg, get_runtime_invoke_sig (csig));
3334 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3335 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3337 csig->ret = &(mono_class_from_name (
3338 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3339 csig->params [0] = &mono_defaults.string_class->byval_arg;
3340 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3341 add_method (acfg, get_runtime_invoke_sig (csig));
3343 /* runtime-invoke used by finalizers */
3344 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3346 /* This is used by mono_runtime_capture_context () */
3347 method = mono_get_context_capture_method ();
3349 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3351 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3352 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3356 add_method (acfg, mono_marshal_get_stelemref ());
3358 if (MONO_ARCH_HAVE_TLS_GET) {
3359 /* Managed Allocators */
3360 nallocators = mono_gc_get_managed_allocator_types ();
3361 for (i = 0; i < nallocators; ++i) {
3362 m = mono_gc_get_managed_allocator_by_type (i);
3364 add_method (acfg, m);
3367 /* Monitor Enter/Exit */
3368 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3369 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3370 /* This is a v4 method */
3372 method = mono_monitor_get_fast_path (orig_method);
3374 add_method (acfg, method);
3376 mono_method_desc_free (desc);
3378 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3379 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3380 g_assert (orig_method);
3381 mono_method_desc_free (desc);
3382 method = mono_monitor_get_fast_path (orig_method);
3384 add_method (acfg, method);
3387 /* Stelemref wrappers */
3389 MonoMethod **wrappers;
3392 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3393 for (i = 0; i < nwrappers; ++i)
3394 add_method (acfg, wrappers [i]);
3398 /* castclass_with_check wrapper */
3399 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3400 /* isinst_with_check wrapper */
3401 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3403 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3405 MonoMethodDesc *desc;
3408 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3409 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3410 mono_method_desc_free (desc);
3412 m = mono_monitor_get_fast_path (m);
3414 add_method (acfg, m);
3419 /* JIT icall wrappers */
3420 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3421 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3425 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3426 * we use the original method instead at runtime.
3427 * Since full-aot doesn't support remoting, this is not a problem.
3430 /* remoting-invoke wrappers */
3431 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3432 MonoMethodSignature *sig;
3434 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3435 method = mono_get_method (acfg->image, token, NULL);
3437 sig = mono_method_signature (method);
3439 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3440 m = mono_marshal_get_remoting_invoke_with_check (method);
3442 add_method (acfg, m);
3447 /* delegate-invoke wrappers */
3448 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3450 MonoCustomAttrInfo *cattr;
3452 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3453 klass = mono_class_get (acfg->image, token);
3456 mono_loader_clear_error ();
3460 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3463 if (!klass->generic_container) {
3464 method = mono_get_delegate_invoke (klass);
3466 m = mono_marshal_get_delegate_invoke (method, NULL);
3468 add_method (acfg, m);
3470 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3472 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3474 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3476 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3478 cattr = mono_custom_attrs_from_class (klass);
3483 for (j = 0; j < cattr->num_attrs; ++j)
3484 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3486 if (j < cattr->num_attrs)
3487 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3489 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3490 MonoGenericContext ctx;
3491 MonoMethod *inst, *gshared;
3494 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3497 method = mono_get_delegate_invoke (klass);
3498 create_gsharedvt_inst (acfg, method, &ctx);
3500 inst = mono_class_inflate_generic_method (method, &ctx);
3502 m = mono_marshal_get_delegate_invoke (inst, NULL);
3503 g_assert (m->is_inflated);
3505 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3506 add_extra_method (acfg, gshared);
3509 method = mono_get_delegate_begin_invoke (klass);
3510 create_gsharedvt_inst (acfg, method, &ctx);
3512 inst = mono_class_inflate_generic_method (method, &ctx);
3514 m = mono_marshal_get_delegate_begin_invoke (inst);
3515 g_assert (m->is_inflated);
3517 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3518 add_extra_method (acfg, gshared);
3521 method = mono_get_delegate_end_invoke (klass);
3522 create_gsharedvt_inst (acfg, method, &ctx);
3524 inst = mono_class_inflate_generic_method (method, &ctx);
3526 m = mono_marshal_get_delegate_end_invoke (inst);
3527 g_assert (m->is_inflated);
3529 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3530 add_extra_method (acfg, gshared);
3535 /* array access wrappers */
3536 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3539 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3540 klass = mono_class_get (acfg->image, token);
3543 mono_loader_clear_error ();
3547 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3548 MonoMethod *m, *wrapper;
3550 /* Add runtime-invoke wrappers too */
3552 m = mono_class_get_method_from_name (klass, "Get", -1);
3554 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3555 add_extra_method (acfg, wrapper);
3556 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3558 m = mono_class_get_method_from_name (klass, "Set", -1);
3560 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3561 add_extra_method (acfg, wrapper);
3562 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3566 /* Synchronized wrappers */
3567 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3568 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3569 method = mono_get_method (acfg->image, token, NULL);
3571 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3572 if (method->is_generic) {
3574 } else if (method->klass->generic_container) {
3575 MonoGenericContext ctx;
3576 MonoMethod *inst, *gshared, *m;
3579 * Create a generic wrapper for a generic instance, and AOT that.
3581 create_gsharedvt_inst (acfg, method, &ctx);
3582 inst = mono_class_inflate_generic_method (method, &ctx);
3583 m = mono_marshal_get_synchronized_wrapper (inst);
3584 g_assert (m->is_inflated);
3585 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3586 add_method (acfg, gshared);
3588 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3593 /* pinvoke wrappers */
3594 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3596 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3598 method = mono_get_method (acfg->image, token, NULL);
3600 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3601 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3602 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3606 /* native-to-managed wrappers */
3607 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3609 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3610 MonoCustomAttrInfo *cattr;
3613 method = mono_get_method (acfg->image, token, NULL);
3616 * Only generate native-to-managed wrappers for methods which have an
3617 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3618 * name to avoid defining a new assembly to contain it.
3620 cattr = mono_custom_attrs_from_method (method);
3623 for (j = 0; j < cattr->num_attrs; ++j)
3624 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3626 if (j < cattr->num_attrs) {
3627 MonoCustomAttrEntry *e = &cattr->attrs [j];
3628 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3629 const char *p = (const char*)e->data;
3631 int slen, num_named, named_type, data_type;
3635 char *export_name = NULL;
3636 MonoMethod *wrapper;
3638 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3639 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3640 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3641 mono_method_full_name (method, TRUE));
3645 g_assert (sig->param_count == 1);
3646 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3649 * Decode the cattr manually since we can't create objects
3650 * during aot compilation.
3656 /* From load_cattr_value () in reflection.c */
3657 slen = mono_metadata_decode_value (p, &p);
3658 n = g_memdup (p, slen + 1);
3660 t = mono_reflection_type_from_name (n, acfg->image);
3664 klass = mono_class_from_mono_type (t);
3665 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3669 num_named = read16 (p);
3672 g_assert (num_named < 2);
3673 if (num_named == 1) {
3676 MonoType *prop_type;
3678 /* parse ExportSymbol attribute */
3680 named_type = *named;
3685 name_len = mono_metadata_decode_blob_size (named, &named);
3686 name = g_malloc (name_len + 1);
3687 memcpy (name, named, name_len);
3688 name [name_len] = 0;
3691 g_assert (named_type == 0x54);
3692 g_assert (!strcmp (name, "ExportSymbol"));
3694 prop_type = &mono_defaults.string_class->byval_arg;
3696 /* load_cattr_value (), string case */
3697 g_assert (*named != (char)0xff);
3698 slen = mono_metadata_decode_value (named, &named);
3699 export_name = g_malloc (slen + 1);
3700 memcpy (export_name, named, slen);
3701 export_name [slen] = 0;
3705 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3706 add_method (acfg, wrapper);
3708 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3712 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3713 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3714 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3718 /* StructureToPtr/PtrToStructure wrappers */
3719 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3722 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3723 klass = mono_class_get (acfg->image, token);
3726 mono_loader_clear_error ();
3730 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3731 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3732 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3733 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3739 has_type_vars (MonoClass *klass)
3741 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3744 return has_type_vars (klass->element_class);
3745 if (klass->generic_class) {
3746 MonoGenericContext *context = &klass->generic_class->context;
3747 if (context->class_inst) {
3750 for (i = 0; i < context->class_inst->type_argc; ++i)
3751 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3755 if (klass->generic_container)
3761 is_vt_inst (MonoGenericInst *inst)
3765 for (i = 0; i < inst->type_argc; ++i) {
3766 MonoType *t = inst->type_argv [i];
3767 if (t->type == MONO_TYPE_VALUETYPE)
3774 method_has_type_vars (MonoMethod *method)
3776 if (has_type_vars (method->klass))
3779 if (method->is_inflated) {
3780 MonoGenericContext *context = mono_method_get_context (method);
3781 if (context->method_inst) {
3784 for (i = 0; i < context->method_inst->type_argc; ++i)
3785 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3792 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3795 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3797 /* This might lead to a huge code blowup so only do it if neccesary */
3798 if (!acfg->aot_opts.full_aot && !force)
3801 add_generic_class_with_depth (acfg, klass, 0, ref);
3805 check_type_depth (MonoType *t, int depth)
3813 case MONO_TYPE_GENERICINST: {
3814 MonoGenericClass *gklass = t->data.generic_class;
3815 MonoGenericInst *ginst = gklass->context.class_inst;
3818 for (i = 0; i < ginst->type_argc; ++i) {
3819 if (check_type_depth (ginst->type_argv [i], depth + 1))
3833 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3836 * add_generic_class:
3838 * Add all methods of a generic class.
3841 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3844 MonoClassField *field;
3846 gboolean use_gsharedvt = FALSE;
3848 if (!acfg->ginst_hash)
3849 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3851 mono_class_init (klass);
3853 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3856 if (has_type_vars (klass))
3859 if (!klass->generic_class && !klass->rank)
3862 if (klass->exception_type)
3865 if (!acfg->ginst_hash)
3866 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3868 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3871 if (check_type_depth (&klass->byval_arg, 0))
3874 if (acfg->aot_opts.log_generics)
3875 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3877 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3880 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3881 * Enable this only for some classes since gsharedvt might not support all methods.
3883 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) && (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1")))
3884 use_gsharedvt = TRUE;
3887 while ((method = mono_class_get_methods (klass, &iter))) {
3888 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3890 * This is partial sharing, and we can't handle it yet
3895 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
3897 add_types_from_method_header (acfg, method);
3901 if (method->is_generic)
3906 * FIXME: Instances which are referenced by these methods are not added,
3907 * for example Array.Resize<int> for List<int>.Add ().
3909 add_extra_method_with_depth (acfg, method, depth + 1);
3913 while ((field = mono_class_get_fields (klass, &iter))) {
3914 if (field->type->type == MONO_TYPE_GENERICINST)
3915 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3918 if (klass->delegate) {
3919 method = mono_get_delegate_invoke (klass);
3921 method = mono_marshal_get_delegate_invoke (method, NULL);
3923 if (acfg->aot_opts.log_generics)
3924 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3926 add_method (acfg, method);
3929 /* Add superclasses */
3931 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3934 * For ICollection<T>, add instances of the helper methods
3935 * in Array, since a T[] could be cast to ICollection<T>.
3937 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3938 (!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"))) {
3939 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3940 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3944 if (!strcmp (klass->name, "IEnumerator`1"))
3945 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3947 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3949 /* Add the T[]/InternalEnumerator class */
3950 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3954 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3955 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3959 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3960 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3964 while ((method = mono_class_get_methods (array_class, &iter))) {
3965 if (strstr (method->name, name_prefix)) {
3966 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3968 add_extra_method_with_depth (acfg, m, depth);
3972 g_free (name_prefix);
3975 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3976 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3977 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3978 MonoClass *icomparable, *gcomparer;
3979 MonoGenericContext ctx;
3980 MonoType *args [16];
3982 memset (&ctx, 0, sizeof (ctx));
3984 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3985 g_assert (icomparable);
3986 args [0] = &tclass->byval_arg;
3987 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3989 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3990 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3991 g_assert (gcomparer);
3992 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3996 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3997 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3998 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3999 MonoClass *iface, *gcomparer;
4000 MonoGenericContext ctx;
4001 MonoType *args [16];
4003 memset (&ctx, 0, sizeof (ctx));
4005 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4007 args [0] = &tclass->byval_arg;
4008 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4010 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4011 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4012 g_assert (gcomparer);
4013 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4019 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4022 MonoGenericContext ctx;
4023 MonoType *args [16];
4025 if (acfg->aot_opts.no_instances)
4028 memset (&ctx, 0, sizeof (ctx));
4030 for (i = 0; i < ninsts; ++i) {
4031 args [0] = insts [i];
4032 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4033 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4038 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4040 MonoMethodHeader *header;
4041 MonoMethodSignature *sig;
4044 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4046 sig = mono_method_signature (method);
4049 for (j = 0; j < sig->param_count; ++j)
4050 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4051 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4054 header = mono_method_get_header (method);
4057 for (j = 0; j < header->num_locals; ++j)
4058 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4059 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4061 mono_loader_clear_error ();
4066 * add_generic_instances:
4068 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4071 add_generic_instances (MonoAotCompile *acfg)
4076 MonoGenericContext *context;
4078 if (acfg->aot_opts.no_instances)
4081 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4082 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4083 method = mono_get_method (acfg->image, token, NULL);
4088 if (method->klass->image != acfg->image)
4091 context = mono_method_get_context (method);
4093 if (context && ((context->class_inst && context->class_inst->is_open)))
4097 * For open methods, create an instantiation which can be passed to the JIT.
4098 * FIXME: Handle class_inst as well.
4100 if (context && context->method_inst && context->method_inst->is_open) {
4101 MonoGenericContext shared_context;
4102 MonoGenericInst *inst;
4103 MonoType **type_argv;
4105 MonoMethod *declaring_method;
4106 gboolean supported = TRUE;
4108 /* Check that the context doesn't contain open constructed types */
4109 if (context->class_inst) {
4110 inst = context->class_inst;
4111 for (i = 0; i < inst->type_argc; ++i) {
4112 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)
4114 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4118 if (context->method_inst) {
4119 inst = context->method_inst;
4120 for (i = 0; i < inst->type_argc; ++i) {
4121 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)
4123 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4131 memset (&shared_context, 0, sizeof (MonoGenericContext));
4133 inst = context->class_inst;
4135 type_argv = g_new0 (MonoType*, inst->type_argc);
4136 for (i = 0; i < inst->type_argc; ++i) {
4137 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)
4138 type_argv [i] = &mono_defaults.object_class->byval_arg;
4140 type_argv [i] = inst->type_argv [i];
4143 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4147 inst = context->method_inst;
4149 type_argv = g_new0 (MonoType*, inst->type_argc);
4150 for (i = 0; i < inst->type_argc; ++i) {
4151 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)
4152 type_argv [i] = &mono_defaults.object_class->byval_arg;
4154 type_argv [i] = inst->type_argv [i];
4157 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4161 if (method->is_generic || method->klass->generic_container)
4162 declaring_method = method;
4164 declaring_method = mono_method_get_declaring_generic_method (method);
4166 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4170 * If the method is fully sharable, it was already added in place of its
4171 * generic definition.
4173 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4177 * FIXME: Partially shared methods are not shared here, so we end up with
4178 * many identical methods.
4180 add_extra_method (acfg, method);
4183 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4186 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4188 klass = mono_class_get (acfg->image, token);
4189 if (!klass || klass->rank) {
4190 mono_loader_clear_error ();
4194 add_generic_class (acfg, klass, FALSE, "typespec");
4197 /* Add types of args/locals */
4198 for (i = 0; i < acfg->methods->len; ++i) {
4199 method = g_ptr_array_index (acfg->methods, i);
4200 add_types_from_method_header (acfg, method);
4203 if (acfg->image == mono_defaults.corlib) {
4205 MonoType *insts [256];
4208 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4209 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4210 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4211 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4212 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4213 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4214 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4215 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4216 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4217 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4218 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4219 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4221 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4222 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4224 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4225 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4227 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4229 /* Add instances of the array generic interfaces for primitive types */
4230 /* This will add instances of the InternalArray_ helper methods in Array too */
4231 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4233 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4234 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4236 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4237 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4239 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4242 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4243 * used for all instances of GetGenericValueImpl by the AOT runtime.
4246 MonoGenericContext ctx;
4247 MonoType *args [16];
4248 MonoMethod *get_method;
4249 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4251 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4254 memset (&ctx, 0, sizeof (ctx));
4255 args [0] = &mono_defaults.object_class->byval_arg;
4256 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4257 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4261 /* Same for CompareExchange<T>/Exchange<T> */
4263 MonoGenericContext ctx;
4264 MonoType *args [16];
4266 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4267 gpointer iter = NULL;
4269 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4270 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4271 memset (&ctx, 0, sizeof (ctx));
4272 args [0] = &mono_defaults.object_class->byval_arg;
4273 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4274 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4279 /* Same for Volatile.Read/Write<T> */
4281 MonoGenericContext ctx;
4282 MonoType *args [16];
4284 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4285 gpointer iter = NULL;
4287 if (volatile_klass) {
4288 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4289 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4290 memset (&ctx, 0, sizeof (ctx));
4291 args [0] = &mono_defaults.object_class->byval_arg;
4292 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4293 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4302 * is_direct_callable:
4304 * Return whenever the method identified by JI is directly callable without
4305 * going through the PLT.
4308 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4310 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4311 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4313 gboolean direct_callable = TRUE;
4315 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4316 direct_callable = FALSE;
4317 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4318 // FIXME: Maybe call the wrapper directly ?
4319 direct_callable = FALSE;
4321 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4322 /* Disable this so all calls go through load_method (), see the
4323 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4324 * mono_debugger_agent_init ().
4326 direct_callable = FALSE;
4329 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4330 /* sgen does some initialization when the allocator method is created */
4331 direct_callable = FALSE;
4333 if (direct_callable)
4336 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4337 if (acfg->aot_opts.direct_pinvoke)
4339 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4340 if (acfg->aot_opts.direct_icalls)
4348 #ifdef MONO_ARCH_AOT_SUPPORTED
4350 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4352 MonoImage *image = method->klass->image;
4353 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4354 MonoTableInfo *tables = image->tables;
4355 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4356 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4357 guint32 im_cols [MONO_IMPLMAP_SIZE];
4360 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4364 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4367 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4369 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4372 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4374 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4381 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4383 if (a->native_offset == b->native_offset)
4384 return a->il_offset - b->il_offset;
4386 return a->native_offset - b->native_offset;
4390 * compute_line_numbers:
4392 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4395 static MonoDebugSourceLocation**
4396 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4398 MonoDebugMethodInfo *minfo;
4399 MonoDebugLineNumberEntry *ln_array;
4400 MonoDebugSourceLocation *loc;
4401 int i, prev_line, prev_il_offset;
4402 int *native_to_il_offset = NULL;
4403 MonoDebugSourceLocation **res;
4406 minfo = mono_debug_lookup_method (method);
4409 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4410 if (debug_info->code_size != code_size)
4413 g_assert (code_size);
4415 /* Compute the native->IL offset mapping */
4417 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4418 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4420 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4422 native_to_il_offset = g_new0 (int, code_size + 1);
4424 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4426 MonoDebugLineNumberEntry *lne = &ln_array [i];
4429 for (j = 0; j < lne->native_offset; ++j)
4430 native_to_il_offset [j] = -1;
4433 if (i < debug_info->num_line_numbers - 1) {
4434 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4436 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4437 native_to_il_offset [j] = lne->il_offset;
4439 for (j = lne->native_offset; j < code_size; ++j)
4440 native_to_il_offset [j] = lne->il_offset;
4445 /* Compute the native->line number mapping */
4446 res = g_new0 (MonoDebugSourceLocation*, code_size);
4447 prev_il_offset = -1;
4450 for (i = 0; i < code_size; ++i) {
4451 int il_offset = native_to_il_offset [i];
4453 if (il_offset == -1 || il_offset == prev_il_offset)
4455 prev_il_offset = il_offset;
4456 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4457 if (!(loc && loc->source_file))
4459 if (loc->row == prev_line) {
4460 mono_debug_symfile_free_location (loc);
4463 prev_line = loc->row;
4464 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4466 /* This will cover the prolog too */
4476 get_file_index (MonoAotCompile *acfg, const char *source_file)
4480 // FIXME: Free these
4481 if (!acfg->dwarf_ln_filenames)
4482 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4483 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4485 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4486 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4487 emit_unset_mode (acfg);
4488 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4496 * emit_and_reloc_code:
4498 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4499 * is true, calls are made through the GOT too. This is used for emitting trampolines
4500 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4501 * since trampolines are needed to make PTL work.
4504 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4506 int i, pindex, start_index, method_index;
4508 MonoJumpInfo *patch_info;
4509 MonoMethodHeader *header;
4510 MonoDebugSourceLocation **locs = NULL;
4512 #ifdef MONO_ARCH_AOT_SUPPORTED
4513 gboolean direct_call, external_call;
4515 const char *direct_call_target = 0;
4516 const char *direct_pinvoke;
4520 header = mono_method_get_header (method);
4522 method_index = get_method_index (acfg, method);
4525 if (acfg->gas_line_numbers && method && debug_info) {
4526 locs = compute_line_numbers (method, code_len, debug_info);
4528 int findex = get_file_index (acfg, "<unknown>");
4529 emit_unset_mode (acfg);
4530 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4534 /* Collect and sort relocations */
4535 patches = g_ptr_array_new ();
4536 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4537 g_ptr_array_add (patches, patch_info);
4538 g_ptr_array_sort (patches, compare_patches);
4541 for (i = 0; i < code_len; i += INST_LEN) {
4543 for (pindex = start_index; pindex < patches->len; ++pindex) {
4544 patch_info = g_ptr_array_index (patches, pindex);
4545 if (patch_info->ip.i >= i)
4549 if (locs && locs [i]) {
4550 MonoDebugSourceLocation *loc = locs [i];
4553 findex = get_file_index (acfg, loc->source_file);
4554 emit_unset_mode (acfg);
4555 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4556 mono_debug_symfile_free_location (loc);
4560 #ifdef MONO_ARCH_AOT_SUPPORTED
4561 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4562 start_index = pindex;
4564 switch (patch_info->type) {
4565 case MONO_PATCH_INFO_NONE:
4567 case MONO_PATCH_INFO_GOT_OFFSET: {
4570 arch_emit_got_offset (acfg, code + i, &code_size);
4571 i += code_size - INST_LEN;
4573 patch_info->type = MONO_PATCH_INFO_NONE;
4576 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4577 int code_size, index;
4578 char *selector = (void*)patch_info->data.target;
4580 if (!acfg->objc_selector_to_index)
4581 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4582 if (!acfg->objc_selectors)
4583 acfg->objc_selectors = g_ptr_array_new ();
4584 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4588 index = acfg->objc_selector_index;
4589 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4590 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4591 acfg->objc_selector_index ++;
4594 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4595 i += code_size - INST_LEN;
4597 patch_info->type = MONO_PATCH_INFO_NONE;
4602 * If this patch is a call, try emitting a direct call instead of
4603 * through a PLT entry. This is possible if the called method is in
4604 * the same assembly and requires no initialization.
4606 direct_call = FALSE;
4607 external_call = FALSE;
4608 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4609 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4610 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4611 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4613 direct_call_target = callee_cfg->asm_symbol;
4614 patch_info->type = MONO_PATCH_INFO_NONE;
4615 acfg->stats.direct_calls ++;
4618 acfg->stats.all_calls ++;
4619 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4620 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4621 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4622 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4624 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4625 if (direct_pinvoke) {
4627 g_assert (strlen (direct_pinvoke) < 1000);
4628 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4631 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4632 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4633 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4634 /* Call to a C function implementing a jit icall */
4636 external_call = TRUE;
4637 g_assert (strlen (sym) < 1000);
4638 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4640 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4641 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4642 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4643 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4644 /* Call to a jit icall without a wrapper */
4646 external_call = TRUE;
4647 g_assert (strlen (sym) < 1000);
4648 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4653 patch_info->type = MONO_PATCH_INFO_NONE;
4654 acfg->stats.direct_calls ++;
4657 if (!got_only && !direct_call) {
4658 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4660 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4662 direct_call_target = plt_entry->symbol;
4664 /* Nullify the patch */
4665 patch_info->type = MONO_PATCH_INFO_NONE;
4666 plt_entry->jit_used = TRUE;
4673 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4674 i += call_size - INST_LEN;
4678 got_slot = get_got_offset (acfg, patch_info);
4680 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4681 i += code_size - INST_LEN;
4687 #endif /* MONO_ARCH_AOT_SUPPORTED */
4690 /* Find next patch */
4692 for (pindex = start_index; pindex < patches->len; ++pindex) {
4693 patch_info = g_ptr_array_index (patches, pindex);
4694 if (patch_info->ip.i >= i)
4698 /* Try to emit multiple bytes at once */
4699 if (pindex < patches->len && patch_info->ip.i > i) {
4702 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4703 if (locs && locs [limit])
4707 emit_code_bytes (acfg, code + i, limit - i);
4708 i = limit - INST_LEN;
4710 emit_code_bytes (acfg, code + i, INST_LEN);
4721 * Return a modified version of S which only includes characters permissible in symbols.
4724 sanitize_symbol (MonoAotCompile *acfg, char *s)
4726 gboolean process = FALSE;
4735 for (i = 0; i < len; ++i)
4736 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4741 gs = g_string_sized_new (len);
4742 for (i = 0; i < len; ++i) {
4744 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4745 g_string_append_c (gs, c);
4746 } else if (c > 0x7f) {
4747 /* multi-byte utf8 */
4748 g_string_append_printf (gs, "_0x%x", c);
4751 while (c >> 6 == 0x2) {
4752 g_string_append_printf (gs, "%x", c);
4756 g_string_append_printf (gs, "_");
4759 g_string_append_c (gs, '_');
4763 res = mono_mempool_strdup (acfg->mempool, gs->str);
4764 g_string_free (gs, TRUE);
4769 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4771 char *name1, *name2, *cached;
4772 int i, j, len, count;
4775 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4776 if (!prefix || !*prefix)
4780 name1 = mono_method_full_name (method, TRUE);
4781 len = strlen (name1);
4782 name2 = malloc (strlen (prefix) + len + 16);
4783 memcpy (name2, prefix, strlen (prefix));
4784 j = strlen (prefix);
4785 for (i = 0; i < len; ++i) {
4786 if (isalnum (name1 [i])) {
4787 name2 [j ++] = name1 [i];
4788 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4790 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4793 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4802 while (g_hash_table_lookup (cache, name2)) {
4803 sprintf (name2 + j, "_%d", count);
4807 cached = g_strdup (name2);
4808 g_hash_table_insert (cache, cached, cached);
4814 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4819 char *debug_sym = NULL;
4820 char *symbol = NULL;
4821 int func_alignment = AOT_FUNC_ALIGNMENT;
4822 MonoMethodHeader *header;
4825 method = cfg->orig_method;
4826 code = cfg->native_code;
4827 header = cfg->header;
4829 method_index = get_method_index (acfg, method);
4830 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4833 /* Make the labels local */
4834 emit_section_change (acfg, ".text", 0);
4835 emit_alignment (acfg, func_alignment);
4837 if (acfg->global_symbols && acfg->need_no_dead_strip)
4838 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4840 emit_label (acfg, cfg->asm_symbol);
4842 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4844 * Write a C style symbol for every method, this has two uses:
4845 * - it works on platforms where the dwarf debugging info is not
4847 * - it allows the setting of breakpoints of aot-ed methods.
4849 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4851 if (acfg->need_no_dead_strip)
4852 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4853 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4854 emit_label (acfg, debug_sym);
4857 export_name = g_hash_table_lookup (acfg->export_names, method);
4859 /* Emit a global symbol for the method */
4860 emit_global_inner (acfg, export_name, TRUE);
4861 emit_label (acfg, export_name);
4864 if (cfg->verbose_level > 0)
4865 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4867 acfg->stats.code_size += cfg->code_len;
4869 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4871 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 ()));
4875 if (acfg->aot_opts.write_symbols) {
4876 emit_symbol_size (acfg, debug_sym, ".");
4880 emit_label (acfg, symbol);
4887 * Encode PATCH_INFO into its disk representation.
4890 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4894 switch (patch_info->type) {
4895 case MONO_PATCH_INFO_NONE:
4897 case MONO_PATCH_INFO_IMAGE:
4898 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4900 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4901 case MONO_PATCH_INFO_JIT_TLS_ID:
4902 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4903 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4905 case MONO_PATCH_INFO_METHOD_REL:
4906 encode_value ((gint)patch_info->data.offset, p, &p);
4908 case MONO_PATCH_INFO_SWITCH: {
4909 gpointer *table = (gpointer *)patch_info->data.table->table;
4912 encode_value (patch_info->data.table->table_size, p, &p);
4913 for (k = 0; k < patch_info->data.table->table_size; k++)
4914 encode_value ((int)(gssize)table [k], p, &p);
4917 case MONO_PATCH_INFO_METHODCONST:
4918 case MONO_PATCH_INFO_METHOD:
4919 case MONO_PATCH_INFO_METHOD_JUMP:
4920 case MONO_PATCH_INFO_ICALL_ADDR:
4921 case MONO_PATCH_INFO_METHOD_RGCTX:
4922 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
4923 encode_method_ref (acfg, patch_info->data.method, p, &p);
4925 case MONO_PATCH_INFO_INTERNAL_METHOD:
4926 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4927 guint32 len = strlen (patch_info->data.name);
4929 encode_value (len, p, &p);
4931 memcpy (p, patch_info->data.name, len);
4936 case MONO_PATCH_INFO_LDSTR: {
4937 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4938 guint32 token = patch_info->data.token->token;
4939 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4940 encode_value (image_index, p, &p);
4941 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4944 case MONO_PATCH_INFO_RVA:
4945 case MONO_PATCH_INFO_DECLSEC:
4946 case MONO_PATCH_INFO_LDTOKEN:
4947 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4948 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4949 encode_value (patch_info->data.token->token, p, &p);
4950 encode_value (patch_info->data.token->has_context, p, &p);
4951 if (patch_info->data.token->has_context)
4952 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4954 case MONO_PATCH_INFO_EXC_NAME: {
4955 MonoClass *ex_class;
4958 mono_class_from_name (mono_defaults.exception_class->image,
4959 "System", patch_info->data.target);
4960 g_assert (ex_class);
4961 encode_klass_ref (acfg, ex_class, p, &p);
4964 case MONO_PATCH_INFO_R4:
4965 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4967 case MONO_PATCH_INFO_R8:
4968 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4969 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4971 case MONO_PATCH_INFO_VTABLE:
4972 case MONO_PATCH_INFO_CLASS:
4973 case MONO_PATCH_INFO_IID:
4974 case MONO_PATCH_INFO_ADJUSTED_IID:
4975 case MONO_PATCH_INFO_CLASS_INIT:
4976 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4978 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4979 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
4980 if (patch_info->data.del_tramp->method) {
4981 encode_value (1, p, &p);
4982 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
4984 encode_value (0, p, &p);
4987 case MONO_PATCH_INFO_FIELD:
4988 case MONO_PATCH_INFO_SFLDA:
4989 encode_field_info (acfg, patch_info->data.field, p, &p);
4991 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4993 case MONO_PATCH_INFO_RGCTX_FETCH: {
4994 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4999 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5000 * reference the same method, so encode the method only once.
5002 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5004 buf2 = g_malloc (1024);
5007 encode_method_ref (acfg, entry->method, p2, &p2);
5008 g_assert (p2 - buf2 < 1024);
5010 offset = add_to_blob (acfg, buf2, p2 - buf2);
5013 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5018 encode_value (offset, p, &p);
5019 g_assert ((int)entry->info_type < 256);
5020 g_assert (entry->data->type < 256);
5021 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5022 encode_patch (acfg, entry->data, p, &p);
5025 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5026 case MONO_PATCH_INFO_MONITOR_ENTER:
5027 case MONO_PATCH_INFO_MONITOR_EXIT:
5028 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5030 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5031 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5032 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5034 case MONO_PATCH_INFO_SIGNATURE:
5035 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5037 case MONO_PATCH_INFO_TLS_OFFSET:
5038 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5040 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5041 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5042 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5044 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5045 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5048 encode_method_ref (acfg, info->method, p, &p);
5049 encode_value (info->num_entries, p, &p);
5050 for (i = 0; i < info->num_entries; ++i) {
5051 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5053 encode_value (template->info_type, p, &p);
5054 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5055 case MONO_PATCH_INFO_CLASS:
5056 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5058 case MONO_PATCH_INFO_FIELD:
5059 encode_field_info (acfg, template->data, p, &p);
5062 g_assert_not_reached ();
5069 g_warning ("unable to handle jump info %d", patch_info->type);
5070 g_assert_not_reached ();
5077 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5080 guint32 pindex, offset;
5081 MonoJumpInfo *patch_info;
5083 encode_value (n_patches, p, &p);
5085 for (pindex = 0; pindex < patches->len; ++pindex) {
5086 patch_info = g_ptr_array_index (patches, pindex);
5088 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5092 offset = get_got_offset (acfg, patch_info);
5093 encode_value (offset, p, &p);
5100 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5104 int pindex, buf_size, n_patches;
5106 MonoJumpInfo *patch_info;
5107 MonoMethodHeader *header;
5108 guint32 method_index;
5110 guint32 first_got_offset;
5112 method = cfg->orig_method;
5113 header = mono_method_get_header (method);
5115 method_index = get_method_index (acfg, method);
5117 /* Sort relocations */
5118 patches = g_ptr_array_new ();
5119 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5120 g_ptr_array_add (patches, patch_info);
5121 g_ptr_array_sort (patches, compare_patches);
5123 first_got_offset = acfg->cfgs [method_index]->got_offset;
5125 /**********************/
5126 /* Encode method info */
5127 /**********************/
5129 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5130 p = buf = g_malloc (buf_size);
5132 if (mono_class_get_cctor (method->klass))
5133 encode_klass_ref (acfg, method->klass, p, &p);
5135 /* Not needed when loading the method */
5136 encode_value (0, p, &p);
5139 if (cfg->opt & MONO_OPT_SHARED) {
5140 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5141 for (l = cfg->ldstr_list; l; l = l->next) {
5142 encode_value ((long)l->data, p, &p);
5146 /* Used only in shared mode */
5147 g_assert (!cfg->ldstr_list);
5150 for (pindex = 0; pindex < patches->len; ++pindex) {
5151 patch_info = g_ptr_array_index (patches, pindex);
5153 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5154 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5155 patch_info->type = MONO_PATCH_INFO_NONE;
5160 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5161 /* Stored in a GOT slot initialized at module load time */
5162 patch_info->type = MONO_PATCH_INFO_NONE;
5166 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5167 /* Stored in a GOT slot initialized at module load time */
5168 patch_info->type = MONO_PATCH_INFO_NONE;
5172 if (is_plt_patch (patch_info)) {
5173 /* Calls are made through the PLT */
5174 patch_info->type = MONO_PATCH_INFO_NONE;
5182 g_assert (cfg->has_got_slots);
5184 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5186 acfg->stats.info_size += p - buf;
5188 g_assert (p - buf < buf_size);
5190 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5195 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5197 guint32 cache_index;
5200 /* Reuse the unwind module to canonize and store unwind info entries */
5201 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5203 /* Use +/- 1 to distinguish 0s from missing entries */
5204 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5212 * It would be easier to use assembler symbols, but the caller needs an
5215 offset = acfg->unwind_info_offset;
5216 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5217 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5220 encode_value (encoded_len, p, &p);
5222 acfg->unwind_info_offset += encoded_len + (p - buf);
5228 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5231 int i, k, buf_size, method_index;
5232 guint32 debug_info_size;
5234 MonoMethodHeader *header;
5235 guint8 *p, *buf, *debug_info;
5236 MonoJitInfo *jinfo = cfg->jit_info;
5238 gboolean use_unwind_ops = FALSE;
5239 MonoSeqPointInfo *seq_points;
5241 method = cfg->orig_method;
5242 code = cfg->native_code;
5243 header = cfg->header;
5245 method_index = get_method_index (acfg, method);
5247 if (!acfg->aot_opts.nodebug) {
5248 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5251 debug_info_size = 0;
5254 seq_points = cfg->seq_point_info;
5256 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 128) : 0) + cfg->gc_map_size;
5257 p = buf = g_malloc (buf_size);
5259 use_unwind_ops = cfg->unwind_ops != NULL;
5261 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);
5263 encode_value (flags, p, &p);
5265 if (use_unwind_ops) {
5266 guint32 encoded_len;
5270 * This is a duplicate of the data in the .debug_frame section, but that
5271 * section cannot be accessed using the dl interface.
5273 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5274 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5277 encode_value (jinfo->used_regs, p, &p);
5280 /*Encode the number of holes before the number of clauses to make decoding easier*/
5281 if (jinfo->has_try_block_holes) {
5282 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5283 encode_value (table->num_holes, p, &p);
5286 /* Exception table */
5287 if (cfg->compile_llvm) {
5289 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5290 * since the information is only available to llc. Instead, we let llc save the data
5291 * into the LSDA, and read it from there at runtime.
5293 /* The assembly might be CIL stripped so emit the data ourselves */
5294 if (header->num_clauses)
5295 encode_value (header->num_clauses, p, &p);
5297 for (k = 0; k < header->num_clauses; ++k) {
5298 MonoExceptionClause *clause;
5300 clause = &header->clauses [k];
5302 encode_value (clause->flags, p, &p);
5303 if (clause->data.catch_class) {
5304 encode_value (1, p, &p);
5305 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5307 encode_value (0, p, &p);
5310 /* Emit a list of nesting clauses */
5311 for (i = 0; i < header->num_clauses; ++i) {
5313 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5315 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5317 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5318 encode_value (i, p, &p);
5320 encode_value (-1, p, &p);
5323 if (jinfo->num_clauses)
5324 encode_value (jinfo->num_clauses, p, &p);
5326 for (k = 0; k < jinfo->num_clauses; ++k) {
5327 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5329 encode_value (ei->flags, p, &p);
5330 encode_value (ei->exvar_offset, p, &p);
5332 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5333 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5335 if (ei->data.catch_class) {
5339 buf2 = g_malloc (4096);
5341 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5343 g_assert (len < 4096);
5344 encode_value (len, p, &p);
5345 memcpy (p, buf2, len);
5349 encode_value (0, p, &p);
5353 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5354 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5355 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5359 if (jinfo->has_try_block_holes) {
5360 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5361 for (i = 0; i < table->num_holes; ++i) {
5362 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5363 encode_value (hole->clause, p, &p);
5364 encode_value (hole->length, p, &p);
5365 encode_value (hole->offset, p, &p);
5369 if (jinfo->has_arch_eh_info) {
5370 MonoArchEHJitInfo *eh_info;
5372 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5373 encode_value (eh_info->stack_size, p, &p);
5376 if (jinfo->has_generic_jit_info) {
5377 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5378 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5384 encode_value (gi->nlocs, p, &p);
5386 for (i = 0; i < gi->nlocs; ++i) {
5387 MonoDwarfLocListEntry *entry = &gi->locations [i];
5389 encode_value (entry->is_reg ? 1 : 0, p, &p);
5390 encode_value (entry->reg, p, &p);
5392 encode_value (entry->offset, p, &p);
5394 g_assert (entry->from == 0);
5396 encode_value (entry->from, p, &p);
5397 encode_value (entry->to, p, &p);
5400 if (!cfg->compile_llvm) {
5401 encode_value (gi->has_this ? 1 : 0, p, &p);
5402 encode_value (gi->this_reg, p, &p);
5403 encode_value (gi->this_offset, p, &p);
5408 * Need to encode jinfo->method too, since it is not equal to 'method'
5409 * when using generic sharing.
5411 buf2 = g_malloc (4096);
5413 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5415 g_assert (len < 4096);
5416 encode_value (len, p, &p);
5417 memcpy (p, buf2, len);
5421 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5422 MonoMethodInflated *inflated;
5423 MonoGenericContext *context;
5424 MonoGenericInst *inst;
5426 g_assert (jinfo->d.method->is_inflated);
5427 inflated = (MonoMethodInflated*)jinfo->d.method;
5428 context = &inflated->context;
5430 encode_value (1, p, &p);
5431 if (context->class_inst) {
5432 inst = context->class_inst;
5434 encode_value (inst->type_argc, p, &p);
5435 for (i = 0; i < inst->type_argc; ++i)
5436 encode_value (gsctx->var_is_vt [i], p, &p);
5438 encode_value (0, p, &p);
5440 if (context->method_inst) {
5441 inst = context->method_inst;
5443 encode_value (inst->type_argc, p, &p);
5444 for (i = 0; i < inst->type_argc; ++i)
5445 encode_value (gsctx->mvar_is_vt [i], p, &p);
5447 encode_value (0, p, &p);
5450 encode_value (0, p, &p);
5455 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5457 encode_value (seq_points->len, p, &p);
5458 last_il_offset = last_native_offset = 0;
5459 for (i = 0; i < seq_points->len; ++i) {
5460 SeqPoint *sp = &seq_points->seq_points [i];
5461 il_offset = sp->il_offset;
5462 native_offset = sp->native_offset;
5463 encode_value (il_offset - last_il_offset, p, &p);
5464 encode_value (native_offset - last_native_offset, p, &p);
5465 last_il_offset = il_offset;
5466 last_native_offset = native_offset;
5468 encode_value (sp->flags, p, &p);
5469 encode_value (sp->next_len, p, &p);
5470 for (j = 0; j < sp->next_len; ++j)
5471 encode_value (sp->next [j], p, &p);
5475 g_assert (debug_info_size < buf_size);
5477 encode_value (debug_info_size, p, &p);
5478 if (debug_info_size) {
5479 memcpy (p, debug_info, debug_info_size);
5480 p += debug_info_size;
5481 g_free (debug_info);
5486 encode_value (cfg->gc_map_size, p, &p);
5487 /* The GC map requires 4 bytes of alignment */
5488 while ((gsize)p % 4)
5490 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5491 p += cfg->gc_map_size;
5494 acfg->stats.ex_info_size += p - buf;
5496 g_assert (p - buf < buf_size);
5499 /* The GC Map requires 4 byte alignment */
5500 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5505 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5507 MonoClass *klass = mono_class_get (acfg->image, token);
5509 int i, buf_size, res;
5510 gboolean no_special_static, cant_encode;
5511 gpointer iter = NULL;
5514 mono_loader_clear_error ();
5518 p = buf = g_malloc (buf_size);
5520 /* Mark as unusable */
5521 encode_value (-1, p, &p);
5523 res = add_to_blob (acfg, buf, p - buf);
5529 buf_size = 10240 + (klass->vtable_size * 16);
5530 p = buf = g_malloc (buf_size);
5534 mono_class_init (klass);
5536 mono_class_get_nested_types (klass, &iter);
5537 g_assert (klass->nested_classes_inited);
5539 mono_class_setup_vtable (klass);
5542 * Emit all the information which is required for creating vtables so
5543 * the runtime does not need to create the MonoMethod structures which
5544 * take up a lot of space.
5547 no_special_static = !mono_class_has_special_static_fields (klass);
5549 /* Check whenever we have enough info to encode the vtable */
5550 cant_encode = FALSE;
5551 for (i = 0; i < klass->vtable_size; ++i) {
5552 MonoMethod *cm = klass->vtable [i];
5554 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5558 mono_class_has_finalizer (klass);
5560 if (klass->generic_container || cant_encode) {
5561 encode_value (-1, p, &p);
5563 encode_value (klass->vtable_size, p, &p);
5564 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);
5565 if (klass->has_cctor)
5566 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5567 if (klass->has_finalize)
5568 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5570 encode_value (klass->instance_size, p, &p);
5571 encode_value (mono_class_data_size (klass), p, &p);
5572 encode_value (klass->packing_size, p, &p);
5573 encode_value (klass->min_align, p, &p);
5575 for (i = 0; i < klass->vtable_size; ++i) {
5576 MonoMethod *cm = klass->vtable [i];
5579 encode_method_ref (acfg, cm, p, &p);
5581 encode_value (0, p, &p);
5585 acfg->stats.class_info_size += p - buf;
5587 g_assert (p - buf < buf_size);
5588 res = add_to_blob (acfg, buf, p - buf);
5595 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5597 char *debug_sym = NULL;
5601 case MONO_PATCH_INFO_METHOD:
5602 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5604 case MONO_PATCH_INFO_INTERNAL_METHOD:
5605 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5607 case MONO_PATCH_INFO_CLASS_INIT:
5608 s = mono_type_get_name (&ji->data.klass->byval_arg);
5609 debug_sym = g_strdup_printf ("plt__class_init_%s", s);
5612 case MONO_PATCH_INFO_RGCTX_FETCH:
5613 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5615 case MONO_PATCH_INFO_ICALL_ADDR: {
5616 char *s = get_debug_sym (ji->data.method, "", cache);
5618 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5622 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5623 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5625 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5626 debug_sym = g_strdup_printf ("plt__generic_class_init");
5632 return sanitize_symbol (acfg, debug_sym);
5636 * Calls made from AOTed code are routed through a table of jumps similar to the
5637 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5638 * control to the AOT runtime through a trampoline.
5641 emit_plt (MonoAotCompile *acfg)
5647 sprintf (symbol, "plt");
5649 emit_section_change (acfg, ".text", 0);
5650 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5651 emit_label (acfg, symbol);
5652 emit_label (acfg, acfg->plt_symbol);
5654 for (i = 0; i < acfg->plt_offset; ++i) {
5655 char *debug_sym = NULL;
5656 MonoPltEntry *plt_entry = NULL;
5661 * The first plt entry is unused.
5665 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5670 * If the target is directly callable, alias the plt symbol to point to
5672 * FIXME: Use this to simplify emit_and_reloc_code ().
5673 * FIXME: Avoid the got slot.
5674 * FIXME: Add support to the binary writer.
5676 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5677 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5680 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5681 /* LLVM calls the PLT entries using bl, so emit a stub */
5682 emit_set_thumb_mode (acfg);
5683 fprintf (acfg->fp, "\n.thumb_func\n");
5684 emit_label (acfg, plt_entry->llvm_symbol);
5685 fprintf (acfg->fp, "bx pc\n");
5686 fprintf (acfg->fp, "nop\n");
5687 emit_set_arm_mode (acfg);
5688 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5690 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5697 debug_sym = plt_entry->debug_sym;
5699 if (acfg->thumb_mixed && !plt_entry->jit_used)
5700 /* Emit only a thumb version */
5703 if (acfg->llvm && !acfg->thumb_mixed)
5704 emit_label (acfg, plt_entry->llvm_symbol);
5707 if (acfg->need_no_dead_strip) {
5708 emit_unset_mode (acfg);
5709 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5711 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5712 emit_label (acfg, debug_sym);
5715 emit_label (acfg, plt_entry->symbol);
5717 arch_emit_plt_entry (acfg, i);
5720 emit_symbol_size (acfg, debug_sym, ".");
5723 if (acfg->thumb_mixed) {
5724 /* Make sure the ARM symbols don't alias the thumb ones */
5725 emit_zero_bytes (acfg, 16);
5728 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5731 for (i = 0; i < acfg->plt_offset; ++i) {
5732 char *debug_sym = NULL;
5733 MonoPltEntry *plt_entry = NULL;
5739 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5742 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5745 /* Skip plt entries not actually called by LLVM code */
5746 if (!plt_entry->llvm_used)
5749 if (acfg->aot_opts.write_symbols) {
5750 if (plt_entry->debug_sym)
5751 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5755 #if defined(TARGET_MACH)
5756 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5757 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5759 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5760 emit_label (acfg, debug_sym);
5762 fprintf (acfg->fp, "\n.thumb_func\n");
5764 emit_label (acfg, plt_entry->llvm_symbol);
5766 arch_emit_llvm_plt_entry (acfg, i);
5769 emit_symbol_size (acfg, debug_sym, ".");
5775 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5777 sprintf (symbol, "plt_end");
5778 emit_label (acfg, symbol);
5782 * emit_trampoline_full:
5784 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5785 * create_jit_info_for_trampoline ().
5787 static G_GNUC_UNUSED void
5788 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5790 char start_symbol [256];
5791 char end_symbol [256];
5793 guint32 buf_size, info_offset;
5794 MonoJumpInfo *patch_info;
5807 code_size = info->code_size;
5809 unwind_ops = info->unwind_ops;
5811 #ifdef __native_client_codegen__
5812 mono_nacl_fix_patches (code, ji);
5817 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5819 emit_section_change (acfg, ".text", 0);
5820 emit_global (acfg, start_symbol, TRUE);
5821 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5822 emit_label (acfg, start_symbol);
5824 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5825 emit_label (acfg, symbol);
5828 * The code should access everything through the GOT, so we pass
5831 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5833 emit_symbol_size (acfg, start_symbol, ".");
5836 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5837 emit_label (acfg, end_symbol);
5842 /* Sort relocations */
5843 patches = g_ptr_array_new ();
5844 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5845 if (patch_info->type != MONO_PATCH_INFO_NONE)
5846 g_ptr_array_add (patches, patch_info);
5847 g_ptr_array_sort (patches, compare_patches);
5849 buf_size = patches->len * 128 + 128;
5850 buf = g_malloc (buf_size);
5853 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5854 g_assert (p - buf < buf_size);
5856 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5858 info_offset = add_to_blob (acfg, buf, p - buf);
5860 emit_section_change (acfg, RODATA_SECT, 0);
5861 emit_global (acfg, symbol, FALSE);
5862 emit_label (acfg, symbol);
5864 emit_int32 (acfg, info_offset);
5868 guint32 encoded_len;
5872 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5874 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5875 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5878 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5879 emit_int32 (acfg, uw_offset);
5882 /* Emit debug info */
5886 sprintf (symbol, "%s", name);
5887 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5890 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5894 static G_GNUC_UNUSED void
5895 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5897 emit_trampoline_full (acfg, got_offset, info, FALSE);
5901 emit_trampolines (MonoAotCompile *acfg)
5904 char end_symbol [256];
5905 int i, tramp_got_offset;
5906 MonoAotTrampoline ntype;
5907 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5911 if (!acfg->aot_opts.full_aot)
5914 g_assert (acfg->image->assembly);
5916 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5917 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5918 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5919 MonoTrampInfo *info;
5922 * Emit the generic trampolines.
5924 * We could save some code by treating the generic trampolines as a wrapper
5925 * method, but that approach has its own complexities, so we choose the simpler
5928 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5929 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5930 #ifdef DISABLE_REMOTING
5931 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5934 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5935 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5938 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5939 emit_trampoline (acfg, acfg->got_offset, info);
5942 mono_arch_get_nullified_class_init_trampoline (&info);
5943 emit_trampoline (acfg, acfg->got_offset, info);
5944 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5945 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5946 emit_trampoline (acfg, acfg->got_offset, info);
5947 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5948 emit_trampoline (acfg, acfg->got_offset, info);
5951 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5952 emit_trampoline (acfg, acfg->got_offset, info);
5954 /* Emit the exception related code pieces */
5955 mono_arch_get_restore_context (&info, TRUE);
5956 emit_trampoline (acfg, acfg->got_offset, info);
5957 mono_arch_get_call_filter (&info, TRUE);
5958 emit_trampoline (acfg, acfg->got_offset, info);
5959 mono_arch_get_throw_exception (&info, TRUE);
5960 emit_trampoline (acfg, acfg->got_offset, info);
5961 mono_arch_get_rethrow_exception (&info, TRUE);
5962 emit_trampoline (acfg, acfg->got_offset, info);
5963 mono_arch_get_throw_corlib_exception (&info, TRUE);
5964 emit_trampoline (acfg, acfg->got_offset, info);
5966 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5967 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5969 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5971 /* Create a separate out trampoline for more information in stack traces */
5972 info->name = g_strdup ("gsharedvt_out_trampoline");
5973 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5977 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5979 GSList *l = mono_arch_get_trampolines (TRUE);
5982 MonoTrampInfo *info = l->data;
5984 emit_trampoline (acfg, acfg->got_offset, info);
5990 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5993 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5994 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5995 emit_trampoline (acfg, acfg->got_offset, info);
5997 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5998 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5999 emit_trampoline (acfg, acfg->got_offset, info);
6002 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6003 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6004 emit_trampoline (acfg, acfg->got_offset, info);
6010 /* delegate_invoke_impl trampolines */
6011 l = mono_arch_get_delegate_invoke_impls ();
6013 MonoTrampInfo *info = l->data;
6015 emit_trampoline (acfg, acfg->got_offset, info);
6020 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6022 /* Emit trampolines which are numerous */
6025 * These include the following:
6026 * - specific trampolines
6027 * - static rgctx invoke trampolines
6029 * These trampolines have the same code, they are parameterized by GOT
6031 * They are defined in this file, in the arch_... routines instead of
6032 * in tramp-<ARCH>.c, since it is easier to do it this way.
6036 * When running in aot-only mode, we can't create specific trampolines at
6037 * runtime, so we create a few, and save them in the AOT file.
6038 * Normal trampolines embed their argument as a literal inside the
6039 * trampoline code, we can't do that here, so instead we embed an offset
6040 * which needs to be added to the trampoline address to get the address of
6041 * the GOT slot which contains the argument value.
6042 * The generated trampolines jump to the generic trampolines using another
6043 * GOT slot, which will be setup by the AOT loader to point to the
6044 * generic trampoline code of the given type.
6048 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6052 emit_section_change (acfg, ".text", 0);
6054 tramp_got_offset = acfg->got_offset;
6056 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6058 case MONO_AOT_TRAMP_SPECIFIC:
6059 sprintf (symbol, "specific_trampolines");
6061 case MONO_AOT_TRAMP_STATIC_RGCTX:
6062 sprintf (symbol, "static_rgctx_trampolines");
6064 case MONO_AOT_TRAMP_IMT_THUNK:
6065 sprintf (symbol, "imt_thunks");
6067 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6068 sprintf (symbol, "gsharedvt_arg_trampolines");
6071 g_assert_not_reached ();
6074 sprintf (end_symbol, "%s_e", symbol);
6076 if (acfg->aot_opts.write_symbols)
6077 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6079 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6080 emit_label (acfg, symbol);
6082 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6084 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6088 case MONO_AOT_TRAMP_SPECIFIC:
6089 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6090 tramp_got_offset += 2;
6092 case MONO_AOT_TRAMP_STATIC_RGCTX:
6093 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6094 tramp_got_offset += 2;
6096 case MONO_AOT_TRAMP_IMT_THUNK:
6097 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6098 tramp_got_offset += 1;
6100 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6101 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6102 tramp_got_offset += 2;
6105 g_assert_not_reached ();
6107 #ifdef __native_client_codegen__
6108 /* align to avoid 32-byte boundary crossings */
6109 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6112 if (!acfg->trampoline_size [ntype]) {
6113 g_assert (tramp_size);
6114 acfg->trampoline_size [ntype] = tramp_size;
6118 emit_label (acfg, end_symbol);
6119 emit_int32 (acfg, 0);
6122 arch_emit_specific_trampoline_pages (acfg);
6124 /* Reserve some entries at the end of the GOT for our use */
6125 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6128 acfg->got_offset += acfg->num_trampoline_got_entries;
6132 str_begins_with (const char *str1, const char *str2)
6134 int len = strlen (str2);
6135 return strncmp (str1, str2, len) == 0;
6139 mono_aot_readonly_field_override (MonoClassField *field)
6142 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6143 char *p = rdv->name;
6145 len = strlen (field->parent->name_space);
6146 if (strncmp (p, field->parent->name_space, len))
6151 len = strlen (field->parent->name);
6152 if (strncmp (p, field->parent->name, len))
6157 if (strcmp (p, field->name))
6159 switch (rdv->type) {
6161 return &rdv->value.i1;
6163 return &rdv->value.i2;
6165 return &rdv->value.i4;
6174 add_readonly_value (MonoAotOptions *opts, const char *val)
6179 /* the format of val is:
6180 * namespace.typename.fieldname=type/value
6181 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6183 fval = strrchr (val, '/');
6185 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6188 tval = strrchr (val, '=');
6190 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6193 rdv = g_new0 (ReadOnlyValue, 1);
6194 rdv->name = g_malloc0 (tval - val + 1);
6195 memcpy (rdv->name, val, tval - val);
6198 if (strncmp (tval, "i1", 2) == 0) {
6199 rdv->value.i1 = atoi (fval);
6200 rdv->type = MONO_TYPE_I1;
6201 } else if (strncmp (tval, "i2", 2) == 0) {
6202 rdv->value.i2 = atoi (fval);
6203 rdv->type = MONO_TYPE_I2;
6204 } else if (strncmp (tval, "i4", 2) == 0) {
6205 rdv->value.i4 = atoi (fval);
6206 rdv->type = MONO_TYPE_I4;
6208 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6211 rdv->next = readonly_values;
6212 readonly_values = rdv;
6216 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6218 gchar **args, **ptr;
6220 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6221 for (ptr = args; ptr && *ptr; ptr ++) {
6222 const char *arg = *ptr;
6224 if (str_begins_with (arg, "outfile=")) {
6225 opts->outfile = g_strdup (arg + strlen ("outfile="));
6226 } else if (str_begins_with (arg, "save-temps")) {
6227 opts->save_temps = TRUE;
6228 } else if (str_begins_with (arg, "keep-temps")) {
6229 opts->save_temps = TRUE;
6230 } else if (str_begins_with (arg, "write-symbols")) {
6231 opts->write_symbols = TRUE;
6232 } else if (str_begins_with (arg, "no-write-symbols")) {
6233 opts->write_symbols = FALSE;
6234 } else if (str_begins_with (arg, "metadata-only")) {
6235 opts->metadata_only = TRUE;
6236 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6237 opts->bind_to_runtime_version = TRUE;
6238 } else if (str_begins_with (arg, "full")) {
6239 opts->full_aot = TRUE;
6240 } else if (str_begins_with (arg, "threads=")) {
6241 opts->nthreads = atoi (arg + strlen ("threads="));
6242 } else if (str_begins_with (arg, "static")) {
6243 opts->static_link = TRUE;
6244 opts->no_dlsym = TRUE;
6245 } else if (str_begins_with (arg, "asmonly")) {
6246 opts->asm_only = TRUE;
6247 } else if (str_begins_with (arg, "asmwriter")) {
6248 opts->asm_writer = TRUE;
6249 } else if (str_begins_with (arg, "nodebug")) {
6250 opts->nodebug = TRUE;
6251 } else if (str_begins_with (arg, "dwarfdebug")) {
6252 opts->dwarf_debug = TRUE;
6253 } else if (str_begins_with (arg, "nopagetrampolines")) {
6254 opts->use_trampolines_page = FALSE;
6255 } else if (str_begins_with (arg, "ntrampolines=")) {
6256 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6257 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6258 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6259 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6260 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6261 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6262 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6263 } else if (str_begins_with (arg, "autoreg")) {
6264 opts->autoreg = TRUE;
6265 } else if (str_begins_with (arg, "tool-prefix=")) {
6266 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6267 } else if (str_begins_with (arg, "soft-debug")) {
6268 opts->soft_debug = TRUE;
6269 } else if (str_begins_with (arg, "direct-pinvoke")) {
6270 opts->direct_pinvoke = TRUE;
6271 } else if (str_begins_with (arg, "direct-icalls")) {
6272 opts->direct_icalls = TRUE;
6273 #if defined(TARGET_ARM)
6274 } else if (str_begins_with (arg, "iphone-abi")) {
6275 // older full-aot users did depend on this.
6277 } else if (str_begins_with (arg, "no-direct-calls")) {
6278 opts->no_direct_calls = TRUE;
6279 } else if (str_begins_with (arg, "print-skipped")) {
6280 opts->print_skipped_methods = TRUE;
6281 } else if (str_begins_with (arg, "stats")) {
6283 } else if (str_begins_with (arg, "no-instances")) {
6284 opts->no_instances = TRUE;
6285 } else if (str_begins_with (arg, "log-generics")) {
6286 opts->log_generics = TRUE;
6287 } else if (str_begins_with (arg, "mtriple=")) {
6288 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6289 } else if (str_begins_with (arg, "llvm-path=")) {
6290 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6291 } else if (str_begins_with (arg, "readonly-value=")) {
6292 add_readonly_value (opts, arg + strlen ("readonly-value="));
6293 } else if (str_begins_with (arg, "info")) {
6294 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6296 } else if (str_begins_with (arg, "gc-maps")) {
6297 mini_gc_enable_gc_maps_for_aot ();
6298 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6299 printf ("Supported options for --aot:\n");
6300 printf (" outfile=\n");
6301 printf (" save-temps\n");
6302 printf (" keep-temps\n");
6303 printf (" write-symbols\n");
6304 printf (" metadata-only\n");
6305 printf (" bind-to-runtime-version\n");
6307 printf (" threads=\n");
6308 printf (" static\n");
6309 printf (" asmonly\n");
6310 printf (" asmwriter\n");
6311 printf (" nodebug\n");
6312 printf (" dwarfdebug\n");
6313 printf (" ntrampolines=\n");
6314 printf (" nrgctx-trampolines=\n");
6315 printf (" nimt-trampolines=\n");
6316 printf (" ngsharedvt-trampolines=\n");
6317 printf (" autoreg\n");
6318 printf (" tool-prefix=\n");
6319 printf (" readonly-value=\n");
6320 printf (" soft-debug\n");
6321 printf (" gc-maps\n");
6322 printf (" print-skipped\n");
6323 printf (" no-instances\n");
6324 printf (" stats\n");
6326 printf (" help/?\n");
6329 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6334 if (opts->use_trampolines_page) {
6335 opts->ntrampolines = 0;
6336 opts->nrgctx_trampolines = 0;
6337 opts->nimt_trampolines = 0;
6338 opts->ngsharedvt_arg_trampolines = 0;
6344 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6346 MonoMethod *method = (MonoMethod*)key;
6347 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6348 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6349 MonoAotCompile *acfg = user_data;
6351 new_ji->image = ji->image;
6352 new_ji->token = ji->token;
6353 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6357 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6359 if (klass->type_token)
6361 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6364 return can_encode_class (acfg, klass->element_class);
6369 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6371 if (method->wrapper_type) {
6372 switch (method->wrapper_type) {
6373 case MONO_WRAPPER_NONE:
6374 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6375 case MONO_WRAPPER_XDOMAIN_INVOKE:
6376 case MONO_WRAPPER_STFLD:
6377 case MONO_WRAPPER_LDFLD:
6378 case MONO_WRAPPER_LDFLDA:
6379 case MONO_WRAPPER_LDFLD_REMOTE:
6380 case MONO_WRAPPER_STFLD_REMOTE:
6381 case MONO_WRAPPER_STELEMREF:
6382 case MONO_WRAPPER_ISINST:
6383 case MONO_WRAPPER_PROXY_ISINST:
6384 case MONO_WRAPPER_ALLOC:
6385 case MONO_WRAPPER_REMOTING_INVOKE:
6386 case MONO_WRAPPER_UNKNOWN:
6387 case MONO_WRAPPER_WRITE_BARRIER:
6388 case MONO_WRAPPER_DELEGATE_INVOKE:
6389 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6390 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6391 case MONO_WRAPPER_SYNCHRONIZED:
6393 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6394 case MONO_WRAPPER_CASTCLASS: {
6395 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6404 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6408 if (!method->token) {
6409 /* The method is part of a constructed type like Int[,].Set (). */
6410 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6411 if (method->klass->rank)
6421 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6423 switch (patch_info->type) {
6424 case MONO_PATCH_INFO_METHOD:
6425 case MONO_PATCH_INFO_METHODCONST:
6426 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6427 MonoMethod *method = patch_info->data.method;
6429 return can_encode_method (acfg, method);
6431 case MONO_PATCH_INFO_VTABLE:
6432 case MONO_PATCH_INFO_CLASS_INIT:
6433 case MONO_PATCH_INFO_CLASS:
6434 case MONO_PATCH_INFO_IID:
6435 case MONO_PATCH_INFO_ADJUSTED_IID:
6436 if (!can_encode_class (acfg, patch_info->data.klass)) {
6437 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6441 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6442 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6443 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6448 case MONO_PATCH_INFO_RGCTX_FETCH: {
6449 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6451 if (!can_encode_method (acfg, entry->method))
6453 if (!can_encode_patch (acfg, entry->data))
6467 * AOT compile a given method.
6468 * This function might be called by multiple threads, so it must be thread-safe.
6471 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6474 MonoJumpInfo *patch_info;
6477 MonoMethod *wrapped;
6479 if (acfg->aot_opts.metadata_only)
6482 mono_acfg_lock (acfg);
6483 index = get_method_index (acfg, method);
6484 mono_acfg_unlock (acfg);
6486 /* fixme: maybe we can also precompile wrapper methods */
6487 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6488 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6489 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6490 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6494 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6497 wrapped = mono_marshal_method_from_wrapper (method);
6498 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6499 // FIXME: The wrapper should be generic too, but it is not
6502 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6505 InterlockedIncrement (&acfg->stats.mcount);
6508 if (method->is_generic || method->klass->generic_container) {
6509 InterlockedIncrement (&acfg->stats.genericcount);
6514 //acfg->aot_opts.print_skipped_methods = TRUE;
6517 * Since these methods are the only ones which are compiled with
6518 * AOT support, and they are not used by runtime startup/shutdown code,
6519 * the runtime will not see AOT methods during AOT compilation,so it
6520 * does not need to support them by creating a fake GOT etc.
6522 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);
6523 mono_loader_clear_error ();
6525 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6526 if (acfg->aot_opts.print_skipped_methods)
6527 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6528 InterlockedIncrement (&acfg->stats.genericcount);
6531 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6532 if (acfg->aot_opts.print_skipped_methods)
6533 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6534 /* Let the exception happen at runtime */
6538 if (cfg->disable_aot) {
6539 if (acfg->aot_opts.print_skipped_methods)
6540 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6541 InterlockedIncrement (&acfg->stats.ocount);
6542 mono_destroy_compile (cfg);
6545 cfg->method_index = index;
6547 /* Nullify patches which need no aot processing */
6548 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6549 switch (patch_info->type) {
6550 case MONO_PATCH_INFO_LABEL:
6551 case MONO_PATCH_INFO_BB:
6552 patch_info->type = MONO_PATCH_INFO_NONE;
6559 /* Collect method->token associations from the cfg */
6560 mono_acfg_lock (acfg);
6561 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6562 mono_acfg_unlock (acfg);
6565 * Check for absolute addresses.
6568 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6569 switch (patch_info->type) {
6570 case MONO_PATCH_INFO_ABS:
6571 /* unable to handle this */
6580 if (acfg->aot_opts.print_skipped_methods)
6581 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6582 InterlockedIncrement (&acfg->stats.abscount);
6583 mono_destroy_compile (cfg);
6587 /* Lock for the rest of the code */
6588 mono_acfg_lock (acfg);
6591 * Check for methods/klasses we can't encode.
6594 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6595 if (!can_encode_patch (acfg, patch_info))
6600 if (acfg->aot_opts.print_skipped_methods)
6601 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6602 acfg->stats.ocount++;
6603 mono_destroy_compile (cfg);
6604 mono_acfg_unlock (acfg);
6608 /* Adds generic instances referenced by this method */
6610 * The depth is used to avoid infinite loops when generic virtual recursion is
6613 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6614 if (!acfg->aot_opts.no_instances && depth < 32) {
6615 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6616 switch (patch_info->type) {
6617 case MONO_PATCH_INFO_METHOD: {
6618 MonoMethod *m = patch_info->data.method;
6619 if (m->is_inflated) {
6620 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6621 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6622 !method_has_type_vars (m)) {
6623 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6624 if (acfg->aot_opts.full_aot)
6625 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6627 add_extra_method_with_depth (acfg, m, depth + 1);
6628 add_types_from_method_header (acfg, m);
6631 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6633 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6634 add_extra_method_with_depth (acfg, m, depth + 1);
6637 case MONO_PATCH_INFO_VTABLE: {
6638 MonoClass *klass = patch_info->data.klass;
6640 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6641 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6644 case MONO_PATCH_INFO_SFLDA: {
6645 MonoClass *klass = patch_info->data.field->parent;
6647 /* The .cctor needs to run at runtime. */
6648 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6649 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6658 /* Determine whenever the method has GOT slots */
6659 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6660 switch (patch_info->type) {
6661 case MONO_PATCH_INFO_GOT_OFFSET:
6662 case MONO_PATCH_INFO_NONE:
6663 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6665 case MONO_PATCH_INFO_IMAGE:
6666 /* The assembly is stored in GOT slot 0 */
6667 if (patch_info->data.image != acfg->image)
6668 cfg->has_got_slots = TRUE;
6671 if (!is_plt_patch (patch_info))
6672 cfg->has_got_slots = TRUE;
6677 if (!cfg->has_got_slots)
6678 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6681 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6683 /* Make a copy of the patch info which is in the mempool */
6685 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6687 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6688 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6691 patches = new_patch_info;
6693 patches_end->next = new_patch_info;
6694 patches_end = new_patch_info;
6696 cfg->patch_info = patches;
6698 /* Make a copy of the unwind info */
6700 GSList *l, *unwind_ops;
6704 for (l = cfg->unwind_ops; l; l = l->next) {
6705 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6706 memcpy (op, l->data, sizeof (MonoUnwindOp));
6707 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6709 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6711 /* Make a copy of the argument/local info */
6713 MonoInst **args, **locals;
6714 MonoMethodSignature *sig;
6715 MonoMethodHeader *header;
6718 sig = mono_method_signature (method);
6719 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6720 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6721 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6722 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6726 header = mono_method_get_header (method);
6727 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6728 for (i = 0; i < header->num_locals; ++i) {
6729 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6730 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6732 cfg->locals = locals;
6735 /* Free some fields used by cfg to conserve memory */
6736 mono_mempool_destroy (cfg->mempool);
6737 cfg->mempool = NULL;
6738 g_free (cfg->varinfo);
6739 cfg->varinfo = NULL;
6743 mono_regstate_free (cfg->rs);
6747 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6749 while (index >= acfg->cfgs_size) {
6750 MonoCompile **new_cfgs;
6753 new_size = acfg->cfgs_size * 2;
6754 new_cfgs = g_new0 (MonoCompile*, new_size);
6755 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6756 g_free (acfg->cfgs);
6757 acfg->cfgs = new_cfgs;
6758 acfg->cfgs_size = new_size;
6760 acfg->cfgs [index] = cfg;
6762 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6765 if (cfg->orig_method->wrapper_type)
6766 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6769 mono_acfg_unlock (acfg);
6771 InterlockedIncrement (&acfg->stats.ccount);
6775 compile_thread_main (gpointer *user_data)
6777 MonoDomain *domain = user_data [0];
6778 MonoAotCompile *acfg = user_data [1];
6779 GPtrArray *methods = user_data [2];
6782 mono_thread_attach (domain);
6784 for (i = 0; i < methods->len; ++i)
6785 compile_method (acfg, g_ptr_array_index (methods, i));
6789 load_profile_files (MonoAotCompile *acfg)
6793 int file_index, res, method_index, i;
6796 GList *unordered, *l;
6801 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6803 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6808 infile = fopen (tmp, "r");
6811 printf ("Using profile data file '%s'\n", tmp);
6816 res = fscanf (infile, "%32s\n", ver);
6817 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6818 printf ("Profile file has wrong version or invalid.\n");
6825 MonoMethodDesc *desc;
6828 if (fgets (name, 1023, infile) == NULL)
6831 /* Kill the newline */
6832 if (strlen (name) > 0)
6833 name [strlen (name) - 1] = '\0';
6835 desc = mono_method_desc_new (name, TRUE);
6837 method = mono_method_desc_search_in_image (desc, acfg->image);
6839 if (method && mono_method_get_token (method)) {
6840 token = mono_method_get_token (method);
6841 method_index = mono_metadata_token_index (token) - 1;
6844 for (i = 0; i < acfg->method_order->len; ++i) {
6845 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6851 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6853 //printf ("No method found matching '%s'.\n", name);
6859 /* Add missing methods */
6861 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6863 for (i = 0; i < acfg->method_order->len; ++i) {
6864 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6870 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6872 unordered = g_list_reverse (unordered);
6873 for (l = unordered; l; l = l->next)
6874 g_ptr_array_add (acfg->method_order, l->data);
6877 /* Used by the LLVM backend */
6879 mono_aot_get_got_offset (MonoJumpInfo *ji)
6881 return get_got_offset (llvm_acfg, ji);
6885 mono_aot_get_method_name (MonoCompile *cfg)
6887 if (llvm_acfg->aot_opts.static_link)
6888 /* Include the assembly name too to avoid duplicate symbol errors */
6889 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6891 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6895 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6897 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6898 MonoPltEntry *plt_entry;
6901 ji->data.target = data;
6903 if (!can_encode_patch (llvm_acfg, ji))
6906 plt_entry = get_plt_entry (llvm_acfg, ji);
6907 plt_entry->llvm_used = TRUE;
6909 #if defined(TARGET_MACH)
6910 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6912 return g_strdup_printf (plt_entry->llvm_symbol);
6917 mono_aot_get_method_index (MonoMethod *method)
6919 g_assert (llvm_acfg);
6920 return get_method_index (llvm_acfg, method);
6924 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6928 mono_acfg_lock (llvm_acfg);
6929 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6930 mono_acfg_unlock (llvm_acfg);
6940 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6944 emit_llvm_file (MonoAotCompile *acfg)
6946 char *command, *opts, *tempbc;
6948 MonoJumpInfo *patch_info;
6951 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6955 /* Compute the final size of the got */
6956 for (i = 0; i < acfg->nmethods; ++i) {
6957 if (acfg->cfgs [i]) {
6958 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6959 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6960 if (!is_plt_patch (patch_info))
6961 get_got_offset (acfg, patch_info);
6963 get_plt_entry (acfg, patch_info);
6969 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6971 if (acfg->aot_opts.full_aot) {
6975 * Need to add the got entries used by the trampolines.
6976 * This is only a conservative approximation.
6978 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6979 /* For the generic + rgctx trampolines */
6980 acfg->final_got_size += 400;
6981 /* For the specific trampolines */
6982 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6983 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6988 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
6989 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6993 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6994 * a lot of time, and doesn't seem to save much space.
6995 * The following optimizations cannot be enabled:
6997 * - 'jump-threading' changes our blockaddress references to int constants.
6998 * - 'basiccg' fails because it contains:
6999 * if (CS && !isa<IntrinsicInst>(II)) {
7000 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7001 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7002 * The opt list below was produced by taking the output of:
7003 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7004 * then removing tailcallelim + the global opts.
7005 * strip-dead-prototypes deletes unused intrinsics definitions.
7007 opts = g_strdup ("-instcombine -simplifycfg");
7008 //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");
7009 /* The dse pass is disabled because of #13734 and #17616 */
7011 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7012 * // If we have no DataLayout information around, then the size of the store
7013 * // is inferrable from the pointee type. If they are the same type, then
7014 * // we know that the store is safe.
7015 * if (AA.getDataLayout() == 0 &&
7016 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7017 * return OverwriteComplete;
7018 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7020 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");
7022 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7023 printf ("Executing opt: %s\n", command);
7024 if (system (command) != 0) {
7030 if (!acfg->llc_args)
7031 acfg->llc_args = g_string_new ("");
7033 /* Verbose asm slows down llc greatly */
7034 g_string_append (acfg->llc_args, " -asm-verbose=false");
7036 if (acfg->aot_opts.mtriple)
7037 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7039 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7040 /* ios requires PIC code now */
7041 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7043 if (llvm_acfg->aot_opts.static_link)
7044 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7046 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7048 unlink (acfg->tmpfname);
7050 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);
7052 printf ("Executing llc: %s\n", command);
7054 if (system (command) != 0) {
7061 emit_code (MonoAotCompile *acfg)
7063 int oindex, i, prev_index;
7066 #if defined(TARGET_POWERPC64)
7067 sprintf (symbol, ".Lgot_addr");
7068 emit_section_change (acfg, ".text", 0);
7069 emit_alignment (acfg, 8);
7070 emit_label (acfg, symbol);
7071 emit_pointer (acfg, acfg->got_symbol);
7075 * This global symbol is used to compute the address of each method using the
7076 * code_offsets array. It is also used to compute the memory ranges occupied by
7077 * AOT code, so it must be equal to the address of the first emitted method.
7079 emit_section_change (acfg, ".text", 0);
7080 emit_alignment (acfg, 8);
7082 for (i = 0; i < acfg->nmethods; ++i) {
7083 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7084 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7089 if (!acfg->methods_symbol) {
7090 sprintf (symbol, "methods");
7091 emit_label (acfg, symbol);
7092 acfg->methods_symbol = g_strdup (symbol);
7096 * Emit some padding so the local symbol for the first method doesn't have the
7097 * same address as 'methods'.
7099 #if defined(__default_codegen__)
7100 emit_zero_bytes (acfg, 16);
7101 #elif defined(__native_client_codegen__)
7103 const int kPaddingSize = 16;
7104 guint8 pad_buffer[kPaddingSize];
7105 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7106 emit_bytes (acfg, pad_buffer, kPaddingSize);
7110 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7114 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7116 cfg = acfg->cfgs [i];
7121 method = cfg->orig_method;
7123 /* Emit unbox trampoline */
7124 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7125 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7127 emit_section_change (acfg, ".text", 0);
7128 #ifdef __native_client_codegen__
7129 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7132 if (acfg->thumb_mixed && cfg->compile_llvm) {
7133 emit_set_thumb_mode (acfg);
7134 fprintf (acfg->fp, "\n.thumb_func\n");
7137 emit_label (acfg, symbol);
7139 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7141 if (acfg->thumb_mixed && cfg->compile_llvm) {
7142 emit_set_arm_mode (acfg);
7146 if (cfg->compile_llvm)
7147 acfg->stats.llvm_count ++;
7149 emit_method_code (acfg, cfg);
7152 sprintf (symbol, "methods_end");
7153 emit_section_change (acfg, ".text", 0);
7154 emit_alignment (acfg, 8);
7155 emit_label (acfg, symbol);
7156 /* To distinguish it from the next symbol */
7157 emit_int32 (acfg, 0);
7160 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7161 * from optimizing them away, since it doesn't see that code_offsets references them.
7162 * JITted methods don't need this since they are referenced using assembler local
7164 * FIXME: This is why write-symbols doesn't work on OSX ?
7166 if (acfg->llvm && acfg->need_no_dead_strip) {
7167 fprintf (acfg->fp, "\n");
7168 for (i = 0; i < acfg->nmethods; ++i) {
7169 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7170 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7174 if (acfg->direct_method_addresses) {
7175 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7178 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7179 * This is PIE code, and the linker can update it if needed.
7181 sprintf (symbol, "method_addresses");
7182 emit_section_change (acfg, ".text", 1);
7183 emit_alignment (acfg, 8);
7184 emit_label (acfg, symbol);
7185 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7186 emit_unset_mode (acfg);
7187 if (acfg->need_no_dead_strip)
7188 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7190 for (i = 0; i < acfg->nmethods; ++i) {
7193 #ifdef MONO_ARCH_AOT_SUPPORTED
7195 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7197 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7201 sprintf (symbol, "method_addresses_end");
7202 emit_label (acfg, symbol);
7205 sprintf (symbol, "code_offsets");
7206 emit_section_change (acfg, RODATA_SECT, 1);
7207 emit_alignment (acfg, 8);
7208 emit_label (acfg, symbol);
7209 emit_int32 (acfg, 0);
7211 sprintf (symbol, "code_offsets");
7212 emit_section_change (acfg, RODATA_SECT, 1);
7213 emit_alignment (acfg, 8);
7214 emit_label (acfg, symbol);
7216 acfg->stats.offsets_size += acfg->nmethods * 4;
7218 for (i = 0; i < acfg->nmethods; ++i) {
7219 if (acfg->cfgs [i]) {
7220 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7222 emit_int32 (acfg, 0xffffffff);
7228 /* Emit a sorted table mapping methods to their unbox trampolines */
7229 sprintf (symbol, "unbox_trampolines");
7230 if (acfg->direct_method_addresses)
7231 emit_section_change (acfg, ".text", 0);
7233 emit_section_change (acfg, RODATA_SECT, 0);
7234 emit_alignment (acfg, 8);
7235 emit_label (acfg, symbol);
7238 for (i = 0; i < acfg->nmethods; ++i) {
7243 cfg = acfg->cfgs [i];
7247 method = cfg->orig_method;
7249 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7252 index = get_method_index (acfg, method);
7253 sprintf (symbol, "ut_%d", index);
7255 emit_int32 (acfg, index);
7256 if (acfg->direct_method_addresses) {
7257 #ifdef MONO_ARCH_AOT_SUPPORTED
7258 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7261 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7263 /* Make sure the table is sorted by index */
7264 g_assert (index > prev_index);
7268 sprintf (symbol, "unbox_trampolines_end");
7269 emit_label (acfg, symbol);
7270 emit_int32 (acfg, 0);
7274 emit_info (MonoAotCompile *acfg)
7280 offsets = g_new0 (gint32, acfg->nmethods);
7282 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7283 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7285 if (acfg->cfgs [i]) {
7286 emit_method_info (acfg, acfg->cfgs [i]);
7287 offsets [i] = acfg->cfgs [i]->method_info_offset;
7293 sprintf (symbol, "method_info_offsets");
7294 emit_section_change (acfg, RODATA_SECT, 1);
7295 emit_alignment (acfg, 8);
7296 emit_label (acfg, symbol);
7298 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7303 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7305 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7306 #define mix(a,b,c) { \
7307 a -= c; a ^= rot(c, 4); c += b; \
7308 b -= a; b ^= rot(a, 6); a += c; \
7309 c -= b; c ^= rot(b, 8); b += a; \
7310 a -= c; a ^= rot(c,16); c += b; \
7311 b -= a; b ^= rot(a,19); a += c; \
7312 c -= b; c ^= rot(b, 4); b += a; \
7314 #define final(a,b,c) { \
7315 c ^= b; c -= rot(b,14); \
7316 a ^= c; a -= rot(c,11); \
7317 b ^= a; b -= rot(a,25); \
7318 c ^= b; c -= rot(b,16); \
7319 a ^= c; a -= rot(c,4); \
7320 b ^= a; b -= rot(a,14); \
7321 c ^= b; c -= rot(b,24); \
7325 mono_aot_type_hash (MonoType *t1)
7327 guint hash = t1->type;
7329 hash |= t1->byref << 6; /* do not collide with t1->type values */
7331 case MONO_TYPE_VALUETYPE:
7332 case MONO_TYPE_CLASS:
7333 case MONO_TYPE_SZARRAY:
7334 /* check if the distribution is good enough */
7335 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7337 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7338 case MONO_TYPE_ARRAY:
7339 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7340 case MONO_TYPE_GENERICINST:
7341 return ((hash << 5) - hash) ^ 0;
7348 * mono_aot_method_hash:
7350 * Return a hash code for methods which only depends on metadata.
7353 mono_aot_method_hash (MonoMethod *method)
7355 MonoMethodSignature *sig;
7359 guint32 *hashes_start, *hashes;
7361 MonoGenericInst *ginst = NULL;
7363 /* Similar to the hash in mono_method_get_imt_slot () */
7365 sig = mono_method_signature (method);
7367 if (method->is_inflated)
7368 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7370 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7371 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7372 hashes = hashes_start;
7374 /* Some wrappers are assigned to random classes */
7375 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7376 klass = method->klass;
7378 klass = mono_defaults.object_class;
7380 if (!method->wrapper_type) {
7381 char *full_name = mono_type_full_name (&klass->byval_arg);
7383 hashes [0] = mono_metadata_str_hash (full_name);
7387 hashes [0] = mono_metadata_str_hash (klass->name);
7388 hashes [1] = mono_metadata_str_hash (klass->name_space);
7390 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7391 /* The method name includes a stringified pointer */
7394 hashes [2] = mono_metadata_str_hash (method->name);
7395 hashes [3] = method->wrapper_type;
7396 hashes [4] = mono_aot_type_hash (sig->ret);
7398 for (i = 0; i < sig->param_count; i++) {
7399 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7402 for (i = 0; i < ginst->type_argc; ++i)
7403 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7405 g_assert (hindex == hashes_count);
7407 /* Setup internal state */
7408 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7410 /* Handle most of the hashes */
7411 while (hashes_count > 3) {
7420 /* Handle the last 3 hashes (all the case statements fall through) */
7421 switch (hashes_count) {
7422 case 3 : c += hashes [2];
7423 case 2 : b += hashes [1];
7424 case 1 : a += hashes [0];
7426 case 0: /* nothing left to add */
7430 free (hashes_start);
7439 * mono_aot_get_array_helper_from_wrapper;
7441 * Get the helper method in Array called by an array wrapper method.
7444 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7448 MonoGenericContext ctx;
7449 MonoType *args [16];
7450 char *mname, *iname, *s, *s2, *helper_name = NULL;
7452 prefix = "System.Collections.Generic";
7453 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7454 s2 = strstr (s, "`1.");
7460 //printf ("X: %s %s\n", iname, mname);
7462 if (!strcmp (iname, "IList"))
7463 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7465 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7466 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7468 g_free (helper_name);
7471 if (m->is_generic) {
7472 memset (&ctx, 0, sizeof (ctx));
7473 args [0] = &method->klass->element_class->byval_arg;
7474 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7475 m = mono_class_inflate_generic_method (m, &ctx);
7481 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7483 typedef struct HashEntry {
7484 guint32 key, value, index;
7485 struct HashEntry *next;
7489 * emit_extra_methods:
7491 * Emit methods which are not in the METHOD table, like wrappers.
7494 emit_extra_methods (MonoAotCompile *acfg)
7496 int i, table_size, buf_size;
7499 guint32 *info_offsets;
7502 HashEntry *entry, *new_entry;
7503 int nmethods, max_chain_length;
7506 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7508 /* Emit method info */
7510 for (i = 0; i < acfg->extra_methods->len; ++i) {
7511 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7512 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7518 p = buf = g_malloc (buf_size);
7522 method = cfg->method_to_register;
7524 encode_method_ref (acfg, method, p, &p);
7526 g_assert ((p - buf) < buf_size);
7528 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7533 * Construct a chained hash table for mapping indexes in extra_method_info to
7536 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7537 table = g_ptr_array_sized_new (table_size);
7538 for (i = 0; i < table_size; ++i)
7539 g_ptr_array_add (table, NULL);
7540 chain_lengths = g_new0 (int, table_size);
7541 max_chain_length = 0;
7542 for (i = 0; i < acfg->extra_methods->len; ++i) {
7543 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7544 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7550 key = info_offsets [i];
7551 value = get_method_index (acfg, method);
7553 hash = mono_aot_method_hash (method) % table_size;
7554 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7556 chain_lengths [hash] ++;
7557 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7559 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7560 new_entry->key = key;
7561 new_entry->value = value;
7563 entry = g_ptr_array_index (table, hash);
7564 if (entry == NULL) {
7565 new_entry->index = hash;
7566 g_ptr_array_index (table, hash) = new_entry;
7569 entry = entry->next;
7571 entry->next = new_entry;
7572 new_entry->index = table->len;
7573 g_ptr_array_add (table, new_entry);
7577 //printf ("MAX: %d\n", max_chain_length);
7579 /* Emit the table */
7580 sprintf (symbol, "extra_method_table");
7581 emit_section_change (acfg, RODATA_SECT, 0);
7582 emit_alignment (acfg, 8);
7583 emit_label (acfg, symbol);
7585 emit_int32 (acfg, table_size);
7586 for (i = 0; i < table->len; ++i) {
7587 HashEntry *entry = g_ptr_array_index (table, i);
7589 if (entry == NULL) {
7590 emit_int32 (acfg, 0);
7591 emit_int32 (acfg, 0);
7592 emit_int32 (acfg, 0);
7594 //g_assert (entry->key > 0);
7595 emit_int32 (acfg, entry->key);
7596 emit_int32 (acfg, entry->value);
7598 emit_int32 (acfg, entry->next->index);
7600 emit_int32 (acfg, 0);
7605 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7606 * This is used by mono_aot_find_jit_info ().
7608 sprintf (symbol, "extra_method_info_offsets");
7609 emit_section_change (acfg, RODATA_SECT, 0);
7610 emit_alignment (acfg, 8);
7611 emit_label (acfg, symbol);
7613 emit_int32 (acfg, acfg->extra_methods->len);
7614 for (i = 0; i < acfg->extra_methods->len; ++i) {
7615 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7617 emit_int32 (acfg, get_method_index (acfg, method));
7618 emit_int32 (acfg, info_offsets [i]);
7623 emit_exception_info (MonoAotCompile *acfg)
7629 offsets = g_new0 (gint32, acfg->nmethods);
7630 for (i = 0; i < acfg->nmethods; ++i) {
7631 if (acfg->cfgs [i]) {
7632 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7633 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7639 sprintf (symbol, "ex_info_offsets");
7640 emit_section_change (acfg, RODATA_SECT, 1);
7641 emit_alignment (acfg, 8);
7642 emit_label (acfg, symbol);
7644 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7649 emit_unwind_info (MonoAotCompile *acfg)
7655 * The unwind info contains a lot of duplicates so we emit each unique
7656 * entry once, and only store the offset from the start of the table in the
7660 sprintf (symbol, "unwind_info");
7661 emit_section_change (acfg, RODATA_SECT, 1);
7662 emit_alignment (acfg, 8);
7663 emit_label (acfg, symbol);
7665 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7666 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7667 guint8 *unwind_info;
7668 guint32 unwind_info_len;
7672 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7675 encode_value (unwind_info_len, p, &p);
7676 emit_bytes (acfg, buf, p - buf);
7677 emit_bytes (acfg, unwind_info, unwind_info_len);
7679 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7684 emit_class_info (MonoAotCompile *acfg)
7690 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7691 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7692 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7694 sprintf (symbol, "class_info_offsets");
7695 emit_section_change (acfg, RODATA_SECT, 1);
7696 emit_alignment (acfg, 8);
7697 emit_label (acfg, symbol);
7699 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7703 typedef struct ClassNameTableEntry {
7704 guint32 token, index;
7705 struct ClassNameTableEntry *next;
7706 } ClassNameTableEntry;
7709 emit_class_name_table (MonoAotCompile *acfg)
7712 guint32 token, hash;
7717 ClassNameTableEntry *entry, *new_entry;
7720 * Construct a chained hash table for mapping class names to typedef tokens.
7722 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7723 table = g_ptr_array_sized_new (table_size);
7724 for (i = 0; i < table_size; ++i)
7725 g_ptr_array_add (table, NULL);
7726 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7727 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7728 klass = mono_class_get (acfg->image, token);
7730 mono_loader_clear_error ();
7733 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7734 hash = mono_metadata_str_hash (full_name) % table_size;
7737 /* FIXME: Allocate from the mempool */
7738 new_entry = g_new0 (ClassNameTableEntry, 1);
7739 new_entry->token = token;
7741 entry = g_ptr_array_index (table, hash);
7742 if (entry == NULL) {
7743 new_entry->index = hash;
7744 g_ptr_array_index (table, hash) = new_entry;
7747 entry = entry->next;
7749 entry->next = new_entry;
7750 new_entry->index = table->len;
7751 g_ptr_array_add (table, new_entry);
7755 /* Emit the table */
7756 sprintf (symbol, "class_name_table");
7757 emit_section_change (acfg, RODATA_SECT, 0);
7758 emit_alignment (acfg, 8);
7759 emit_label (acfg, symbol);
7761 /* FIXME: Optimize memory usage */
7762 g_assert (table_size < 65000);
7763 emit_int16 (acfg, table_size);
7764 g_assert (table->len < 65000);
7765 for (i = 0; i < table->len; ++i) {
7766 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7768 if (entry == NULL) {
7769 emit_int16 (acfg, 0);
7770 emit_int16 (acfg, 0);
7772 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7774 emit_int16 (acfg, entry->next->index);
7776 emit_int16 (acfg, 0);
7782 emit_image_table (MonoAotCompile *acfg)
7788 * The image table is small but referenced in a lot of places.
7789 * So we emit it at once, and reference its elements by an index.
7792 sprintf (symbol, "image_table");
7793 emit_section_change (acfg, RODATA_SECT, 1);
7794 emit_alignment (acfg, 8);
7795 emit_label (acfg, symbol);
7797 emit_int32 (acfg, acfg->image_table->len);
7798 for (i = 0; i < acfg->image_table->len; i++) {
7799 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7800 MonoAssemblyName *aname = &image->assembly->aname;
7802 /* FIXME: Support multi-module assemblies */
7803 g_assert (image->assembly->image == image);
7805 emit_string (acfg, image->assembly_name);
7806 emit_string (acfg, image->guid);
7807 emit_string (acfg, aname->culture ? aname->culture : "");
7808 emit_string (acfg, (const char*)aname->public_key_token);
7810 emit_alignment (acfg, 8);
7811 emit_int32 (acfg, aname->flags);
7812 emit_int32 (acfg, aname->major);
7813 emit_int32 (acfg, aname->minor);
7814 emit_int32 (acfg, aname->build);
7815 emit_int32 (acfg, aname->revision);
7820 emit_got_info (MonoAotCompile *acfg)
7823 int i, first_plt_got_patch, buf_size;
7825 guint32 *got_info_offsets;
7827 /* Add the patches needed by the PLT to the GOT */
7828 acfg->plt_got_offset_base = acfg->got_offset;
7829 first_plt_got_patch = acfg->got_patches->len;
7830 for (i = 1; i < acfg->plt_offset; ++i) {
7831 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7833 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7835 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7838 acfg->got_offset += acfg->plt_offset;
7842 * - optimize offsets table.
7843 * - reduce number of exported symbols.
7844 * - emit info for a klass only once.
7845 * - determine when a method uses a GOT slot which is guaranteed to be already
7847 * - clean up and document the code.
7848 * - use String.Empty in class libs.
7851 /* Encode info required to decode shared GOT entries */
7852 buf_size = acfg->got_patches->len * 128;
7853 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7854 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7855 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7857 if (acfg->plt_offset)
7858 acfg->plt_got_info_offsets [0] = 0;
7859 for (i = 0; i < acfg->got_patches->len; ++i) {
7860 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7865 encode_value (ji->type, p, &p);
7867 encode_patch (acfg, ji, p, &p);
7868 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7869 g_assert (p - buf <= buf_size);
7870 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7872 if (i >= first_plt_got_patch)
7873 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7874 acfg->stats.got_info_size += p - buf;
7877 /* Emit got_info_offsets table */
7878 sprintf (symbol, "got_info_offsets");
7879 emit_section_change (acfg, RODATA_SECT, 1);
7880 emit_alignment (acfg, 8);
7881 emit_label (acfg, symbol);
7883 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7884 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7888 emit_got (MonoAotCompile *acfg)
7893 /* Don't make GOT global so accesses to it don't need relocations */
7894 sprintf (symbol, "%s", acfg->got_symbol);
7895 emit_section_change (acfg, ".bss", 0);
7896 emit_alignment (acfg, 8);
7897 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7898 emit_label (acfg, symbol);
7899 if (acfg->got_offset > 0)
7900 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7902 sprintf (symbol, "got_end");
7903 emit_label (acfg, symbol);
7907 typedef struct GlobalsTableEntry {
7908 guint32 value, index;
7909 struct GlobalsTableEntry *next;
7910 } GlobalsTableEntry;
7913 emit_globals (MonoAotCompile *acfg)
7919 GlobalsTableEntry *entry, *new_entry;
7921 if (!acfg->aot_opts.static_link)
7925 * When static linking, we emit a table containing our globals.
7929 * Construct a chained hash table for mapping global names to their index in
7930 * the globals table.
7932 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7933 table = g_ptr_array_sized_new (table_size);
7934 for (i = 0; i < table_size; ++i)
7935 g_ptr_array_add (table, NULL);
7936 for (i = 0; i < acfg->globals->len; ++i) {
7937 char *name = g_ptr_array_index (acfg->globals, i);
7939 hash = mono_metadata_str_hash (name) % table_size;
7941 /* FIXME: Allocate from the mempool */
7942 new_entry = g_new0 (GlobalsTableEntry, 1);
7943 new_entry->value = i;
7945 entry = g_ptr_array_index (table, hash);
7946 if (entry == NULL) {
7947 new_entry->index = hash;
7948 g_ptr_array_index (table, hash) = new_entry;
7951 entry = entry->next;
7953 entry->next = new_entry;
7954 new_entry->index = table->len;
7955 g_ptr_array_add (table, new_entry);
7959 /* Emit the table */
7960 sprintf (symbol, ".Lglobals_hash");
7961 emit_section_change (acfg, RODATA_SECT, 0);
7962 emit_alignment (acfg, 8);
7963 emit_label (acfg, symbol);
7965 /* FIXME: Optimize memory usage */
7966 g_assert (table_size < 65000);
7967 emit_int16 (acfg, table_size);
7968 for (i = 0; i < table->len; ++i) {
7969 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7971 if (entry == NULL) {
7972 emit_int16 (acfg, 0);
7973 emit_int16 (acfg, 0);
7975 emit_int16 (acfg, entry->value + 1);
7977 emit_int16 (acfg, entry->next->index);
7979 emit_int16 (acfg, 0);
7983 /* Emit the names */
7984 for (i = 0; i < acfg->globals->len; ++i) {
7985 char *name = g_ptr_array_index (acfg->globals, i);
7987 sprintf (symbol, "name_%d", i);
7988 emit_section_change (acfg, RODATA_SECT, 1);
7990 emit_alignment (acfg, 4);
7992 emit_label (acfg, symbol);
7993 emit_string (acfg, name);
7996 /* Emit the globals table */
7997 sprintf (symbol, "globals");
7998 emit_section_change (acfg, ".data", 0);
7999 /* This is not a global, since it is accessed by the init function */
8000 emit_alignment (acfg, 8);
8001 emit_label (acfg, symbol);
8003 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8004 emit_pointer (acfg, symbol);
8006 for (i = 0; i < acfg->globals->len; ++i) {
8007 char *name = g_ptr_array_index (acfg->globals, i);
8009 sprintf (symbol, "name_%d", i);
8010 emit_pointer (acfg, symbol);
8012 sprintf (symbol, "%s", name);
8013 emit_pointer (acfg, symbol);
8015 /* Null terminate the table */
8016 emit_int32 (acfg, 0);
8017 emit_int32 (acfg, 0);
8021 emit_autoreg (MonoAotCompile *acfg)
8026 * Emit a function into the .ctor section which will be called by the ELF
8027 * loader to register this module with the runtime.
8029 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8032 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8034 arch_emit_autoreg (acfg, symbol);
8040 emit_mem_end (MonoAotCompile *acfg)
8044 sprintf (symbol, "mem_end");
8045 emit_section_change (acfg, ".text", 1);
8046 emit_alignment (acfg, 8);
8047 emit_label (acfg, symbol);
8051 * Emit a structure containing all the information not stored elsewhere.
8054 emit_file_info (MonoAotCompile *acfg)
8059 const char *gc_name;
8062 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8064 if (acfg->aot_opts.bind_to_runtime_version) {
8065 build_info = mono_get_runtime_build_info ();
8066 emit_string_symbol (acfg, "runtime_version", build_info);
8067 g_free (build_info);
8069 emit_string_symbol (acfg, "runtime_version", "");
8072 /* Emit a string holding the assembly name */
8073 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8076 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8079 gc_name = mono_gc_get_gc_name ();
8080 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8082 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8083 emit_section_change (acfg, ".data", 0);
8084 emit_alignment (acfg, 8);
8085 emit_label (acfg, symbol);
8086 if (!acfg->aot_opts.static_link)
8087 emit_global (acfg, symbol, FALSE);
8089 /* The data emitted here must match MonoAotFileInfo. */
8091 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8092 emit_int32 (acfg, 0);
8095 * We emit pointers to our data structures instead of emitting global symbols which
8096 * point to them, to reduce the number of globals, and because using globals leads to
8097 * various problems (i.e. arm/thumb).
8099 emit_pointer (acfg, acfg->got_symbol);
8100 emit_pointer (acfg, acfg->methods_symbol);
8103 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8105 emit_pointer (acfg, "mono_eh_frame");
8107 emit_pointer (acfg, NULL);
8109 emit_pointer (acfg, "blob");
8110 emit_pointer (acfg, "class_name_table");
8111 emit_pointer (acfg, "class_info_offsets");
8112 emit_pointer (acfg, "method_info_offsets");
8113 emit_pointer (acfg, "ex_info_offsets");
8114 emit_pointer (acfg, "code_offsets");
8115 if (acfg->direct_method_addresses)
8116 emit_pointer (acfg, "method_addresses");
8118 emit_pointer (acfg, NULL);
8119 emit_pointer (acfg, "extra_method_info_offsets");
8120 emit_pointer (acfg, "extra_method_table");
8121 emit_pointer (acfg, "got_info_offsets");
8122 emit_pointer (acfg, "methods_end");
8123 emit_pointer (acfg, "unwind_info");
8124 emit_pointer (acfg, "mem_end");
8125 emit_pointer (acfg, "image_table");
8126 emit_pointer (acfg, "plt");
8127 emit_pointer (acfg, "plt_end");
8128 emit_pointer (acfg, "assembly_guid");
8129 emit_pointer (acfg, "runtime_version");
8130 if (acfg->num_trampoline_got_entries) {
8131 emit_pointer (acfg, "specific_trampolines");
8132 emit_pointer (acfg, "static_rgctx_trampolines");
8133 emit_pointer (acfg, "imt_thunks");
8134 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8136 emit_pointer (acfg, NULL);
8137 emit_pointer (acfg, NULL);
8138 emit_pointer (acfg, NULL);
8139 emit_pointer (acfg, NULL);
8141 if (acfg->thumb_mixed) {
8142 emit_pointer (acfg, "thumb_end");
8144 emit_pointer (acfg, NULL);
8146 if (acfg->aot_opts.static_link) {
8147 emit_pointer (acfg, "globals");
8149 emit_pointer (acfg, NULL);
8151 emit_pointer (acfg, "assembly_name");
8152 emit_pointer (acfg, "unbox_trampolines");
8153 emit_pointer (acfg, "unbox_trampolines_end");
8155 emit_int32 (acfg, acfg->plt_got_offset_base);
8156 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8157 emit_int32 (acfg, acfg->plt_offset);
8158 emit_int32 (acfg, acfg->nmethods);
8159 emit_int32 (acfg, acfg->flags);
8160 emit_int32 (acfg, acfg->opts);
8161 emit_int32 (acfg, acfg->simd_opts);
8162 emit_int32 (acfg, gc_name_offset);
8164 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8165 emit_int32 (acfg, acfg->num_trampolines [i]);
8166 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8167 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8168 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8169 emit_int32 (acfg, acfg->trampoline_size [i]);
8170 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8172 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8177 memset (&t, 0, sizeof (MonoType));
8178 t.type = MONO_TYPE_R8;
8179 mono_type_size (&t, &align);
8180 emit_int32 (acfg, align);
8182 memset (&t, 0, sizeof (MonoType));
8183 t.type = MONO_TYPE_I8;
8184 mono_type_size (&t, &align);
8186 emit_int32 (acfg, align);
8189 emit_int32 (acfg, __alignof__ (double));
8190 emit_int32 (acfg, __alignof__ (gint64));
8192 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8193 emit_int32 (acfg, acfg->tramp_page_size);
8194 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8195 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8197 if (acfg->aot_opts.static_link) {
8201 * Emit a global symbol which can be passed by an embedding app to
8202 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8205 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8207 /* Get rid of characters which cannot occur in symbols */
8209 for (p = symbol; *p; ++p) {
8210 if (!(isalnum (*p) || *p == '_'))
8213 acfg->static_linking_symbol = g_strdup (symbol);
8214 emit_global_inner (acfg, symbol, FALSE);
8215 emit_alignment (acfg, sizeof (gpointer));
8216 emit_label (acfg, symbol);
8217 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8222 emit_blob (MonoAotCompile *acfg)
8226 sprintf (symbol, "blob");
8227 emit_section_change (acfg, RODATA_SECT, 1);
8228 emit_alignment (acfg, 8);
8229 emit_label (acfg, symbol);
8231 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8235 emit_objc_selectors (MonoAotCompile *acfg)
8239 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8244 * cat > foo.m << EOF
8247 * return @selector(print:);
8252 img_writer_emit_unset_mode (acfg->w);
8253 g_assert (acfg->fp);
8254 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8255 fprintf (acfg->fp, ".align 2\n");
8256 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8257 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8258 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8260 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8261 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8262 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8263 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8266 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8267 fprintf (acfg->fp, ".align 2\n");
8268 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8269 fprintf (acfg->fp, ".long 0\n");
8270 fprintf (acfg->fp, ".long 16\n");
8274 emit_dwarf_info (MonoAotCompile *acfg)
8276 #ifdef EMIT_DWARF_INFO
8280 /* DIEs for methods */
8281 for (i = 0; i < acfg->nmethods; ++i) {
8282 MonoCompile *cfg = acfg->cfgs [i];
8287 // FIXME: LLVM doesn't define .Lme_...
8288 if (cfg->compile_llvm)
8291 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8293 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 ()));
8299 collect_methods (MonoAotCompile *acfg)
8302 MonoImage *image = acfg->image;
8304 /* Collect methods */
8305 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8307 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8309 method = mono_get_method (acfg->image, token, NULL);
8312 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8313 printf ("Run with MONO_LOG_LEVEL=debug for more information.\n");
8317 /* Load all methods eagerly to skip the slower lazy loading code */
8318 mono_class_setup_methods (method->klass);
8320 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8321 /* Compile the wrapper instead */
8322 /* We do this here instead of add_wrappers () because it is easy to do it here */
8323 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8327 /* FIXME: Some mscorlib methods don't have debug info */
8329 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8330 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8331 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8332 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8333 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8334 if (!mono_debug_lookup_method (method)) {
8335 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8342 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8343 add_method_with_index (acfg, method, i, FALSE);
8344 acfg->method_index ++;
8347 /* gsharedvt methods */
8348 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8350 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8352 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8355 method = mono_get_method (acfg->image, token, NULL);
8359 if (strcmp (method->name, "gshared2"))
8363 if (!strstr (method->klass->image->name, "mini"))
8366 if (method->is_generic || method->klass->generic_container) {
8367 MonoMethod *gshared;
8369 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8370 add_extra_method (acfg, gshared);
8374 add_generic_instances (acfg);
8376 if (acfg->aot_opts.full_aot)
8377 add_wrappers (acfg);
8381 compile_methods (MonoAotCompile *acfg)
8385 if (acfg->aot_opts.nthreads > 0) {
8390 gpointer *user_data;
8391 MonoMethod **methods;
8393 methods_len = acfg->methods->len;
8395 len = acfg->methods->len / acfg->aot_opts.nthreads;
8398 * Partition the list of methods into fragments, and hand it to threads to
8401 threads = g_ptr_array_new ();
8402 /* Make a copy since acfg->methods is modified by compile_method () */
8403 methods = g_new0 (MonoMethod*, methods_len);
8404 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8405 for (i = 0; i < methods_len; ++i)
8406 methods [i] = g_ptr_array_index (acfg->methods, i);
8408 while (i < methods_len) {
8409 frag = g_ptr_array_new ();
8410 for (j = 0; j < len; ++j) {
8411 if (i < methods_len) {
8412 g_ptr_array_add (frag, methods [i]);
8417 user_data = g_new0 (gpointer, 3);
8418 user_data [0] = mono_domain_get ();
8419 user_data [1] = acfg;
8420 user_data [2] = frag;
8422 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8423 g_ptr_array_add (threads, handle);
8427 for (i = 0; i < threads->len; ++i) {
8428 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8434 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8435 for (i = methods_len; i < acfg->methods->len; ++i) {
8436 /* This can new methods to acfg->methods */
8437 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8442 compile_asm (MonoAotCompile *acfg)
8444 char *command, *objfile;
8445 char *outfile_name, *tmp_outfile_name;
8446 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8448 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8449 #define AS_OPTIONS "--64"
8450 #elif defined(TARGET_POWERPC64)
8451 #define AS_OPTIONS "-a64 -mppc64"
8452 #define LD_OPTIONS "-m elf64ppc"
8453 #elif defined(sparc) && SIZEOF_VOID_P == 8
8454 #define AS_OPTIONS "-xarch=v9"
8455 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8456 #define AS_OPTIONS "-arch i386"
8458 #define AS_OPTIONS ""
8461 #ifdef __native_client_codegen__
8462 #if defined(TARGET_AMD64)
8463 #define AS_NAME "nacl64-as"
8465 #define AS_NAME "nacl-as"
8467 #elif defined(TARGET_OSX)
8468 #define AS_NAME "clang -c -x assembler"
8470 #define AS_NAME "as"
8474 #define LD_OPTIONS ""
8478 #define LD_NAME "ld -shared -G"
8479 #elif defined(__ppc__) && defined(TARGET_MACH)
8480 #define LD_NAME "gcc -dynamiclib"
8481 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8482 #define LD_NAME "clang --shared"
8483 #elif defined(HOST_WIN32)
8484 #define LD_NAME "gcc -shared --dll"
8485 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8486 #define LD_NAME "clang -m32 -dynamiclib"
8489 if (acfg->aot_opts.asm_only) {
8490 printf ("Output file: '%s'.\n", acfg->tmpfname);
8491 if (acfg->aot_opts.static_link)
8492 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8496 if (acfg->aot_opts.static_link) {
8497 if (acfg->aot_opts.outfile)
8498 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8500 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8502 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8504 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);
8505 printf ("Executing the native assembler: %s\n", command);
8506 if (system (command) != 0) {
8514 if (acfg->aot_opts.static_link) {
8515 printf ("Output file: '%s'.\n", objfile);
8516 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8521 if (acfg->aot_opts.outfile)
8522 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8524 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8526 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8529 command = g_strdup_printf ("%s -o %s %s.o", LD_NAME, tmp_outfile_name, acfg->tmpfname);
8531 command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8533 printf ("Executing the native linker: %s\n", command);
8534 if (system (command) != 0) {
8535 g_free (tmp_outfile_name);
8536 g_free (outfile_name);
8544 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8545 printf ("Stripping the binary: %s\n", com);
8549 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8551 * gas generates 'mapping symbols' each time code and data is mixed, which
8552 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8554 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8555 printf ("Stripping the binary: %s\n", command);
8556 if (system (command) != 0) {
8557 g_free (tmp_outfile_name);
8558 g_free (outfile_name);
8565 rename (tmp_outfile_name, outfile_name);
8567 #if defined(TARGET_MACH)
8568 command = g_strdup_printf ("dsymutil %s", outfile_name);
8569 printf ("Executing dsymutil: %s\n", command);
8570 if (system (command) != 0) {
8575 if (!acfg->aot_opts.save_temps)
8578 g_free (tmp_outfile_name);
8579 g_free (outfile_name);
8582 if (acfg->aot_opts.save_temps)
8583 printf ("Retained input file.\n");
8585 unlink (acfg->tmpfname);
8590 static MonoAotCompile*
8591 acfg_create (MonoAssembly *ass, guint32 opts)
8593 MonoImage *image = ass->image;
8594 MonoAotCompile *acfg;
8597 acfg = g_new0 (MonoAotCompile, 1);
8598 acfg->methods = g_ptr_array_new ();
8599 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8600 acfg->method_depth = g_hash_table_new (NULL, NULL);
8601 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8602 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8603 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8604 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8605 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8606 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8607 acfg->got_patches = g_ptr_array_new ();
8608 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8609 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8610 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8611 acfg->image_hash = g_hash_table_new (NULL, NULL);
8612 acfg->image_table = g_ptr_array_new ();
8613 acfg->globals = g_ptr_array_new ();
8614 acfg->image = image;
8616 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8617 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8618 acfg->mempool = mono_mempool_new ();
8619 acfg->extra_methods = g_ptr_array_new ();
8620 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8621 acfg->unwind_ops = g_ptr_array_new ();
8622 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8623 acfg->method_order = g_ptr_array_new ();
8624 acfg->export_names = g_hash_table_new (NULL, NULL);
8625 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8626 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8627 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8628 InitializeCriticalSection (&acfg->mutex);
8634 acfg_free (MonoAotCompile *acfg)
8638 img_writer_destroy (acfg->w);
8639 for (i = 0; i < acfg->nmethods; ++i)
8641 g_free (acfg->cfgs [i]);
8642 g_free (acfg->cfgs);
8643 g_free (acfg->static_linking_symbol);
8644 g_free (acfg->got_symbol);
8645 g_free (acfg->plt_symbol);
8646 g_ptr_array_free (acfg->methods, TRUE);
8647 g_ptr_array_free (acfg->got_patches, TRUE);
8648 g_ptr_array_free (acfg->image_table, TRUE);
8649 g_ptr_array_free (acfg->globals, TRUE);
8650 g_ptr_array_free (acfg->unwind_ops, TRUE);
8651 g_hash_table_destroy (acfg->method_indexes);
8652 g_hash_table_destroy (acfg->method_depth);
8653 g_hash_table_destroy (acfg->plt_offset_to_entry);
8654 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8655 if (acfg->patch_to_plt_entry [i])
8656 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8658 g_free (acfg->patch_to_plt_entry);
8659 g_hash_table_destroy (acfg->patch_to_got_offset);
8660 g_hash_table_destroy (acfg->method_to_cfg);
8661 g_hash_table_destroy (acfg->token_info_hash);
8662 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8663 g_hash_table_destroy (acfg->image_hash);
8664 g_hash_table_destroy (acfg->unwind_info_offsets);
8665 g_hash_table_destroy (acfg->method_label_hash);
8666 g_hash_table_destroy (acfg->export_names);
8667 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8668 g_hash_table_destroy (acfg->klass_blob_hash);
8669 g_hash_table_destroy (acfg->method_blob_hash);
8670 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8671 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8672 g_free (acfg->patch_to_got_offset_by_type);
8673 mono_mempool_destroy (acfg->mempool);
8678 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8680 MonoImage *image = ass->image;
8681 int i, res, all_sizes;
8682 MonoAotCompile *acfg;
8683 char *outfile_name, *tmp_outfile_name, *p;
8684 char llvm_stats_msg [256];
8688 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8689 if (opts & MONO_OPT_GSHAREDVT) {
8690 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8695 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8697 acfg = acfg_create (ass, opts);
8699 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8700 acfg->aot_opts.write_symbols = TRUE;
8701 acfg->aot_opts.ntrampolines = 1024;
8702 acfg->aot_opts.nrgctx_trampolines = 1024;
8703 acfg->aot_opts.nimt_trampolines = 128;
8704 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8705 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8706 acfg->aot_opts.llvm_path = g_strdup ("");
8708 acfg->aot_opts.use_trampolines_page = TRUE;
8711 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8713 if (acfg->aot_opts.static_link)
8714 acfg->aot_opts.autoreg = TRUE;
8716 //acfg->aot_opts.print_skipped_methods = TRUE;
8718 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8719 if (acfg->aot_opts.full_aot) {
8720 printf ("--aot=full is not supported on this platform.\n");
8725 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8726 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8730 if (acfg->aot_opts.static_link)
8731 acfg->aot_opts.asm_writer = TRUE;
8733 if (acfg->aot_opts.soft_debug) {
8734 MonoDebugOptions *opt = mini_get_debug_options ();
8736 opt->mdb_optimizations = TRUE;
8737 opt->gen_seq_points = TRUE;
8739 if (!mono_debug_enabled ()) {
8740 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8743 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8746 if (mono_use_llvm) {
8748 acfg->aot_opts.asm_writer = TRUE;
8749 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8751 if (acfg->aot_opts.soft_debug) {
8752 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8757 if (acfg->aot_opts.full_aot)
8758 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8760 load_profile_files (acfg);
8762 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8763 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8764 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8766 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8767 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8768 if (acfg->opts & MONO_OPT_GSHAREDVT)
8769 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8772 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8776 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8777 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8778 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8780 /* Get rid of characters which cannot occur in symbols */
8781 for (p = acfg->got_symbol_base; *p; ++p) {
8782 if (!(isalnum (*p) || *p == '_'))
8785 for (p = acfg->plt_symbol; *p; ++p) {
8786 if (!(isalnum (*p) || *p == '_'))
8789 for (p = acfg->assembly_name_sym; *p; ++p) {
8790 if (!(isalnum (*p) || *p == '_'))
8794 acfg->method_index = 1;
8798 if (acfg->aot_opts.full_aot)
8799 mono_set_partial_sharing_supported (TRUE);
8802 collect_methods (acfg);
8804 acfg->cfgs_size = acfg->methods->len + 32;
8805 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8807 /* PLT offset 0 is reserved for the PLT trampoline */
8808 acfg->plt_offset = 1;
8813 mono_llvm_create_aot_module (acfg->got_symbol_base);
8817 /* GOT offset 0 is reserved for the address of the current assembly */
8821 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8822 ji->type = MONO_PATCH_INFO_IMAGE;
8823 ji->data.image = acfg->image;
8825 get_got_offset (acfg, ji);
8827 /* Slot 1 is reserved for the mscorlib got addr */
8828 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8829 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8830 get_got_offset (acfg, ji);
8832 /* This is very common */
8833 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8834 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8835 get_got_offset (acfg, ji);
8837 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8838 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8839 get_got_offset (acfg, ji);
8844 compile_methods (acfg);
8848 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8854 if (acfg->aot_opts.asm_only) {
8855 if (acfg->aot_opts.outfile) {
8856 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8857 acfg->tmpbasename = g_strdup (acfg->tmpfname);
8859 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
8860 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8863 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
8864 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8867 emit_llvm_file (acfg);
8871 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8872 if (acfg->aot_opts.outfile)
8873 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8875 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8878 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8879 * it might be in another file system so the rename () won't work.
8881 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8883 acfg->fp = fopen (tmp_outfile_name, "w");
8885 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8889 acfg->w = img_writer_create (acfg->fp, TRUE);
8890 acfg->use_bin_writer = TRUE;
8893 /* Append to the .s file created by llvm */
8894 /* FIXME: Use multiple files instead */
8895 acfg->fp = fopen (acfg->tmpfname, "a+");
8897 if (acfg->aot_opts.asm_only) {
8898 if (acfg->aot_opts.outfile)
8899 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8901 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8902 acfg->fp = fopen (acfg->tmpfname, "w+");
8904 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8905 acfg->fp = fdopen (i, "w+");
8908 if (acfg->fp == 0) {
8909 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8912 acfg->w = img_writer_create (acfg->fp, FALSE);
8914 tmp_outfile_name = NULL;
8915 outfile_name = NULL;
8918 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8920 /* Compute symbols for methods */
8921 for (i = 0; i < acfg->nmethods; ++i) {
8922 if (acfg->cfgs [i]) {
8923 MonoCompile *cfg = acfg->cfgs [i];
8924 int method_index = get_method_index (acfg, cfg->orig_method);
8926 if (COMPILE_LLVM (cfg))
8927 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8928 else if (acfg->global_symbols)
8929 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8931 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8935 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
8937 * CLANG supports GAS .file/.loc directives, so emit line number information this way
8938 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
8941 //acfg->gas_line_numbers = TRUE;
8944 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8945 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
8946 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8949 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
8952 img_writer_emit_start (acfg->w);
8955 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
8957 if (acfg->thumb_mixed) {
8960 * This global symbol marks the end of THUMB code, and the beginning of ARM
8961 * code generated by our JIT.
8963 sprintf (symbol, "thumb_end");
8964 emit_section_change (acfg, ".text", 0);
8965 emit_alignment (acfg, 8);
8966 emit_label (acfg, symbol);
8967 emit_zero_bytes (acfg, 16);
8969 fprintf (acfg->fp, ".arm\n");
8976 emit_extra_methods (acfg);
8978 emit_trampolines (acfg);
8980 emit_class_name_table (acfg);
8982 emit_got_info (acfg);
8984 emit_exception_info (acfg);
8986 emit_unwind_info (acfg);
8988 emit_class_info (acfg);
8992 emit_image_table (acfg);
8996 emit_file_info (acfg);
9000 emit_objc_selectors (acfg);
9002 emit_globals (acfg);
9004 emit_autoreg (acfg);
9007 emit_dwarf_info (acfg);
9008 mono_dwarf_writer_close (acfg->dwarf);
9011 emit_mem_end (acfg);
9013 if (acfg->need_pt_gnu_stack) {
9014 /* This is required so the .so doesn't have an executable stack */
9015 /* The bin writer already emits this */
9016 if (!acfg->use_bin_writer)
9017 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9022 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9025 g_assert (acfg->got_offset <= acfg->final_got_size);
9028 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9030 strcpy (llvm_stats_msg, "");
9032 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;
9034 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",
9035 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9036 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9037 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9038 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9039 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9040 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9041 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9042 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9043 (int)(acfg->got_offset * sizeof (gpointer)));
9044 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9045 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9047 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9048 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9049 if (acfg->stats.genericcount)
9050 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9051 if (acfg->stats.abscount)
9052 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9053 if (acfg->stats.lmfcount)
9054 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9055 if (acfg->stats.ocount)
9056 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9059 res = img_writer_emit_writeout (acfg->w);
9064 if (acfg->use_bin_writer) {
9065 int err = rename (tmp_outfile_name, outfile_name);
9068 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9072 res = compile_asm (acfg);
9079 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9081 if (acfg->aot_opts.stats) {
9084 printf ("GOT slot distribution:\n");
9085 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9086 if (acfg->stats.got_slot_types [i])
9087 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9090 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);
9102 mono_aot_readonly_field_override (MonoClassField *field)
9108 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)