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;
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;
214 GHashTable *unwind_info_offsets;
215 GPtrArray *unwind_ops;
216 guint32 unwind_info_offset;
217 char *got_symbol_base;
220 char *methods_symbol;
221 GHashTable *method_label_hash;
222 const char *temp_prefix;
223 const char *user_symbol_prefix;
224 const char *llvm_label_prefix;
225 guint32 label_generator;
227 MonoAotFileFlags flags;
228 MonoDynamicStream blob;
229 MonoClass **typespec_classes;
232 char *assembly_name_sym;
233 GHashTable *plt_entry_debug_sym_cache;
234 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
235 GHashTable *ginst_hash;
236 GHashTable *dwarf_ln_filenames;
237 gboolean global_symbols;
238 gboolean direct_method_addresses;
239 int objc_selector_index, objc_selector_index_2;
240 GPtrArray *objc_selectors;
241 GHashTable *objc_selector_to_index;
246 char *symbol, *llvm_symbol, *debug_sym;
248 gboolean jit_used, llvm_used;
251 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
252 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
254 /* This points to the current acfg in LLVM mode */
255 static MonoAotCompile *llvm_acfg;
257 #ifdef HAVE_ARRAY_ELEM_INIT
258 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
259 #define MSGSTRFIELD1(line) str##line
260 static const struct msgstr_t {
261 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
262 #include "patch-info.h"
265 #define PATCH_INFO(a,b) b,
266 #include "patch-info.h"
269 static const gint16 opidx [] = {
270 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
271 #include "patch-info.h"
275 static G_GNUC_UNUSED const char*
276 get_patch_name (int info)
278 return (const char*)&opstr + opidx [info];
282 #define PATCH_INFO(a,b) b,
283 static const char* const
284 patch_types [MONO_PATCH_INFO_NUM + 1] = {
285 #include "patch-info.h"
289 static G_GNUC_UNUSED const char*
290 get_patch_name (int info)
292 return patch_types [info];
298 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
300 /* Wrappers around the image writer functions */
303 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
305 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
309 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
311 img_writer_emit_push_section (acfg->w, section_name, subsection);
315 emit_pop_section (MonoAotCompile *acfg)
317 img_writer_emit_pop_section (acfg->w);
321 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
323 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
327 emit_label (MonoAotCompile *acfg, const char *name)
329 img_writer_emit_label (acfg->w, name);
333 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
335 img_writer_emit_bytes (acfg->w, buf, size);
339 emit_string (MonoAotCompile *acfg, const char *value)
341 img_writer_emit_string (acfg->w, value);
345 emit_line (MonoAotCompile *acfg)
347 img_writer_emit_line (acfg->w);
351 emit_alignment (MonoAotCompile *acfg, int size)
353 img_writer_emit_alignment (acfg->w, size);
357 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
359 img_writer_emit_pointer_unaligned (acfg->w, target);
363 emit_pointer (MonoAotCompile *acfg, const char *target)
365 img_writer_emit_pointer (acfg->w, target);
369 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
371 if (prefix [0] != '\0') {
372 char *s = g_strdup_printf ("%s%s", prefix, target);
373 img_writer_emit_pointer (acfg->w, s);
376 img_writer_emit_pointer (acfg->w, target);
381 emit_int16 (MonoAotCompile *acfg, int value)
383 img_writer_emit_int16 (acfg->w, value);
387 emit_int32 (MonoAotCompile *acfg, int value)
389 img_writer_emit_int32 (acfg->w, value);
393 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
395 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
399 emit_zero_bytes (MonoAotCompile *acfg, int num)
401 img_writer_emit_zero_bytes (acfg->w, num);
405 emit_byte (MonoAotCompile *acfg, guint8 val)
407 img_writer_emit_byte (acfg->w, val);
410 #ifdef __native_client_codegen__
412 emit_nacl_call_alignment (MonoAotCompile *acfg)
414 img_writer_emit_nacl_call_alignment (acfg->w);
418 static G_GNUC_UNUSED void
419 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
421 img_writer_emit_global (acfg->w, name, func);
425 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
427 if (acfg->aot_opts.no_dlsym) {
428 g_ptr_array_add (acfg->globals, g_strdup (name));
429 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
431 img_writer_emit_global (acfg->w, name, func);
436 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
438 img_writer_emit_symbol_size (acfg->w, name, end_label);
442 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
444 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
446 /* On apple, all symbols need to be aligned to avoid warnings from ld */
447 emit_alignment (acfg, 4);
449 img_writer_emit_label (acfg->w, name);
450 img_writer_emit_string (acfg->w, value);
453 static G_GNUC_UNUSED void
454 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
457 guint8 b = value & 0x7f;
459 if (value != 0) /* more bytes to come */
465 static G_GNUC_UNUSED void
466 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
469 gboolean negative = (value < 0);
476 /* the following is unnecessary if the
477 * implementation of >>= uses an arithmetic rather
478 * than logical shift for a signed left operand
482 value |= - ((gint64)1 <<(size - 7));
483 /* sign bit of byte is second high order bit (0x40) */
484 if ((value == 0 && !(byte & 0x40)) ||
485 (value == -1 && (byte & 0x40)))
489 emit_byte (acfg, byte);
493 static G_GNUC_UNUSED void
494 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
499 guint8 b = value & 0x7f;
501 if (value != 0) /* more bytes to come */
509 static G_GNUC_UNUSED void
510 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
513 gboolean negative = (value < 0);
521 /* the following is unnecessary if the
522 * implementation of >>= uses an arithmetic rather
523 * than logical shift for a signed left operand
527 value |= - (1 <<(size - 7));
528 /* sign bit of byte is second high order bit (0x40) */
529 if ((value == 0 && !(byte & 0x40)) ||
530 (value == -1 && (byte & 0x40)))
541 emit_unset_mode (MonoAotCompile *acfg)
543 img_writer_emit_unset_mode (acfg->w);
546 static G_GNUC_UNUSED void
547 emit_set_thumb_mode (MonoAotCompile *acfg)
549 emit_unset_mode (acfg);
550 fprintf (acfg->fp, ".code 16\n");
553 static G_GNUC_UNUSED void
554 emit_set_arm_mode (MonoAotCompile *acfg)
556 emit_unset_mode (acfg);
557 fprintf (acfg->fp, ".code 32\n");
560 /* ARCHITECTURE SPECIFIC CODE */
562 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
563 #define EMIT_DWARF_INFO 1
566 #if defined(TARGET_ARM)
567 #define AOT_FUNC_ALIGNMENT 4
569 #define AOT_FUNC_ALIGNMENT 16
571 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
572 #undef AOT_FUNC_ALIGNMENT
573 #define AOT_FUNC_ALIGNMENT 32
576 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
577 #define PPC_LD_OP "ld"
578 #define PPC_LDX_OP "ldx"
580 #define PPC_LD_OP "lwz"
581 #define PPC_LDX_OP "lwzx"
585 #define AOT_TARGET_STR "AMD64"
590 #define AOT_TARGET_STR "ARM (MACH)"
592 #define AOT_TARGET_STR "ARM (!MACH)"
596 #ifdef TARGET_POWERPC64
597 #ifdef __mono_ilp32__
598 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
600 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
603 #ifdef TARGET_POWERPC
604 #ifdef __mono_ilp32__
605 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
607 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
614 #define AOT_TARGET_STR "X86 (WIN32)"
615 #elif defined(__native_client_codegen__)
616 #define AOT_TARGET_STR "X86 (native client codegen)"
618 #define AOT_TARGET_STR "X86 (!native client codegen)"
622 #ifndef AOT_TARGET_STR
623 #define AOT_TARGET_STR ""
627 arch_init (MonoAotCompile *acfg)
629 acfg->llc_args = g_string_new ("");
630 acfg->as_args = g_string_new ("");
633 * The prefix LLVM likes to put in front of symbol names on darwin.
634 * The mach-os specs require this for globals, but LLVM puts them in front of all
635 * symbols. We need to handle this, since we need to refer to LLVM generated
638 acfg->llvm_label_prefix = "";
639 acfg->user_symbol_prefix = "";
641 #if defined(TARGET_AMD64) && defined(TARGET_MACH)
642 /* osx contains an old as which doesn't support avx opcodes */
643 g_string_append (acfg->llc_args, "-mattr=-avx");
646 #if defined(TARGET_AMD64)
647 g_string_append (acfg->llc_args, " -march=x86-64");
651 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
652 g_string_append (acfg->llc_args, "-mattr=+v6");
655 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
656 g_string_append (acfg->as_args, " -mfpu=vfp3");
658 g_string_append (acfg->llc_args, " -soft-float");
661 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
662 acfg->thumb_mixed = TRUE;
664 if (acfg->aot_opts.mtriple)
665 mono_arch_set_target (acfg->aot_opts.mtriple);
669 acfg->user_symbol_prefix = "_";
670 acfg->llvm_label_prefix = "_";
671 acfg->need_no_dead_strip = TRUE;
672 acfg->aot_opts.gnu_asm = TRUE;
675 #if defined(__linux__) && !defined(TARGET_ARM)
676 acfg->need_pt_gnu_stack = TRUE;
680 acfg->direct_method_addresses = TRUE;
681 acfg->global_symbols = TRUE;
686 * arch_emit_direct_call:
688 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
692 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, MonoJumpInfo *ji, int *call_size)
694 #if defined(TARGET_X86) || defined(TARGET_AMD64)
695 /* Need to make sure this is exactly 5 bytes long */
696 if (external && !acfg->use_bin_writer) {
697 emit_unset_mode (acfg);
698 fprintf (acfg->fp, "call %s\n", target);
700 emit_byte (acfg, '\xe8');
701 emit_symbol_diff (acfg, target, ".", -4);
704 #elif defined(TARGET_ARM)
705 if (acfg->use_bin_writer) {
712 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
713 emit_bytes (acfg, buf, 4);
715 emit_unset_mode (acfg);
716 fprintf (acfg->fp, "bl %s\n", target);
719 #elif defined(TARGET_POWERPC)
720 if (acfg->use_bin_writer) {
721 g_assert_not_reached ();
723 emit_unset_mode (acfg);
724 fprintf (acfg->fp, "bl %s\n", target);
728 g_assert_not_reached ();
734 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
736 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
737 * in in the 2. slot of every GOT, and require every method to place the GOT
738 * address in r30, even when it doesn't access the GOT otherwise. This way,
739 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
744 * PPC64 uses function descriptors which greatly complicate all code, since
745 * these are used very inconsistently in the runtime. Some functions like
746 * mono_compile_method () return ftn descriptors, while others like the
747 * trampoline creation functions do not.
748 * We assume that all GOT slots contain function descriptors, and create
749 * descriptors in aot-runtime.c when needed.
750 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
751 * from function descriptors, we could do the same, but it would require
752 * rewriting all the ppc/aot code to handle function descriptors properly.
753 * So instead, we use the same approach as on PPC32.
754 * This is a horrible mess, but fixing it would probably lead to an even bigger
760 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
763 #ifdef MONO_ARCH_AOT_SUPPORTED
765 * arch_emit_got_offset:
767 * The memory pointed to by CODE should hold native code for computing the GOT
768 * address. Emit this code while patching it with the offset between code and
769 * the GOT. CODE_SIZE is set to the number of bytes emitted.
772 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
774 #if defined(TARGET_POWERPC64)
775 g_assert (!acfg->use_bin_writer);
776 emit_unset_mode (acfg);
778 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
779 * unsupported relocations. So we store the got address into the .Lgot_addr
780 * symbol which is in the text segment, compute its address, and load it.
782 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
783 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
784 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
785 fprintf (acfg->fp, "add 30, 30, 0\n");
786 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
787 acfg->label_generator ++;
789 #elif defined(TARGET_POWERPC)
790 g_assert (!acfg->use_bin_writer);
791 emit_unset_mode (acfg);
792 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
793 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
794 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
795 acfg->label_generator ++;
798 guint32 offset = mono_arch_get_patch_offset (code);
799 emit_bytes (acfg, code, offset);
800 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
802 *code_size = offset + 4;
807 * arch_emit_got_access:
809 * The memory pointed to by CODE should hold native code for loading a GOT
810 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
811 * CODE_SIZE is set to the number of bytes emitted.
814 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
816 /* Emit beginning of instruction */
817 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
819 /* Emit the offset */
821 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
822 *code_size = mono_arch_get_patch_offset (code) + 4;
823 #elif defined(TARGET_X86)
824 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
825 *code_size = mono_arch_get_patch_offset (code) + 4;
826 #elif defined(TARGET_ARM)
827 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
828 *code_size = mono_arch_get_patch_offset (code) + 4;
829 #elif defined(TARGET_POWERPC)
835 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
836 g_assert (code - buf == 8);
837 emit_bytes (acfg, buf, code - buf);
838 *code_size = code - buf;
841 g_assert_not_reached ();
848 * arch_emit_objc_selector_ref:
850 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
853 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
855 #if defined(TARGET_ARM)
858 int lindex = acfg->objc_selector_index_2 ++;
861 emit_bytes (acfg, code, 8);
863 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
864 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
866 emit_label (acfg, symbol1);
867 img_writer_emit_unset_mode (acfg->w);
868 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
872 g_assert_not_reached ();
877 * arch_emit_plt_entry:
879 * Emit code for the PLT entry with index INDEX.
882 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
884 #if defined(TARGET_X86)
885 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
886 #if defined(__default_codegen__)
887 /* jmp *<offset>(%ebx) */
888 emit_byte (acfg, 0xff);
889 emit_byte (acfg, 0xa3);
890 emit_int32 (acfg, offset);
891 /* Used by mono_aot_get_plt_info_offset */
892 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
893 #elif defined(__native_client_codegen__)
894 const guint8 kSizeOfNaClJmp = 11;
895 guint8 bytes[kSizeOfNaClJmp];
896 guint8 *pbytes = &bytes[0];
898 x86_jump_membase32 (pbytes, X86_EBX, offset);
899 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
900 /* four bytes of data, used by mono_arch_patch_plt_entry */
901 /* For Native Client, make this work with data embedded in push. */
902 emit_byte (acfg, 0x68); /* hide data in a push */
903 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
904 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
905 #endif /*__native_client_codegen__*/
906 #elif defined(TARGET_AMD64)
907 #if defined(__default_codegen__)
909 * We can't emit jumps because they are 32 bits only so they can't be patched.
910 * So we make indirect calls through GOT entries which are patched by the AOT
911 * loader to point to .Lpd entries.
913 /* jmpq *<offset>(%rip) */
914 emit_byte (acfg, '\xff');
915 emit_byte (acfg, '\x25');
916 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
917 /* Used by mono_aot_get_plt_info_offset */
918 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
919 #elif defined(__native_client_codegen__)
921 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
922 guint8 *code = buf_aligned;
924 /* mov <OFFSET>(%rip), %r11d */
925 emit_byte (acfg, '\x45');
926 emit_byte (acfg, '\x8b');
927 emit_byte (acfg, '\x1d');
928 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
930 amd64_jump_reg (code, AMD64_R11);
931 /* This should be constant for the plt patch */
932 g_assert ((size_t)(code-buf_aligned) == 10);
933 emit_bytes (acfg, buf_aligned, code - buf_aligned);
935 /* Hide data in a push imm32 so it passes validation */
936 emit_byte (acfg, 0x68); /* push */
937 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
938 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
939 #endif /*__native_client_codegen__*/
940 #elif defined(TARGET_ARM)
945 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
946 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
947 emit_bytes (acfg, buf, code - buf);
948 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
949 /* Used by mono_aot_get_plt_info_offset */
950 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
951 #elif defined(TARGET_POWERPC)
952 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
954 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
955 g_assert (!acfg->use_bin_writer);
956 emit_unset_mode (acfg);
957 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
958 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
959 fprintf (acfg->fp, "add 11, 11, 30\n");
960 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
961 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
962 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
963 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
965 fprintf (acfg->fp, "mtctr 11\n");
966 fprintf (acfg->fp, "bctr\n");
967 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
969 g_assert_not_reached ();
974 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
976 #if defined(TARGET_ARM)
978 /* LLVM calls the PLT entries using bl, so emit a stub */
979 /* FIXME: Too much overhead on every call */
980 fprintf (acfg->fp, ".thumb_func\n");
981 fprintf (acfg->fp, "bx pc\n");
982 fprintf (acfg->fp, "nop\n");
983 fprintf (acfg->fp, ".arm\n");
985 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
986 /* The caller already transitioned to thumb */
987 /* The code below should be 12 bytes long */
988 /* clang has trouble encoding these instructions, so emit the binary */
990 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
991 /* thumb can't encode ld pc, [pc, ip] */
992 fprintf (acfg->fp, "add ip, pc, ip\n");
993 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
994 fprintf (acfg->fp, "bx ip\n");
996 emit_set_thumb_mode (acfg);
997 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
998 fprintf (acfg->fp, ".2byte 0x44fc\n");
999 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1000 fprintf (acfg->fp, ".2byte 0x4760\n");
1001 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1002 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1003 emit_unset_mode (acfg);
1004 emit_set_arm_mode (acfg);
1006 g_assert_not_reached ();
1011 * arch_emit_specific_trampoline_pages:
1013 * Emits a page full of trampolines: each trampoline uses its own address to
1014 * lookup both the generic trampoline code and the data argument.
1015 * This page can be remapped in process multiple times so we can get an
1016 * unlimited number of trampolines.
1017 * Specifically this implementation uses the following trick: two memory pages
1018 * are allocated, with the first containing the data and the second containing the trampolines.
1019 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1020 * implementation does all the lifting.
1021 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1022 * on the arm 32 bit system.
1025 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1027 #if defined(TARGET_ARM)
1030 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1032 #define COMMON_TRAMP_SIZE 16
1033 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1034 int imm8, rot_amount;
1037 if (!acfg->aot_opts.use_trampolines_page)
1040 acfg->tramp_page_size = mono_pagesize ();
1042 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1043 emit_alignment (acfg, mono_pagesize ());
1044 emit_global (acfg, symbol, TRUE);
1045 emit_label (acfg, symbol);
1047 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1049 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1050 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1051 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1052 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1054 g_assert (code - buf == COMMON_TRAMP_SIZE);
1057 emit_bytes (acfg, buf, code - buf);
1059 for (i = 0; i < count; ++i) {
1061 ARM_PUSH (code, 0x5fff);
1063 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1064 g_assert (code - buf == 8);
1065 emit_bytes (acfg, buf, code - buf);
1068 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1069 * the instruction pointer address, so the generic trampoline at the start of the page
1070 * subtracts 4096 to get to the data page and loads the values
1071 * We again fit the generic trampiline in 16 bytes.
1073 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1074 emit_global (acfg, symbol, TRUE);
1075 emit_label (acfg, symbol);
1077 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1078 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1079 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1080 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1082 g_assert (code - buf == COMMON_TRAMP_SIZE);
1085 emit_bytes (acfg, buf, code - buf);
1087 for (i = 0; i < count; ++i) {
1089 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1091 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1092 g_assert (code - buf == 8);
1093 emit_bytes (acfg, buf, code - buf);
1097 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1099 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1100 emit_global (acfg, symbol, TRUE);
1101 emit_label (acfg, symbol);
1103 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1104 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1105 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1106 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1107 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1108 g_assert (code - buf == COMMON_TRAMP_SIZE);
1110 emit_bytes (acfg, buf, code - buf);
1112 for (i = 0; i < count; ++i) {
1114 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1116 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1117 g_assert (code - buf == 8);
1118 emit_bytes (acfg, buf, code - buf);
1121 /* now the imt trampolines: each specific trampolines puts in the ip register
1122 * the instruction pointer address, so the generic trampoline at the start of the page
1123 * subtracts 4096 to get to the data page and loads the values
1124 * We again fit the generic trampiline in 16 bytes.
1126 #define IMT_TRAMP_SIZE 72
1127 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1128 emit_global (acfg, symbol, TRUE);
1129 emit_label (acfg, symbol);
1131 /* Need at least two free registers, plus a slot for storing the pc */
1132 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1134 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1135 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1136 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1138 /* The IMT method is in v5, r0 has the imt array address */
1141 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1142 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1143 imt_found_check = code;
1144 ARM_B_COND (code, ARMCOND_EQ, 0);
1146 /* End-of-loop check */
1147 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1148 loop_end_check = code;
1149 ARM_B_COND (code, ARMCOND_EQ, 0);
1152 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1153 loop_branch_back = code;
1155 arm_patch (loop_branch_back, loop_start);
1158 arm_patch (imt_found_check, code);
1159 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1160 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1161 /* Save it to the third stack slot */
1162 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1163 /* Restore the registers and branch */
1164 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1167 arm_patch (loop_end_check, code);
1168 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1169 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1170 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1174 g_assert (code - buf == IMT_TRAMP_SIZE);
1175 emit_bytes (acfg, buf, code - buf);
1177 for (i = 0; i < count; ++i) {
1179 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1181 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1182 g_assert (code - buf == 8);
1183 emit_bytes (acfg, buf, code - buf);
1189 * arch_emit_specific_trampoline:
1191 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1192 * two GOT slots which contain the generic trampoline address and the trampoline
1193 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1196 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1199 * The trampolines created here are variations of the specific
1200 * trampolines created in mono_arch_create_specific_trampoline (). The
1202 * - the generic trampoline address is taken from a got slot.
1203 * - the offset of the got slot where the trampoline argument is stored
1204 * is embedded in the instruction stream, and the generic trampoline
1205 * can load the argument by loading the offset, adding it to the
1206 * address of the trampoline to get the address of the got slot, and
1207 * loading the argument from there.
1208 * - all the trampolines should be of the same length.
1210 #if defined(TARGET_AMD64)
1211 #if defined(__default_codegen__)
1212 /* This should be exactly 16 bytes long */
1214 /* call *<offset>(%rip) */
1215 emit_byte (acfg, '\x41');
1216 emit_byte (acfg, '\xff');
1217 emit_byte (acfg, '\x15');
1218 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1219 /* This should be relative to the start of the trampoline */
1220 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1221 emit_zero_bytes (acfg, 5);
1222 #elif defined(__native_client_codegen__)
1224 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1225 guint8 *code = buf_aligned;
1230 /* Emit this call in 'code' so we can find out how long it is. */
1231 amd64_call_reg (code, AMD64_R11);
1232 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1233 call_len = code - call_start;
1235 /* The tramp_size is twice the NaCl alignment because it starts with */
1236 /* a call which needs to be aligned to the end of the boundary. */
1237 *tramp_size = kNaClAlignment*2;
1239 /* Emit nops to align call site below which is 7 bytes plus */
1240 /* the length of the call sequence emitted above. */
1241 /* Note: this requires the specific trampoline starts on a */
1242 /* kNaclAlignedment aligned address, which it does because */
1243 /* it's its own function that is aligned. */
1244 guint8 nop_buf[256];
1245 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1246 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1247 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1249 /* The trampoline is stored at the offset'th pointer, the -4 is */
1250 /* present because RIP relative addressing starts at the end of */
1251 /* the current instruction, while the label "." is relative to */
1252 /* the beginning of the current asm location, which in this case */
1253 /* is not the mov instruction, but the offset itself, due to the */
1254 /* way the bytes and ints are emitted here. */
1255 got_offset = (offset * sizeof(gpointer)) - 4;
1257 /* mov <OFFSET>(%rip), %r11d */
1258 emit_byte (acfg, '\x45');
1259 emit_byte (acfg, '\x8b');
1260 emit_byte (acfg, '\x1d');
1261 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1264 emit_bytes (acfg, call_start, call_len);
1266 /* The arg is stored at the offset+1 pointer, relative to beginning */
1267 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1268 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1270 /* We can't emit this data directly, hide in a "push imm32" */
1271 emit_byte (acfg, '\x68'); /* push */
1272 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1273 emit_alignment (acfg, kNaClAlignment);
1274 #endif /*__native_client_codegen__*/
1275 #elif defined(TARGET_ARM)
1279 /* This should be exactly 20 bytes long */
1282 ARM_PUSH (code, 0x5fff);
1283 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1284 /* Load the value from the GOT */
1285 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1287 ARM_BLX_REG (code, ARMREG_R1);
1289 g_assert (code - buf == 16);
1292 emit_bytes (acfg, buf, code - buf);
1294 * Only one offset is needed, since the second one would be equal to the
1297 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1298 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1299 #elif defined(TARGET_POWERPC)
1306 g_assert (!acfg->use_bin_writer);
1309 * PPC has no ip relative addressing, so we need to compute the address
1310 * of the mscorlib got. That is slow and complex, so instead, we store it
1311 * in the second got slot of every aot image. The caller already computed
1312 * the address of its got and placed it into r30.
1314 emit_unset_mode (acfg);
1315 /* Load mscorlib got address */
1316 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1317 /* Load generic trampoline address */
1318 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1319 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1320 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1321 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1322 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1324 fprintf (acfg->fp, "mtctr 11\n");
1325 /* Load trampoline argument */
1326 /* On ppc, we pass it normally to the generic trampoline */
1327 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1328 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1329 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1330 /* Branch to generic trampoline */
1331 fprintf (acfg->fp, "bctr\n");
1333 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1334 *tramp_size = 10 * 4;
1336 *tramp_size = 9 * 4;
1338 #elif defined(TARGET_X86)
1342 /* Similar to the PPC code above */
1344 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1346 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1347 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1348 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1352 /* Load mscorlib got address */
1353 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1354 /* Push trampoline argument */
1355 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1356 /* Load generic trampoline address */
1357 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1358 /* Branch to generic trampoline */
1359 x86_jump_reg (code, X86_ECX);
1361 #ifdef __native_client_codegen__
1363 /* emit nops to next 32 byte alignment */
1364 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1365 while (code < (buf + a)) x86_nop(code);
1368 emit_bytes (acfg, buf, code - buf);
1370 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1371 g_assert (code - buf == *tramp_size);
1373 g_assert_not_reached ();
1378 * arch_emit_unbox_trampoline:
1380 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1381 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1384 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1386 #if defined(TARGET_AMD64)
1391 this_reg = mono_arch_get_this_arg_reg (NULL);
1393 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1395 emit_bytes (acfg, buf, code - buf);
1397 emit_byte (acfg, '\xe9');
1398 emit_symbol_diff (acfg, call_target, ".", -4);
1399 #elif defined(TARGET_X86)
1406 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1408 emit_bytes (acfg, buf, code - buf);
1411 emit_byte (acfg, '\xe9');
1412 emit_symbol_diff (acfg, call_target, ".", -4);
1413 #elif defined(TARGET_ARM)
1417 if (acfg->thumb_mixed && cfg->compile_llvm) {
1418 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1419 fprintf (acfg->fp, "b %s\n", call_target);
1420 fprintf (acfg->fp, ".arm\n");
1421 fprintf (acfg->fp, ".align 2\n");
1427 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1429 emit_bytes (acfg, buf, code - buf);
1430 /* jump to method */
1431 if (acfg->use_bin_writer) {
1438 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1439 emit_bytes (acfg, buf, 4);
1441 if (acfg->thumb_mixed && cfg->compile_llvm)
1442 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1444 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1446 #elif defined(TARGET_POWERPC)
1449 g_assert (!acfg->use_bin_writer);
1451 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1452 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1454 g_assert_not_reached ();
1459 * arch_emit_static_rgctx_trampoline:
1461 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1462 * two GOT slots which contain the rgctx argument, and the method to jump to.
1463 * TRAMP_SIZE is set to the size of the emitted trampoline.
1464 * These kinds of trampolines cannot be enumerated statically, since there could
1465 * be one trampoline per method instantiation, so we emit the same code for all
1466 * trampolines, and parameterize them using two GOT slots.
1469 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1471 #if defined(TARGET_AMD64)
1472 #if defined(__default_codegen__)
1473 /* This should be exactly 13 bytes long */
1476 /* mov <OFFSET>(%rip), %r10 */
1477 emit_byte (acfg, '\x4d');
1478 emit_byte (acfg, '\x8b');
1479 emit_byte (acfg, '\x15');
1480 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1482 /* jmp *<offset>(%rip) */
1483 emit_byte (acfg, '\xff');
1484 emit_byte (acfg, '\x25');
1485 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1486 #elif defined(__native_client_codegen__)
1488 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1489 guint8 *code = buf_aligned;
1491 /* mov <OFFSET>(%rip), %r10d */
1492 emit_byte (acfg, '\x45');
1493 emit_byte (acfg, '\x8b');
1494 emit_byte (acfg, '\x15');
1495 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1497 /* mov <OFFSET>(%rip), %r11d */
1498 emit_byte (acfg, '\x45');
1499 emit_byte (acfg, '\x8b');
1500 emit_byte (acfg, '\x1d');
1501 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1504 amd64_jump_reg (code, AMD64_R11);
1505 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1507 emit_alignment (acfg, kNaClAlignment);
1508 *tramp_size = kNaClAlignment;
1509 #endif /*__native_client_codegen__*/
1511 #elif defined(TARGET_ARM)
1515 /* This should be exactly 24 bytes long */
1518 /* Load rgctx value */
1519 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1520 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1521 /* Load branch addr + branch */
1522 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1523 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1525 g_assert (code - buf == 16);
1528 emit_bytes (acfg, buf, code - buf);
1529 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1530 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1531 #elif defined(TARGET_POWERPC)
1538 g_assert (!acfg->use_bin_writer);
1541 * PPC has no ip relative addressing, so we need to compute the address
1542 * of the mscorlib got. That is slow and complex, so instead, we store it
1543 * in the second got slot of every aot image. The caller already computed
1544 * the address of its got and placed it into r30.
1546 emit_unset_mode (acfg);
1547 /* Load mscorlib got address */
1548 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1550 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1551 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1552 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1553 /* Load target address */
1554 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1555 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1556 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1557 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1558 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1559 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1561 fprintf (acfg->fp, "mtctr 11\n");
1562 /* Branch to the target address */
1563 fprintf (acfg->fp, "bctr\n");
1565 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1566 *tramp_size = 11 * 4;
1568 *tramp_size = 9 * 4;
1571 #elif defined(TARGET_X86)
1575 /* Similar to the PPC code above */
1577 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1580 /* Load mscorlib got address */
1581 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1583 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1584 /* Branch to the target address */
1585 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1587 #ifdef __native_client_codegen__
1589 /* emit nops to next 32 byte alignment */
1590 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1591 while (code < (buf + a)) x86_nop(code);
1595 emit_bytes (acfg, buf, code - buf);
1597 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1598 g_assert (code - buf == *tramp_size);
1600 g_assert_not_reached ();
1605 * arch_emit_imt_thunk:
1607 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1608 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1609 * key is the IMT key, and ptr holds the address of a memory location holding
1610 * the address to branch to if the IMT arg matches the key. The array is
1611 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1613 * TRAMP_SIZE is set to the size of the emitted trampoline.
1616 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1618 #if defined(TARGET_AMD64)
1620 #if defined(__native_client_codegen__)
1623 guint8 *labels [16];
1625 guint8 *mov_buf_ptr = mov_buf;
1627 const int kSizeOfMove = 7;
1628 #if defined(__default_codegen__)
1629 code = buf = g_malloc (256);
1630 #elif defined(__native_client_codegen__)
1631 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1632 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1633 /* The RIP relative move below is emitted first */
1638 /* FIXME: Optimize this, i.e. use binary search etc. */
1639 /* Maybe move the body into a separate function (slower, but much smaller) */
1641 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1644 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1646 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1649 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1651 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1654 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1655 amd64_jump_code (code, labels [0]);
1658 mono_amd64_patch (labels [2], code);
1659 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1660 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1663 mono_amd64_patch (labels [1], code);
1664 /* Load fail tramp */
1665 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1666 /* Check if there is a fail tramp */
1667 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1669 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1670 /* Jump to fail tramp */
1671 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1674 mono_amd64_patch (labels [3], code);
1675 x86_breakpoint (code);
1677 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1678 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1679 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1680 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1681 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1682 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1684 emit_bytes (acfg, buf, code - buf);
1686 *tramp_size = code - buf + kSizeOfMove;
1687 #if defined(__native_client_codegen__)
1688 /* The tramp will be padded to the next kNaClAlignment bundle. */
1689 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1692 #if defined(__default_codegen__)
1694 #elif defined(__native_client_codegen__)
1698 #elif defined(TARGET_X86)
1700 #ifdef __native_client_codegen__
1703 guint8 *labels [16];
1705 #if defined(__default_codegen__)
1706 code = buf = g_malloc (256);
1707 #elif defined(__native_client_codegen__)
1708 buf_alloc = g_malloc (256 + kNaClAlignment);
1709 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1712 /* Allocate a temporary stack slot */
1713 x86_push_reg (code, X86_EAX);
1715 x86_push_reg (code, X86_EAX);
1717 /* Load mscorlib got address */
1718 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1720 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1723 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1725 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1728 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1730 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1733 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1734 x86_jump_code (code, labels [0]);
1737 mono_x86_patch (labels [2], code);
1738 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1739 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1740 /* Save the target address to the temporary stack location */
1741 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1743 x86_pop_reg (code, X86_EAX);
1744 /* Jump to the target address */
1748 mono_x86_patch (labels [1], code);
1749 /* Load fail tramp */
1750 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1751 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1753 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1754 /* Jump to fail tramp */
1755 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1756 x86_pop_reg (code, X86_EAX);
1760 mono_x86_patch (labels [3], code);
1761 x86_breakpoint (code);
1763 #ifdef __native_client_codegen__
1765 /* emit nops to next 32 byte alignment */
1766 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1767 while (code < (buf + a)) x86_nop(code);
1770 emit_bytes (acfg, buf, code - buf);
1772 *tramp_size = code - buf;
1774 #if defined(__default_codegen__)
1776 #elif defined(__native_client_codegen__)
1780 #elif defined(TARGET_ARM)
1782 guint8 *code, *code2, *labels [16];
1786 /* The IMT method is in v5 */
1788 /* Need at least two free registers, plus a slot for storing the pc */
1789 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1791 /* Load the parameter from the GOT */
1792 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1793 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1796 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1797 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1799 ARM_B_COND (code, ARMCOND_EQ, 0);
1801 /* End-of-loop check */
1802 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1804 ARM_B_COND (code, ARMCOND_EQ, 0);
1807 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1810 arm_patch (labels [4], labels [1]);
1813 arm_patch (labels [2], code);
1814 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1815 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1816 /* Save it to the third stack slot */
1817 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1818 /* Restore the registers and branch */
1819 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1822 arm_patch (labels [3], code);
1823 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1824 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1825 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1829 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1831 emit_bytes (acfg, buf, code - buf);
1832 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1834 *tramp_size = code - buf + 4;
1835 #elif defined(TARGET_POWERPC)
1837 guint8 *code, *labels [16];
1841 /* Load the mscorlib got address */
1842 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1843 /* Load the parameter from the GOT */
1844 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1845 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1847 /* Load and check key */
1849 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1850 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1852 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1854 /* End-of-loop check */
1855 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1857 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1860 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1863 mono_ppc_patch (labels [4], labels [1]);
1866 mono_ppc_patch (labels [2], code);
1867 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1868 /* r11 now contains the value of the vtable slot */
1869 /* this is not a function descriptor on ppc64 */
1870 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1871 ppc_mtctr (code, ppc_r11);
1872 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1875 mono_ppc_patch (labels [3], code);
1879 *tramp_size = code - buf;
1881 emit_bytes (acfg, buf, code - buf);
1883 g_assert_not_reached ();
1888 * arch_emit_gsharedvt_arg_trampoline:
1890 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1891 * two GOT slots which contain the argument, and the code to jump to.
1892 * TRAMP_SIZE is set to the size of the emitted trampoline.
1893 * These kinds of trampolines cannot be enumerated statically, since there could
1894 * be one trampoline per method instantiation, so we emit the same code for all
1895 * trampolines, and parameterize them using two GOT slots.
1898 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1900 #if defined(TARGET_X86)
1904 /* Similar to the PPC code above */
1906 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1909 /* Load mscorlib got address */
1910 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1912 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1913 /* Branch to the target address */
1914 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1916 #ifdef __native_client_codegen__
1918 /* emit nops to next 32 byte alignment */
1919 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1920 while (code < (buf + a)) x86_nop(code);
1924 emit_bytes (acfg, buf, code - buf);
1926 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1927 g_assert (code - buf == *tramp_size);
1928 #elif defined(TARGET_ARM)
1932 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1933 /* Similar to arch_emit_specific_trampoline () */
1936 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1937 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1938 /* Load the arg value from the GOT */
1939 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1940 /* Load the addr from the GOT */
1941 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1943 ARM_BX (code, ARMREG_R1);
1945 g_assert (code - buf == 20);
1948 emit_bytes (acfg, buf, code - buf);
1949 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1951 g_assert_not_reached ();
1956 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1958 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1959 /* Based on code generated by gcc */
1960 emit_unset_mode (acfg);
1963 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1964 ".section .ctors,\"aw\",@progbits\n"
1968 ".section .opd,\"aw\"\n"
1971 ".long .%s,.TOC.@tocbase32\n"
1974 ".type .%s,@function\n"
1976 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1978 ".section .ctors,\"aw\",@progbits\n"
1982 ".section .opd,\"aw\"\n"
1985 ".long .%1$s,.TOC.@tocbase32\n"
1986 ".size %1$s,.-%1$s\n"
1988 ".type .%1$s,@function\n"
1990 ".%1$s:\n", symbol);
2001 "lis 3, .Lglobals@h\n"
2002 "ori 3, 3, .Lglobals@l\n"
2003 "bl .mono_aot_register_module\n"
2011 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2013 ".size .%s,.-.%s\n", symbol, symbol);
2016 ".size .%1$s,.-.%1$s\n", symbol);
2022 /* END OF ARCH SPECIFIC CODE */
2025 mono_get_field_token (MonoClassField *field)
2027 MonoClass *klass = field->parent;
2030 for (i = 0; i < klass->field.count; ++i) {
2031 if (field == &klass->fields [i])
2032 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2035 g_assert_not_reached ();
2040 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2044 //printf ("ENCODE: %d 0x%x.\n", value, value);
2047 * Same encoding as the one used in the metadata, extended to handle values
2048 * greater than 0x1fffffff.
2050 if ((value >= 0) && (value <= 127))
2052 else if ((value >= 0) && (value <= 16383)) {
2053 p [0] = 0x80 | (value >> 8);
2054 p [1] = value & 0xff;
2056 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2057 p [0] = (value >> 24) | 0xc0;
2058 p [1] = (value >> 16) & 0xff;
2059 p [2] = (value >> 8) & 0xff;
2060 p [3] = value & 0xff;
2065 p [1] = (value >> 24) & 0xff;
2066 p [2] = (value >> 16) & 0xff;
2067 p [3] = (value >> 8) & 0xff;
2068 p [4] = value & 0xff;
2076 stream_init (MonoDynamicStream *sh)
2079 sh->alloc_size = 4096;
2080 sh->data = g_malloc (4096);
2082 /* So offsets are > 0 */
2088 make_room_in_stream (MonoDynamicStream *stream, int size)
2090 if (size <= stream->alloc_size)
2093 while (stream->alloc_size <= size) {
2094 if (stream->alloc_size < 4096)
2095 stream->alloc_size = 4096;
2097 stream->alloc_size *= 2;
2100 stream->data = g_realloc (stream->data, stream->alloc_size);
2104 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2108 make_room_in_stream (stream, stream->index + len);
2109 memcpy (stream->data + stream->index, data, len);
2110 idx = stream->index;
2111 stream->index += len;
2118 * Add data to the binary blob inside the aot image. Returns the offset inside the
2119 * blob where the data was stored.
2122 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2124 if (acfg->blob.alloc_size == 0)
2125 stream_init (&acfg->blob);
2127 return add_stream_data (&acfg->blob, (char*)data, data_len);
2131 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2136 if (acfg->blob.alloc_size == 0)
2137 stream_init (&acfg->blob);
2139 count = acfg->blob.index % align;
2141 /* we assume the stream data will be aligned */
2143 add_stream_data (&acfg->blob, buf, 4 - count);
2145 return add_stream_data (&acfg->blob, (char*)data, data_len);
2149 * emit_offset_table:
2151 * Emit a table of increasing offsets in a compact form using differential encoding.
2152 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2153 * group size, the more compact the table becomes, but the slower it becomes to compute
2154 * a given entry. Returns the size of the table.
2157 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2159 gint32 current_offset;
2160 int i, buf_size, ngroups, index_entry_size;
2162 guint32 *index_offsets;
2164 ngroups = (noffsets + (group_size - 1)) / group_size;
2166 index_offsets = g_new0 (guint32, ngroups);
2168 buf_size = noffsets * 4;
2169 p = buf = g_malloc0 (buf_size);
2172 for (i = 0; i < noffsets; ++i) {
2173 //printf ("D: %d -> %d\n", i, offsets [i]);
2174 if ((i % group_size) == 0) {
2175 index_offsets [i / group_size] = p - buf;
2176 /* Emit the full value for these entries */
2177 encode_value (offsets [i], p, &p);
2179 /* The offsets are allowed to be non-increasing */
2180 //g_assert (offsets [i] >= current_offset);
2181 encode_value (offsets [i] - current_offset, p, &p);
2183 current_offset = offsets [i];
2186 if (ngroups && index_offsets [ngroups - 1] < 65000)
2187 index_entry_size = 2;
2189 index_entry_size = 4;
2191 /* Emit the header */
2192 emit_int32 (acfg, noffsets);
2193 emit_int32 (acfg, group_size);
2194 emit_int32 (acfg, ngroups);
2195 emit_int32 (acfg, index_entry_size);
2197 /* Emit the index */
2198 for (i = 0; i < ngroups; ++i) {
2199 if (index_entry_size == 2)
2200 emit_int16 (acfg, index_offsets [i]);
2202 emit_int32 (acfg, index_offsets [i]);
2206 emit_bytes (acfg, buf, p - buf);
2208 return (int)(p - buf) + (ngroups * 4);
2212 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2216 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2220 index = g_hash_table_size (cfg->image_hash);
2221 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2222 g_ptr_array_add (cfg->image_table, image);
2228 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2231 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2233 /* FIXME: Search referenced images as well */
2234 if (!acfg->typespec_classes) {
2235 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2236 for (i = 0; i < len; ++i) {
2237 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2240 for (i = 0; i < len; ++i) {
2241 if (acfg->typespec_classes [i] == klass)
2246 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2252 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2255 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2258 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2261 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2264 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2269 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2273 if (klass->generic_class) {
2275 g_assert (klass->type_token);
2277 /* Find a typespec for a class if possible */
2278 token = find_typespec_for_class (acfg, klass);
2280 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2281 encode_value (token, p, &p);
2283 MonoClass *gclass = klass->generic_class->container_class;
2284 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2285 static int count = 0;
2288 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2289 encode_klass_ref (acfg, gclass, p, &p);
2290 encode_ginst (acfg, inst, p, &p);
2294 } else if (klass->type_token) {
2295 int iindex = get_image_index (acfg, klass->image);
2297 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2299 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2300 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2302 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2303 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2304 encode_value (get_image_index (acfg, klass->image), p, &p);
2306 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2307 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2308 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2310 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2311 encode_value (klass->byval_arg.type, p, &p);
2312 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2314 encode_value (container ? 1 : 0, p, &p);
2316 encode_value (container->is_method, p, &p);
2317 g_assert (par->serial == 0);
2318 if (container->is_method)
2319 encode_method_ref (acfg, container->owner.method, p, &p);
2321 encode_klass_ref (acfg, container->owner.klass, p, &p);
2323 encode_value (par->serial, p, &p);
2325 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2326 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2327 encode_type (acfg, &klass->byval_arg, p, &p);
2330 g_assert (klass->rank > 0);
2331 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2332 encode_value (klass->rank, p, &p);
2333 encode_klass_ref (acfg, klass->element_class, p, &p);
2341 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2342 * standard metadata encoding.
2345 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2347 gboolean shared = FALSE;
2350 * The encoding of generic instances is large so emit them only once.
2352 if (klass->generic_class) {
2354 g_assert (klass->type_token);
2356 /* Find a typespec for a class if possible */
2357 token = find_typespec_for_class (acfg, klass);
2360 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2365 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2369 buf2 = g_malloc (1024);
2372 encode_klass_ref_inner (acfg, klass, p, &p);
2373 g_assert (p - buf2 < 1024);
2375 offset = add_to_blob (acfg, buf2, p - buf2);
2378 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2384 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2385 encode_value (offset, p, &p);
2390 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2394 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2396 guint32 token = mono_get_field_token (field);
2399 encode_klass_ref (cfg, field->parent, p, &p);
2400 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2401 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2406 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2411 encode_value (inst->type_argc, p, &p);
2412 for (i = 0; i < inst->type_argc; ++i)
2413 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2418 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2421 MonoGenericInst *inst;
2423 inst = context->class_inst;
2425 g_assert (inst->type_argc);
2426 encode_ginst (acfg, inst, p, &p);
2428 encode_value (0, p, &p);
2430 inst = context->method_inst;
2432 g_assert (inst->type_argc);
2433 encode_ginst (acfg, inst, p, &p);
2435 encode_value (0, p, &p);
2441 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2445 g_assert (t->num_mods == 0);
2446 /* t->attrs can be ignored */
2447 //g_assert (t->attrs == 0);
2450 *p = MONO_TYPE_PINNED;
2454 *p = MONO_TYPE_BYREF;
2462 case MONO_TYPE_VOID:
2463 case MONO_TYPE_BOOLEAN:
2464 case MONO_TYPE_CHAR:
2477 case MONO_TYPE_STRING:
2478 case MONO_TYPE_OBJECT:
2479 case MONO_TYPE_TYPEDBYREF:
2481 case MONO_TYPE_VALUETYPE:
2482 case MONO_TYPE_CLASS:
2483 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2485 case MONO_TYPE_SZARRAY:
2486 encode_klass_ref (acfg, t->data.klass, p, &p);
2489 encode_type (acfg, t->data.type, p, &p);
2491 case MONO_TYPE_GENERICINST: {
2492 MonoClass *gclass = t->data.generic_class->container_class;
2493 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2495 encode_klass_ref (acfg, gclass, p, &p);
2496 encode_ginst (acfg, inst, p, &p);
2499 case MONO_TYPE_ARRAY: {
2500 MonoArrayType *array = t->data.array;
2503 encode_klass_ref (acfg, array->eklass, p, &p);
2504 encode_value (array->rank, p, &p);
2505 encode_value (array->numsizes, p, &p);
2506 for (i = 0; i < array->numsizes; ++i)
2507 encode_value (array->sizes [i], p, &p);
2508 encode_value (array->numlobounds, p, &p);
2509 for (i = 0; i < array->numlobounds; ++i)
2510 encode_value (array->lobounds [i], p, &p);
2514 case MONO_TYPE_MVAR:
2515 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2518 g_assert_not_reached ();
2525 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2531 /* Similar to the metadata encoding */
2532 if (sig->generic_param_count)
2536 if (sig->explicit_this)
2538 flags |= (sig->call_convention & 0x0F);
2542 if (sig->generic_param_count)
2543 encode_value (sig->generic_param_count, p, &p);
2544 encode_value (sig->param_count, p, &p);
2546 encode_type (acfg, sig->ret, p, &p);
2547 for (i = 0; i < sig->param_count; ++i) {
2548 if (sig->sentinelpos == i) {
2549 *p = MONO_TYPE_SENTINEL;
2552 encode_type (acfg, sig->params [i], p, &p);
2558 #define MAX_IMAGE_INDEX 250
2561 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2563 guint32 image_index = get_image_index (acfg, method->klass->image);
2564 guint32 token = method->token;
2565 MonoJumpInfoToken *ji;
2569 * The encoding for most methods is as follows:
2570 * - image index encoded as a leb128
2571 * - token index encoded as a leb128
2572 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2573 * types of method encodings.
2576 /* Mark methods which can't use aot trampolines because they need the further
2577 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2579 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2580 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2581 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2583 if (method->wrapper_type) {
2584 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2586 encode_value (method->wrapper_type, p, &p);
2588 switch (method->wrapper_type) {
2589 case MONO_WRAPPER_REMOTING_INVOKE:
2590 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2591 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2594 m = mono_marshal_method_from_wrapper (method);
2596 encode_method_ref (acfg, m, p, &p);
2599 case MONO_WRAPPER_PROXY_ISINST:
2600 case MONO_WRAPPER_LDFLD:
2601 case MONO_WRAPPER_LDFLDA:
2602 case MONO_WRAPPER_STFLD:
2603 case MONO_WRAPPER_ISINST: {
2604 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2605 encode_klass_ref (acfg, proxy_class, p, &p);
2608 case MONO_WRAPPER_LDFLD_REMOTE:
2609 case MONO_WRAPPER_STFLD_REMOTE:
2611 case MONO_WRAPPER_ALLOC: {
2612 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2614 /* The GC name is saved once in MonoAotFileInfo */
2615 g_assert (info->alloc_type != -1);
2616 encode_value (info->alloc_type, p, &p);
2619 case MONO_WRAPPER_WRITE_BARRIER:
2621 case MONO_WRAPPER_STELEMREF: {
2622 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2625 encode_value (info->subtype, p, &p);
2626 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2627 encode_value (info->d.virtual_stelemref.kind, p, &p);
2630 case MONO_WRAPPER_UNKNOWN: {
2631 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2634 encode_value (info->subtype, p, &p);
2635 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2636 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2637 encode_klass_ref (acfg, method->klass, p, &p);
2638 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2639 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2640 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2641 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2644 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2645 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2648 encode_value (info->subtype, p, &p);
2649 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2650 strcpy ((char*)p, method->name);
2651 p += strlen (method->name) + 1;
2652 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2653 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2655 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2656 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2660 case MONO_WRAPPER_SYNCHRONIZED: {
2663 m = mono_marshal_method_from_wrapper (method);
2665 g_assert (m != method);
2666 encode_method_ref (acfg, m, p, &p);
2669 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2670 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2673 encode_value (info->subtype, p, &p);
2675 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2676 encode_value (info->d.element_addr.rank, p, &p);
2677 encode_value (info->d.element_addr.elem_size, p, &p);
2678 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2679 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2681 g_assert_not_reached ();
2685 case MONO_WRAPPER_CASTCLASS: {
2686 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2689 encode_value (info->subtype, p, &p);
2692 case MONO_WRAPPER_RUNTIME_INVOKE: {
2693 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2696 encode_value (info->subtype, p, &p);
2697 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2698 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2699 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2700 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2703 case MONO_WRAPPER_DELEGATE_INVOKE:
2704 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2705 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2706 if (method->is_inflated) {
2707 /* These wrappers are identified by their class */
2708 encode_value (1, p, &p);
2709 encode_klass_ref (acfg, method->klass, p, &p);
2711 MonoMethodSignature *sig = mono_method_signature (method);
2712 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2714 encode_value (0, p, &p);
2715 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2716 encode_value (info ? info->subtype : 0, p, &p);
2717 encode_signature (acfg, sig, p, &p);
2721 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2722 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2725 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2726 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2730 g_assert_not_reached ();
2732 } else if (mono_method_signature (method)->is_inflated) {
2734 * This is a generic method, find the original token which referenced it and
2736 * Obtain the token from information recorded by the JIT.
2738 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2740 image_index = get_image_index (acfg, ji->image);
2741 g_assert (image_index < MAX_IMAGE_INDEX);
2744 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2745 encode_value (image_index, p, &p);
2746 encode_value (token, p, &p);
2748 MonoMethod *declaring;
2749 MonoGenericContext *context = mono_method_get_context (method);
2751 g_assert (method->is_inflated);
2752 declaring = ((MonoMethodInflated*)method)->declaring;
2755 * This might be a non-generic method of a generic instance, which
2756 * doesn't have a token since the reference is generated by the JIT
2757 * like Nullable:Box/Unbox, or by generic sharing.
2759 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2760 /* Encode the klass */
2761 encode_klass_ref (acfg, method->klass, p, &p);
2762 /* Encode the method */
2763 image_index = get_image_index (acfg, method->klass->image);
2764 g_assert (image_index < MAX_IMAGE_INDEX);
2765 g_assert (declaring->token);
2766 token = declaring->token;
2767 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2768 encode_value (image_index, p, &p);
2769 encode_value (token, p, &p);
2770 encode_generic_context (acfg, context, p, &p);
2772 } else if (token == 0) {
2773 /* This might be a method of a constructed type like int[,].Set */
2774 /* Obtain the token from information recorded by the JIT */
2775 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2777 image_index = get_image_index (acfg, ji->image);
2778 g_assert (image_index < MAX_IMAGE_INDEX);
2781 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2782 encode_value (image_index, p, &p);
2783 encode_value (token, p, &p);
2786 g_assert (method->klass->rank);
2788 /* Encode directly */
2789 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2790 encode_klass_ref (acfg, method->klass, p, &p);
2791 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2792 encode_value (0, p, &p);
2793 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2794 encode_value (1, p, &p);
2795 else if (!strcmp (method->name, "Get"))
2796 encode_value (2, p, &p);
2797 else if (!strcmp (method->name, "Address"))
2798 encode_value (3, p, &p);
2799 else if (!strcmp (method->name, "Set"))
2800 encode_value (4, p, &p);
2802 g_assert_not_reached ();
2805 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2807 if (image_index >= MONO_AOT_METHODREF_MIN) {
2808 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2809 encode_value (image_index, p, &p);
2810 encode_value (mono_metadata_token_index (token), p, &p);
2812 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2819 compare_patches (gconstpointer a, gconstpointer b)
2823 i = (*(MonoJumpInfo**)a)->ip.i;
2824 j = (*(MonoJumpInfo**)b)->ip.i;
2835 static G_GNUC_UNUSED char*
2836 patch_to_string (MonoJumpInfo *patch_info)
2840 str = g_string_new ("");
2842 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2844 switch (patch_info->type) {
2845 case MONO_PATCH_INFO_VTABLE:
2846 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2851 g_string_append_printf (str, ")");
2852 return g_string_free (str, FALSE);
2858 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2861 static inline gboolean
2862 is_plt_patch (MonoJumpInfo *patch_info)
2864 switch (patch_info->type) {
2865 case MONO_PATCH_INFO_METHOD:
2866 case MONO_PATCH_INFO_INTERNAL_METHOD:
2867 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2868 case MONO_PATCH_INFO_ICALL_ADDR:
2869 case MONO_PATCH_INFO_CLASS_INIT:
2870 case MONO_PATCH_INFO_RGCTX_FETCH:
2871 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2872 case MONO_PATCH_INFO_MONITOR_ENTER:
2873 case MONO_PATCH_INFO_MONITOR_EXIT:
2874 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2884 * Return the symbol identifying the plt entry PLT_OFFSET.
2887 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2891 * The Apple linker reorganizes object files, so it doesn't like branches to local
2892 * labels, since those have no relocations.
2894 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2896 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2903 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2905 static MonoPltEntry*
2906 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2910 if (!is_plt_patch (patch_info))
2913 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2915 // FIXME: This breaks the calculation of final_got_size
2916 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2918 * Allocate a separate PLT slot for each such patch, since some plt
2919 * entries will refer to the method itself, and some will refer to the
2926 MonoJumpInfo *new_ji;
2928 g_assert (!acfg->final_got_size);
2930 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2932 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2933 res->plt_offset = acfg->plt_offset;
2935 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2936 if (acfg->aot_opts.write_symbols)
2937 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2939 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2941 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2943 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2945 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2947 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2948 //mono_print_ji (patch_info); printf ("\n");
2949 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2951 acfg->plt_offset ++;
2960 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2961 * JI could be found if it exists, otherwise allocates a new one.
2964 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2968 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2970 return got_offset - 1;
2972 got_offset = acfg->got_offset;
2973 acfg->got_offset ++;
2975 if (acfg->final_got_size)
2976 g_assert (got_offset < acfg->final_got_size);
2978 acfg->stats.got_slots ++;
2979 acfg->stats.got_slot_types [ji->type] ++;
2981 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2982 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2983 g_ptr_array_add (acfg->got_patches, ji);
2988 /* Add a method to the list of methods which need to be emitted */
2990 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2993 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2994 g_ptr_array_add (acfg->methods, method);
2995 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2996 acfg->nmethods = acfg->methods->len + 1;
2999 if (method->wrapper_type || extra)
3000 g_ptr_array_add (acfg->extra_methods, method);
3004 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3006 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3014 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3018 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3022 index = acfg->method_index;
3023 add_method_with_index (acfg, method, index, extra);
3025 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3027 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3029 acfg->method_index ++;
3035 add_method (MonoAotCompile *acfg, MonoMethod *method)
3037 return add_method_full (acfg, method, FALSE, 0);
3041 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3043 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3044 method = mini_get_shared_method (method);
3046 if (acfg->aot_opts.log_generics)
3047 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3049 add_method_full (acfg, method, TRUE, depth);
3053 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3055 add_extra_method_with_depth (acfg, method, 0);
3059 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3061 MonoAotCompile *acfg = user_data;
3062 MonoJitICallInfo *callinfo = value;
3063 MonoMethod *wrapper;
3069 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3070 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3073 add_method (acfg, wrapper);
3077 get_runtime_invoke_sig (MonoMethodSignature *sig)
3079 MonoMethodBuilder *mb;
3082 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3083 m = mono_mb_create_method (mb, sig, 16);
3084 return mono_marshal_get_runtime_invoke (m, FALSE);
3088 can_marshal_struct (MonoClass *klass)
3090 MonoClassField *field;
3091 gboolean can_marshal = TRUE;
3092 gpointer iter = NULL;
3093 MonoMarshalType *info;
3096 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3099 info = mono_marshal_load_type_info (klass);
3101 /* Only allow a few field types to avoid asserts in the marshalling code */
3102 while ((field = mono_class_get_fields (klass, &iter))) {
3103 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3106 switch (field->type->type) {
3111 case MONO_TYPE_BOOLEAN:
3114 case MONO_TYPE_CHAR:
3122 case MONO_TYPE_STRING:
3124 case MONO_TYPE_VALUETYPE:
3125 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3126 can_marshal = FALSE;
3128 case MONO_TYPE_SZARRAY: {
3129 gboolean has_mspec = FALSE;
3132 for (i = 0; i < info->num_fields; ++i) {
3133 if (info->fields [i].field == field && info->fields [i].mspec)
3138 can_marshal = FALSE;
3142 can_marshal = FALSE;
3148 /* Its hard to compute whenever these can be marshalled or not */
3149 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3156 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3158 /* Create a vtype instantiation */
3159 MonoGenericContext shared_context;
3161 MonoGenericInst *inst;
3162 MonoGenericContainer *container;
3163 MonoClass **constraints;
3166 memset (ctx, 0, sizeof (MonoGenericContext));
3168 if (method->klass->generic_container) {
3169 shared_context = method->klass->generic_container->context;
3170 inst = shared_context.class_inst;
3172 args = g_new0 (MonoType*, inst->type_argc);
3173 for (i = 0; i < inst->type_argc; ++i) {
3174 args [i] = &mono_defaults.int_class->byval_arg;
3176 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3178 if (method->is_generic) {
3179 container = mono_method_get_generic_container (method);
3180 shared_context = container->context;
3181 inst = shared_context.method_inst;
3183 args = g_new0 (MonoType*, inst->type_argc);
3184 for (i = 0; i < container->type_argc; ++i) {
3185 MonoGenericParamInfo *info = &container->type_params [i].info;
3186 gboolean ref_only = FALSE;
3188 if (info && info->constraints) {
3189 constraints = info->constraints;
3191 while (*constraints) {
3192 MonoClass *cklass = *constraints;
3193 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3194 /* Inflaring the method with our vtype would not be valid */
3201 args [i] = &mono_defaults.object_class->byval_arg;
3203 args [i] = &mono_defaults.int_class->byval_arg;
3205 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3210 add_wrappers (MonoAotCompile *acfg)
3212 MonoMethod *method, *m;
3214 MonoMethodSignature *sig, *csig;
3218 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3219 * so there is only one wrapper of a given type, or inlining their contents into their
3224 * FIXME: This depends on the fact that different wrappers have different
3228 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3230 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3231 gboolean skip = FALSE;
3233 method = mono_get_method (acfg->image, token, NULL);
3235 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3236 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3237 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3240 if (method->is_generic || method->klass->generic_container)
3243 /* Skip methods which can not be handled by get_runtime_invoke () */
3244 sig = mono_method_signature (method);
3247 if ((sig->ret->type == MONO_TYPE_PTR) ||
3248 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3251 for (j = 0; j < sig->param_count; j++) {
3252 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3256 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3257 if (!mono_class_is_contextbound (method->klass)) {
3258 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3259 gboolean has_nullable = FALSE;
3261 for (j = 0; j < sig->param_count; j++) {
3262 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3263 has_nullable = TRUE;
3266 if (info && !has_nullable) {
3267 /* Supported by the dynamic runtime-invoke wrapper */
3275 //printf ("%s\n", mono_method_full_name (method, TRUE));
3276 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3280 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3281 MonoMethodDesc *desc;
3282 MonoMethod *orig_method;
3285 /* Runtime invoke wrappers */
3287 /* void runtime-invoke () [.cctor] */
3288 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3289 csig->ret = &mono_defaults.void_class->byval_arg;
3290 add_method (acfg, get_runtime_invoke_sig (csig));
3292 /* void runtime-invoke () [Finalize] */
3293 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3295 csig->ret = &mono_defaults.void_class->byval_arg;
3296 add_method (acfg, get_runtime_invoke_sig (csig));
3298 /* void runtime-invoke (string) [exception ctor] */
3299 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3301 csig->ret = &mono_defaults.void_class->byval_arg;
3302 csig->params [0] = &mono_defaults.string_class->byval_arg;
3303 add_method (acfg, get_runtime_invoke_sig (csig));
3305 /* void runtime-invoke (string, string) [exception ctor] */
3306 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3308 csig->ret = &mono_defaults.void_class->byval_arg;
3309 csig->params [0] = &mono_defaults.string_class->byval_arg;
3310 csig->params [1] = &mono_defaults.string_class->byval_arg;
3311 add_method (acfg, get_runtime_invoke_sig (csig));
3313 /* string runtime-invoke () [Exception.ToString ()] */
3314 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3316 csig->ret = &mono_defaults.string_class->byval_arg;
3317 add_method (acfg, get_runtime_invoke_sig (csig));
3319 /* void runtime-invoke (string, Exception) [exception ctor] */
3320 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3322 csig->ret = &mono_defaults.void_class->byval_arg;
3323 csig->params [0] = &mono_defaults.string_class->byval_arg;
3324 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3325 add_method (acfg, get_runtime_invoke_sig (csig));
3327 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3328 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3330 csig->ret = &(mono_class_from_name (
3331 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3332 csig->params [0] = &mono_defaults.string_class->byval_arg;
3333 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3334 add_method (acfg, get_runtime_invoke_sig (csig));
3336 /* runtime-invoke used by finalizers */
3337 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3339 /* This is used by mono_runtime_capture_context () */
3340 method = mono_get_context_capture_method ();
3342 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3344 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3345 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3349 add_method (acfg, mono_marshal_get_stelemref ());
3351 if (MONO_ARCH_HAVE_TLS_GET) {
3352 /* Managed Allocators */
3353 nallocators = mono_gc_get_managed_allocator_types ();
3354 for (i = 0; i < nallocators; ++i) {
3355 m = mono_gc_get_managed_allocator_by_type (i);
3357 add_method (acfg, m);
3360 /* Monitor Enter/Exit */
3361 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3362 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3363 /* This is a v4 method */
3365 method = mono_monitor_get_fast_path (orig_method);
3367 add_method (acfg, method);
3369 mono_method_desc_free (desc);
3371 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3372 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3373 g_assert (orig_method);
3374 mono_method_desc_free (desc);
3375 method = mono_monitor_get_fast_path (orig_method);
3377 add_method (acfg, method);
3380 /* Stelemref wrappers */
3382 MonoMethod **wrappers;
3385 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3386 for (i = 0; i < nwrappers; ++i)
3387 add_method (acfg, wrappers [i]);
3391 /* castclass_with_check wrapper */
3392 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3393 /* isinst_with_check wrapper */
3394 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3396 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3398 MonoMethodDesc *desc;
3401 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3402 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3403 mono_method_desc_free (desc);
3405 m = mono_monitor_get_fast_path (m);
3407 add_method (acfg, m);
3412 /* JIT icall wrappers */
3413 /* FIXME: locking */
3414 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3418 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3419 * we use the original method instead at runtime.
3420 * Since full-aot doesn't support remoting, this is not a problem.
3423 /* remoting-invoke wrappers */
3424 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3425 MonoMethodSignature *sig;
3427 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3428 method = mono_get_method (acfg->image, token, NULL);
3430 sig = mono_method_signature (method);
3432 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3433 m = mono_marshal_get_remoting_invoke_with_check (method);
3435 add_method (acfg, m);
3440 /* delegate-invoke wrappers */
3441 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3443 MonoCustomAttrInfo *cattr;
3445 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3446 klass = mono_class_get (acfg->image, token);
3449 mono_loader_clear_error ();
3453 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3456 if (!klass->generic_container) {
3457 method = mono_get_delegate_invoke (klass);
3459 m = mono_marshal_get_delegate_invoke (method, NULL);
3461 add_method (acfg, m);
3463 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3465 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3467 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3469 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3471 cattr = mono_custom_attrs_from_class (klass);
3476 for (j = 0; j < cattr->num_attrs; ++j)
3477 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3479 if (j < cattr->num_attrs)
3480 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3482 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3483 MonoGenericContext ctx;
3484 MonoMethod *inst, *gshared;
3487 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3490 method = mono_get_delegate_invoke (klass);
3491 create_gsharedvt_inst (acfg, method, &ctx);
3493 inst = mono_class_inflate_generic_method (method, &ctx);
3495 m = mono_marshal_get_delegate_invoke (inst, NULL);
3496 g_assert (m->is_inflated);
3498 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3499 add_extra_method (acfg, gshared);
3502 method = mono_get_delegate_begin_invoke (klass);
3503 create_gsharedvt_inst (acfg, method, &ctx);
3505 inst = mono_class_inflate_generic_method (method, &ctx);
3507 m = mono_marshal_get_delegate_begin_invoke (inst);
3508 g_assert (m->is_inflated);
3510 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3511 add_extra_method (acfg, gshared);
3514 method = mono_get_delegate_end_invoke (klass);
3515 create_gsharedvt_inst (acfg, method, &ctx);
3517 inst = mono_class_inflate_generic_method (method, &ctx);
3519 m = mono_marshal_get_delegate_end_invoke (inst);
3520 g_assert (m->is_inflated);
3522 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3523 add_extra_method (acfg, gshared);
3528 /* array access wrappers */
3529 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3532 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3533 klass = mono_class_get (acfg->image, token);
3536 mono_loader_clear_error ();
3540 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3541 MonoMethod *m, *wrapper;
3543 /* Add runtime-invoke wrappers too */
3545 m = mono_class_get_method_from_name (klass, "Get", -1);
3547 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3548 add_extra_method (acfg, wrapper);
3549 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3551 m = mono_class_get_method_from_name (klass, "Set", -1);
3553 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3554 add_extra_method (acfg, wrapper);
3555 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3559 /* Synchronized wrappers */
3560 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3561 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3562 method = mono_get_method (acfg->image, token, NULL);
3564 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3565 if (method->is_generic) {
3567 } else if (method->klass->generic_container) {
3568 MonoGenericContext ctx;
3569 MonoMethod *inst, *gshared, *m;
3572 * Create a generic wrapper for a generic instance, and AOT that.
3574 create_gsharedvt_inst (acfg, method, &ctx);
3575 inst = mono_class_inflate_generic_method (method, &ctx);
3576 m = mono_marshal_get_synchronized_wrapper (inst);
3577 g_assert (m->is_inflated);
3578 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3579 add_method (acfg, gshared);
3581 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3586 /* pinvoke wrappers */
3587 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3589 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3591 method = mono_get_method (acfg->image, token, NULL);
3593 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3594 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3595 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3599 /* native-to-managed wrappers */
3600 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3602 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3603 MonoCustomAttrInfo *cattr;
3606 method = mono_get_method (acfg->image, token, NULL);
3609 * Only generate native-to-managed wrappers for methods which have an
3610 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3611 * name to avoid defining a new assembly to contain it.
3613 cattr = mono_custom_attrs_from_method (method);
3616 for (j = 0; j < cattr->num_attrs; ++j)
3617 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3619 if (j < cattr->num_attrs) {
3620 MonoCustomAttrEntry *e = &cattr->attrs [j];
3621 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3622 const char *p = (const char*)e->data;
3624 int slen, num_named, named_type, data_type;
3628 char *export_name = NULL;
3629 MonoMethod *wrapper;
3631 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3632 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3633 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3634 mono_method_full_name (method, TRUE));
3638 g_assert (sig->param_count == 1);
3639 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3642 * Decode the cattr manually since we can't create objects
3643 * during aot compilation.
3649 /* From load_cattr_value () in reflection.c */
3650 slen = mono_metadata_decode_value (p, &p);
3651 n = g_memdup (p, slen + 1);
3653 t = mono_reflection_type_from_name (n, acfg->image);
3657 klass = mono_class_from_mono_type (t);
3658 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3662 num_named = read16 (p);
3665 g_assert (num_named < 2);
3666 if (num_named == 1) {
3669 MonoType *prop_type;
3671 /* parse ExportSymbol attribute */
3673 named_type = *named;
3678 name_len = mono_metadata_decode_blob_size (named, &named);
3679 name = g_malloc (name_len + 1);
3680 memcpy (name, named, name_len);
3681 name [name_len] = 0;
3684 g_assert (named_type == 0x54);
3685 g_assert (!strcmp (name, "ExportSymbol"));
3687 prop_type = &mono_defaults.string_class->byval_arg;
3689 /* load_cattr_value (), string case */
3690 g_assert (*named != (char)0xff);
3691 slen = mono_metadata_decode_value (named, &named);
3692 export_name = g_malloc (slen + 1);
3693 memcpy (export_name, named, slen);
3694 export_name [slen] = 0;
3698 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3699 add_method (acfg, wrapper);
3701 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3705 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3706 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3707 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3711 /* StructureToPtr/PtrToStructure wrappers */
3712 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3715 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3716 klass = mono_class_get (acfg->image, token);
3719 mono_loader_clear_error ();
3723 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3724 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3725 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3726 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3732 has_type_vars (MonoClass *klass)
3734 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3737 return has_type_vars (klass->element_class);
3738 if (klass->generic_class) {
3739 MonoGenericContext *context = &klass->generic_class->context;
3740 if (context->class_inst) {
3743 for (i = 0; i < context->class_inst->type_argc; ++i)
3744 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3748 if (klass->generic_container)
3754 is_vt_inst (MonoGenericInst *inst)
3758 for (i = 0; i < inst->type_argc; ++i) {
3759 MonoType *t = inst->type_argv [i];
3760 if (t->type == MONO_TYPE_VALUETYPE)
3767 method_has_type_vars (MonoMethod *method)
3769 if (has_type_vars (method->klass))
3772 if (method->is_inflated) {
3773 MonoGenericContext *context = mono_method_get_context (method);
3774 if (context->method_inst) {
3777 for (i = 0; i < context->method_inst->type_argc; ++i)
3778 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3785 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3788 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3790 /* This might lead to a huge code blowup so only do it if neccesary */
3791 if (!acfg->aot_opts.full_aot && !force)
3794 add_generic_class_with_depth (acfg, klass, 0, ref);
3798 check_type_depth (MonoType *t, int depth)
3806 case MONO_TYPE_GENERICINST: {
3807 MonoGenericClass *gklass = t->data.generic_class;
3808 MonoGenericInst *ginst = gklass->context.class_inst;
3811 for (i = 0; i < ginst->type_argc; ++i) {
3812 if (check_type_depth (ginst->type_argv [i], depth + 1))
3826 * add_generic_class:
3828 * Add all methods of a generic class.
3831 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3834 MonoClassField *field;
3836 gboolean use_gsharedvt = FALSE;
3838 if (!acfg->ginst_hash)
3839 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3841 mono_class_init (klass);
3843 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3846 if (has_type_vars (klass))
3849 if (!klass->generic_class && !klass->rank)
3852 if (klass->exception_type)
3855 if (!acfg->ginst_hash)
3856 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3858 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3861 if (check_type_depth (&klass->byval_arg, 0))
3864 if (acfg->aot_opts.log_generics)
3865 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3867 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3870 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3871 * Enable this only for some classes since gsharedvt might not support all methods.
3873 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")))
3874 use_gsharedvt = TRUE;
3877 while ((method = mono_class_get_methods (klass, &iter))) {
3878 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3880 * This is partial sharing, and we can't handle it yet
3885 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt))
3889 if (method->is_generic)
3894 * FIXME: Instances which are referenced by these methods are not added,
3895 * for example Array.Resize<int> for List<int>.Add ().
3897 add_extra_method_with_depth (acfg, method, depth + 1);
3901 while ((field = mono_class_get_fields (klass, &iter))) {
3902 if (field->type->type == MONO_TYPE_GENERICINST)
3903 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3906 if (klass->delegate) {
3907 method = mono_get_delegate_invoke (klass);
3909 method = mono_marshal_get_delegate_invoke (method, NULL);
3911 if (acfg->aot_opts.log_generics)
3912 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3914 add_method (acfg, method);
3917 /* Add superclasses */
3919 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3922 * For ICollection<T>, add instances of the helper methods
3923 * in Array, since a T[] could be cast to ICollection<T>.
3925 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3926 (!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"))) {
3927 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3928 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3932 if (!strcmp (klass->name, "IEnumerator`1"))
3933 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3935 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3937 /* Add the T[]/InternalEnumerator class */
3938 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3942 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3943 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3947 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3948 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3952 while ((method = mono_class_get_methods (array_class, &iter))) {
3953 if (strstr (method->name, name_prefix)) {
3954 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3956 add_extra_method_with_depth (acfg, m, depth);
3960 g_free (name_prefix);
3963 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3964 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3965 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3966 MonoClass *icomparable, *gcomparer;
3967 MonoGenericContext ctx;
3968 MonoType *args [16];
3970 memset (&ctx, 0, sizeof (ctx));
3972 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3973 g_assert (icomparable);
3974 args [0] = &tclass->byval_arg;
3975 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3977 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3978 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3979 g_assert (gcomparer);
3980 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3984 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3985 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3986 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3987 MonoClass *iface, *gcomparer;
3988 MonoGenericContext ctx;
3989 MonoType *args [16];
3991 memset (&ctx, 0, sizeof (ctx));
3993 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3995 args [0] = &tclass->byval_arg;
3996 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3998 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3999 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4000 g_assert (gcomparer);
4001 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4007 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4010 MonoGenericContext ctx;
4011 MonoType *args [16];
4013 if (acfg->aot_opts.no_instances)
4016 memset (&ctx, 0, sizeof (ctx));
4018 for (i = 0; i < ninsts; ++i) {
4019 args [0] = insts [i];
4020 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4021 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4026 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4028 MonoMethodHeader *header;
4029 MonoMethodSignature *sig;
4032 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4034 sig = mono_method_signature (method);
4037 for (j = 0; j < sig->param_count; ++j)
4038 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4039 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4042 header = mono_method_get_header (method);
4045 for (j = 0; j < header->num_locals; ++j)
4046 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4047 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4049 mono_loader_clear_error ();
4054 * add_generic_instances:
4056 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4059 add_generic_instances (MonoAotCompile *acfg)
4064 MonoGenericContext *context;
4066 if (acfg->aot_opts.no_instances)
4069 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4070 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4071 method = mono_get_method (acfg->image, token, NULL);
4076 if (method->klass->image != acfg->image)
4079 context = mono_method_get_context (method);
4081 if (context && ((context->class_inst && context->class_inst->is_open)))
4085 * For open methods, create an instantiation which can be passed to the JIT.
4086 * FIXME: Handle class_inst as well.
4088 if (context && context->method_inst && context->method_inst->is_open) {
4089 MonoGenericContext shared_context;
4090 MonoGenericInst *inst;
4091 MonoType **type_argv;
4093 MonoMethod *declaring_method;
4094 gboolean supported = TRUE;
4096 /* Check that the context doesn't contain open constructed types */
4097 if (context->class_inst) {
4098 inst = context->class_inst;
4099 for (i = 0; i < inst->type_argc; ++i) {
4100 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)
4102 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4106 if (context->method_inst) {
4107 inst = context->method_inst;
4108 for (i = 0; i < inst->type_argc; ++i) {
4109 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)
4111 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4119 memset (&shared_context, 0, sizeof (MonoGenericContext));
4121 inst = context->class_inst;
4123 type_argv = g_new0 (MonoType*, inst->type_argc);
4124 for (i = 0; i < inst->type_argc; ++i) {
4125 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
4126 type_argv [i] = &mono_defaults.object_class->byval_arg;
4128 type_argv [i] = inst->type_argv [i];
4131 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4135 inst = context->method_inst;
4137 type_argv = g_new0 (MonoType*, inst->type_argc);
4138 for (i = 0; i < inst->type_argc; ++i) {
4139 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)
4140 type_argv [i] = &mono_defaults.object_class->byval_arg;
4142 type_argv [i] = inst->type_argv [i];
4145 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4149 if (method->is_generic || method->klass->generic_container)
4150 declaring_method = method;
4152 declaring_method = mono_method_get_declaring_generic_method (method);
4154 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4158 * If the method is fully sharable, it was already added in place of its
4159 * generic definition.
4161 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4165 * FIXME: Partially shared methods are not shared here, so we end up with
4166 * many identical methods.
4168 add_extra_method (acfg, method);
4171 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4174 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4176 klass = mono_class_get (acfg->image, token);
4177 if (!klass || klass->rank) {
4178 mono_loader_clear_error ();
4182 add_generic_class (acfg, klass, FALSE, "typespec");
4185 /* Add types of args/locals */
4186 for (i = 0; i < acfg->methods->len; ++i) {
4187 method = g_ptr_array_index (acfg->methods, i);
4188 add_types_from_method_header (acfg, method);
4191 if (acfg->image == mono_defaults.corlib) {
4193 MonoType *insts [256];
4196 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4197 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4198 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4199 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4200 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4201 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4202 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4203 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4204 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4205 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4206 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4207 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4209 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4210 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4212 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4213 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4215 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4217 /* Add instances of the array generic interfaces for primitive types */
4218 /* This will add instances of the InternalArray_ helper methods in Array too */
4219 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4221 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4222 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4224 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4225 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4227 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4230 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4231 * used for all instances of GetGenericValueImpl by the AOT runtime.
4234 MonoGenericContext ctx;
4235 MonoType *args [16];
4236 MonoMethod *get_method;
4237 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4239 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4242 memset (&ctx, 0, sizeof (ctx));
4243 args [0] = &mono_defaults.object_class->byval_arg;
4244 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4245 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4249 /* Same for CompareExchange<T>/Exchange<T> */
4251 MonoGenericContext ctx;
4252 MonoType *args [16];
4254 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4255 gpointer iter = NULL;
4257 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4258 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4259 memset (&ctx, 0, sizeof (ctx));
4260 args [0] = &mono_defaults.object_class->byval_arg;
4261 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4262 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4267 /* Same for Volatile.Read/Write<T> */
4269 MonoGenericContext ctx;
4270 MonoType *args [16];
4272 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4273 gpointer iter = NULL;
4275 if (volatile_klass) {
4276 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4277 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4278 memset (&ctx, 0, sizeof (ctx));
4279 args [0] = &mono_defaults.object_class->byval_arg;
4280 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4281 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4290 * is_direct_callable:
4292 * Return whenever the method identified by JI is directly callable without
4293 * going through the PLT.
4296 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4298 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4299 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4301 gboolean direct_callable = TRUE;
4303 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4304 direct_callable = FALSE;
4305 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4306 // FIXME: Maybe call the wrapper directly ?
4307 direct_callable = FALSE;
4309 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4310 /* Disable this so all calls go through load_method (), see the
4311 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4312 * mono_debugger_agent_init ().
4314 direct_callable = FALSE;
4317 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4318 /* sgen does some initialization when the allocator method is created */
4319 direct_callable = FALSE;
4321 if (direct_callable)
4324 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4325 if (acfg->aot_opts.direct_pinvoke)
4327 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4328 if (acfg->aot_opts.direct_icalls)
4337 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4339 MonoImage *image = method->klass->image;
4340 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4341 MonoTableInfo *tables = image->tables;
4342 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4343 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4344 guint32 im_cols [MONO_IMPLMAP_SIZE];
4347 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4351 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4354 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4356 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4359 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4361 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4367 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4369 if (a->native_offset == b->native_offset)
4370 return a->il_offset - b->il_offset;
4372 return a->native_offset - b->native_offset;
4376 * compute_line_numbers:
4378 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4381 static MonoDebugSourceLocation**
4382 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4384 MonoDebugMethodInfo *minfo;
4385 MonoDebugLineNumberEntry *ln_array;
4386 MonoDebugSourceLocation *loc;
4387 int i, prev_line, prev_il_offset;
4388 int *native_to_il_offset = NULL;
4389 MonoDebugSourceLocation **res;
4392 minfo = mono_debug_lookup_method (method);
4395 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4396 if (debug_info->code_size != code_size)
4399 g_assert (code_size);
4401 /* Compute the native->IL offset mapping */
4403 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4404 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4406 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4408 native_to_il_offset = g_new0 (int, code_size + 1);
4410 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4412 MonoDebugLineNumberEntry *lne = &ln_array [i];
4415 for (j = 0; j < lne->native_offset; ++j)
4416 native_to_il_offset [j] = -1;
4419 if (i < debug_info->num_line_numbers - 1) {
4420 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4422 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4423 native_to_il_offset [j] = lne->il_offset;
4425 for (j = lne->native_offset; j < code_size; ++j)
4426 native_to_il_offset [j] = lne->il_offset;
4431 /* Compute the native->line number mapping */
4432 res = g_new0 (MonoDebugSourceLocation*, code_size);
4433 prev_il_offset = -1;
4436 for (i = 0; i < code_size; ++i) {
4437 int il_offset = native_to_il_offset [i];
4439 if (il_offset == -1 || il_offset == prev_il_offset)
4441 prev_il_offset = il_offset;
4442 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4443 if (!(loc && loc->source_file))
4445 if (loc->row == prev_line) {
4446 mono_debug_symfile_free_location (loc);
4449 prev_line = loc->row;
4450 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4452 /* This will cover the prolog too */
4462 get_file_index (MonoAotCompile *acfg, const char *source_file)
4466 // FIXME: Free these
4467 if (!acfg->dwarf_ln_filenames)
4468 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4469 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4471 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4472 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4473 emit_unset_mode (acfg);
4474 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4480 * emit_and_reloc_code:
4482 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4483 * is true, calls are made through the GOT too. This is used for emitting trampolines
4484 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4485 * since trampolines are needed to make PTL work.
4488 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4490 int i, pindex, start_index, method_index;
4492 MonoJumpInfo *patch_info;
4493 MonoMethodHeader *header;
4494 MonoDebugSourceLocation **locs = NULL;
4495 gboolean skip, direct_call, external_call;
4497 const char *direct_call_target = 0;
4498 const char *direct_pinvoke;
4501 header = mono_method_get_header (method);
4503 method_index = get_method_index (acfg, method);
4506 if (acfg->gas_line_numbers && method && debug_info) {
4507 locs = compute_line_numbers (method, code_len, debug_info);
4509 int findex = get_file_index (acfg, "<unknown>");
4510 emit_unset_mode (acfg);
4511 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4515 /* Collect and sort relocations */
4516 patches = g_ptr_array_new ();
4517 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4518 g_ptr_array_add (patches, patch_info);
4519 g_ptr_array_sort (patches, compare_patches);
4522 for (i = 0; i < code_len; i++) {
4524 for (pindex = start_index; pindex < patches->len; ++pindex) {
4525 patch_info = g_ptr_array_index (patches, pindex);
4526 if (patch_info->ip.i >= i)
4530 if (locs && locs [i]) {
4531 MonoDebugSourceLocation *loc = locs [i];
4534 findex = get_file_index (acfg, loc->source_file);
4535 emit_unset_mode (acfg);
4536 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4537 mono_debug_symfile_free_location (loc);
4541 #ifdef MONO_ARCH_AOT_SUPPORTED
4542 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4543 start_index = pindex;
4545 switch (patch_info->type) {
4546 case MONO_PATCH_INFO_NONE:
4548 case MONO_PATCH_INFO_GOT_OFFSET: {
4551 arch_emit_got_offset (acfg, code + i, &code_size);
4554 patch_info->type = MONO_PATCH_INFO_NONE;
4557 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4558 int code_size, index;
4559 char *selector = (void*)patch_info->data.target;
4561 if (!acfg->objc_selector_to_index)
4562 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4563 if (!acfg->objc_selectors)
4564 acfg->objc_selectors = g_ptr_array_new ();
4565 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4569 index = acfg->objc_selector_index;
4570 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4571 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4572 acfg->objc_selector_index ++;
4575 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4578 patch_info->type = MONO_PATCH_INFO_NONE;
4583 * If this patch is a call, try emitting a direct call instead of
4584 * through a PLT entry. This is possible if the called method is in
4585 * the same assembly and requires no initialization.
4587 direct_call = FALSE;
4588 external_call = FALSE;
4589 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4590 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4591 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4592 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4594 direct_call_target = callee_cfg->asm_symbol;
4595 patch_info->type = MONO_PATCH_INFO_NONE;
4596 acfg->stats.direct_calls ++;
4599 acfg->stats.all_calls ++;
4600 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4601 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4602 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4603 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4605 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4606 if (direct_pinvoke) {
4608 g_assert (strlen (direct_pinvoke) < 1000);
4609 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4612 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4613 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4614 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4615 /* Call to a C function implementing a jit icall */
4617 external_call = TRUE;
4618 g_assert (strlen (sym) < 1000);
4619 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4621 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4622 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4623 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4624 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4625 /* Call to a jit icall without a wrapper */
4627 external_call = TRUE;
4628 g_assert (strlen (sym) < 1000);
4629 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4634 patch_info->type = MONO_PATCH_INFO_NONE;
4635 acfg->stats.direct_calls ++;
4638 if (!got_only && !direct_call) {
4639 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4641 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4643 direct_call_target = plt_entry->symbol;
4645 /* Nullify the patch */
4646 patch_info->type = MONO_PATCH_INFO_NONE;
4647 plt_entry->jit_used = TRUE;
4654 arch_emit_direct_call (acfg, direct_call_target, external_call, patch_info, &call_size);
4659 got_slot = get_got_offset (acfg, patch_info);
4661 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4668 #endif /* MONO_ARCH_AOT_SUPPORTED */
4671 /* Find next patch */
4673 for (pindex = start_index; pindex < patches->len; ++pindex) {
4674 patch_info = g_ptr_array_index (patches, pindex);
4675 if (patch_info->ip.i >= i)
4679 /* Try to emit multiple bytes at once */
4680 if (pindex < patches->len && patch_info->ip.i > i) {
4683 for (limit = i + 1; limit < patch_info->ip.i; ++limit) {
4684 if (locs && locs [limit])
4688 emit_bytes (acfg, code + i, limit - i);
4691 emit_bytes (acfg, code + i, 1);
4702 * Modify SYMBOL so it only includes characters permissible in symbols.
4705 sanitize_symbol (char *symbol)
4707 int i, len = strlen (symbol);
4709 for (i = 0; i < len; ++i)
4710 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
4715 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4717 char *name1, *name2, *cached;
4718 int i, j, len, count;
4721 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4722 if (!prefix || !*prefix)
4726 name1 = mono_method_full_name (method, TRUE);
4727 len = strlen (name1);
4728 name2 = malloc (strlen (prefix) + len + 16);
4729 memcpy (name2, prefix, strlen (prefix));
4730 j = strlen (prefix);
4731 for (i = 0; i < len; ++i) {
4732 if (isalnum (name1 [i])) {
4733 name2 [j ++] = name1 [i];
4734 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4736 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4739 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4748 while (g_hash_table_lookup (cache, name2)) {
4749 sprintf (name2 + j, "_%d", count);
4753 cached = g_strdup (name2);
4754 g_hash_table_insert (cache, cached, cached);
4760 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4765 char *debug_sym = NULL;
4766 char *symbol = NULL;
4767 int func_alignment = AOT_FUNC_ALIGNMENT;
4768 MonoMethodHeader *header;
4771 method = cfg->orig_method;
4772 code = cfg->native_code;
4773 header = cfg->header;
4775 method_index = get_method_index (acfg, method);
4776 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4779 /* Make the labels local */
4780 emit_section_change (acfg, ".text", 0);
4781 emit_alignment (acfg, func_alignment);
4783 if (acfg->global_symbols && acfg->need_no_dead_strip)
4784 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4786 emit_label (acfg, cfg->asm_symbol);
4788 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4790 * Write a C style symbol for every method, this has two uses:
4791 * - it works on platforms where the dwarf debugging info is not
4793 * - it allows the setting of breakpoints of aot-ed methods.
4795 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4797 if (acfg->need_no_dead_strip)
4798 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4799 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4800 emit_label (acfg, debug_sym);
4803 export_name = g_hash_table_lookup (acfg->export_names, method);
4805 /* Emit a global symbol for the method */
4806 emit_global_inner (acfg, export_name, TRUE);
4807 emit_label (acfg, export_name);
4810 if (cfg->verbose_level > 0)
4811 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4813 acfg->stats.code_size += cfg->code_len;
4815 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4817 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 ()));
4821 if (acfg->aot_opts.write_symbols) {
4822 emit_symbol_size (acfg, debug_sym, ".");
4826 emit_label (acfg, symbol);
4833 * Encode PATCH_INFO into its disk representation.
4836 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4840 switch (patch_info->type) {
4841 case MONO_PATCH_INFO_NONE:
4843 case MONO_PATCH_INFO_IMAGE:
4844 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4846 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4847 case MONO_PATCH_INFO_JIT_TLS_ID:
4848 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4849 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4851 case MONO_PATCH_INFO_METHOD_REL:
4852 encode_value ((gint)patch_info->data.offset, p, &p);
4854 case MONO_PATCH_INFO_SWITCH: {
4855 gpointer *table = (gpointer *)patch_info->data.table->table;
4858 encode_value (patch_info->data.table->table_size, p, &p);
4859 for (k = 0; k < patch_info->data.table->table_size; k++)
4860 encode_value ((int)(gssize)table [k], p, &p);
4863 case MONO_PATCH_INFO_METHODCONST:
4864 case MONO_PATCH_INFO_METHOD:
4865 case MONO_PATCH_INFO_METHOD_JUMP:
4866 case MONO_PATCH_INFO_ICALL_ADDR:
4867 case MONO_PATCH_INFO_METHOD_RGCTX:
4868 encode_method_ref (acfg, patch_info->data.method, p, &p);
4870 case MONO_PATCH_INFO_INTERNAL_METHOD:
4871 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4872 guint32 len = strlen (patch_info->data.name);
4874 encode_value (len, p, &p);
4876 memcpy (p, patch_info->data.name, len);
4881 case MONO_PATCH_INFO_LDSTR: {
4882 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4883 guint32 token = patch_info->data.token->token;
4884 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4885 encode_value (image_index, p, &p);
4886 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4889 case MONO_PATCH_INFO_RVA:
4890 case MONO_PATCH_INFO_DECLSEC:
4891 case MONO_PATCH_INFO_LDTOKEN:
4892 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4893 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4894 encode_value (patch_info->data.token->token, p, &p);
4895 encode_value (patch_info->data.token->has_context, p, &p);
4896 if (patch_info->data.token->has_context)
4897 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4899 case MONO_PATCH_INFO_EXC_NAME: {
4900 MonoClass *ex_class;
4903 mono_class_from_name (mono_defaults.exception_class->image,
4904 "System", patch_info->data.target);
4905 g_assert (ex_class);
4906 encode_klass_ref (acfg, ex_class, p, &p);
4909 case MONO_PATCH_INFO_R4:
4910 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4912 case MONO_PATCH_INFO_R8:
4913 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4914 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4916 case MONO_PATCH_INFO_VTABLE:
4917 case MONO_PATCH_INFO_CLASS:
4918 case MONO_PATCH_INFO_IID:
4919 case MONO_PATCH_INFO_ADJUSTED_IID:
4920 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4922 case MONO_PATCH_INFO_CLASS_INIT:
4923 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4924 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4926 case MONO_PATCH_INFO_FIELD:
4927 case MONO_PATCH_INFO_SFLDA:
4928 encode_field_info (acfg, patch_info->data.field, p, &p);
4930 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4932 case MONO_PATCH_INFO_RGCTX_FETCH: {
4933 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4938 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4939 * reference the same method, so encode the method only once.
4941 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4943 buf2 = g_malloc (1024);
4946 encode_method_ref (acfg, entry->method, p2, &p2);
4947 g_assert (p2 - buf2 < 1024);
4949 offset = add_to_blob (acfg, buf2, p2 - buf2);
4952 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4957 encode_value (offset, p, &p);
4958 g_assert ((int)entry->info_type < 256);
4959 g_assert (entry->data->type < 256);
4960 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4961 encode_patch (acfg, entry->data, p, &p);
4964 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4965 case MONO_PATCH_INFO_MONITOR_ENTER:
4966 case MONO_PATCH_INFO_MONITOR_EXIT:
4967 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4969 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4970 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4971 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4973 case MONO_PATCH_INFO_SIGNATURE:
4974 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4976 case MONO_PATCH_INFO_TLS_OFFSET:
4977 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
4979 case MONO_PATCH_INFO_GSHAREDVT_CALL:
4980 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
4981 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
4983 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
4984 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
4987 encode_method_ref (acfg, info->method, p, &p);
4988 encode_value (info->entries->len, p, &p);
4989 for (i = 0; i < info->entries->len; ++i) {
4990 MonoRuntimeGenericContextInfoTemplate *template = g_ptr_array_index (info->entries, i);
4992 encode_value (template->info_type, p, &p);
4993 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
4994 case MONO_PATCH_INFO_CLASS:
4995 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
4997 case MONO_PATCH_INFO_FIELD:
4998 encode_field_info (acfg, template->data, p, &p);
5001 g_assert_not_reached ();
5008 g_warning ("unable to handle jump info %d", patch_info->type);
5009 g_assert_not_reached ();
5016 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5019 guint32 pindex, offset;
5020 MonoJumpInfo *patch_info;
5022 encode_value (n_patches, p, &p);
5024 for (pindex = 0; pindex < patches->len; ++pindex) {
5025 patch_info = g_ptr_array_index (patches, pindex);
5027 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5031 offset = get_got_offset (acfg, patch_info);
5032 encode_value (offset, p, &p);
5039 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5043 int pindex, buf_size, n_patches;
5045 MonoJumpInfo *patch_info;
5046 MonoMethodHeader *header;
5047 guint32 method_index;
5049 guint32 first_got_offset;
5051 method = cfg->orig_method;
5052 header = mono_method_get_header (method);
5054 method_index = get_method_index (acfg, method);
5056 /* Sort relocations */
5057 patches = g_ptr_array_new ();
5058 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5059 g_ptr_array_add (patches, patch_info);
5060 g_ptr_array_sort (patches, compare_patches);
5062 first_got_offset = acfg->cfgs [method_index]->got_offset;
5064 /**********************/
5065 /* Encode method info */
5066 /**********************/
5068 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5069 p = buf = g_malloc (buf_size);
5071 if (mono_class_get_cctor (method->klass))
5072 encode_klass_ref (acfg, method->klass, p, &p);
5074 /* Not needed when loading the method */
5075 encode_value (0, p, &p);
5078 if (cfg->opt & MONO_OPT_SHARED) {
5079 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5080 for (l = cfg->ldstr_list; l; l = l->next) {
5081 encode_value ((long)l->data, p, &p);
5085 /* Used only in shared mode */
5086 g_assert (!cfg->ldstr_list);
5089 for (pindex = 0; pindex < patches->len; ++pindex) {
5090 patch_info = g_ptr_array_index (patches, pindex);
5092 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5093 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5094 patch_info->type = MONO_PATCH_INFO_NONE;
5099 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5100 /* Stored in a GOT slot initialized at module load time */
5101 patch_info->type = MONO_PATCH_INFO_NONE;
5105 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5106 /* Stored in a GOT slot initialized at module load time */
5107 patch_info->type = MONO_PATCH_INFO_NONE;
5111 if (is_plt_patch (patch_info)) {
5112 /* Calls are made through the PLT */
5113 patch_info->type = MONO_PATCH_INFO_NONE;
5121 g_assert (cfg->has_got_slots);
5123 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5125 acfg->stats.info_size += p - buf;
5127 g_assert (p - buf < buf_size);
5129 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5134 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5136 guint32 cache_index;
5139 /* Reuse the unwind module to canonize and store unwind info entries */
5140 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5142 /* Use +/- 1 to distinguish 0s from missing entries */
5143 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5151 * It would be easier to use assembler symbols, but the caller needs an
5154 offset = acfg->unwind_info_offset;
5155 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5156 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5159 encode_value (encoded_len, p, &p);
5161 acfg->unwind_info_offset += encoded_len + (p - buf);
5167 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5170 int i, k, buf_size, method_index;
5171 guint32 debug_info_size;
5173 MonoMethodHeader *header;
5174 guint8 *p, *buf, *debug_info;
5175 MonoJitInfo *jinfo = cfg->jit_info;
5177 gboolean use_unwind_ops = FALSE;
5178 MonoSeqPointInfo *seq_points;
5180 method = cfg->orig_method;
5181 code = cfg->native_code;
5182 header = cfg->header;
5184 method_index = get_method_index (acfg, method);
5186 if (!acfg->aot_opts.nodebug) {
5187 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5190 debug_info_size = 0;
5193 seq_points = cfg->seq_point_info;
5195 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
5196 p = buf = g_malloc (buf_size);
5198 use_unwind_ops = cfg->unwind_ops != NULL;
5200 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);
5202 encode_value (flags, p, &p);
5204 if (use_unwind_ops) {
5205 guint32 encoded_len;
5209 * This is a duplicate of the data in the .debug_frame section, but that
5210 * section cannot be accessed using the dl interface.
5212 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5213 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5216 encode_value (jinfo->used_regs, p, &p);
5219 /*Encode the number of holes before the number of clauses to make decoding easier*/
5220 if (jinfo->has_try_block_holes) {
5221 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5222 encode_value (table->num_holes, p, &p);
5225 /* Exception table */
5226 if (cfg->compile_llvm) {
5228 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5229 * since the information is only available to llc. Instead, we let llc save the data
5230 * into the LSDA, and read it from there at runtime.
5232 /* The assembly might be CIL stripped so emit the data ourselves */
5233 if (header->num_clauses)
5234 encode_value (header->num_clauses, p, &p);
5236 for (k = 0; k < header->num_clauses; ++k) {
5237 MonoExceptionClause *clause;
5239 clause = &header->clauses [k];
5241 encode_value (clause->flags, p, &p);
5242 if (clause->data.catch_class) {
5243 encode_value (1, p, &p);
5244 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5246 encode_value (0, p, &p);
5249 /* Emit a list of nesting clauses */
5250 for (i = 0; i < header->num_clauses; ++i) {
5252 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5254 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5256 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5257 encode_value (i, p, &p);
5259 encode_value (-1, p, &p);
5262 if (jinfo->num_clauses)
5263 encode_value (jinfo->num_clauses, p, &p);
5265 for (k = 0; k < jinfo->num_clauses; ++k) {
5266 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5268 encode_value (ei->flags, p, &p);
5269 encode_value (ei->exvar_offset, p, &p);
5271 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5272 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5274 if (ei->data.catch_class) {
5278 buf2 = g_malloc (4096);
5280 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5282 g_assert (len < 4096);
5283 encode_value (len, p, &p);
5284 memcpy (p, buf2, len);
5288 encode_value (0, p, &p);
5292 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5293 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5294 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5298 if (jinfo->has_try_block_holes) {
5299 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5300 for (i = 0; i < table->num_holes; ++i) {
5301 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5302 encode_value (hole->clause, p, &p);
5303 encode_value (hole->length, p, &p);
5304 encode_value (hole->offset, p, &p);
5308 if (jinfo->has_arch_eh_info) {
5309 MonoArchEHJitInfo *eh_info;
5311 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5312 encode_value (eh_info->stack_size, p, &p);
5315 if (jinfo->has_generic_jit_info) {
5316 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5317 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5323 encode_value (gi->nlocs, p, &p);
5325 for (i = 0; i < gi->nlocs; ++i) {
5326 MonoDwarfLocListEntry *entry = &gi->locations [i];
5328 encode_value (entry->is_reg ? 1 : 0, p, &p);
5329 encode_value (entry->reg, p, &p);
5331 encode_value (entry->offset, p, &p);
5333 g_assert (entry->from == 0);
5335 encode_value (entry->from, p, &p);
5336 encode_value (entry->to, p, &p);
5339 if (!cfg->compile_llvm) {
5340 encode_value (gi->has_this ? 1 : 0, p, &p);
5341 encode_value (gi->this_reg, p, &p);
5342 encode_value (gi->this_offset, p, &p);
5347 * Need to encode jinfo->method too, since it is not equal to 'method'
5348 * when using generic sharing.
5350 buf2 = g_malloc (4096);
5352 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5354 g_assert (len < 4096);
5355 encode_value (len, p, &p);
5356 memcpy (p, buf2, len);
5360 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5361 MonoMethodInflated *inflated;
5362 MonoGenericContext *context;
5363 MonoGenericInst *inst;
5365 g_assert (jinfo->d.method->is_inflated);
5366 inflated = (MonoMethodInflated*)jinfo->d.method;
5367 context = &inflated->context;
5369 encode_value (1, p, &p);
5370 if (context->class_inst) {
5371 inst = context->class_inst;
5373 encode_value (inst->type_argc, p, &p);
5374 for (i = 0; i < inst->type_argc; ++i)
5375 encode_value (gsctx->var_is_vt [i], p, &p);
5377 encode_value (0, p, &p);
5379 if (context->method_inst) {
5380 inst = context->method_inst;
5382 encode_value (inst->type_argc, p, &p);
5383 for (i = 0; i < inst->type_argc; ++i)
5384 encode_value (gsctx->mvar_is_vt [i], p, &p);
5386 encode_value (0, p, &p);
5389 encode_value (0, p, &p);
5394 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5396 encode_value (seq_points->len, p, &p);
5397 last_il_offset = last_native_offset = 0;
5398 for (i = 0; i < seq_points->len; ++i) {
5399 SeqPoint *sp = &seq_points->seq_points [i];
5400 il_offset = sp->il_offset;
5401 native_offset = sp->native_offset;
5402 encode_value (il_offset - last_il_offset, p, &p);
5403 encode_value (native_offset - last_native_offset, p, &p);
5404 last_il_offset = il_offset;
5405 last_native_offset = native_offset;
5407 encode_value (sp->flags, p, &p);
5408 encode_value (sp->next_len, p, &p);
5409 for (j = 0; j < sp->next_len; ++j)
5410 encode_value (sp->next [j], p, &p);
5414 g_assert (debug_info_size < buf_size);
5416 encode_value (debug_info_size, p, &p);
5417 if (debug_info_size) {
5418 memcpy (p, debug_info, debug_info_size);
5419 p += debug_info_size;
5420 g_free (debug_info);
5425 encode_value (cfg->gc_map_size, p, &p);
5426 /* The GC map requires 4 bytes of alignment */
5427 while ((gsize)p % 4)
5429 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5430 p += cfg->gc_map_size;
5433 acfg->stats.ex_info_size += p - buf;
5435 g_assert (p - buf < buf_size);
5438 /* The GC Map requires 4 byte alignment */
5439 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5444 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5446 MonoClass *klass = mono_class_get (acfg->image, token);
5448 int i, buf_size, res;
5449 gboolean no_special_static, cant_encode;
5450 gpointer iter = NULL;
5453 mono_loader_clear_error ();
5457 p = buf = g_malloc (buf_size);
5459 /* Mark as unusable */
5460 encode_value (-1, p, &p);
5462 res = add_to_blob (acfg, buf, p - buf);
5468 buf_size = 10240 + (klass->vtable_size * 16);
5469 p = buf = g_malloc (buf_size);
5473 mono_class_init (klass);
5475 mono_class_get_nested_types (klass, &iter);
5476 g_assert (klass->nested_classes_inited);
5478 mono_class_setup_vtable (klass);
5481 * Emit all the information which is required for creating vtables so
5482 * the runtime does not need to create the MonoMethod structures which
5483 * take up a lot of space.
5486 no_special_static = !mono_class_has_special_static_fields (klass);
5488 /* Check whenever we have enough info to encode the vtable */
5489 cant_encode = FALSE;
5490 for (i = 0; i < klass->vtable_size; ++i) {
5491 MonoMethod *cm = klass->vtable [i];
5493 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5497 mono_class_has_finalizer (klass);
5499 if (klass->generic_container || cant_encode) {
5500 encode_value (-1, p, &p);
5502 encode_value (klass->vtable_size, p, &p);
5503 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);
5504 if (klass->has_cctor)
5505 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5506 if (klass->has_finalize)
5507 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5509 encode_value (klass->instance_size, p, &p);
5510 encode_value (mono_class_data_size (klass), p, &p);
5511 encode_value (klass->packing_size, p, &p);
5512 encode_value (klass->min_align, p, &p);
5514 for (i = 0; i < klass->vtable_size; ++i) {
5515 MonoMethod *cm = klass->vtable [i];
5518 encode_method_ref (acfg, cm, p, &p);
5520 encode_value (0, p, &p);
5524 acfg->stats.class_info_size += p - buf;
5526 g_assert (p - buf < buf_size);
5527 res = add_to_blob (acfg, buf, p - buf);
5534 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5536 char *debug_sym = NULL;
5539 case MONO_PATCH_INFO_METHOD:
5540 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5542 case MONO_PATCH_INFO_INTERNAL_METHOD:
5543 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5545 case MONO_PATCH_INFO_CLASS_INIT:
5546 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
5547 sanitize_symbol (debug_sym);
5549 case MONO_PATCH_INFO_RGCTX_FETCH:
5550 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5552 case MONO_PATCH_INFO_ICALL_ADDR: {
5553 char *s = get_debug_sym (ji->data.method, "", cache);
5555 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5559 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5560 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5562 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5563 debug_sym = g_strdup_printf ("plt__generic_class_init");
5573 * Calls made from AOTed code are routed through a table of jumps similar to the
5574 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5575 * control to the AOT runtime through a trampoline.
5578 emit_plt (MonoAotCompile *acfg)
5584 sprintf (symbol, "plt");
5586 emit_section_change (acfg, ".text", 0);
5587 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5588 emit_label (acfg, symbol);
5589 emit_label (acfg, acfg->plt_symbol);
5591 for (i = 0; i < acfg->plt_offset; ++i) {
5592 char *debug_sym = NULL;
5593 MonoPltEntry *plt_entry = NULL;
5598 * The first plt entry is unused.
5602 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5607 * If the target is directly callable, alias the plt symbol to point to
5609 * FIXME: Use this to simplify emit_and_reloc_code ().
5610 * FIXME: Avoid the got slot.
5611 * FIXME: Add support to the binary writer.
5613 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5614 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5617 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5618 /* LLVM calls the PLT entries using bl, so emit a stub */
5619 emit_set_thumb_mode (acfg);
5620 fprintf (acfg->fp, "\n.thumb_func\n");
5621 emit_label (acfg, plt_entry->llvm_symbol);
5622 fprintf (acfg->fp, "bx pc\n");
5623 fprintf (acfg->fp, "nop\n");
5624 emit_set_arm_mode (acfg);
5625 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5627 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5634 debug_sym = plt_entry->debug_sym;
5636 if (acfg->thumb_mixed && !plt_entry->jit_used)
5637 /* Emit only a thumb version */
5640 if (acfg->llvm && !acfg->thumb_mixed)
5641 emit_label (acfg, plt_entry->llvm_symbol);
5644 if (acfg->need_no_dead_strip) {
5645 emit_unset_mode (acfg);
5646 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5648 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5649 emit_label (acfg, debug_sym);
5652 emit_label (acfg, plt_entry->symbol);
5654 arch_emit_plt_entry (acfg, i);
5657 emit_symbol_size (acfg, debug_sym, ".");
5660 if (acfg->thumb_mixed) {
5661 /* Make sure the ARM symbols don't alias the thumb ones */
5662 emit_zero_bytes (acfg, 16);
5665 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5668 for (i = 0; i < acfg->plt_offset; ++i) {
5669 char *debug_sym = NULL;
5670 MonoPltEntry *plt_entry = NULL;
5676 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5679 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5682 /* Skip plt entries not actually called by LLVM code */
5683 if (!plt_entry->llvm_used)
5686 if (acfg->aot_opts.write_symbols) {
5687 if (plt_entry->debug_sym)
5688 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5692 #if defined(TARGET_MACH)
5693 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5694 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5696 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5697 emit_label (acfg, debug_sym);
5699 fprintf (acfg->fp, "\n.thumb_func\n");
5701 emit_label (acfg, plt_entry->llvm_symbol);
5703 arch_emit_llvm_plt_entry (acfg, i);
5706 emit_symbol_size (acfg, debug_sym, ".");
5712 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5714 sprintf (symbol, "plt_end");
5715 emit_label (acfg, symbol);
5719 * emit_trampoline_full:
5721 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5722 * create_jit_info_for_trampoline ().
5724 static G_GNUC_UNUSED void
5725 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5727 char start_symbol [256];
5728 char end_symbol [256];
5730 guint32 buf_size, info_offset;
5731 MonoJumpInfo *patch_info;
5744 code_size = info->code_size;
5746 unwind_ops = info->unwind_ops;
5748 #ifdef __native_client_codegen__
5749 mono_nacl_fix_patches (code, ji);
5754 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5756 emit_section_change (acfg, ".text", 0);
5757 emit_global (acfg, start_symbol, TRUE);
5758 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5759 emit_label (acfg, start_symbol);
5761 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5762 emit_label (acfg, symbol);
5765 * The code should access everything through the GOT, so we pass
5768 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5770 emit_symbol_size (acfg, start_symbol, ".");
5773 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5774 emit_label (acfg, end_symbol);
5779 /* Sort relocations */
5780 patches = g_ptr_array_new ();
5781 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5782 if (patch_info->type != MONO_PATCH_INFO_NONE)
5783 g_ptr_array_add (patches, patch_info);
5784 g_ptr_array_sort (patches, compare_patches);
5786 buf_size = patches->len * 128 + 128;
5787 buf = g_malloc (buf_size);
5790 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5791 g_assert (p - buf < buf_size);
5793 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5795 info_offset = add_to_blob (acfg, buf, p - buf);
5797 emit_section_change (acfg, RODATA_SECT, 0);
5798 emit_global (acfg, symbol, FALSE);
5799 emit_label (acfg, symbol);
5801 emit_int32 (acfg, info_offset);
5805 guint32 encoded_len;
5809 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5811 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5812 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5815 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5816 emit_int32 (acfg, uw_offset);
5819 /* Emit debug info */
5823 sprintf (symbol, "%s", name);
5824 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5827 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5831 static G_GNUC_UNUSED void
5832 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5834 emit_trampoline_full (acfg, got_offset, info, FALSE);
5838 emit_trampolines (MonoAotCompile *acfg)
5841 char end_symbol [256];
5842 int i, tramp_got_offset;
5843 MonoAotTrampoline ntype;
5844 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5848 if (!acfg->aot_opts.full_aot)
5851 g_assert (acfg->image->assembly);
5853 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5854 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5855 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5856 MonoTrampInfo *info;
5859 * Emit the generic trampolines.
5861 * We could save some code by treating the generic trampolines as a wrapper
5862 * method, but that approach has its own complexities, so we choose the simpler
5865 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5866 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5867 #ifdef DISABLE_REMOTING
5868 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5871 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5872 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5875 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5876 emit_trampoline (acfg, acfg->got_offset, info);
5879 mono_arch_get_nullified_class_init_trampoline (&info);
5880 emit_trampoline (acfg, acfg->got_offset, info);
5881 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5882 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5883 emit_trampoline (acfg, acfg->got_offset, info);
5884 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5885 emit_trampoline (acfg, acfg->got_offset, info);
5888 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5889 emit_trampoline (acfg, acfg->got_offset, info);
5891 /* Emit the exception related code pieces */
5892 mono_arch_get_restore_context (&info, TRUE);
5893 emit_trampoline (acfg, acfg->got_offset, info);
5894 mono_arch_get_call_filter (&info, TRUE);
5895 emit_trampoline (acfg, acfg->got_offset, info);
5896 mono_arch_get_throw_exception (&info, TRUE);
5897 emit_trampoline (acfg, acfg->got_offset, info);
5898 mono_arch_get_rethrow_exception (&info, TRUE);
5899 emit_trampoline (acfg, acfg->got_offset, info);
5900 mono_arch_get_throw_corlib_exception (&info, TRUE);
5901 emit_trampoline (acfg, acfg->got_offset, info);
5903 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5904 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5906 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5908 /* Create a separate out trampoline for more information in stack traces */
5909 info->name = g_strdup ("gsharedvt_out_trampoline");
5910 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5914 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5916 GSList *l = mono_arch_get_trampolines (TRUE);
5919 MonoTrampInfo *info = l->data;
5921 emit_trampoline (acfg, acfg->got_offset, info);
5927 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5930 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5931 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5932 emit_trampoline (acfg, acfg->got_offset, info);
5934 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5935 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5936 emit_trampoline (acfg, acfg->got_offset, info);
5939 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
5940 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
5941 emit_trampoline (acfg, acfg->got_offset, info);
5947 /* delegate_invoke_impl trampolines */
5948 l = mono_arch_get_delegate_invoke_impls ();
5950 MonoTrampInfo *info = l->data;
5952 emit_trampoline (acfg, acfg->got_offset, info);
5957 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5959 /* Emit trampolines which are numerous */
5962 * These include the following:
5963 * - specific trampolines
5964 * - static rgctx invoke trampolines
5966 * These trampolines have the same code, they are parameterized by GOT
5968 * They are defined in this file, in the arch_... routines instead of
5969 * in tramp-<ARCH>.c, since it is easier to do it this way.
5973 * When running in aot-only mode, we can't create specific trampolines at
5974 * runtime, so we create a few, and save them in the AOT file.
5975 * Normal trampolines embed their argument as a literal inside the
5976 * trampoline code, we can't do that here, so instead we embed an offset
5977 * which needs to be added to the trampoline address to get the address of
5978 * the GOT slot which contains the argument value.
5979 * The generated trampolines jump to the generic trampolines using another
5980 * GOT slot, which will be setup by the AOT loader to point to the
5981 * generic trampoline code of the given type.
5985 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5989 emit_section_change (acfg, ".text", 0);
5991 tramp_got_offset = acfg->got_offset;
5993 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5995 case MONO_AOT_TRAMP_SPECIFIC:
5996 sprintf (symbol, "specific_trampolines");
5998 case MONO_AOT_TRAMP_STATIC_RGCTX:
5999 sprintf (symbol, "static_rgctx_trampolines");
6001 case MONO_AOT_TRAMP_IMT_THUNK:
6002 sprintf (symbol, "imt_thunks");
6004 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6005 sprintf (symbol, "gsharedvt_arg_trampolines");
6008 g_assert_not_reached ();
6011 sprintf (end_symbol, "%s_e", symbol);
6013 if (acfg->aot_opts.write_symbols)
6014 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6016 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6017 emit_label (acfg, symbol);
6019 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6021 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6025 case MONO_AOT_TRAMP_SPECIFIC:
6026 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6027 tramp_got_offset += 2;
6029 case MONO_AOT_TRAMP_STATIC_RGCTX:
6030 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6031 tramp_got_offset += 2;
6033 case MONO_AOT_TRAMP_IMT_THUNK:
6034 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6035 tramp_got_offset += 1;
6037 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6038 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6039 tramp_got_offset += 2;
6042 g_assert_not_reached ();
6044 #ifdef __native_client_codegen__
6045 /* align to avoid 32-byte boundary crossings */
6046 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6049 if (!acfg->trampoline_size [ntype]) {
6050 g_assert (tramp_size);
6051 acfg->trampoline_size [ntype] = tramp_size;
6055 emit_label (acfg, end_symbol);
6056 emit_int32 (acfg, 0);
6059 arch_emit_specific_trampoline_pages (acfg);
6061 /* Reserve some entries at the end of the GOT for our use */
6062 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6065 acfg->got_offset += acfg->num_trampoline_got_entries;
6069 str_begins_with (const char *str1, const char *str2)
6071 int len = strlen (str2);
6072 return strncmp (str1, str2, len) == 0;
6076 mono_aot_readonly_field_override (MonoClassField *field)
6079 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6080 char *p = rdv->name;
6082 len = strlen (field->parent->name_space);
6083 if (strncmp (p, field->parent->name_space, len))
6088 len = strlen (field->parent->name);
6089 if (strncmp (p, field->parent->name, len))
6094 if (strcmp (p, field->name))
6096 switch (rdv->type) {
6098 return &rdv->value.i1;
6100 return &rdv->value.i2;
6102 return &rdv->value.i4;
6111 add_readonly_value (MonoAotOptions *opts, const char *val)
6116 /* the format of val is:
6117 * namespace.typename.fieldname=type/value
6118 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6120 fval = strrchr (val, '/');
6122 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6125 tval = strrchr (val, '=');
6127 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6130 rdv = g_new0 (ReadOnlyValue, 1);
6131 rdv->name = g_malloc0 (tval - val + 1);
6132 memcpy (rdv->name, val, tval - val);
6135 if (strncmp (tval, "i1", 2) == 0) {
6136 rdv->value.i1 = atoi (fval);
6137 rdv->type = MONO_TYPE_I1;
6138 } else if (strncmp (tval, "i2", 2) == 0) {
6139 rdv->value.i2 = atoi (fval);
6140 rdv->type = MONO_TYPE_I2;
6141 } else if (strncmp (tval, "i4", 2) == 0) {
6142 rdv->value.i4 = atoi (fval);
6143 rdv->type = MONO_TYPE_I4;
6145 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6148 rdv->next = readonly_values;
6149 readonly_values = rdv;
6153 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6155 gchar **args, **ptr;
6157 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6158 for (ptr = args; ptr && *ptr; ptr ++) {
6159 const char *arg = *ptr;
6161 if (str_begins_with (arg, "outfile=")) {
6162 opts->outfile = g_strdup (arg + strlen ("outfile="));
6163 } else if (str_begins_with (arg, "save-temps")) {
6164 opts->save_temps = TRUE;
6165 } else if (str_begins_with (arg, "keep-temps")) {
6166 opts->save_temps = TRUE;
6167 } else if (str_begins_with (arg, "write-symbols")) {
6168 opts->write_symbols = TRUE;
6169 } else if (str_begins_with (arg, "no-write-symbols")) {
6170 opts->write_symbols = FALSE;
6171 } else if (str_begins_with (arg, "metadata-only")) {
6172 opts->metadata_only = TRUE;
6173 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6174 opts->bind_to_runtime_version = TRUE;
6175 } else if (str_begins_with (arg, "full")) {
6176 opts->full_aot = TRUE;
6177 } else if (str_begins_with (arg, "threads=")) {
6178 opts->nthreads = atoi (arg + strlen ("threads="));
6179 } else if (str_begins_with (arg, "static")) {
6180 opts->static_link = TRUE;
6181 opts->no_dlsym = TRUE;
6182 } else if (str_begins_with (arg, "asmonly")) {
6183 opts->asm_only = TRUE;
6184 } else if (str_begins_with (arg, "asmwriter")) {
6185 opts->asm_writer = TRUE;
6186 } else if (str_begins_with (arg, "nodebug")) {
6187 opts->nodebug = TRUE;
6188 } else if (str_begins_with (arg, "dwarfdebug")) {
6189 opts->dwarf_debug = TRUE;
6190 } else if (str_begins_with (arg, "nopagetrampolines")) {
6191 opts->use_trampolines_page = FALSE;
6192 } else if (str_begins_with (arg, "ntrampolines=")) {
6193 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6194 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6195 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6196 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6197 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6198 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6199 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6200 } else if (str_begins_with (arg, "autoreg")) {
6201 opts->autoreg = TRUE;
6202 } else if (str_begins_with (arg, "tool-prefix=")) {
6203 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6204 } else if (str_begins_with (arg, "soft-debug")) {
6205 opts->soft_debug = TRUE;
6206 } else if (str_begins_with (arg, "direct-pinvoke")) {
6207 opts->direct_pinvoke = TRUE;
6208 } else if (str_begins_with (arg, "direct-icalls")) {
6209 opts->direct_icalls = TRUE;
6210 #if defined(TARGET_ARM)
6211 } else if (str_begins_with (arg, "iphone-abi")) {
6212 // older full-aot users did depend on this.
6214 } else if (str_begins_with (arg, "no-direct-calls")) {
6215 opts->no_direct_calls = TRUE;
6216 } else if (str_begins_with (arg, "print-skipped")) {
6217 opts->print_skipped_methods = TRUE;
6218 } else if (str_begins_with (arg, "stats")) {
6220 } else if (str_begins_with (arg, "no-instances")) {
6221 opts->no_instances = TRUE;
6222 } else if (str_begins_with (arg, "log-generics")) {
6223 opts->log_generics = TRUE;
6224 } else if (str_begins_with (arg, "mtriple=")) {
6225 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6226 } else if (str_begins_with (arg, "llvm-path=")) {
6227 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6228 } else if (str_begins_with (arg, "readonly-value=")) {
6229 add_readonly_value (opts, arg + strlen ("readonly-value="));
6230 } else if (str_begins_with (arg, "info")) {
6231 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6233 } else if (str_begins_with (arg, "gc-maps")) {
6234 mini_gc_enable_gc_maps_for_aot ();
6235 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6236 printf ("Supported options for --aot:\n");
6237 printf (" outfile=\n");
6238 printf (" save-temps\n");
6239 printf (" keep-temps\n");
6240 printf (" write-symbols\n");
6241 printf (" metadata-only\n");
6242 printf (" bind-to-runtime-version\n");
6244 printf (" threads=\n");
6245 printf (" static\n");
6246 printf (" asmonly\n");
6247 printf (" asmwriter\n");
6248 printf (" nodebug\n");
6249 printf (" dwarfdebug\n");
6250 printf (" ntrampolines=\n");
6251 printf (" nrgctx-trampolines=\n");
6252 printf (" nimt-trampolines=\n");
6253 printf (" ngsharedvt-trampolines=\n");
6254 printf (" autoreg\n");
6255 printf (" tool-prefix=\n");
6256 printf (" readonly-value=\n");
6257 printf (" soft-debug\n");
6258 printf (" gc-maps\n");
6259 printf (" print-skipped\n");
6260 printf (" no-instances\n");
6261 printf (" stats\n");
6263 printf (" help/?\n");
6266 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6271 if (opts->use_trampolines_page) {
6272 opts->ntrampolines = 0;
6273 opts->nrgctx_trampolines = 0;
6274 opts->nimt_trampolines = 0;
6275 opts->ngsharedvt_arg_trampolines = 0;
6281 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6283 MonoMethod *method = (MonoMethod*)key;
6284 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6285 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6286 MonoAotCompile *acfg = user_data;
6288 new_ji->image = ji->image;
6289 new_ji->token = ji->token;
6290 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6294 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6296 if (klass->type_token)
6298 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6301 return can_encode_class (acfg, klass->element_class);
6306 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6308 if (method->wrapper_type) {
6309 switch (method->wrapper_type) {
6310 case MONO_WRAPPER_NONE:
6311 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6312 case MONO_WRAPPER_XDOMAIN_INVOKE:
6313 case MONO_WRAPPER_STFLD:
6314 case MONO_WRAPPER_LDFLD:
6315 case MONO_WRAPPER_LDFLDA:
6316 case MONO_WRAPPER_LDFLD_REMOTE:
6317 case MONO_WRAPPER_STFLD_REMOTE:
6318 case MONO_WRAPPER_STELEMREF:
6319 case MONO_WRAPPER_ISINST:
6320 case MONO_WRAPPER_PROXY_ISINST:
6321 case MONO_WRAPPER_ALLOC:
6322 case MONO_WRAPPER_REMOTING_INVOKE:
6323 case MONO_WRAPPER_UNKNOWN:
6324 case MONO_WRAPPER_WRITE_BARRIER:
6325 case MONO_WRAPPER_DELEGATE_INVOKE:
6326 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6327 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6328 case MONO_WRAPPER_SYNCHRONIZED:
6330 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6331 case MONO_WRAPPER_CASTCLASS: {
6332 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6341 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6345 if (!method->token) {
6346 /* The method is part of a constructed type like Int[,].Set (). */
6347 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6348 if (method->klass->rank)
6358 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6360 switch (patch_info->type) {
6361 case MONO_PATCH_INFO_METHOD:
6362 case MONO_PATCH_INFO_METHODCONST: {
6363 MonoMethod *method = patch_info->data.method;
6365 return can_encode_method (acfg, method);
6367 case MONO_PATCH_INFO_VTABLE:
6368 case MONO_PATCH_INFO_CLASS_INIT:
6369 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6370 case MONO_PATCH_INFO_CLASS:
6371 case MONO_PATCH_INFO_IID:
6372 case MONO_PATCH_INFO_ADJUSTED_IID:
6373 if (!can_encode_class (acfg, patch_info->data.klass)) {
6374 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6378 case MONO_PATCH_INFO_RGCTX_FETCH: {
6379 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6381 if (!can_encode_method (acfg, entry->method))
6383 if (!can_encode_patch (acfg, entry->data))
6397 * AOT compile a given method.
6398 * This function might be called by multiple threads, so it must be thread-safe.
6401 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6404 MonoJumpInfo *patch_info;
6407 MonoMethod *wrapped;
6409 if (acfg->aot_opts.metadata_only)
6412 mono_acfg_lock (acfg);
6413 index = get_method_index (acfg, method);
6414 mono_acfg_unlock (acfg);
6416 /* fixme: maybe we can also precompile wrapper methods */
6417 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6418 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6419 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6420 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6424 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6427 wrapped = mono_marshal_method_from_wrapper (method);
6428 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6429 // FIXME: The wrapper should be generic too, but it is not
6432 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6435 InterlockedIncrement (&acfg->stats.mcount);
6438 if (method->is_generic || method->klass->generic_container) {
6439 InterlockedIncrement (&acfg->stats.genericcount);
6444 //acfg->aot_opts.print_skipped_methods = TRUE;
6447 * Since these methods are the only ones which are compiled with
6448 * AOT support, and they are not used by runtime startup/shutdown code,
6449 * the runtime will not see AOT methods during AOT compilation,so it
6450 * does not need to support them by creating a fake GOT etc.
6452 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
6453 mono_loader_clear_error ();
6455 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6456 if (acfg->aot_opts.print_skipped_methods)
6457 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6458 InterlockedIncrement (&acfg->stats.genericcount);
6461 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6462 if (acfg->aot_opts.print_skipped_methods)
6463 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6464 /* Let the exception happen at runtime */
6468 if (cfg->disable_aot) {
6469 if (acfg->aot_opts.print_skipped_methods)
6470 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6471 InterlockedIncrement (&acfg->stats.ocount);
6472 mono_destroy_compile (cfg);
6475 cfg->method_index = index;
6477 /* Nullify patches which need no aot processing */
6478 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6479 switch (patch_info->type) {
6480 case MONO_PATCH_INFO_LABEL:
6481 case MONO_PATCH_INFO_BB:
6482 patch_info->type = MONO_PATCH_INFO_NONE;
6489 /* Collect method->token associations from the cfg */
6490 mono_acfg_lock (acfg);
6491 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6492 mono_acfg_unlock (acfg);
6495 * Check for absolute addresses.
6498 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6499 switch (patch_info->type) {
6500 case MONO_PATCH_INFO_ABS:
6501 /* unable to handle this */
6510 if (acfg->aot_opts.print_skipped_methods)
6511 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6512 InterlockedIncrement (&acfg->stats.abscount);
6513 mono_destroy_compile (cfg);
6517 /* Lock for the rest of the code */
6518 mono_acfg_lock (acfg);
6521 * Check for methods/klasses we can't encode.
6524 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6525 if (!can_encode_patch (acfg, patch_info))
6530 if (acfg->aot_opts.print_skipped_methods)
6531 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6532 acfg->stats.ocount++;
6533 mono_destroy_compile (cfg);
6534 mono_acfg_unlock (acfg);
6538 /* Adds generic instances referenced by this method */
6540 * The depth is used to avoid infinite loops when generic virtual recursion is
6543 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6544 if (!acfg->aot_opts.no_instances && depth < 32) {
6545 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6546 switch (patch_info->type) {
6547 case MONO_PATCH_INFO_METHOD: {
6548 MonoMethod *m = patch_info->data.method;
6549 if (m->is_inflated) {
6550 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6551 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6552 !method_has_type_vars (m)) {
6553 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6554 if (acfg->aot_opts.full_aot)
6555 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6557 add_extra_method_with_depth (acfg, m, depth + 1);
6558 add_types_from_method_header (acfg, m);
6561 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6563 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6564 add_extra_method_with_depth (acfg, m, depth + 1);
6567 case MONO_PATCH_INFO_VTABLE: {
6568 MonoClass *klass = patch_info->data.klass;
6570 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6571 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6574 case MONO_PATCH_INFO_SFLDA: {
6575 MonoClass *klass = patch_info->data.field->parent;
6577 /* The .cctor needs to run at runtime. */
6578 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6579 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6588 /* Determine whenever the method has GOT slots */
6589 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6590 switch (patch_info->type) {
6591 case MONO_PATCH_INFO_GOT_OFFSET:
6592 case MONO_PATCH_INFO_NONE:
6593 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6595 case MONO_PATCH_INFO_IMAGE:
6596 /* The assembly is stored in GOT slot 0 */
6597 if (patch_info->data.image != acfg->image)
6598 cfg->has_got_slots = TRUE;
6601 if (!is_plt_patch (patch_info))
6602 cfg->has_got_slots = TRUE;
6607 if (!cfg->has_got_slots)
6608 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6611 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6613 /* Make a copy of the patch info which is in the mempool */
6615 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6617 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6618 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6621 patches = new_patch_info;
6623 patches_end->next = new_patch_info;
6624 patches_end = new_patch_info;
6626 cfg->patch_info = patches;
6628 /* Make a copy of the unwind info */
6630 GSList *l, *unwind_ops;
6634 for (l = cfg->unwind_ops; l; l = l->next) {
6635 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6636 memcpy (op, l->data, sizeof (MonoUnwindOp));
6637 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6639 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6641 /* Make a copy of the argument/local info */
6643 MonoInst **args, **locals;
6644 MonoMethodSignature *sig;
6645 MonoMethodHeader *header;
6648 sig = mono_method_signature (method);
6649 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6650 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6651 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6652 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6656 header = mono_method_get_header (method);
6657 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6658 for (i = 0; i < header->num_locals; ++i) {
6659 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6660 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6662 cfg->locals = locals;
6665 /* Free some fields used by cfg to conserve memory */
6666 mono_mempool_destroy (cfg->mempool);
6667 cfg->mempool = NULL;
6668 g_free (cfg->varinfo);
6669 cfg->varinfo = NULL;
6673 mono_regstate_free (cfg->rs);
6677 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6679 while (index >= acfg->cfgs_size) {
6680 MonoCompile **new_cfgs;
6683 new_size = acfg->cfgs_size * 2;
6684 new_cfgs = g_new0 (MonoCompile*, new_size);
6685 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6686 g_free (acfg->cfgs);
6687 acfg->cfgs = new_cfgs;
6688 acfg->cfgs_size = new_size;
6690 acfg->cfgs [index] = cfg;
6692 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6695 if (cfg->orig_method->wrapper_type)
6696 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6699 mono_acfg_unlock (acfg);
6701 InterlockedIncrement (&acfg->stats.ccount);
6705 compile_thread_main (gpointer *user_data)
6707 MonoDomain *domain = user_data [0];
6708 MonoAotCompile *acfg = user_data [1];
6709 GPtrArray *methods = user_data [2];
6712 mono_thread_attach (domain);
6714 for (i = 0; i < methods->len; ++i)
6715 compile_method (acfg, g_ptr_array_index (methods, i));
6719 load_profile_files (MonoAotCompile *acfg)
6723 int file_index, res, method_index, i;
6726 GList *unordered, *l;
6731 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6733 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6738 infile = fopen (tmp, "r");
6741 printf ("Using profile data file '%s'\n", tmp);
6746 res = fscanf (infile, "%32s\n", ver);
6747 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6748 printf ("Profile file has wrong version or invalid.\n");
6755 MonoMethodDesc *desc;
6758 if (fgets (name, 1023, infile) == NULL)
6761 /* Kill the newline */
6762 if (strlen (name) > 0)
6763 name [strlen (name) - 1] = '\0';
6765 desc = mono_method_desc_new (name, TRUE);
6767 method = mono_method_desc_search_in_image (desc, acfg->image);
6769 if (method && mono_method_get_token (method)) {
6770 token = mono_method_get_token (method);
6771 method_index = mono_metadata_token_index (token) - 1;
6774 for (i = 0; i < acfg->method_order->len; ++i) {
6775 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6781 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6783 //printf ("No method found matching '%s'.\n", name);
6789 /* Add missing methods */
6791 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6793 for (i = 0; i < acfg->method_order->len; ++i) {
6794 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6800 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6802 unordered = g_list_reverse (unordered);
6803 for (l = unordered; l; l = l->next)
6804 g_ptr_array_add (acfg->method_order, l->data);
6807 /* Used by the LLVM backend */
6809 mono_aot_get_got_offset (MonoJumpInfo *ji)
6811 return get_got_offset (llvm_acfg, ji);
6815 mono_aot_get_method_name (MonoCompile *cfg)
6817 if (llvm_acfg->aot_opts.static_link)
6818 /* Include the assembly name too to avoid duplicate symbol errors */
6819 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6821 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6825 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6827 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6828 MonoPltEntry *plt_entry;
6831 ji->data.target = data;
6833 if (!can_encode_patch (llvm_acfg, ji))
6836 plt_entry = get_plt_entry (llvm_acfg, ji);
6837 plt_entry->llvm_used = TRUE;
6839 #if defined(TARGET_MACH)
6840 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6842 return g_strdup_printf (plt_entry->llvm_symbol);
6847 mono_aot_get_method_index (MonoMethod *method)
6849 g_assert (llvm_acfg);
6850 return get_method_index (llvm_acfg, method);
6854 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6858 mono_acfg_lock (llvm_acfg);
6859 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6860 mono_acfg_unlock (llvm_acfg);
6870 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6874 emit_llvm_file (MonoAotCompile *acfg)
6876 char *command, *opts, *tempbc;
6878 MonoJumpInfo *patch_info;
6881 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6885 /* Compute the final size of the got */
6886 for (i = 0; i < acfg->nmethods; ++i) {
6887 if (acfg->cfgs [i]) {
6888 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6889 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6890 if (!is_plt_patch (patch_info))
6891 get_got_offset (acfg, patch_info);
6893 get_plt_entry (acfg, patch_info);
6899 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6901 if (acfg->aot_opts.full_aot) {
6905 * Need to add the got entries used by the trampolines.
6906 * This is only a conservative approximation.
6908 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6909 /* For the generic + rgctx trampolines */
6910 acfg->final_got_size += 400;
6911 /* For the specific trampolines */
6912 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6913 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6918 tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
6919 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6923 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6924 * a lot of time, and doesn't seem to save much space.
6925 * The following optimizations cannot be enabled:
6927 * - 'jump-threading' changes our blockaddress references to int constants.
6928 * - 'basiccg' fails because it contains:
6929 * if (CS && !isa<IntrinsicInst>(II)) {
6930 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
6931 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
6932 * The opt list below was produced by taking the output of:
6933 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
6934 * then removing tailcallelim + the global opts.
6935 * strip-dead-prototypes deletes unused intrinsics definitions.
6937 opts = g_strdup ("-instcombine -simplifycfg");
6938 //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 -preverify -domtree -verify");
6939 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -sroa -domtree -early-cse -simplify-libcalls -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 -dse -adce -simplifycfg -instcombine -strip-dead-prototypes -preverify -domtree -verify");
6941 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
6942 printf ("Executing opt: %s\n", command);
6943 if (system (command) != 0) {
6949 if (!acfg->llc_args)
6950 acfg->llc_args = g_string_new ("");
6952 /* Verbose asm slows down llc greatly */
6953 g_string_append (acfg->llc_args, " -asm-verbose=false");
6955 if (acfg->aot_opts.mtriple)
6956 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
6958 #if defined(TARGET_MACH) && defined(TARGET_ARM)
6959 /* ios requires PIC code now */
6960 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6962 if (llvm_acfg->aot_opts.static_link)
6963 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
6965 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6967 unlink (acfg->tmpfname);
6969 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->tmpfname);
6971 printf ("Executing llc: %s\n", command);
6973 if (system (command) != 0) {
6980 emit_code (MonoAotCompile *acfg)
6982 int oindex, i, prev_index;
6985 #if defined(TARGET_POWERPC64)
6986 sprintf (symbol, ".Lgot_addr");
6987 emit_section_change (acfg, ".text", 0);
6988 emit_alignment (acfg, 8);
6989 emit_label (acfg, symbol);
6990 emit_pointer (acfg, acfg->got_symbol);
6994 * This global symbol is used to compute the address of each method using the
6995 * code_offsets array. It is also used to compute the memory ranges occupied by
6996 * AOT code, so it must be equal to the address of the first emitted method.
6998 emit_section_change (acfg, ".text", 0);
6999 emit_alignment (acfg, 8);
7001 for (i = 0; i < acfg->nmethods; ++i) {
7002 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7003 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7008 if (!acfg->methods_symbol) {
7009 sprintf (symbol, "methods");
7010 emit_label (acfg, symbol);
7011 acfg->methods_symbol = g_strdup (symbol);
7015 * Emit some padding so the local symbol for the first method doesn't have the
7016 * same address as 'methods'.
7018 #if defined(__default_codegen__)
7019 emit_zero_bytes (acfg, 16);
7020 #elif defined(__native_client_codegen__)
7022 const int kPaddingSize = 16;
7023 guint8 pad_buffer[kPaddingSize];
7024 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7025 emit_bytes (acfg, pad_buffer, kPaddingSize);
7029 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7033 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7035 cfg = acfg->cfgs [i];
7040 method = cfg->orig_method;
7042 /* Emit unbox trampoline */
7043 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7044 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7046 emit_section_change (acfg, ".text", 0);
7047 #ifdef __native_client_codegen__
7048 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7051 if (acfg->thumb_mixed && cfg->compile_llvm) {
7052 emit_set_thumb_mode (acfg);
7053 fprintf (acfg->fp, "\n.thumb_func\n");
7056 emit_label (acfg, symbol);
7058 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7060 if (acfg->thumb_mixed && cfg->compile_llvm) {
7061 emit_set_arm_mode (acfg);
7065 if (cfg->compile_llvm)
7066 acfg->stats.llvm_count ++;
7068 emit_method_code (acfg, cfg);
7071 sprintf (symbol, "methods_end");
7072 emit_section_change (acfg, ".text", 0);
7073 emit_alignment (acfg, 8);
7074 emit_label (acfg, symbol);
7075 /* To distinguish it from the next symbol */
7076 emit_int32 (acfg, 0);
7079 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7080 * from optimizing them away, since it doesn't see that code_offsets references them.
7081 * JITted methods don't need this since they are referenced using assembler local
7083 * FIXME: This is why write-symbols doesn't work on OSX ?
7085 if (acfg->llvm && acfg->need_no_dead_strip) {
7086 fprintf (acfg->fp, "\n");
7087 for (i = 0; i < acfg->nmethods; ++i) {
7088 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7089 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7094 if (acfg->direct_method_addresses) {
7095 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7098 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7099 * This is PIE code, and the linker can update it if needed.
7101 sprintf (symbol, "method_addresses");
7102 emit_section_change (acfg, ".text", 1);
7103 emit_alignment (acfg, 8);
7104 emit_label (acfg, symbol);
7105 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7106 emit_unset_mode (acfg);
7107 if (acfg->need_no_dead_strip)
7108 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7110 for (i = 0; i < acfg->nmethods; ++i) {
7111 if (acfg->cfgs [i]) {
7112 if (acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm)
7113 fprintf (acfg->fp, "\tblx %s\n", acfg->cfgs [i]->asm_symbol);
7115 fprintf (acfg->fp, "\tbl %s\n", acfg->cfgs [i]->asm_symbol);
7117 fprintf (acfg->fp, "\tbl method_addresses\n");
7121 sprintf (symbol, "method_addresses_end");
7122 emit_label (acfg, symbol);
7125 sprintf (symbol, "code_offsets");
7126 emit_section_change (acfg, RODATA_SECT, 1);
7127 emit_alignment (acfg, 8);
7128 emit_label (acfg, symbol);
7129 emit_int32 (acfg, 0);
7131 sprintf (symbol, "code_offsets");
7132 emit_section_change (acfg, RODATA_SECT, 1);
7133 emit_alignment (acfg, 8);
7134 emit_label (acfg, symbol);
7136 acfg->stats.offsets_size += acfg->nmethods * 4;
7138 for (i = 0; i < acfg->nmethods; ++i) {
7139 if (acfg->cfgs [i]) {
7140 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7142 emit_int32 (acfg, 0xffffffff);
7147 sprintf (symbol, "code_offsets");
7148 emit_section_change (acfg, RODATA_SECT, 1);
7149 emit_alignment (acfg, 8);
7150 emit_label (acfg, symbol);
7152 acfg->stats.offsets_size += acfg->nmethods * 4;
7154 for (i = 0; i < acfg->nmethods; ++i) {
7155 if (acfg->cfgs [i]) {
7156 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7158 emit_int32 (acfg, 0xffffffff);
7164 /* Emit a sorted table mapping methods to their unbox trampolines */
7165 sprintf (symbol, "unbox_trampolines");
7166 if (acfg->direct_method_addresses)
7167 emit_section_change (acfg, ".text", 0);
7169 emit_section_change (acfg, RODATA_SECT, 0);
7170 emit_alignment (acfg, 8);
7171 emit_label (acfg, symbol);
7174 for (i = 0; i < acfg->nmethods; ++i) {
7179 cfg = acfg->cfgs [i];
7183 method = cfg->orig_method;
7185 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7186 index = get_method_index (acfg, method);
7187 sprintf (symbol, "ut_%d", index);
7189 emit_int32 (acfg, index);
7190 if (acfg->direct_method_addresses) {
7191 emit_unset_mode (acfg);
7192 if (acfg->thumb_mixed && cfg->compile_llvm)
7193 fprintf (acfg->fp, "\n\tblx %s\n", symbol);
7195 fprintf (acfg->fp, "\n\tbl %s\n", symbol);
7197 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7199 /* Make sure the table is sorted by index */
7200 g_assert (index > prev_index);
7204 sprintf (symbol, "unbox_trampolines_end");
7205 emit_label (acfg, symbol);
7206 emit_int32 (acfg, 0);
7210 emit_info (MonoAotCompile *acfg)
7216 offsets = g_new0 (gint32, acfg->nmethods);
7218 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7219 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7221 if (acfg->cfgs [i]) {
7222 emit_method_info (acfg, acfg->cfgs [i]);
7223 offsets [i] = acfg->cfgs [i]->method_info_offset;
7229 sprintf (symbol, "method_info_offsets");
7230 emit_section_change (acfg, RODATA_SECT, 1);
7231 emit_alignment (acfg, 8);
7232 emit_label (acfg, symbol);
7234 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7239 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7241 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7242 #define mix(a,b,c) { \
7243 a -= c; a ^= rot(c, 4); c += b; \
7244 b -= a; b ^= rot(a, 6); a += c; \
7245 c -= b; c ^= rot(b, 8); b += a; \
7246 a -= c; a ^= rot(c,16); c += b; \
7247 b -= a; b ^= rot(a,19); a += c; \
7248 c -= b; c ^= rot(b, 4); b += a; \
7250 #define final(a,b,c) { \
7251 c ^= b; c -= rot(b,14); \
7252 a ^= c; a -= rot(c,11); \
7253 b ^= a; b -= rot(a,25); \
7254 c ^= b; c -= rot(b,16); \
7255 a ^= c; a -= rot(c,4); \
7256 b ^= a; b -= rot(a,14); \
7257 c ^= b; c -= rot(b,24); \
7261 mono_aot_type_hash (MonoType *t1)
7263 guint hash = t1->type;
7265 hash |= t1->byref << 6; /* do not collide with t1->type values */
7267 case MONO_TYPE_VALUETYPE:
7268 case MONO_TYPE_CLASS:
7269 case MONO_TYPE_SZARRAY:
7270 /* check if the distribution is good enough */
7271 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7273 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7274 case MONO_TYPE_ARRAY:
7275 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7276 case MONO_TYPE_GENERICINST:
7277 return ((hash << 5) - hash) ^ 0;
7284 * mono_aot_method_hash:
7286 * Return a hash code for methods which only depends on metadata.
7289 mono_aot_method_hash (MonoMethod *method)
7291 MonoMethodSignature *sig;
7295 guint32 *hashes_start, *hashes;
7297 MonoGenericInst *ginst = NULL;
7299 /* Similar to the hash in mono_method_get_imt_slot () */
7301 sig = mono_method_signature (method);
7303 if (method->is_inflated)
7304 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7306 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7307 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7308 hashes = hashes_start;
7310 /* Some wrappers are assigned to random classes */
7311 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7312 klass = method->klass;
7314 klass = mono_defaults.object_class;
7316 if (!method->wrapper_type) {
7317 char *full_name = mono_type_full_name (&klass->byval_arg);
7319 hashes [0] = mono_metadata_str_hash (full_name);
7323 hashes [0] = mono_metadata_str_hash (klass->name);
7324 hashes [1] = mono_metadata_str_hash (klass->name_space);
7326 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7327 /* The method name includes a stringified pointer */
7330 hashes [2] = mono_metadata_str_hash (method->name);
7331 hashes [3] = method->wrapper_type;
7332 hashes [4] = mono_aot_type_hash (sig->ret);
7334 for (i = 0; i < sig->param_count; i++) {
7335 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7338 for (i = 0; i < ginst->type_argc; ++i)
7339 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7341 g_assert (hindex == hashes_count);
7343 /* Setup internal state */
7344 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7346 /* Handle most of the hashes */
7347 while (hashes_count > 3) {
7356 /* Handle the last 3 hashes (all the case statements fall through) */
7357 switch (hashes_count) {
7358 case 3 : c += hashes [2];
7359 case 2 : b += hashes [1];
7360 case 1 : a += hashes [0];
7362 case 0: /* nothing left to add */
7366 free (hashes_start);
7375 * mono_aot_get_array_helper_from_wrapper;
7377 * Get the helper method in Array called by an array wrapper method.
7380 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7384 MonoGenericContext ctx;
7385 MonoType *args [16];
7386 char *mname, *iname, *s, *s2, *helper_name = NULL;
7388 prefix = "System.Collections.Generic";
7389 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7390 s2 = strstr (s, "`1.");
7396 //printf ("X: %s %s\n", iname, mname);
7398 if (!strcmp (iname, "IList"))
7399 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7401 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7402 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7404 g_free (helper_name);
7407 if (m->is_generic) {
7408 memset (&ctx, 0, sizeof (ctx));
7409 args [0] = &method->klass->element_class->byval_arg;
7410 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7411 m = mono_class_inflate_generic_method (m, &ctx);
7417 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7419 typedef struct HashEntry {
7420 guint32 key, value, index;
7421 struct HashEntry *next;
7425 * emit_extra_methods:
7427 * Emit methods which are not in the METHOD table, like wrappers.
7430 emit_extra_methods (MonoAotCompile *acfg)
7432 int i, table_size, buf_size;
7435 guint32 *info_offsets;
7438 HashEntry *entry, *new_entry;
7439 int nmethods, max_chain_length;
7442 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7444 /* Emit method info */
7446 for (i = 0; i < acfg->extra_methods->len; ++i) {
7447 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7448 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7454 p = buf = g_malloc (buf_size);
7458 method = cfg->method_to_register;
7460 encode_method_ref (acfg, method, p, &p);
7462 g_assert ((p - buf) < buf_size);
7464 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7469 * Construct a chained hash table for mapping indexes in extra_method_info to
7472 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7473 table = g_ptr_array_sized_new (table_size);
7474 for (i = 0; i < table_size; ++i)
7475 g_ptr_array_add (table, NULL);
7476 chain_lengths = g_new0 (int, table_size);
7477 max_chain_length = 0;
7478 for (i = 0; i < acfg->extra_methods->len; ++i) {
7479 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7480 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7486 key = info_offsets [i];
7487 value = get_method_index (acfg, method);
7489 hash = mono_aot_method_hash (method) % table_size;
7490 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7492 chain_lengths [hash] ++;
7493 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7495 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7496 new_entry->key = key;
7497 new_entry->value = value;
7499 entry = g_ptr_array_index (table, hash);
7500 if (entry == NULL) {
7501 new_entry->index = hash;
7502 g_ptr_array_index (table, hash) = new_entry;
7505 entry = entry->next;
7507 entry->next = new_entry;
7508 new_entry->index = table->len;
7509 g_ptr_array_add (table, new_entry);
7513 //printf ("MAX: %d\n", max_chain_length);
7515 /* Emit the table */
7516 sprintf (symbol, "extra_method_table");
7517 emit_section_change (acfg, RODATA_SECT, 0);
7518 emit_alignment (acfg, 8);
7519 emit_label (acfg, symbol);
7521 emit_int32 (acfg, table_size);
7522 for (i = 0; i < table->len; ++i) {
7523 HashEntry *entry = g_ptr_array_index (table, i);
7525 if (entry == NULL) {
7526 emit_int32 (acfg, 0);
7527 emit_int32 (acfg, 0);
7528 emit_int32 (acfg, 0);
7530 //g_assert (entry->key > 0);
7531 emit_int32 (acfg, entry->key);
7532 emit_int32 (acfg, entry->value);
7534 emit_int32 (acfg, entry->next->index);
7536 emit_int32 (acfg, 0);
7541 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7542 * This is used by mono_aot_find_jit_info ().
7544 sprintf (symbol, "extra_method_info_offsets");
7545 emit_section_change (acfg, RODATA_SECT, 0);
7546 emit_alignment (acfg, 8);
7547 emit_label (acfg, symbol);
7549 emit_int32 (acfg, acfg->extra_methods->len);
7550 for (i = 0; i < acfg->extra_methods->len; ++i) {
7551 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7553 emit_int32 (acfg, get_method_index (acfg, method));
7554 emit_int32 (acfg, info_offsets [i]);
7559 emit_exception_info (MonoAotCompile *acfg)
7565 offsets = g_new0 (gint32, acfg->nmethods);
7566 for (i = 0; i < acfg->nmethods; ++i) {
7567 if (acfg->cfgs [i]) {
7568 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7569 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7575 sprintf (symbol, "ex_info_offsets");
7576 emit_section_change (acfg, RODATA_SECT, 1);
7577 emit_alignment (acfg, 8);
7578 emit_label (acfg, symbol);
7580 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7585 emit_unwind_info (MonoAotCompile *acfg)
7591 * The unwind info contains a lot of duplicates so we emit each unique
7592 * entry once, and only store the offset from the start of the table in the
7596 sprintf (symbol, "unwind_info");
7597 emit_section_change (acfg, RODATA_SECT, 1);
7598 emit_alignment (acfg, 8);
7599 emit_label (acfg, symbol);
7601 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7602 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7603 guint8 *unwind_info;
7604 guint32 unwind_info_len;
7608 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7611 encode_value (unwind_info_len, p, &p);
7612 emit_bytes (acfg, buf, p - buf);
7613 emit_bytes (acfg, unwind_info, unwind_info_len);
7615 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7620 emit_class_info (MonoAotCompile *acfg)
7626 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7627 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7628 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7630 sprintf (symbol, "class_info_offsets");
7631 emit_section_change (acfg, RODATA_SECT, 1);
7632 emit_alignment (acfg, 8);
7633 emit_label (acfg, symbol);
7635 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7639 typedef struct ClassNameTableEntry {
7640 guint32 token, index;
7641 struct ClassNameTableEntry *next;
7642 } ClassNameTableEntry;
7645 emit_class_name_table (MonoAotCompile *acfg)
7648 guint32 token, hash;
7653 ClassNameTableEntry *entry, *new_entry;
7656 * Construct a chained hash table for mapping class names to typedef tokens.
7658 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7659 table = g_ptr_array_sized_new (table_size);
7660 for (i = 0; i < table_size; ++i)
7661 g_ptr_array_add (table, NULL);
7662 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7663 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7664 klass = mono_class_get (acfg->image, token);
7666 mono_loader_clear_error ();
7669 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7670 hash = mono_metadata_str_hash (full_name) % table_size;
7673 /* FIXME: Allocate from the mempool */
7674 new_entry = g_new0 (ClassNameTableEntry, 1);
7675 new_entry->token = token;
7677 entry = g_ptr_array_index (table, hash);
7678 if (entry == NULL) {
7679 new_entry->index = hash;
7680 g_ptr_array_index (table, hash) = new_entry;
7683 entry = entry->next;
7685 entry->next = new_entry;
7686 new_entry->index = table->len;
7687 g_ptr_array_add (table, new_entry);
7691 /* Emit the table */
7692 sprintf (symbol, "class_name_table");
7693 emit_section_change (acfg, RODATA_SECT, 0);
7694 emit_alignment (acfg, 8);
7695 emit_label (acfg, symbol);
7697 /* FIXME: Optimize memory usage */
7698 g_assert (table_size < 65000);
7699 emit_int16 (acfg, table_size);
7700 g_assert (table->len < 65000);
7701 for (i = 0; i < table->len; ++i) {
7702 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7704 if (entry == NULL) {
7705 emit_int16 (acfg, 0);
7706 emit_int16 (acfg, 0);
7708 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7710 emit_int16 (acfg, entry->next->index);
7712 emit_int16 (acfg, 0);
7718 emit_image_table (MonoAotCompile *acfg)
7724 * The image table is small but referenced in a lot of places.
7725 * So we emit it at once, and reference its elements by an index.
7728 sprintf (symbol, "image_table");
7729 emit_section_change (acfg, RODATA_SECT, 1);
7730 emit_alignment (acfg, 8);
7731 emit_label (acfg, symbol);
7733 emit_int32 (acfg, acfg->image_table->len);
7734 for (i = 0; i < acfg->image_table->len; i++) {
7735 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7736 MonoAssemblyName *aname = &image->assembly->aname;
7738 /* FIXME: Support multi-module assemblies */
7739 g_assert (image->assembly->image == image);
7741 emit_string (acfg, image->assembly_name);
7742 emit_string (acfg, image->guid);
7743 emit_string (acfg, aname->culture ? aname->culture : "");
7744 emit_string (acfg, (const char*)aname->public_key_token);
7746 emit_alignment (acfg, 8);
7747 emit_int32 (acfg, aname->flags);
7748 emit_int32 (acfg, aname->major);
7749 emit_int32 (acfg, aname->minor);
7750 emit_int32 (acfg, aname->build);
7751 emit_int32 (acfg, aname->revision);
7756 emit_got_info (MonoAotCompile *acfg)
7759 int i, first_plt_got_patch, buf_size;
7761 guint32 *got_info_offsets;
7763 /* Add the patches needed by the PLT to the GOT */
7764 acfg->plt_got_offset_base = acfg->got_offset;
7765 first_plt_got_patch = acfg->got_patches->len;
7766 for (i = 1; i < acfg->plt_offset; ++i) {
7767 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7769 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7771 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7774 acfg->got_offset += acfg->plt_offset;
7778 * - optimize offsets table.
7779 * - reduce number of exported symbols.
7780 * - emit info for a klass only once.
7781 * - determine when a method uses a GOT slot which is guaranteed to be already
7783 * - clean up and document the code.
7784 * - use String.Empty in class libs.
7787 /* Encode info required to decode shared GOT entries */
7788 buf_size = acfg->got_patches->len * 128;
7789 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7790 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7791 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7793 if (acfg->plt_offset)
7794 acfg->plt_got_info_offsets [0] = 0;
7795 for (i = 0; i < acfg->got_patches->len; ++i) {
7796 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7801 encode_value (ji->type, p, &p);
7803 encode_patch (acfg, ji, p, &p);
7804 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7805 g_assert (p - buf <= buf_size);
7806 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7808 if (i >= first_plt_got_patch)
7809 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7810 acfg->stats.got_info_size += p - buf;
7813 /* Emit got_info_offsets table */
7814 sprintf (symbol, "got_info_offsets");
7815 emit_section_change (acfg, RODATA_SECT, 1);
7816 emit_alignment (acfg, 8);
7817 emit_label (acfg, symbol);
7819 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7820 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7824 emit_got (MonoAotCompile *acfg)
7829 /* Don't make GOT global so accesses to it don't need relocations */
7830 sprintf (symbol, "%s", acfg->got_symbol);
7831 emit_section_change (acfg, ".bss", 0);
7832 emit_alignment (acfg, 8);
7833 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7834 emit_label (acfg, symbol);
7835 if (acfg->got_offset > 0)
7836 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7838 sprintf (symbol, "got_end");
7839 emit_label (acfg, symbol);
7843 typedef struct GlobalsTableEntry {
7844 guint32 value, index;
7845 struct GlobalsTableEntry *next;
7846 } GlobalsTableEntry;
7849 emit_globals (MonoAotCompile *acfg)
7855 GlobalsTableEntry *entry, *new_entry;
7857 if (!acfg->aot_opts.static_link)
7861 * When static linking, we emit a table containing our globals.
7865 * Construct a chained hash table for mapping global names to their index in
7866 * the globals table.
7868 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7869 table = g_ptr_array_sized_new (table_size);
7870 for (i = 0; i < table_size; ++i)
7871 g_ptr_array_add (table, NULL);
7872 for (i = 0; i < acfg->globals->len; ++i) {
7873 char *name = g_ptr_array_index (acfg->globals, i);
7875 hash = mono_metadata_str_hash (name) % table_size;
7877 /* FIXME: Allocate from the mempool */
7878 new_entry = g_new0 (GlobalsTableEntry, 1);
7879 new_entry->value = i;
7881 entry = g_ptr_array_index (table, hash);
7882 if (entry == NULL) {
7883 new_entry->index = hash;
7884 g_ptr_array_index (table, hash) = new_entry;
7887 entry = entry->next;
7889 entry->next = new_entry;
7890 new_entry->index = table->len;
7891 g_ptr_array_add (table, new_entry);
7895 /* Emit the table */
7896 sprintf (symbol, ".Lglobals_hash");
7897 emit_section_change (acfg, RODATA_SECT, 0);
7898 emit_alignment (acfg, 8);
7899 emit_label (acfg, symbol);
7901 /* FIXME: Optimize memory usage */
7902 g_assert (table_size < 65000);
7903 emit_int16 (acfg, table_size);
7904 for (i = 0; i < table->len; ++i) {
7905 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7907 if (entry == NULL) {
7908 emit_int16 (acfg, 0);
7909 emit_int16 (acfg, 0);
7911 emit_int16 (acfg, entry->value + 1);
7913 emit_int16 (acfg, entry->next->index);
7915 emit_int16 (acfg, 0);
7919 /* Emit the names */
7920 for (i = 0; i < acfg->globals->len; ++i) {
7921 char *name = g_ptr_array_index (acfg->globals, i);
7923 sprintf (symbol, "name_%d", i);
7924 emit_section_change (acfg, RODATA_SECT, 1);
7926 emit_alignment (acfg, 4);
7928 emit_label (acfg, symbol);
7929 emit_string (acfg, name);
7932 /* Emit the globals table */
7933 sprintf (symbol, "globals");
7934 emit_section_change (acfg, ".data", 0);
7935 /* This is not a global, since it is accessed by the init function */
7936 emit_alignment (acfg, 8);
7937 emit_label (acfg, symbol);
7939 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
7940 emit_pointer (acfg, symbol);
7942 for (i = 0; i < acfg->globals->len; ++i) {
7943 char *name = g_ptr_array_index (acfg->globals, i);
7945 sprintf (symbol, "name_%d", i);
7946 emit_pointer (acfg, symbol);
7948 sprintf (symbol, "%s", name);
7949 emit_pointer (acfg, symbol);
7951 /* Null terminate the table */
7952 emit_int32 (acfg, 0);
7953 emit_int32 (acfg, 0);
7957 emit_autoreg (MonoAotCompile *acfg)
7962 * Emit a function into the .ctor section which will be called by the ELF
7963 * loader to register this module with the runtime.
7965 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
7968 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
7970 arch_emit_autoreg (acfg, symbol);
7976 emit_mem_end (MonoAotCompile *acfg)
7980 sprintf (symbol, "mem_end");
7981 emit_section_change (acfg, ".text", 1);
7982 emit_alignment (acfg, 8);
7983 emit_label (acfg, symbol);
7987 * Emit a structure containing all the information not stored elsewhere.
7990 emit_file_info (MonoAotCompile *acfg)
7995 const char *gc_name;
7998 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8000 if (acfg->aot_opts.bind_to_runtime_version) {
8001 build_info = mono_get_runtime_build_info ();
8002 emit_string_symbol (acfg, "runtime_version", build_info);
8003 g_free (build_info);
8005 emit_string_symbol (acfg, "runtime_version", "");
8008 /* Emit a string holding the assembly name */
8009 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8012 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8015 gc_name = mono_gc_get_gc_name ();
8016 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8018 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8019 emit_section_change (acfg, ".data", 0);
8020 emit_alignment (acfg, 8);
8021 emit_label (acfg, symbol);
8022 if (!acfg->aot_opts.static_link)
8023 emit_global (acfg, symbol, FALSE);
8025 /* The data emitted here must match MonoAotFileInfo. */
8027 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8028 emit_int32 (acfg, 0);
8031 * We emit pointers to our data structures instead of emitting global symbols which
8032 * point to them, to reduce the number of globals, and because using globals leads to
8033 * various problems (i.e. arm/thumb).
8035 emit_pointer (acfg, acfg->got_symbol);
8036 emit_pointer (acfg, acfg->methods_symbol);
8039 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8041 emit_pointer (acfg, "mono_eh_frame");
8043 emit_pointer (acfg, NULL);
8045 emit_pointer (acfg, "blob");
8046 emit_pointer (acfg, "class_name_table");
8047 emit_pointer (acfg, "class_info_offsets");
8048 emit_pointer (acfg, "method_info_offsets");
8049 emit_pointer (acfg, "ex_info_offsets");
8050 emit_pointer (acfg, "code_offsets");
8051 if (acfg->direct_method_addresses)
8052 emit_pointer (acfg, "method_addresses");
8054 emit_pointer (acfg, NULL);
8055 emit_pointer (acfg, "extra_method_info_offsets");
8056 emit_pointer (acfg, "extra_method_table");
8057 emit_pointer (acfg, "got_info_offsets");
8058 emit_pointer (acfg, "methods_end");
8059 emit_pointer (acfg, "unwind_info");
8060 emit_pointer (acfg, "mem_end");
8061 emit_pointer (acfg, "image_table");
8062 emit_pointer (acfg, "plt");
8063 emit_pointer (acfg, "plt_end");
8064 emit_pointer (acfg, "assembly_guid");
8065 emit_pointer (acfg, "runtime_version");
8066 if (acfg->num_trampoline_got_entries) {
8067 emit_pointer (acfg, "specific_trampolines");
8068 emit_pointer (acfg, "static_rgctx_trampolines");
8069 emit_pointer (acfg, "imt_thunks");
8070 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8072 emit_pointer (acfg, NULL);
8073 emit_pointer (acfg, NULL);
8074 emit_pointer (acfg, NULL);
8075 emit_pointer (acfg, NULL);
8077 if (acfg->thumb_mixed) {
8078 emit_pointer (acfg, "thumb_end");
8080 emit_pointer (acfg, NULL);
8082 if (acfg->aot_opts.static_link) {
8083 emit_pointer (acfg, "globals");
8085 emit_pointer (acfg, NULL);
8087 emit_pointer (acfg, "assembly_name");
8088 emit_pointer (acfg, "unbox_trampolines");
8089 emit_pointer (acfg, "unbox_trampolines_end");
8091 emit_int32 (acfg, acfg->plt_got_offset_base);
8092 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8093 emit_int32 (acfg, acfg->plt_offset);
8094 emit_int32 (acfg, acfg->nmethods);
8095 emit_int32 (acfg, acfg->flags);
8096 emit_int32 (acfg, acfg->opts);
8097 emit_int32 (acfg, acfg->simd_opts);
8098 emit_int32 (acfg, gc_name_offset);
8100 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8101 emit_int32 (acfg, acfg->num_trampolines [i]);
8102 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8103 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8104 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8105 emit_int32 (acfg, acfg->trampoline_size [i]);
8106 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8108 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8113 memset (&t, 0, sizeof (MonoType));
8114 t.type = MONO_TYPE_R8;
8115 mono_type_size (&t, &align);
8116 emit_int32 (acfg, align);
8118 memset (&t, 0, sizeof (MonoType));
8119 t.type = MONO_TYPE_I8;
8120 mono_type_size (&t, &align);
8122 emit_int32 (acfg, align);
8125 emit_int32 (acfg, __alignof__ (double));
8126 emit_int32 (acfg, __alignof__ (gint64));
8128 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8129 emit_int32 (acfg, acfg->tramp_page_size);
8130 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8131 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8133 if (acfg->aot_opts.static_link) {
8137 * Emit a global symbol which can be passed by an embedding app to
8138 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8141 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8143 /* Get rid of characters which cannot occur in symbols */
8145 for (p = symbol; *p; ++p) {
8146 if (!(isalnum (*p) || *p == '_'))
8149 acfg->static_linking_symbol = g_strdup (symbol);
8150 emit_global_inner (acfg, symbol, FALSE);
8151 emit_alignment (acfg, sizeof (gpointer));
8152 emit_label (acfg, symbol);
8153 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8158 emit_blob (MonoAotCompile *acfg)
8162 sprintf (symbol, "blob");
8163 emit_section_change (acfg, RODATA_SECT, 1);
8164 emit_alignment (acfg, 8);
8165 emit_label (acfg, symbol);
8167 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8171 emit_objc_selectors (MonoAotCompile *acfg)
8175 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8180 * cat > foo.m << EOF
8183 * return @selector(print:);
8188 img_writer_emit_unset_mode (acfg->w);
8189 g_assert (acfg->fp);
8190 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8191 fprintf (acfg->fp, ".align 2\n");
8192 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8193 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8194 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8196 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8197 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8198 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8199 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8202 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8203 fprintf (acfg->fp, ".align 2\n");
8204 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8205 fprintf (acfg->fp, ".long 0\n");
8206 fprintf (acfg->fp, ".long 16\n");
8210 emit_dwarf_info (MonoAotCompile *acfg)
8212 #ifdef EMIT_DWARF_INFO
8216 /* DIEs for methods */
8217 for (i = 0; i < acfg->nmethods; ++i) {
8218 MonoCompile *cfg = acfg->cfgs [i];
8223 // FIXME: LLVM doesn't define .Lme_...
8224 if (cfg->compile_llvm)
8227 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8229 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 ()));
8235 collect_methods (MonoAotCompile *acfg)
8238 MonoImage *image = acfg->image;
8240 /* Collect methods */
8241 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8243 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8245 method = mono_get_method (acfg->image, token, NULL);
8248 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8252 /* Load all methods eagerly to skip the slower lazy loading code */
8253 mono_class_setup_methods (method->klass);
8255 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8256 /* Compile the wrapper instead */
8257 /* We do this here instead of add_wrappers () because it is easy to do it here */
8258 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8262 /* FIXME: Some mscorlib methods don't have debug info */
8264 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8265 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8266 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8267 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8268 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8269 if (!mono_debug_lookup_method (method)) {
8270 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8277 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8278 add_method_with_index (acfg, method, i, FALSE);
8279 acfg->method_index ++;
8282 /* gsharedvt methods */
8283 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8285 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8287 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8290 method = mono_get_method (acfg->image, token, NULL);
8294 if (strcmp (method->name, "gshared2"))
8298 if (!strstr (method->klass->image->name, "mini"))
8301 if (method->is_generic || method->klass->generic_container) {
8302 MonoMethod *gshared;
8304 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8305 add_extra_method (acfg, gshared);
8309 add_generic_instances (acfg);
8311 if (acfg->aot_opts.full_aot)
8312 add_wrappers (acfg);
8316 compile_methods (MonoAotCompile *acfg)
8320 if (acfg->aot_opts.nthreads > 0) {
8325 gpointer *user_data;
8326 MonoMethod **methods;
8328 methods_len = acfg->methods->len;
8330 len = acfg->methods->len / acfg->aot_opts.nthreads;
8333 * Partition the list of methods into fragments, and hand it to threads to
8336 threads = g_ptr_array_new ();
8337 /* Make a copy since acfg->methods is modified by compile_method () */
8338 methods = g_new0 (MonoMethod*, methods_len);
8339 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8340 for (i = 0; i < methods_len; ++i)
8341 methods [i] = g_ptr_array_index (acfg->methods, i);
8343 while (i < methods_len) {
8344 frag = g_ptr_array_new ();
8345 for (j = 0; j < len; ++j) {
8346 if (i < methods_len) {
8347 g_ptr_array_add (frag, methods [i]);
8352 user_data = g_new0 (gpointer, 3);
8353 user_data [0] = mono_domain_get ();
8354 user_data [1] = acfg;
8355 user_data [2] = frag;
8357 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
8358 g_ptr_array_add (threads, handle);
8362 for (i = 0; i < threads->len; ++i) {
8363 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8369 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8370 for (i = methods_len; i < acfg->methods->len; ++i) {
8371 /* This can new methods to acfg->methods */
8372 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8377 compile_asm (MonoAotCompile *acfg)
8379 char *command, *objfile;
8380 char *outfile_name, *tmp_outfile_name;
8381 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8383 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8384 #define AS_OPTIONS "--64"
8385 #elif defined(TARGET_POWERPC64)
8386 #define AS_OPTIONS "-a64 -mppc64"
8387 #define LD_OPTIONS "-m elf64ppc"
8388 #elif defined(sparc) && SIZEOF_VOID_P == 8
8389 #define AS_OPTIONS "-xarch=v9"
8390 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8391 #define AS_OPTIONS "-arch i386 -W"
8393 #define AS_OPTIONS ""
8396 #ifdef __native_client_codegen__
8397 #if defined(TARGET_AMD64)
8398 #define AS_NAME "nacl64-as"
8400 #define AS_NAME "nacl-as"
8402 #elif defined(TARGET_OSX)
8403 #define AS_NAME "clang -c -x assembler"
8405 #define AS_NAME "as"
8409 #define LD_OPTIONS ""
8412 #define EH_LD_OPTIONS ""
8414 if (acfg->aot_opts.asm_only) {
8415 printf ("Output file: '%s'.\n", acfg->tmpfname);
8416 if (acfg->aot_opts.static_link)
8417 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8421 if (acfg->aot_opts.static_link) {
8422 if (acfg->aot_opts.outfile)
8423 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8425 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8427 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8429 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);
8430 printf ("Executing the native assembler: %s\n", command);
8431 if (system (command) != 0) {
8439 if (acfg->aot_opts.static_link) {
8440 printf ("Output file: '%s'.\n", objfile);
8441 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8446 if (acfg->aot_opts.outfile)
8447 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8449 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8451 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8454 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8455 #elif defined(__ppc__) && defined(TARGET_MACH)
8456 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8457 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8458 command = g_strdup_printf ("clang --shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8459 #elif defined(HOST_WIN32)
8460 command = g_strdup_printf ("gcc -shared --dll -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8461 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8462 command = g_strdup_printf ("clang -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8464 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8466 printf ("Executing the native linker: %s\n", command);
8467 if (system (command) != 0) {
8468 g_free (tmp_outfile_name);
8469 g_free (outfile_name);
8477 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8478 printf ("Stripping the binary: %s\n", com);
8482 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8484 * gas generates 'mapping symbols' each time code and data is mixed, which
8485 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8487 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8488 printf ("Stripping the binary: %s\n", command);
8489 if (system (command) != 0) {
8490 g_free (tmp_outfile_name);
8491 g_free (outfile_name);
8498 rename (tmp_outfile_name, outfile_name);
8500 #if defined(TARGET_MACH)
8501 command = g_strdup_printf ("dsymutil %s", outfile_name);
8502 printf ("Generating debug symbols: %s\n", command);
8503 if (system (command) != 0) {
8508 if (!acfg->aot_opts.save_temps)
8511 g_free (tmp_outfile_name);
8512 g_free (outfile_name);
8515 if (acfg->aot_opts.save_temps)
8516 printf ("Retained input file.\n");
8518 unlink (acfg->tmpfname);
8523 static MonoAotCompile*
8524 acfg_create (MonoAssembly *ass, guint32 opts)
8526 MonoImage *image = ass->image;
8527 MonoAotCompile *acfg;
8530 acfg = g_new0 (MonoAotCompile, 1);
8531 acfg->methods = g_ptr_array_new ();
8532 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8533 acfg->method_depth = g_hash_table_new (NULL, NULL);
8534 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8535 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8536 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8537 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8538 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8539 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8540 acfg->got_patches = g_ptr_array_new ();
8541 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8542 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8543 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8544 acfg->image_hash = g_hash_table_new (NULL, NULL);
8545 acfg->image_table = g_ptr_array_new ();
8546 acfg->globals = g_ptr_array_new ();
8547 acfg->image = image;
8549 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8550 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8551 acfg->mempool = mono_mempool_new ();
8552 acfg->extra_methods = g_ptr_array_new ();
8553 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8554 acfg->unwind_ops = g_ptr_array_new ();
8555 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8556 acfg->method_order = g_ptr_array_new ();
8557 acfg->export_names = g_hash_table_new (NULL, NULL);
8558 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8559 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8560 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8561 InitializeCriticalSection (&acfg->mutex);
8567 acfg_free (MonoAotCompile *acfg)
8571 img_writer_destroy (acfg->w);
8572 for (i = 0; i < acfg->nmethods; ++i)
8574 g_free (acfg->cfgs [i]);
8575 g_free (acfg->cfgs);
8576 g_free (acfg->static_linking_symbol);
8577 g_free (acfg->got_symbol);
8578 g_free (acfg->plt_symbol);
8579 g_ptr_array_free (acfg->methods, TRUE);
8580 g_ptr_array_free (acfg->got_patches, TRUE);
8581 g_ptr_array_free (acfg->image_table, TRUE);
8582 g_ptr_array_free (acfg->globals, TRUE);
8583 g_ptr_array_free (acfg->unwind_ops, TRUE);
8584 g_hash_table_destroy (acfg->method_indexes);
8585 g_hash_table_destroy (acfg->method_depth);
8586 g_hash_table_destroy (acfg->plt_offset_to_entry);
8587 g_hash_table_destroy (acfg->patch_to_plt_entry);
8588 g_hash_table_destroy (acfg->patch_to_got_offset);
8589 g_hash_table_destroy (acfg->method_to_cfg);
8590 g_hash_table_destroy (acfg->token_info_hash);
8591 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8592 g_hash_table_destroy (acfg->image_hash);
8593 g_hash_table_destroy (acfg->unwind_info_offsets);
8594 g_hash_table_destroy (acfg->method_label_hash);
8595 g_hash_table_destroy (acfg->export_names);
8596 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8597 g_hash_table_destroy (acfg->klass_blob_hash);
8598 g_hash_table_destroy (acfg->method_blob_hash);
8599 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8600 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8601 g_free (acfg->patch_to_got_offset_by_type);
8602 mono_mempool_destroy (acfg->mempool);
8607 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8609 MonoImage *image = ass->image;
8611 MonoAotCompile *acfg;
8612 char *outfile_name, *tmp_outfile_name, *p;
8613 char llvm_stats_msg [256];
8617 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || (!defined(MONO_EXTENSIONS) && !defined(MONOTOUCH))
8618 if (opts & MONO_OPT_GSHAREDVT) {
8619 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8624 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8626 acfg = acfg_create (ass, opts);
8628 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8629 acfg->aot_opts.write_symbols = TRUE;
8630 acfg->aot_opts.ntrampolines = 1024;
8631 acfg->aot_opts.nrgctx_trampolines = 1024;
8632 acfg->aot_opts.nimt_trampolines = 128;
8633 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8634 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8635 acfg->aot_opts.llvm_path = g_strdup ("");
8637 acfg->aot_opts.use_trampolines_page = TRUE;
8640 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8642 if (acfg->aot_opts.static_link)
8643 acfg->aot_opts.autoreg = TRUE;
8645 //acfg->aot_opts.print_skipped_methods = TRUE;
8647 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8648 if (acfg->aot_opts.full_aot) {
8649 printf ("--aot=full is not supported on this platform.\n");
8654 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8655 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8659 if (acfg->aot_opts.static_link)
8660 acfg->aot_opts.asm_writer = TRUE;
8662 if (acfg->aot_opts.soft_debug) {
8663 MonoDebugOptions *opt = mini_get_debug_options ();
8665 opt->mdb_optimizations = TRUE;
8666 opt->gen_seq_points = TRUE;
8668 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8669 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8672 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8675 if (mono_use_llvm) {
8677 acfg->aot_opts.asm_writer = TRUE;
8678 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8680 if (acfg->aot_opts.soft_debug) {
8681 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8686 if (acfg->aot_opts.full_aot)
8687 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8689 load_profile_files (acfg);
8691 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8692 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8693 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8695 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8696 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8697 if (acfg->opts & MONO_OPT_GSHAREDVT)
8698 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8701 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8705 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8706 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8707 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8709 /* Get rid of characters which cannot occur in symbols */
8710 for (p = acfg->got_symbol_base; *p; ++p) {
8711 if (!(isalnum (*p) || *p == '_'))
8714 for (p = acfg->plt_symbol; *p; ++p) {
8715 if (!(isalnum (*p) || *p == '_'))
8718 for (p = acfg->assembly_name_sym; *p; ++p) {
8719 if (!(isalnum (*p) || *p == '_'))
8723 acfg->method_index = 1;
8727 if (acfg->aot_opts.full_aot)
8728 mono_set_partial_sharing_supported (TRUE);
8731 collect_methods (acfg);
8733 acfg->cfgs_size = acfg->methods->len + 32;
8734 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8736 /* PLT offset 0 is reserved for the PLT trampoline */
8737 acfg->plt_offset = 1;
8742 mono_llvm_create_aot_module (acfg->got_symbol_base);
8746 /* GOT offset 0 is reserved for the address of the current assembly */
8750 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8751 ji->type = MONO_PATCH_INFO_IMAGE;
8752 ji->data.image = acfg->image;
8754 get_got_offset (acfg, ji);
8756 /* Slot 1 is reserved for the mscorlib got addr */
8757 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8758 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8759 get_got_offset (acfg, ji);
8761 /* This is very common */
8762 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8763 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8764 get_got_offset (acfg, ji);
8766 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8767 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8768 get_got_offset (acfg, ji);
8773 compile_methods (acfg);
8777 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8783 if (acfg->aot_opts.asm_only) {
8784 if (acfg->aot_opts.outfile)
8785 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8787 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8789 acfg->tmpfname = g_strdup ("temp.s");
8792 emit_llvm_file (acfg);
8796 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8797 if (acfg->aot_opts.outfile)
8798 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8800 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8803 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8804 * it might be in another file system so the rename () won't work.
8806 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8808 acfg->fp = fopen (tmp_outfile_name, "w");
8810 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8814 acfg->w = img_writer_create (acfg->fp, TRUE);
8815 acfg->use_bin_writer = TRUE;
8818 /* Append to the .s file created by llvm */
8819 /* FIXME: Use multiple files instead */
8820 acfg->fp = fopen (acfg->tmpfname, "a+");
8822 if (acfg->aot_opts.asm_only) {
8823 if (acfg->aot_opts.outfile)
8824 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8826 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8827 acfg->fp = fopen (acfg->tmpfname, "w+");
8829 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8830 acfg->fp = fdopen (i, "w+");
8833 if (acfg->fp == 0) {
8834 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8837 acfg->w = img_writer_create (acfg->fp, FALSE);
8839 tmp_outfile_name = NULL;
8840 outfile_name = NULL;
8843 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8845 /* Compute symbols for methods */
8846 for (i = 0; i < acfg->nmethods; ++i) {
8847 if (acfg->cfgs [i]) {
8848 MonoCompile *cfg = acfg->cfgs [i];
8849 int method_index = get_method_index (acfg, cfg->orig_method);
8851 if (COMPILE_LLVM (cfg))
8852 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8853 else if (acfg->global_symbols)
8854 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8856 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8860 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
8862 * CLANG supports GAS .file/.loc directives, so emit line number information this way
8864 acfg->gas_line_numbers = TRUE;
8867 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8868 if (acfg->aot_opts.dwarf_debug && mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8869 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8872 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
8875 img_writer_emit_start (acfg->w);
8878 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
8880 if (acfg->thumb_mixed) {
8883 * This global symbol marks the end of THUMB code, and the beginning of ARM
8884 * code generated by our JIT.
8886 sprintf (symbol, "thumb_end");
8887 emit_section_change (acfg, ".text", 0);
8888 emit_alignment (acfg, 8);
8889 emit_label (acfg, symbol);
8890 emit_zero_bytes (acfg, 16);
8892 fprintf (acfg->fp, ".arm\n");
8899 emit_extra_methods (acfg);
8901 emit_trampolines (acfg);
8903 emit_class_name_table (acfg);
8905 emit_got_info (acfg);
8907 emit_exception_info (acfg);
8909 emit_unwind_info (acfg);
8911 emit_class_info (acfg);
8915 emit_image_table (acfg);
8919 emit_file_info (acfg);
8923 emit_objc_selectors (acfg);
8925 emit_globals (acfg);
8927 emit_autoreg (acfg);
8930 emit_dwarf_info (acfg);
8931 mono_dwarf_writer_close (acfg->dwarf);
8934 emit_mem_end (acfg);
8936 if (acfg->need_pt_gnu_stack) {
8937 /* This is required so the .so doesn't have an executable stack */
8938 /* The bin writer already emits this */
8939 if (!acfg->use_bin_writer)
8940 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
8945 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
8948 g_assert (acfg->got_offset <= acfg->final_got_size);
8951 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
8953 strcpy (llvm_stats_msg, "");
8954 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
8955 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
8956 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
8958 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
8959 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
8960 if (acfg->stats.genericcount)
8961 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
8962 if (acfg->stats.abscount)
8963 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
8964 if (acfg->stats.lmfcount)
8965 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
8966 if (acfg->stats.ocount)
8967 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
8970 res = img_writer_emit_writeout (acfg->w);
8975 if (acfg->use_bin_writer) {
8976 int err = rename (tmp_outfile_name, outfile_name);
8979 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
8983 res = compile_asm (acfg);
8990 acfg->stats.link_time = TV_ELAPSED (atv, btv);
8992 if (acfg->aot_opts.stats) {
8995 printf ("GOT slot distribution:\n");
8996 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
8997 if (acfg->stats.got_slot_types [i])
8998 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9001 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);
9013 mono_aot_readonly_field_override (MonoClassField *field)
9019 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)