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;
215 GHashTable *unwind_info_offsets;
216 GPtrArray *unwind_ops;
217 guint32 unwind_info_offset;
218 char *got_symbol_base;
221 char *methods_symbol;
222 GHashTable *method_label_hash;
223 const char *temp_prefix;
224 const char *user_symbol_prefix;
225 const char *llvm_label_prefix;
226 guint32 label_generator;
228 MonoAotFileFlags flags;
229 MonoDynamicStream blob;
230 MonoClass **typespec_classes;
233 char *assembly_name_sym;
234 GHashTable *plt_entry_debug_sym_cache;
235 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
236 GHashTable *ginst_hash;
237 GHashTable *dwarf_ln_filenames;
238 gboolean global_symbols;
239 gboolean direct_method_addresses;
240 int objc_selector_index, objc_selector_index_2;
241 GPtrArray *objc_selectors;
242 GHashTable *objc_selector_to_index;
247 char *symbol, *llvm_symbol, *debug_sym;
249 gboolean jit_used, llvm_used;
252 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
253 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
255 /* This points to the current acfg in LLVM mode */
256 static MonoAotCompile *llvm_acfg;
258 #ifdef HAVE_ARRAY_ELEM_INIT
259 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
260 #define MSGSTRFIELD1(line) str##line
261 static const struct msgstr_t {
262 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
263 #include "patch-info.h"
266 #define PATCH_INFO(a,b) b,
267 #include "patch-info.h"
270 static const gint16 opidx [] = {
271 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
272 #include "patch-info.h"
276 static G_GNUC_UNUSED const char*
277 get_patch_name (int info)
279 return (const char*)&opstr + opidx [info];
283 #define PATCH_INFO(a,b) b,
284 static const char* const
285 patch_types [MONO_PATCH_INFO_NUM + 1] = {
286 #include "patch-info.h"
290 static G_GNUC_UNUSED const char*
291 get_patch_name (int info)
293 return patch_types [info];
299 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
301 /* Wrappers around the image writer functions */
304 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
306 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
310 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
312 img_writer_emit_push_section (acfg->w, section_name, subsection);
316 emit_pop_section (MonoAotCompile *acfg)
318 img_writer_emit_pop_section (acfg->w);
322 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
324 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
328 emit_label (MonoAotCompile *acfg, const char *name)
330 img_writer_emit_label (acfg->w, name);
334 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
336 img_writer_emit_bytes (acfg->w, buf, size);
340 emit_string (MonoAotCompile *acfg, const char *value)
342 img_writer_emit_string (acfg->w, value);
346 emit_line (MonoAotCompile *acfg)
348 img_writer_emit_line (acfg->w);
352 emit_alignment (MonoAotCompile *acfg, int size)
354 img_writer_emit_alignment (acfg->w, size);
358 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
360 img_writer_emit_pointer_unaligned (acfg->w, target);
364 emit_pointer (MonoAotCompile *acfg, const char *target)
366 img_writer_emit_pointer (acfg->w, target);
370 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
372 if (prefix [0] != '\0') {
373 char *s = g_strdup_printf ("%s%s", prefix, target);
374 img_writer_emit_pointer (acfg->w, s);
377 img_writer_emit_pointer (acfg->w, target);
382 emit_int16 (MonoAotCompile *acfg, int value)
384 img_writer_emit_int16 (acfg->w, value);
388 emit_int32 (MonoAotCompile *acfg, int value)
390 img_writer_emit_int32 (acfg->w, value);
394 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
396 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
400 emit_zero_bytes (MonoAotCompile *acfg, int num)
402 img_writer_emit_zero_bytes (acfg->w, num);
406 emit_byte (MonoAotCompile *acfg, guint8 val)
408 img_writer_emit_byte (acfg->w, val);
411 #ifdef __native_client_codegen__
413 emit_nacl_call_alignment (MonoAotCompile *acfg)
415 img_writer_emit_nacl_call_alignment (acfg->w);
419 static G_GNUC_UNUSED void
420 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
422 img_writer_emit_global (acfg->w, name, func);
426 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
428 if (acfg->aot_opts.no_dlsym) {
429 g_ptr_array_add (acfg->globals, g_strdup (name));
430 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
432 img_writer_emit_global (acfg->w, name, func);
437 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
439 img_writer_emit_symbol_size (acfg->w, name, end_label);
443 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
445 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
447 /* On apple, all symbols need to be aligned to avoid warnings from ld */
448 emit_alignment (acfg, 4);
450 img_writer_emit_label (acfg->w, name);
451 img_writer_emit_string (acfg->w, value);
454 static G_GNUC_UNUSED void
455 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
458 guint8 b = value & 0x7f;
460 if (value != 0) /* more bytes to come */
466 static G_GNUC_UNUSED void
467 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
470 gboolean negative = (value < 0);
477 /* the following is unnecessary if the
478 * implementation of >>= uses an arithmetic rather
479 * than logical shift for a signed left operand
483 value |= - ((gint64)1 <<(size - 7));
484 /* sign bit of byte is second high order bit (0x40) */
485 if ((value == 0 && !(byte & 0x40)) ||
486 (value == -1 && (byte & 0x40)))
490 emit_byte (acfg, byte);
494 static G_GNUC_UNUSED void
495 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
500 guint8 b = value & 0x7f;
502 if (value != 0) /* more bytes to come */
510 static G_GNUC_UNUSED void
511 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
514 gboolean negative = (value < 0);
522 /* the following is unnecessary if the
523 * implementation of >>= uses an arithmetic rather
524 * than logical shift for a signed left operand
528 value |= - (1 <<(size - 7));
529 /* sign bit of byte is second high order bit (0x40) */
530 if ((value == 0 && !(byte & 0x40)) ||
531 (value == -1 && (byte & 0x40)))
542 emit_unset_mode (MonoAotCompile *acfg)
544 img_writer_emit_unset_mode (acfg->w);
547 static G_GNUC_UNUSED void
548 emit_set_thumb_mode (MonoAotCompile *acfg)
550 emit_unset_mode (acfg);
551 fprintf (acfg->fp, ".code 16\n");
554 static G_GNUC_UNUSED void
555 emit_set_arm_mode (MonoAotCompile *acfg)
557 emit_unset_mode (acfg);
558 fprintf (acfg->fp, ".code 32\n");
561 /* ARCHITECTURE SPECIFIC CODE */
563 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
564 #define EMIT_DWARF_INFO 1
567 #if defined(TARGET_ARM)
568 #define AOT_FUNC_ALIGNMENT 4
570 #define AOT_FUNC_ALIGNMENT 16
572 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
573 #undef AOT_FUNC_ALIGNMENT
574 #define AOT_FUNC_ALIGNMENT 32
577 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
578 #define PPC_LD_OP "ld"
579 #define PPC_LDX_OP "ldx"
581 #define PPC_LD_OP "lwz"
582 #define PPC_LDX_OP "lwzx"
586 #define AOT_TARGET_STR "AMD64"
591 #define AOT_TARGET_STR "ARM (MACH)"
593 #define AOT_TARGET_STR "ARM (!MACH)"
597 #ifdef TARGET_POWERPC64
598 #ifdef __mono_ilp32__
599 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
601 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
604 #ifdef TARGET_POWERPC
605 #ifdef __mono_ilp32__
606 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
608 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
615 #define AOT_TARGET_STR "X86 (WIN32)"
616 #elif defined(__native_client_codegen__)
617 #define AOT_TARGET_STR "X86 (native client codegen)"
619 #define AOT_TARGET_STR "X86 (!native client codegen)"
623 #ifndef AOT_TARGET_STR
624 #define AOT_TARGET_STR ""
628 arch_init (MonoAotCompile *acfg)
630 acfg->llc_args = g_string_new ("");
631 acfg->as_args = g_string_new ("");
634 * The prefix LLVM likes to put in front of symbol names on darwin.
635 * The mach-os specs require this for globals, but LLVM puts them in front of all
636 * symbols. We need to handle this, since we need to refer to LLVM generated
639 acfg->llvm_label_prefix = "";
640 acfg->user_symbol_prefix = "";
642 #if defined(TARGET_AMD64) && defined(TARGET_MACH)
643 /* osx contains an old as which doesn't support avx opcodes */
644 g_string_append (acfg->llc_args, "-mattr=-avx");
647 #if defined(TARGET_AMD64)
648 g_string_append (acfg->llc_args, " -march=x86-64");
652 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
653 g_string_append (acfg->llc_args, "-mattr=+v6");
656 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
657 g_string_append (acfg->as_args, " -mfpu=vfp3");
659 g_string_append (acfg->llc_args, " -soft-float");
662 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
663 acfg->thumb_mixed = TRUE;
665 if (acfg->aot_opts.mtriple)
666 mono_arch_set_target (acfg->aot_opts.mtriple);
670 acfg->user_symbol_prefix = "_";
671 acfg->llvm_label_prefix = "_";
672 acfg->need_no_dead_strip = TRUE;
673 acfg->aot_opts.gnu_asm = TRUE;
676 #if defined(__linux__) && !defined(TARGET_ARM)
677 acfg->need_pt_gnu_stack = TRUE;
681 acfg->direct_method_addresses = TRUE;
682 acfg->global_symbols = TRUE;
687 * arch_emit_direct_call:
689 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
693 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, MonoJumpInfo *ji, int *call_size)
695 #if defined(TARGET_X86) || defined(TARGET_AMD64)
696 /* Need to make sure this is exactly 5 bytes long */
697 if (external && !acfg->use_bin_writer) {
698 emit_unset_mode (acfg);
699 fprintf (acfg->fp, "call %s\n", target);
701 emit_byte (acfg, '\xe8');
702 emit_symbol_diff (acfg, target, ".", -4);
705 #elif defined(TARGET_ARM)
706 if (acfg->use_bin_writer) {
713 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
714 emit_bytes (acfg, buf, 4);
716 emit_unset_mode (acfg);
717 fprintf (acfg->fp, "bl %s\n", target);
720 #elif defined(TARGET_POWERPC)
721 if (acfg->use_bin_writer) {
722 g_assert_not_reached ();
724 emit_unset_mode (acfg);
725 fprintf (acfg->fp, "bl %s\n", target);
729 g_assert_not_reached ();
735 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
737 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
738 * in in the 2. slot of every GOT, and require every method to place the GOT
739 * address in r30, even when it doesn't access the GOT otherwise. This way,
740 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
745 * PPC64 uses function descriptors which greatly complicate all code, since
746 * these are used very inconsistently in the runtime. Some functions like
747 * mono_compile_method () return ftn descriptors, while others like the
748 * trampoline creation functions do not.
749 * We assume that all GOT slots contain function descriptors, and create
750 * descriptors in aot-runtime.c when needed.
751 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
752 * from function descriptors, we could do the same, but it would require
753 * rewriting all the ppc/aot code to handle function descriptors properly.
754 * So instead, we use the same approach as on PPC32.
755 * This is a horrible mess, but fixing it would probably lead to an even bigger
761 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
764 #ifdef MONO_ARCH_AOT_SUPPORTED
766 * arch_emit_got_offset:
768 * The memory pointed to by CODE should hold native code for computing the GOT
769 * address. Emit this code while patching it with the offset between code and
770 * the GOT. CODE_SIZE is set to the number of bytes emitted.
773 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
775 #if defined(TARGET_POWERPC64)
776 g_assert (!acfg->use_bin_writer);
777 emit_unset_mode (acfg);
779 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
780 * unsupported relocations. So we store the got address into the .Lgot_addr
781 * symbol which is in the text segment, compute its address, and load it.
783 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
784 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
785 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
786 fprintf (acfg->fp, "add 30, 30, 0\n");
787 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
788 acfg->label_generator ++;
790 #elif defined(TARGET_POWERPC)
791 g_assert (!acfg->use_bin_writer);
792 emit_unset_mode (acfg);
793 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
794 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
795 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
796 acfg->label_generator ++;
799 guint32 offset = mono_arch_get_patch_offset (code);
800 emit_bytes (acfg, code, offset);
801 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
803 *code_size = offset + 4;
808 * arch_emit_got_access:
810 * The memory pointed to by CODE should hold native code for loading a GOT
811 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
812 * CODE_SIZE is set to the number of bytes emitted.
815 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
817 /* Emit beginning of instruction */
818 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
820 /* Emit the offset */
822 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
823 *code_size = mono_arch_get_patch_offset (code) + 4;
824 #elif defined(TARGET_X86)
825 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
826 *code_size = mono_arch_get_patch_offset (code) + 4;
827 #elif defined(TARGET_ARM)
828 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
829 *code_size = mono_arch_get_patch_offset (code) + 4;
830 #elif defined(TARGET_POWERPC)
836 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
837 g_assert (code - buf == 8);
838 emit_bytes (acfg, buf, code - buf);
839 *code_size = code - buf;
842 g_assert_not_reached ();
849 * arch_emit_objc_selector_ref:
851 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
854 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
856 #if defined(TARGET_ARM)
859 int lindex = acfg->objc_selector_index_2 ++;
862 emit_bytes (acfg, code, 8);
864 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
865 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
867 emit_label (acfg, symbol1);
868 img_writer_emit_unset_mode (acfg->w);
869 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
873 g_assert_not_reached ();
878 * arch_emit_plt_entry:
880 * Emit code for the PLT entry with index INDEX.
883 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
885 #if defined(TARGET_X86)
886 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
887 #if defined(__default_codegen__)
888 /* jmp *<offset>(%ebx) */
889 emit_byte (acfg, 0xff);
890 emit_byte (acfg, 0xa3);
891 emit_int32 (acfg, offset);
892 /* Used by mono_aot_get_plt_info_offset */
893 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
894 #elif defined(__native_client_codegen__)
895 const guint8 kSizeOfNaClJmp = 11;
896 guint8 bytes[kSizeOfNaClJmp];
897 guint8 *pbytes = &bytes[0];
899 x86_jump_membase32 (pbytes, X86_EBX, offset);
900 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
901 /* four bytes of data, used by mono_arch_patch_plt_entry */
902 /* For Native Client, make this work with data embedded in push. */
903 emit_byte (acfg, 0x68); /* hide data in a push */
904 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
905 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
906 #endif /*__native_client_codegen__*/
907 #elif defined(TARGET_AMD64)
908 #if defined(__default_codegen__)
910 * We can't emit jumps because they are 32 bits only so they can't be patched.
911 * So we make indirect calls through GOT entries which are patched by the AOT
912 * loader to point to .Lpd entries.
914 /* jmpq *<offset>(%rip) */
915 emit_byte (acfg, '\xff');
916 emit_byte (acfg, '\x25');
917 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
918 /* Used by mono_aot_get_plt_info_offset */
919 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
920 #elif defined(__native_client_codegen__)
922 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
923 guint8 *code = buf_aligned;
925 /* mov <OFFSET>(%rip), %r11d */
926 emit_byte (acfg, '\x45');
927 emit_byte (acfg, '\x8b');
928 emit_byte (acfg, '\x1d');
929 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
931 amd64_jump_reg (code, AMD64_R11);
932 /* This should be constant for the plt patch */
933 g_assert ((size_t)(code-buf_aligned) == 10);
934 emit_bytes (acfg, buf_aligned, code - buf_aligned);
936 /* Hide data in a push imm32 so it passes validation */
937 emit_byte (acfg, 0x68); /* push */
938 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
939 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
940 #endif /*__native_client_codegen__*/
941 #elif defined(TARGET_ARM)
946 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
947 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
948 emit_bytes (acfg, buf, code - buf);
949 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
950 /* Used by mono_aot_get_plt_info_offset */
951 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
952 #elif defined(TARGET_POWERPC)
953 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
955 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
956 g_assert (!acfg->use_bin_writer);
957 emit_unset_mode (acfg);
958 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
959 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
960 fprintf (acfg->fp, "add 11, 11, 30\n");
961 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
962 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
963 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
964 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
966 fprintf (acfg->fp, "mtctr 11\n");
967 fprintf (acfg->fp, "bctr\n");
968 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
970 g_assert_not_reached ();
975 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
977 #if defined(TARGET_ARM)
979 /* LLVM calls the PLT entries using bl, so emit a stub */
980 /* FIXME: Too much overhead on every call */
981 fprintf (acfg->fp, ".thumb_func\n");
982 fprintf (acfg->fp, "bx pc\n");
983 fprintf (acfg->fp, "nop\n");
984 fprintf (acfg->fp, ".arm\n");
986 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
987 /* The caller already transitioned to thumb */
988 /* The code below should be 12 bytes long */
989 /* clang has trouble encoding these instructions, so emit the binary */
991 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
992 /* thumb can't encode ld pc, [pc, ip] */
993 fprintf (acfg->fp, "add ip, pc, ip\n");
994 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
995 fprintf (acfg->fp, "bx ip\n");
997 emit_set_thumb_mode (acfg);
998 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
999 fprintf (acfg->fp, ".2byte 0x44fc\n");
1000 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1001 fprintf (acfg->fp, ".2byte 0x4760\n");
1002 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1003 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1004 emit_unset_mode (acfg);
1005 emit_set_arm_mode (acfg);
1007 g_assert_not_reached ();
1012 * arch_emit_specific_trampoline_pages:
1014 * Emits a page full of trampolines: each trampoline uses its own address to
1015 * lookup both the generic trampoline code and the data argument.
1016 * This page can be remapped in process multiple times so we can get an
1017 * unlimited number of trampolines.
1018 * Specifically this implementation uses the following trick: two memory pages
1019 * are allocated, with the first containing the data and the second containing the trampolines.
1020 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1021 * implementation does all the lifting.
1022 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1023 * on the arm 32 bit system.
1026 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1028 #if defined(TARGET_ARM)
1031 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1033 #define COMMON_TRAMP_SIZE 16
1034 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1035 int imm8, rot_amount;
1038 if (!acfg->aot_opts.use_trampolines_page)
1041 acfg->tramp_page_size = mono_pagesize ();
1043 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1044 emit_alignment (acfg, mono_pagesize ());
1045 emit_global (acfg, symbol, TRUE);
1046 emit_label (acfg, symbol);
1048 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1050 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1051 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1052 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1053 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1055 g_assert (code - buf == COMMON_TRAMP_SIZE);
1058 emit_bytes (acfg, buf, code - buf);
1060 for (i = 0; i < count; ++i) {
1062 ARM_PUSH (code, 0x5fff);
1064 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1065 g_assert (code - buf == 8);
1066 emit_bytes (acfg, buf, code - buf);
1069 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1070 * the instruction pointer address, so the generic trampoline at the start of the page
1071 * subtracts 4096 to get to the data page and loads the values
1072 * We again fit the generic trampiline in 16 bytes.
1074 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1075 emit_global (acfg, symbol, TRUE);
1076 emit_label (acfg, symbol);
1078 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1079 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1080 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1081 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1083 g_assert (code - buf == COMMON_TRAMP_SIZE);
1086 emit_bytes (acfg, buf, code - buf);
1088 for (i = 0; i < count; ++i) {
1090 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1092 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1093 g_assert (code - buf == 8);
1094 emit_bytes (acfg, buf, code - buf);
1098 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1100 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1101 emit_global (acfg, symbol, TRUE);
1102 emit_label (acfg, symbol);
1104 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1105 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1106 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1107 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1108 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1109 g_assert (code - buf == COMMON_TRAMP_SIZE);
1111 emit_bytes (acfg, buf, code - buf);
1113 for (i = 0; i < count; ++i) {
1115 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1117 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1118 g_assert (code - buf == 8);
1119 emit_bytes (acfg, buf, code - buf);
1122 /* now the imt trampolines: each specific trampolines puts in the ip register
1123 * the instruction pointer address, so the generic trampoline at the start of the page
1124 * subtracts 4096 to get to the data page and loads the values
1125 * We again fit the generic trampiline in 16 bytes.
1127 #define IMT_TRAMP_SIZE 72
1128 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1129 emit_global (acfg, symbol, TRUE);
1130 emit_label (acfg, symbol);
1132 /* Need at least two free registers, plus a slot for storing the pc */
1133 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1135 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1136 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1137 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1139 /* The IMT method is in v5, r0 has the imt array address */
1142 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1143 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1144 imt_found_check = code;
1145 ARM_B_COND (code, ARMCOND_EQ, 0);
1147 /* End-of-loop check */
1148 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1149 loop_end_check = code;
1150 ARM_B_COND (code, ARMCOND_EQ, 0);
1153 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1154 loop_branch_back = code;
1156 arm_patch (loop_branch_back, loop_start);
1159 arm_patch (imt_found_check, code);
1160 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1161 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1162 /* Save it to the third stack slot */
1163 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1164 /* Restore the registers and branch */
1165 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1168 arm_patch (loop_end_check, code);
1169 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1170 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1171 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1175 g_assert (code - buf == IMT_TRAMP_SIZE);
1176 emit_bytes (acfg, buf, code - buf);
1178 for (i = 0; i < count; ++i) {
1180 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1182 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1183 g_assert (code - buf == 8);
1184 emit_bytes (acfg, buf, code - buf);
1190 * arch_emit_specific_trampoline:
1192 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1193 * two GOT slots which contain the generic trampoline address and the trampoline
1194 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1197 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1200 * The trampolines created here are variations of the specific
1201 * trampolines created in mono_arch_create_specific_trampoline (). The
1203 * - the generic trampoline address is taken from a got slot.
1204 * - the offset of the got slot where the trampoline argument is stored
1205 * is embedded in the instruction stream, and the generic trampoline
1206 * can load the argument by loading the offset, adding it to the
1207 * address of the trampoline to get the address of the got slot, and
1208 * loading the argument from there.
1209 * - all the trampolines should be of the same length.
1211 #if defined(TARGET_AMD64)
1212 #if defined(__default_codegen__)
1213 /* This should be exactly 16 bytes long */
1215 /* call *<offset>(%rip) */
1216 emit_byte (acfg, '\x41');
1217 emit_byte (acfg, '\xff');
1218 emit_byte (acfg, '\x15');
1219 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1220 /* This should be relative to the start of the trampoline */
1221 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1222 emit_zero_bytes (acfg, 5);
1223 #elif defined(__native_client_codegen__)
1225 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1226 guint8 *code = buf_aligned;
1231 /* Emit this call in 'code' so we can find out how long it is. */
1232 amd64_call_reg (code, AMD64_R11);
1233 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1234 call_len = code - call_start;
1236 /* The tramp_size is twice the NaCl alignment because it starts with */
1237 /* a call which needs to be aligned to the end of the boundary. */
1238 *tramp_size = kNaClAlignment*2;
1240 /* Emit nops to align call site below which is 7 bytes plus */
1241 /* the length of the call sequence emitted above. */
1242 /* Note: this requires the specific trampoline starts on a */
1243 /* kNaclAlignedment aligned address, which it does because */
1244 /* it's its own function that is aligned. */
1245 guint8 nop_buf[256];
1246 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1247 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1248 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1250 /* The trampoline is stored at the offset'th pointer, the -4 is */
1251 /* present because RIP relative addressing starts at the end of */
1252 /* the current instruction, while the label "." is relative to */
1253 /* the beginning of the current asm location, which in this case */
1254 /* is not the mov instruction, but the offset itself, due to the */
1255 /* way the bytes and ints are emitted here. */
1256 got_offset = (offset * sizeof(gpointer)) - 4;
1258 /* mov <OFFSET>(%rip), %r11d */
1259 emit_byte (acfg, '\x45');
1260 emit_byte (acfg, '\x8b');
1261 emit_byte (acfg, '\x1d');
1262 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1265 emit_bytes (acfg, call_start, call_len);
1267 /* The arg is stored at the offset+1 pointer, relative to beginning */
1268 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1269 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1271 /* We can't emit this data directly, hide in a "push imm32" */
1272 emit_byte (acfg, '\x68'); /* push */
1273 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1274 emit_alignment (acfg, kNaClAlignment);
1275 #endif /*__native_client_codegen__*/
1276 #elif defined(TARGET_ARM)
1280 /* This should be exactly 20 bytes long */
1283 ARM_PUSH (code, 0x5fff);
1284 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1285 /* Load the value from the GOT */
1286 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1288 ARM_BLX_REG (code, ARMREG_R1);
1290 g_assert (code - buf == 16);
1293 emit_bytes (acfg, buf, code - buf);
1295 * Only one offset is needed, since the second one would be equal to the
1298 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1299 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1300 #elif defined(TARGET_POWERPC)
1307 g_assert (!acfg->use_bin_writer);
1310 * PPC has no ip relative addressing, so we need to compute the address
1311 * of the mscorlib got. That is slow and complex, so instead, we store it
1312 * in the second got slot of every aot image. The caller already computed
1313 * the address of its got and placed it into r30.
1315 emit_unset_mode (acfg);
1316 /* Load mscorlib got address */
1317 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1318 /* Load generic trampoline address */
1319 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1320 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1321 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1322 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1323 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1325 fprintf (acfg->fp, "mtctr 11\n");
1326 /* Load trampoline argument */
1327 /* On ppc, we pass it normally to the generic trampoline */
1328 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1329 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1330 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1331 /* Branch to generic trampoline */
1332 fprintf (acfg->fp, "bctr\n");
1334 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1335 *tramp_size = 10 * 4;
1337 *tramp_size = 9 * 4;
1339 #elif defined(TARGET_X86)
1343 /* Similar to the PPC code above */
1345 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1347 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1348 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1349 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1353 /* Load mscorlib got address */
1354 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1355 /* Push trampoline argument */
1356 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1357 /* Load generic trampoline address */
1358 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1359 /* Branch to generic trampoline */
1360 x86_jump_reg (code, X86_ECX);
1362 #ifdef __native_client_codegen__
1364 /* emit nops to next 32 byte alignment */
1365 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1366 while (code < (buf + a)) x86_nop(code);
1369 emit_bytes (acfg, buf, code - buf);
1371 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1372 g_assert (code - buf == *tramp_size);
1374 g_assert_not_reached ();
1379 * arch_emit_unbox_trampoline:
1381 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1382 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1385 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1387 #if defined(TARGET_AMD64)
1392 this_reg = mono_arch_get_this_arg_reg (NULL);
1394 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1396 emit_bytes (acfg, buf, code - buf);
1398 emit_byte (acfg, '\xe9');
1399 emit_symbol_diff (acfg, call_target, ".", -4);
1400 #elif defined(TARGET_X86)
1407 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1409 emit_bytes (acfg, buf, code - buf);
1412 emit_byte (acfg, '\xe9');
1413 emit_symbol_diff (acfg, call_target, ".", -4);
1414 #elif defined(TARGET_ARM)
1418 if (acfg->thumb_mixed && cfg->compile_llvm) {
1419 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1420 fprintf (acfg->fp, "b %s\n", call_target);
1421 fprintf (acfg->fp, ".arm\n");
1422 fprintf (acfg->fp, ".align 2\n");
1428 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1430 emit_bytes (acfg, buf, code - buf);
1431 /* jump to method */
1432 if (acfg->use_bin_writer) {
1439 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1440 emit_bytes (acfg, buf, 4);
1442 if (acfg->thumb_mixed && cfg->compile_llvm)
1443 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1445 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1447 #elif defined(TARGET_POWERPC)
1450 g_assert (!acfg->use_bin_writer);
1452 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1453 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1455 g_assert_not_reached ();
1460 * arch_emit_static_rgctx_trampoline:
1462 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1463 * two GOT slots which contain the rgctx argument, and the method to jump to.
1464 * TRAMP_SIZE is set to the size of the emitted trampoline.
1465 * These kinds of trampolines cannot be enumerated statically, since there could
1466 * be one trampoline per method instantiation, so we emit the same code for all
1467 * trampolines, and parameterize them using two GOT slots.
1470 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1472 #if defined(TARGET_AMD64)
1473 #if defined(__default_codegen__)
1474 /* This should be exactly 13 bytes long */
1477 /* mov <OFFSET>(%rip), %r10 */
1478 emit_byte (acfg, '\x4d');
1479 emit_byte (acfg, '\x8b');
1480 emit_byte (acfg, '\x15');
1481 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1483 /* jmp *<offset>(%rip) */
1484 emit_byte (acfg, '\xff');
1485 emit_byte (acfg, '\x25');
1486 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1487 #elif defined(__native_client_codegen__)
1489 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1490 guint8 *code = buf_aligned;
1492 /* mov <OFFSET>(%rip), %r10d */
1493 emit_byte (acfg, '\x45');
1494 emit_byte (acfg, '\x8b');
1495 emit_byte (acfg, '\x15');
1496 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1498 /* mov <OFFSET>(%rip), %r11d */
1499 emit_byte (acfg, '\x45');
1500 emit_byte (acfg, '\x8b');
1501 emit_byte (acfg, '\x1d');
1502 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1505 amd64_jump_reg (code, AMD64_R11);
1506 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1508 emit_alignment (acfg, kNaClAlignment);
1509 *tramp_size = kNaClAlignment;
1510 #endif /*__native_client_codegen__*/
1512 #elif defined(TARGET_ARM)
1516 /* This should be exactly 24 bytes long */
1519 /* Load rgctx value */
1520 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1521 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1522 /* Load branch addr + branch */
1523 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1524 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1526 g_assert (code - buf == 16);
1529 emit_bytes (acfg, buf, code - buf);
1530 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1531 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1532 #elif defined(TARGET_POWERPC)
1539 g_assert (!acfg->use_bin_writer);
1542 * PPC has no ip relative addressing, so we need to compute the address
1543 * of the mscorlib got. That is slow and complex, so instead, we store it
1544 * in the second got slot of every aot image. The caller already computed
1545 * the address of its got and placed it into r30.
1547 emit_unset_mode (acfg);
1548 /* Load mscorlib got address */
1549 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1551 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1552 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1553 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1554 /* Load target address */
1555 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1556 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1557 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1558 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1559 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1560 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1562 fprintf (acfg->fp, "mtctr 11\n");
1563 /* Branch to the target address */
1564 fprintf (acfg->fp, "bctr\n");
1566 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1567 *tramp_size = 11 * 4;
1569 *tramp_size = 9 * 4;
1572 #elif defined(TARGET_X86)
1576 /* Similar to the PPC code above */
1578 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1581 /* Load mscorlib got address */
1582 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1584 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1585 /* Branch to the target address */
1586 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1588 #ifdef __native_client_codegen__
1590 /* emit nops to next 32 byte alignment */
1591 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1592 while (code < (buf + a)) x86_nop(code);
1596 emit_bytes (acfg, buf, code - buf);
1598 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1599 g_assert (code - buf == *tramp_size);
1601 g_assert_not_reached ();
1606 * arch_emit_imt_thunk:
1608 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1609 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1610 * key is the IMT key, and ptr holds the address of a memory location holding
1611 * the address to branch to if the IMT arg matches the key. The array is
1612 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1614 * TRAMP_SIZE is set to the size of the emitted trampoline.
1617 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1619 #if defined(TARGET_AMD64)
1621 #if defined(__native_client_codegen__)
1624 guint8 *labels [16];
1626 guint8 *mov_buf_ptr = mov_buf;
1628 const int kSizeOfMove = 7;
1629 #if defined(__default_codegen__)
1630 code = buf = g_malloc (256);
1631 #elif defined(__native_client_codegen__)
1632 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1633 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1634 /* The RIP relative move below is emitted first */
1639 /* FIXME: Optimize this, i.e. use binary search etc. */
1640 /* Maybe move the body into a separate function (slower, but much smaller) */
1642 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1645 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1647 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1650 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1652 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1655 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1656 amd64_jump_code (code, labels [0]);
1659 mono_amd64_patch (labels [2], code);
1660 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1661 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1664 mono_amd64_patch (labels [1], code);
1665 /* Load fail tramp */
1666 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1667 /* Check if there is a fail tramp */
1668 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1670 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1671 /* Jump to fail tramp */
1672 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1675 mono_amd64_patch (labels [3], code);
1676 x86_breakpoint (code);
1678 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1679 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1680 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1681 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1682 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1683 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1685 emit_bytes (acfg, buf, code - buf);
1687 *tramp_size = code - buf + kSizeOfMove;
1688 #if defined(__native_client_codegen__)
1689 /* The tramp will be padded to the next kNaClAlignment bundle. */
1690 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1693 #if defined(__default_codegen__)
1695 #elif defined(__native_client_codegen__)
1699 #elif defined(TARGET_X86)
1701 #ifdef __native_client_codegen__
1704 guint8 *labels [16];
1706 #if defined(__default_codegen__)
1707 code = buf = g_malloc (256);
1708 #elif defined(__native_client_codegen__)
1709 buf_alloc = g_malloc (256 + kNaClAlignment);
1710 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1713 /* Allocate a temporary stack slot */
1714 x86_push_reg (code, X86_EAX);
1716 x86_push_reg (code, X86_EAX);
1718 /* Load mscorlib got address */
1719 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1721 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1724 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1726 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1729 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1731 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1734 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1735 x86_jump_code (code, labels [0]);
1738 mono_x86_patch (labels [2], code);
1739 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1740 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1741 /* Save the target address to the temporary stack location */
1742 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1744 x86_pop_reg (code, X86_EAX);
1745 /* Jump to the target address */
1749 mono_x86_patch (labels [1], code);
1750 /* Load fail tramp */
1751 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1752 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1754 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1755 /* Jump to fail tramp */
1756 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1757 x86_pop_reg (code, X86_EAX);
1761 mono_x86_patch (labels [3], code);
1762 x86_breakpoint (code);
1764 #ifdef __native_client_codegen__
1766 /* emit nops to next 32 byte alignment */
1767 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1768 while (code < (buf + a)) x86_nop(code);
1771 emit_bytes (acfg, buf, code - buf);
1773 *tramp_size = code - buf;
1775 #if defined(__default_codegen__)
1777 #elif defined(__native_client_codegen__)
1781 #elif defined(TARGET_ARM)
1783 guint8 *code, *code2, *labels [16];
1787 /* The IMT method is in v5 */
1789 /* Need at least two free registers, plus a slot for storing the pc */
1790 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1792 /* Load the parameter from the GOT */
1793 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1794 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1797 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1798 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1800 ARM_B_COND (code, ARMCOND_EQ, 0);
1802 /* End-of-loop check */
1803 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1805 ARM_B_COND (code, ARMCOND_EQ, 0);
1808 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1811 arm_patch (labels [4], labels [1]);
1814 arm_patch (labels [2], code);
1815 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1816 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1817 /* Save it to the third stack slot */
1818 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1819 /* Restore the registers and branch */
1820 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1823 arm_patch (labels [3], code);
1824 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1825 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1826 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1830 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1832 emit_bytes (acfg, buf, code - buf);
1833 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1835 *tramp_size = code - buf + 4;
1836 #elif defined(TARGET_POWERPC)
1838 guint8 *code, *labels [16];
1842 /* Load the mscorlib got address */
1843 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1844 /* Load the parameter from the GOT */
1845 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1846 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1848 /* Load and check key */
1850 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1851 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1853 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1855 /* End-of-loop check */
1856 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1858 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1861 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1864 mono_ppc_patch (labels [4], labels [1]);
1867 mono_ppc_patch (labels [2], code);
1868 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1869 /* r11 now contains the value of the vtable slot */
1870 /* this is not a function descriptor on ppc64 */
1871 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1872 ppc_mtctr (code, ppc_r11);
1873 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1876 mono_ppc_patch (labels [3], code);
1880 *tramp_size = code - buf;
1882 emit_bytes (acfg, buf, code - buf);
1884 g_assert_not_reached ();
1889 * arch_emit_gsharedvt_arg_trampoline:
1891 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1892 * two GOT slots which contain the argument, and the code to jump to.
1893 * TRAMP_SIZE is set to the size of the emitted trampoline.
1894 * These kinds of trampolines cannot be enumerated statically, since there could
1895 * be one trampoline per method instantiation, so we emit the same code for all
1896 * trampolines, and parameterize them using two GOT slots.
1899 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1901 #if defined(TARGET_X86)
1905 /* Similar to the PPC code above */
1907 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1910 /* Load mscorlib got address */
1911 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1913 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1914 /* Branch to the target address */
1915 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1917 #ifdef __native_client_codegen__
1919 /* emit nops to next 32 byte alignment */
1920 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1921 while (code < (buf + a)) x86_nop(code);
1925 emit_bytes (acfg, buf, code - buf);
1927 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1928 g_assert (code - buf == *tramp_size);
1929 #elif defined(TARGET_ARM)
1933 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1934 /* Similar to arch_emit_specific_trampoline () */
1937 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1938 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1939 /* Load the arg value from the GOT */
1940 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1941 /* Load the addr from the GOT */
1942 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1944 ARM_BX (code, ARMREG_R1);
1946 g_assert (code - buf == 20);
1949 emit_bytes (acfg, buf, code - buf);
1950 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1952 g_assert_not_reached ();
1957 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1959 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1960 /* Based on code generated by gcc */
1961 emit_unset_mode (acfg);
1964 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1965 ".section .ctors,\"aw\",@progbits\n"
1969 ".section .opd,\"aw\"\n"
1972 ".long .%s,.TOC.@tocbase32\n"
1975 ".type .%s,@function\n"
1977 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1979 ".section .ctors,\"aw\",@progbits\n"
1983 ".section .opd,\"aw\"\n"
1986 ".long .%1$s,.TOC.@tocbase32\n"
1987 ".size %1$s,.-%1$s\n"
1989 ".type .%1$s,@function\n"
1991 ".%1$s:\n", symbol);
2002 "lis 3, .Lglobals@h\n"
2003 "ori 3, 3, .Lglobals@l\n"
2004 "bl .mono_aot_register_module\n"
2012 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2014 ".size .%s,.-.%s\n", symbol, symbol);
2017 ".size .%1$s,.-.%1$s\n", symbol);
2023 /* END OF ARCH SPECIFIC CODE */
2026 mono_get_field_token (MonoClassField *field)
2028 MonoClass *klass = field->parent;
2031 for (i = 0; i < klass->field.count; ++i) {
2032 if (field == &klass->fields [i])
2033 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2036 g_assert_not_reached ();
2041 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2045 //printf ("ENCODE: %d 0x%x.\n", value, value);
2048 * Same encoding as the one used in the metadata, extended to handle values
2049 * greater than 0x1fffffff.
2051 if ((value >= 0) && (value <= 127))
2053 else if ((value >= 0) && (value <= 16383)) {
2054 p [0] = 0x80 | (value >> 8);
2055 p [1] = value & 0xff;
2057 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2058 p [0] = (value >> 24) | 0xc0;
2059 p [1] = (value >> 16) & 0xff;
2060 p [2] = (value >> 8) & 0xff;
2061 p [3] = value & 0xff;
2066 p [1] = (value >> 24) & 0xff;
2067 p [2] = (value >> 16) & 0xff;
2068 p [3] = (value >> 8) & 0xff;
2069 p [4] = value & 0xff;
2077 stream_init (MonoDynamicStream *sh)
2080 sh->alloc_size = 4096;
2081 sh->data = g_malloc (4096);
2083 /* So offsets are > 0 */
2089 make_room_in_stream (MonoDynamicStream *stream, int size)
2091 if (size <= stream->alloc_size)
2094 while (stream->alloc_size <= size) {
2095 if (stream->alloc_size < 4096)
2096 stream->alloc_size = 4096;
2098 stream->alloc_size *= 2;
2101 stream->data = g_realloc (stream->data, stream->alloc_size);
2105 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2109 make_room_in_stream (stream, stream->index + len);
2110 memcpy (stream->data + stream->index, data, len);
2111 idx = stream->index;
2112 stream->index += len;
2119 * Add data to the binary blob inside the aot image. Returns the offset inside the
2120 * blob where the data was stored.
2123 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2125 if (acfg->blob.alloc_size == 0)
2126 stream_init (&acfg->blob);
2128 return add_stream_data (&acfg->blob, (char*)data, data_len);
2132 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2137 if (acfg->blob.alloc_size == 0)
2138 stream_init (&acfg->blob);
2140 count = acfg->blob.index % align;
2142 /* we assume the stream data will be aligned */
2144 add_stream_data (&acfg->blob, buf, 4 - count);
2146 return add_stream_data (&acfg->blob, (char*)data, data_len);
2150 * emit_offset_table:
2152 * Emit a table of increasing offsets in a compact form using differential encoding.
2153 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2154 * group size, the more compact the table becomes, but the slower it becomes to compute
2155 * a given entry. Returns the size of the table.
2158 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2160 gint32 current_offset;
2161 int i, buf_size, ngroups, index_entry_size;
2163 guint32 *index_offsets;
2165 ngroups = (noffsets + (group_size - 1)) / group_size;
2167 index_offsets = g_new0 (guint32, ngroups);
2169 buf_size = noffsets * 4;
2170 p = buf = g_malloc0 (buf_size);
2173 for (i = 0; i < noffsets; ++i) {
2174 //printf ("D: %d -> %d\n", i, offsets [i]);
2175 if ((i % group_size) == 0) {
2176 index_offsets [i / group_size] = p - buf;
2177 /* Emit the full value for these entries */
2178 encode_value (offsets [i], p, &p);
2180 /* The offsets are allowed to be non-increasing */
2181 //g_assert (offsets [i] >= current_offset);
2182 encode_value (offsets [i] - current_offset, p, &p);
2184 current_offset = offsets [i];
2187 if (ngroups && index_offsets [ngroups - 1] < 65000)
2188 index_entry_size = 2;
2190 index_entry_size = 4;
2192 /* Emit the header */
2193 emit_int32 (acfg, noffsets);
2194 emit_int32 (acfg, group_size);
2195 emit_int32 (acfg, ngroups);
2196 emit_int32 (acfg, index_entry_size);
2198 /* Emit the index */
2199 for (i = 0; i < ngroups; ++i) {
2200 if (index_entry_size == 2)
2201 emit_int16 (acfg, index_offsets [i]);
2203 emit_int32 (acfg, index_offsets [i]);
2207 emit_bytes (acfg, buf, p - buf);
2209 return (int)(p - buf) + (ngroups * 4);
2213 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2217 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2221 index = g_hash_table_size (cfg->image_hash);
2222 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2223 g_ptr_array_add (cfg->image_table, image);
2229 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2232 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2234 /* FIXME: Search referenced images as well */
2235 if (!acfg->typespec_classes) {
2236 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2237 for (i = 0; i < len; ++i) {
2238 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2241 for (i = 0; i < len; ++i) {
2242 if (acfg->typespec_classes [i] == klass)
2247 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2253 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2256 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2259 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2262 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2265 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2270 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2274 if (klass->generic_class) {
2276 g_assert (klass->type_token);
2278 /* Find a typespec for a class if possible */
2279 token = find_typespec_for_class (acfg, klass);
2281 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2282 encode_value (token, p, &p);
2284 MonoClass *gclass = klass->generic_class->container_class;
2285 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2286 static int count = 0;
2289 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2290 encode_klass_ref (acfg, gclass, p, &p);
2291 encode_ginst (acfg, inst, p, &p);
2295 } else if (klass->type_token) {
2296 int iindex = get_image_index (acfg, klass->image);
2298 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2300 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2301 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2303 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2304 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2305 encode_value (get_image_index (acfg, klass->image), p, &p);
2307 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2308 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2309 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2311 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2312 encode_value (klass->byval_arg.type, p, &p);
2313 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2315 encode_value (container ? 1 : 0, p, &p);
2317 encode_value (container->is_method, p, &p);
2318 g_assert (par->serial == 0);
2319 if (container->is_method)
2320 encode_method_ref (acfg, container->owner.method, p, &p);
2322 encode_klass_ref (acfg, container->owner.klass, p, &p);
2324 encode_value (par->serial, p, &p);
2326 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2327 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2328 encode_type (acfg, &klass->byval_arg, p, &p);
2331 g_assert (klass->rank > 0);
2332 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2333 encode_value (klass->rank, p, &p);
2334 encode_klass_ref (acfg, klass->element_class, p, &p);
2342 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2343 * standard metadata encoding.
2346 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2348 gboolean shared = FALSE;
2351 * The encoding of generic instances is large so emit them only once.
2353 if (klass->generic_class) {
2355 g_assert (klass->type_token);
2357 /* Find a typespec for a class if possible */
2358 token = find_typespec_for_class (acfg, klass);
2361 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2366 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2370 buf2 = g_malloc (1024);
2373 encode_klass_ref_inner (acfg, klass, p, &p);
2374 g_assert (p - buf2 < 1024);
2376 offset = add_to_blob (acfg, buf2, p - buf2);
2379 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2385 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2386 encode_value (offset, p, &p);
2391 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2395 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2397 guint32 token = mono_get_field_token (field);
2400 encode_klass_ref (cfg, field->parent, p, &p);
2401 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2402 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2407 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2412 encode_value (inst->type_argc, p, &p);
2413 for (i = 0; i < inst->type_argc; ++i)
2414 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2419 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2422 MonoGenericInst *inst;
2424 inst = context->class_inst;
2426 g_assert (inst->type_argc);
2427 encode_ginst (acfg, inst, p, &p);
2429 encode_value (0, p, &p);
2431 inst = context->method_inst;
2433 g_assert (inst->type_argc);
2434 encode_ginst (acfg, inst, p, &p);
2436 encode_value (0, p, &p);
2442 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2446 g_assert (t->num_mods == 0);
2447 /* t->attrs can be ignored */
2448 //g_assert (t->attrs == 0);
2451 *p = MONO_TYPE_PINNED;
2455 *p = MONO_TYPE_BYREF;
2463 case MONO_TYPE_VOID:
2464 case MONO_TYPE_BOOLEAN:
2465 case MONO_TYPE_CHAR:
2478 case MONO_TYPE_STRING:
2479 case MONO_TYPE_OBJECT:
2480 case MONO_TYPE_TYPEDBYREF:
2482 case MONO_TYPE_VALUETYPE:
2483 case MONO_TYPE_CLASS:
2484 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2486 case MONO_TYPE_SZARRAY:
2487 encode_klass_ref (acfg, t->data.klass, p, &p);
2490 encode_type (acfg, t->data.type, p, &p);
2492 case MONO_TYPE_GENERICINST: {
2493 MonoClass *gclass = t->data.generic_class->container_class;
2494 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2496 encode_klass_ref (acfg, gclass, p, &p);
2497 encode_ginst (acfg, inst, p, &p);
2500 case MONO_TYPE_ARRAY: {
2501 MonoArrayType *array = t->data.array;
2504 encode_klass_ref (acfg, array->eklass, p, &p);
2505 encode_value (array->rank, p, &p);
2506 encode_value (array->numsizes, p, &p);
2507 for (i = 0; i < array->numsizes; ++i)
2508 encode_value (array->sizes [i], p, &p);
2509 encode_value (array->numlobounds, p, &p);
2510 for (i = 0; i < array->numlobounds; ++i)
2511 encode_value (array->lobounds [i], p, &p);
2515 case MONO_TYPE_MVAR:
2516 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2519 g_assert_not_reached ();
2526 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2532 /* Similar to the metadata encoding */
2533 if (sig->generic_param_count)
2537 if (sig->explicit_this)
2539 flags |= (sig->call_convention & 0x0F);
2543 if (sig->generic_param_count)
2544 encode_value (sig->generic_param_count, p, &p);
2545 encode_value (sig->param_count, p, &p);
2547 encode_type (acfg, sig->ret, p, &p);
2548 for (i = 0; i < sig->param_count; ++i) {
2549 if (sig->sentinelpos == i) {
2550 *p = MONO_TYPE_SENTINEL;
2553 encode_type (acfg, sig->params [i], p, &p);
2559 #define MAX_IMAGE_INDEX 250
2562 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2564 guint32 image_index = get_image_index (acfg, method->klass->image);
2565 guint32 token = method->token;
2566 MonoJumpInfoToken *ji;
2570 * The encoding for most methods is as follows:
2571 * - image index encoded as a leb128
2572 * - token index encoded as a leb128
2573 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2574 * types of method encodings.
2577 /* Mark methods which can't use aot trampolines because they need the further
2578 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2580 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2581 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2582 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2584 if (method->wrapper_type) {
2585 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2587 encode_value (method->wrapper_type, p, &p);
2589 switch (method->wrapper_type) {
2590 case MONO_WRAPPER_REMOTING_INVOKE:
2591 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2592 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2595 m = mono_marshal_method_from_wrapper (method);
2597 encode_method_ref (acfg, m, p, &p);
2600 case MONO_WRAPPER_PROXY_ISINST:
2601 case MONO_WRAPPER_LDFLD:
2602 case MONO_WRAPPER_LDFLDA:
2603 case MONO_WRAPPER_STFLD:
2604 case MONO_WRAPPER_ISINST: {
2605 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2606 encode_klass_ref (acfg, proxy_class, p, &p);
2609 case MONO_WRAPPER_LDFLD_REMOTE:
2610 case MONO_WRAPPER_STFLD_REMOTE:
2612 case MONO_WRAPPER_ALLOC: {
2613 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2615 /* The GC name is saved once in MonoAotFileInfo */
2616 g_assert (info->alloc_type != -1);
2617 encode_value (info->alloc_type, p, &p);
2620 case MONO_WRAPPER_WRITE_BARRIER:
2622 case MONO_WRAPPER_STELEMREF: {
2623 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2626 encode_value (info->subtype, p, &p);
2627 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2628 encode_value (info->d.virtual_stelemref.kind, p, &p);
2631 case MONO_WRAPPER_UNKNOWN: {
2632 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2635 encode_value (info->subtype, p, &p);
2636 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2637 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2638 encode_klass_ref (acfg, method->klass, p, &p);
2639 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2640 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2641 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2642 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2645 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2646 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2649 encode_value (info->subtype, p, &p);
2650 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2651 strcpy ((char*)p, method->name);
2652 p += strlen (method->name) + 1;
2653 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2654 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2656 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2657 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2661 case MONO_WRAPPER_SYNCHRONIZED: {
2664 m = mono_marshal_method_from_wrapper (method);
2666 g_assert (m != method);
2667 encode_method_ref (acfg, m, p, &p);
2670 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2671 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2674 encode_value (info->subtype, p, &p);
2676 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2677 encode_value (info->d.element_addr.rank, p, &p);
2678 encode_value (info->d.element_addr.elem_size, p, &p);
2679 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2680 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2682 g_assert_not_reached ();
2686 case MONO_WRAPPER_CASTCLASS: {
2687 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2690 encode_value (info->subtype, p, &p);
2693 case MONO_WRAPPER_RUNTIME_INVOKE: {
2694 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2697 encode_value (info->subtype, p, &p);
2698 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2699 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2700 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2701 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2704 case MONO_WRAPPER_DELEGATE_INVOKE:
2705 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2706 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2707 if (method->is_inflated) {
2708 /* These wrappers are identified by their class */
2709 encode_value (1, p, &p);
2710 encode_klass_ref (acfg, method->klass, p, &p);
2712 MonoMethodSignature *sig = mono_method_signature (method);
2713 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2715 encode_value (0, p, &p);
2716 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2717 encode_value (info ? info->subtype : 0, p, &p);
2718 encode_signature (acfg, sig, p, &p);
2722 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2723 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2726 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2727 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2731 g_assert_not_reached ();
2733 } else if (mono_method_signature (method)->is_inflated) {
2735 * This is a generic method, find the original token which referenced it and
2737 * Obtain the token from information recorded by the JIT.
2739 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2741 image_index = get_image_index (acfg, ji->image);
2742 g_assert (image_index < MAX_IMAGE_INDEX);
2745 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2746 encode_value (image_index, p, &p);
2747 encode_value (token, p, &p);
2749 MonoMethod *declaring;
2750 MonoGenericContext *context = mono_method_get_context (method);
2752 g_assert (method->is_inflated);
2753 declaring = ((MonoMethodInflated*)method)->declaring;
2756 * This might be a non-generic method of a generic instance, which
2757 * doesn't have a token since the reference is generated by the JIT
2758 * like Nullable:Box/Unbox, or by generic sharing.
2760 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2761 /* Encode the klass */
2762 encode_klass_ref (acfg, method->klass, p, &p);
2763 /* Encode the method */
2764 image_index = get_image_index (acfg, method->klass->image);
2765 g_assert (image_index < MAX_IMAGE_INDEX);
2766 g_assert (declaring->token);
2767 token = declaring->token;
2768 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2769 encode_value (image_index, p, &p);
2770 encode_value (token, p, &p);
2771 encode_generic_context (acfg, context, p, &p);
2773 } else if (token == 0) {
2774 /* This might be a method of a constructed type like int[,].Set */
2775 /* Obtain the token from information recorded by the JIT */
2776 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2778 image_index = get_image_index (acfg, ji->image);
2779 g_assert (image_index < MAX_IMAGE_INDEX);
2782 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2783 encode_value (image_index, p, &p);
2784 encode_value (token, p, &p);
2787 g_assert (method->klass->rank);
2789 /* Encode directly */
2790 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2791 encode_klass_ref (acfg, method->klass, p, &p);
2792 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2793 encode_value (0, p, &p);
2794 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2795 encode_value (1, p, &p);
2796 else if (!strcmp (method->name, "Get"))
2797 encode_value (2, p, &p);
2798 else if (!strcmp (method->name, "Address"))
2799 encode_value (3, p, &p);
2800 else if (!strcmp (method->name, "Set"))
2801 encode_value (4, p, &p);
2803 g_assert_not_reached ();
2806 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2808 if (image_index >= MONO_AOT_METHODREF_MIN) {
2809 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2810 encode_value (image_index, p, &p);
2811 encode_value (mono_metadata_token_index (token), p, &p);
2813 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2820 compare_patches (gconstpointer a, gconstpointer b)
2824 i = (*(MonoJumpInfo**)a)->ip.i;
2825 j = (*(MonoJumpInfo**)b)->ip.i;
2836 static G_GNUC_UNUSED char*
2837 patch_to_string (MonoJumpInfo *patch_info)
2841 str = g_string_new ("");
2843 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2845 switch (patch_info->type) {
2846 case MONO_PATCH_INFO_VTABLE:
2847 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2852 g_string_append_printf (str, ")");
2853 return g_string_free (str, FALSE);
2859 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2862 static inline gboolean
2863 is_plt_patch (MonoJumpInfo *patch_info)
2865 switch (patch_info->type) {
2866 case MONO_PATCH_INFO_METHOD:
2867 case MONO_PATCH_INFO_INTERNAL_METHOD:
2868 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2869 case MONO_PATCH_INFO_ICALL_ADDR:
2870 case MONO_PATCH_INFO_CLASS_INIT:
2871 case MONO_PATCH_INFO_RGCTX_FETCH:
2872 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2873 case MONO_PATCH_INFO_MONITOR_ENTER:
2874 case MONO_PATCH_INFO_MONITOR_EXIT:
2875 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2885 * Return the symbol identifying the plt entry PLT_OFFSET.
2888 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2892 * The Apple linker reorganizes object files, so it doesn't like branches to local
2893 * labels, since those have no relocations.
2895 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2897 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2904 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2906 static MonoPltEntry*
2907 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2911 if (!is_plt_patch (patch_info))
2914 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2916 // FIXME: This breaks the calculation of final_got_size
2917 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2919 * Allocate a separate PLT slot for each such patch, since some plt
2920 * entries will refer to the method itself, and some will refer to the
2927 MonoJumpInfo *new_ji;
2929 g_assert (!acfg->final_got_size);
2931 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2933 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2934 res->plt_offset = acfg->plt_offset;
2936 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2937 if (acfg->aot_opts.write_symbols)
2938 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2940 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2942 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2944 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2946 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2948 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2949 //mono_print_ji (patch_info); printf ("\n");
2950 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2952 acfg->plt_offset ++;
2961 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2962 * JI could be found if it exists, otherwise allocates a new one.
2965 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2969 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2971 return got_offset - 1;
2973 got_offset = acfg->got_offset;
2974 acfg->got_offset ++;
2976 if (acfg->final_got_size)
2977 g_assert (got_offset < acfg->final_got_size);
2979 acfg->stats.got_slots ++;
2980 acfg->stats.got_slot_types [ji->type] ++;
2982 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2983 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2984 g_ptr_array_add (acfg->got_patches, ji);
2989 /* Add a method to the list of methods which need to be emitted */
2991 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2994 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2995 g_ptr_array_add (acfg->methods, method);
2996 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2997 acfg->nmethods = acfg->methods->len + 1;
3000 if (method->wrapper_type || extra)
3001 g_ptr_array_add (acfg->extra_methods, method);
3005 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3007 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3015 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3019 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3023 index = acfg->method_index;
3024 add_method_with_index (acfg, method, index, extra);
3026 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3028 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3030 acfg->method_index ++;
3036 add_method (MonoAotCompile *acfg, MonoMethod *method)
3038 return add_method_full (acfg, method, FALSE, 0);
3042 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3044 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3045 method = mini_get_shared_method (method);
3047 if (acfg->aot_opts.log_generics)
3048 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3050 add_method_full (acfg, method, TRUE, depth);
3054 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3056 add_extra_method_with_depth (acfg, method, 0);
3060 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3062 MonoAotCompile *acfg = user_data;
3063 MonoJitICallInfo *callinfo = value;
3064 MonoMethod *wrapper;
3070 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3071 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3074 add_method (acfg, wrapper);
3078 get_runtime_invoke_sig (MonoMethodSignature *sig)
3080 MonoMethodBuilder *mb;
3083 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3084 m = mono_mb_create_method (mb, sig, 16);
3085 return mono_marshal_get_runtime_invoke (m, FALSE);
3089 can_marshal_struct (MonoClass *klass)
3091 MonoClassField *field;
3092 gboolean can_marshal = TRUE;
3093 gpointer iter = NULL;
3094 MonoMarshalType *info;
3097 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3100 info = mono_marshal_load_type_info (klass);
3102 /* Only allow a few field types to avoid asserts in the marshalling code */
3103 while ((field = mono_class_get_fields (klass, &iter))) {
3104 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3107 switch (field->type->type) {
3112 case MONO_TYPE_BOOLEAN:
3115 case MONO_TYPE_CHAR:
3123 case MONO_TYPE_STRING:
3125 case MONO_TYPE_VALUETYPE:
3126 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3127 can_marshal = FALSE;
3129 case MONO_TYPE_SZARRAY: {
3130 gboolean has_mspec = FALSE;
3133 for (i = 0; i < info->num_fields; ++i) {
3134 if (info->fields [i].field == field && info->fields [i].mspec)
3139 can_marshal = FALSE;
3143 can_marshal = FALSE;
3149 /* Its hard to compute whenever these can be marshalled or not */
3150 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3157 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3159 /* Create a vtype instantiation */
3160 MonoGenericContext shared_context;
3162 MonoGenericInst *inst;
3163 MonoGenericContainer *container;
3164 MonoClass **constraints;
3167 memset (ctx, 0, sizeof (MonoGenericContext));
3169 if (method->klass->generic_container) {
3170 shared_context = method->klass->generic_container->context;
3171 inst = shared_context.class_inst;
3173 args = g_new0 (MonoType*, inst->type_argc);
3174 for (i = 0; i < inst->type_argc; ++i) {
3175 args [i] = &mono_defaults.int_class->byval_arg;
3177 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3179 if (method->is_generic) {
3180 container = mono_method_get_generic_container (method);
3181 shared_context = container->context;
3182 inst = shared_context.method_inst;
3184 args = g_new0 (MonoType*, inst->type_argc);
3185 for (i = 0; i < container->type_argc; ++i) {
3186 MonoGenericParamInfo *info = &container->type_params [i].info;
3187 gboolean ref_only = FALSE;
3189 if (info && info->constraints) {
3190 constraints = info->constraints;
3192 while (*constraints) {
3193 MonoClass *cklass = *constraints;
3194 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3195 /* Inflaring the method with our vtype would not be valid */
3202 args [i] = &mono_defaults.object_class->byval_arg;
3204 args [i] = &mono_defaults.int_class->byval_arg;
3206 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3211 add_wrappers (MonoAotCompile *acfg)
3213 MonoMethod *method, *m;
3215 MonoMethodSignature *sig, *csig;
3219 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3220 * so there is only one wrapper of a given type, or inlining their contents into their
3225 * FIXME: This depends on the fact that different wrappers have different
3229 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3231 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3232 gboolean skip = FALSE;
3234 method = mono_get_method (acfg->image, token, NULL);
3236 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3237 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3238 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3241 if (method->is_generic || method->klass->generic_container)
3244 /* Skip methods which can not be handled by get_runtime_invoke () */
3245 sig = mono_method_signature (method);
3248 if ((sig->ret->type == MONO_TYPE_PTR) ||
3249 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3252 for (j = 0; j < sig->param_count; j++) {
3253 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3257 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3258 if (!mono_class_is_contextbound (method->klass)) {
3259 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3260 gboolean has_nullable = FALSE;
3262 for (j = 0; j < sig->param_count; j++) {
3263 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3264 has_nullable = TRUE;
3267 if (info && !has_nullable) {
3268 /* Supported by the dynamic runtime-invoke wrapper */
3276 //printf ("%s\n", mono_method_full_name (method, TRUE));
3277 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3281 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3282 MonoMethodDesc *desc;
3283 MonoMethod *orig_method;
3286 /* Runtime invoke wrappers */
3288 /* void runtime-invoke () [.cctor] */
3289 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3290 csig->ret = &mono_defaults.void_class->byval_arg;
3291 add_method (acfg, get_runtime_invoke_sig (csig));
3293 /* void runtime-invoke () [Finalize] */
3294 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3296 csig->ret = &mono_defaults.void_class->byval_arg;
3297 add_method (acfg, get_runtime_invoke_sig (csig));
3299 /* void runtime-invoke (string) [exception ctor] */
3300 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3302 csig->ret = &mono_defaults.void_class->byval_arg;
3303 csig->params [0] = &mono_defaults.string_class->byval_arg;
3304 add_method (acfg, get_runtime_invoke_sig (csig));
3306 /* void runtime-invoke (string, string) [exception ctor] */
3307 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3309 csig->ret = &mono_defaults.void_class->byval_arg;
3310 csig->params [0] = &mono_defaults.string_class->byval_arg;
3311 csig->params [1] = &mono_defaults.string_class->byval_arg;
3312 add_method (acfg, get_runtime_invoke_sig (csig));
3314 /* string runtime-invoke () [Exception.ToString ()] */
3315 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3317 csig->ret = &mono_defaults.string_class->byval_arg;
3318 add_method (acfg, get_runtime_invoke_sig (csig));
3320 /* void runtime-invoke (string, Exception) [exception ctor] */
3321 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3323 csig->ret = &mono_defaults.void_class->byval_arg;
3324 csig->params [0] = &mono_defaults.string_class->byval_arg;
3325 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3326 add_method (acfg, get_runtime_invoke_sig (csig));
3328 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3329 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3331 csig->ret = &(mono_class_from_name (
3332 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3333 csig->params [0] = &mono_defaults.string_class->byval_arg;
3334 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3335 add_method (acfg, get_runtime_invoke_sig (csig));
3337 /* runtime-invoke used by finalizers */
3338 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3340 /* This is used by mono_runtime_capture_context () */
3341 method = mono_get_context_capture_method ();
3343 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3345 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3346 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3350 add_method (acfg, mono_marshal_get_stelemref ());
3352 if (MONO_ARCH_HAVE_TLS_GET) {
3353 /* Managed Allocators */
3354 nallocators = mono_gc_get_managed_allocator_types ();
3355 for (i = 0; i < nallocators; ++i) {
3356 m = mono_gc_get_managed_allocator_by_type (i);
3358 add_method (acfg, m);
3361 /* Monitor Enter/Exit */
3362 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3363 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3364 /* This is a v4 method */
3366 method = mono_monitor_get_fast_path (orig_method);
3368 add_method (acfg, method);
3370 mono_method_desc_free (desc);
3372 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3373 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3374 g_assert (orig_method);
3375 mono_method_desc_free (desc);
3376 method = mono_monitor_get_fast_path (orig_method);
3378 add_method (acfg, method);
3381 /* Stelemref wrappers */
3383 MonoMethod **wrappers;
3386 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3387 for (i = 0; i < nwrappers; ++i)
3388 add_method (acfg, wrappers [i]);
3392 /* castclass_with_check wrapper */
3393 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3394 /* isinst_with_check wrapper */
3395 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3397 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3399 MonoMethodDesc *desc;
3402 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3403 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3404 mono_method_desc_free (desc);
3406 m = mono_monitor_get_fast_path (m);
3408 add_method (acfg, m);
3413 /* JIT icall wrappers */
3414 /* FIXME: locking */
3415 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3419 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3420 * we use the original method instead at runtime.
3421 * Since full-aot doesn't support remoting, this is not a problem.
3424 /* remoting-invoke wrappers */
3425 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3426 MonoMethodSignature *sig;
3428 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3429 method = mono_get_method (acfg->image, token, NULL);
3431 sig = mono_method_signature (method);
3433 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3434 m = mono_marshal_get_remoting_invoke_with_check (method);
3436 add_method (acfg, m);
3441 /* delegate-invoke wrappers */
3442 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3444 MonoCustomAttrInfo *cattr;
3446 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3447 klass = mono_class_get (acfg->image, token);
3450 mono_loader_clear_error ();
3454 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3457 if (!klass->generic_container) {
3458 method = mono_get_delegate_invoke (klass);
3460 m = mono_marshal_get_delegate_invoke (method, NULL);
3462 add_method (acfg, m);
3464 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3466 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3468 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3470 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3472 cattr = mono_custom_attrs_from_class (klass);
3477 for (j = 0; j < cattr->num_attrs; ++j)
3478 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3480 if (j < cattr->num_attrs)
3481 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3483 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3484 MonoGenericContext ctx;
3485 MonoMethod *inst, *gshared;
3488 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3491 method = mono_get_delegate_invoke (klass);
3492 create_gsharedvt_inst (acfg, method, &ctx);
3494 inst = mono_class_inflate_generic_method (method, &ctx);
3496 m = mono_marshal_get_delegate_invoke (inst, NULL);
3497 g_assert (m->is_inflated);
3499 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3500 add_extra_method (acfg, gshared);
3503 method = mono_get_delegate_begin_invoke (klass);
3504 create_gsharedvt_inst (acfg, method, &ctx);
3506 inst = mono_class_inflate_generic_method (method, &ctx);
3508 m = mono_marshal_get_delegate_begin_invoke (inst);
3509 g_assert (m->is_inflated);
3511 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3512 add_extra_method (acfg, gshared);
3515 method = mono_get_delegate_end_invoke (klass);
3516 create_gsharedvt_inst (acfg, method, &ctx);
3518 inst = mono_class_inflate_generic_method (method, &ctx);
3520 m = mono_marshal_get_delegate_end_invoke (inst);
3521 g_assert (m->is_inflated);
3523 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3524 add_extra_method (acfg, gshared);
3529 /* array access wrappers */
3530 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3533 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3534 klass = mono_class_get (acfg->image, token);
3537 mono_loader_clear_error ();
3541 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3542 MonoMethod *m, *wrapper;
3544 /* Add runtime-invoke wrappers too */
3546 m = mono_class_get_method_from_name (klass, "Get", -1);
3548 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3549 add_extra_method (acfg, wrapper);
3550 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3552 m = mono_class_get_method_from_name (klass, "Set", -1);
3554 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3555 add_extra_method (acfg, wrapper);
3556 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3560 /* Synchronized wrappers */
3561 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3562 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3563 method = mono_get_method (acfg->image, token, NULL);
3565 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3566 if (method->is_generic) {
3568 } else if (method->klass->generic_container) {
3569 MonoGenericContext ctx;
3570 MonoMethod *inst, *gshared, *m;
3573 * Create a generic wrapper for a generic instance, and AOT that.
3575 create_gsharedvt_inst (acfg, method, &ctx);
3576 inst = mono_class_inflate_generic_method (method, &ctx);
3577 m = mono_marshal_get_synchronized_wrapper (inst);
3578 g_assert (m->is_inflated);
3579 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3580 add_method (acfg, gshared);
3582 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3587 /* pinvoke wrappers */
3588 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3590 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3592 method = mono_get_method (acfg->image, token, NULL);
3594 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3595 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3596 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3600 /* native-to-managed wrappers */
3601 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3603 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3604 MonoCustomAttrInfo *cattr;
3607 method = mono_get_method (acfg->image, token, NULL);
3610 * Only generate native-to-managed wrappers for methods which have an
3611 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3612 * name to avoid defining a new assembly to contain it.
3614 cattr = mono_custom_attrs_from_method (method);
3617 for (j = 0; j < cattr->num_attrs; ++j)
3618 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3620 if (j < cattr->num_attrs) {
3621 MonoCustomAttrEntry *e = &cattr->attrs [j];
3622 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3623 const char *p = (const char*)e->data;
3625 int slen, num_named, named_type, data_type;
3629 char *export_name = NULL;
3630 MonoMethod *wrapper;
3632 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3633 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3634 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3635 mono_method_full_name (method, TRUE));
3639 g_assert (sig->param_count == 1);
3640 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3643 * Decode the cattr manually since we can't create objects
3644 * during aot compilation.
3650 /* From load_cattr_value () in reflection.c */
3651 slen = mono_metadata_decode_value (p, &p);
3652 n = g_memdup (p, slen + 1);
3654 t = mono_reflection_type_from_name (n, acfg->image);
3658 klass = mono_class_from_mono_type (t);
3659 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3663 num_named = read16 (p);
3666 g_assert (num_named < 2);
3667 if (num_named == 1) {
3670 MonoType *prop_type;
3672 /* parse ExportSymbol attribute */
3674 named_type = *named;
3679 name_len = mono_metadata_decode_blob_size (named, &named);
3680 name = g_malloc (name_len + 1);
3681 memcpy (name, named, name_len);
3682 name [name_len] = 0;
3685 g_assert (named_type == 0x54);
3686 g_assert (!strcmp (name, "ExportSymbol"));
3688 prop_type = &mono_defaults.string_class->byval_arg;
3690 /* load_cattr_value (), string case */
3691 g_assert (*named != (char)0xff);
3692 slen = mono_metadata_decode_value (named, &named);
3693 export_name = g_malloc (slen + 1);
3694 memcpy (export_name, named, slen);
3695 export_name [slen] = 0;
3699 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3700 add_method (acfg, wrapper);
3702 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3706 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3707 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3708 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3712 /* StructureToPtr/PtrToStructure wrappers */
3713 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3716 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3717 klass = mono_class_get (acfg->image, token);
3720 mono_loader_clear_error ();
3724 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3725 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3726 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3727 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3733 has_type_vars (MonoClass *klass)
3735 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3738 return has_type_vars (klass->element_class);
3739 if (klass->generic_class) {
3740 MonoGenericContext *context = &klass->generic_class->context;
3741 if (context->class_inst) {
3744 for (i = 0; i < context->class_inst->type_argc; ++i)
3745 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3749 if (klass->generic_container)
3755 is_vt_inst (MonoGenericInst *inst)
3759 for (i = 0; i < inst->type_argc; ++i) {
3760 MonoType *t = inst->type_argv [i];
3761 if (t->type == MONO_TYPE_VALUETYPE)
3768 method_has_type_vars (MonoMethod *method)
3770 if (has_type_vars (method->klass))
3773 if (method->is_inflated) {
3774 MonoGenericContext *context = mono_method_get_context (method);
3775 if (context->method_inst) {
3778 for (i = 0; i < context->method_inst->type_argc; ++i)
3779 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3786 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3789 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3791 /* This might lead to a huge code blowup so only do it if neccesary */
3792 if (!acfg->aot_opts.full_aot && !force)
3795 add_generic_class_with_depth (acfg, klass, 0, ref);
3799 check_type_depth (MonoType *t, int depth)
3807 case MONO_TYPE_GENERICINST: {
3808 MonoGenericClass *gklass = t->data.generic_class;
3809 MonoGenericInst *ginst = gklass->context.class_inst;
3812 for (i = 0; i < ginst->type_argc; ++i) {
3813 if (check_type_depth (ginst->type_argv [i], depth + 1))
3827 * add_generic_class:
3829 * Add all methods of a generic class.
3832 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3835 MonoClassField *field;
3837 gboolean use_gsharedvt = FALSE;
3839 if (!acfg->ginst_hash)
3840 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3842 mono_class_init (klass);
3844 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3847 if (has_type_vars (klass))
3850 if (!klass->generic_class && !klass->rank)
3853 if (klass->exception_type)
3856 if (!acfg->ginst_hash)
3857 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3859 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3862 if (check_type_depth (&klass->byval_arg, 0))
3865 if (acfg->aot_opts.log_generics)
3866 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3868 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3871 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3872 * Enable this only for some classes since gsharedvt might not support all methods.
3874 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")))
3875 use_gsharedvt = TRUE;
3878 while ((method = mono_class_get_methods (klass, &iter))) {
3879 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3881 * This is partial sharing, and we can't handle it yet
3886 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt))
3890 if (method->is_generic)
3895 * FIXME: Instances which are referenced by these methods are not added,
3896 * for example Array.Resize<int> for List<int>.Add ().
3898 add_extra_method_with_depth (acfg, method, depth + 1);
3902 while ((field = mono_class_get_fields (klass, &iter))) {
3903 if (field->type->type == MONO_TYPE_GENERICINST)
3904 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3907 if (klass->delegate) {
3908 method = mono_get_delegate_invoke (klass);
3910 method = mono_marshal_get_delegate_invoke (method, NULL);
3912 if (acfg->aot_opts.log_generics)
3913 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3915 add_method (acfg, method);
3918 /* Add superclasses */
3920 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3923 * For ICollection<T>, add instances of the helper methods
3924 * in Array, since a T[] could be cast to ICollection<T>.
3926 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3927 (!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"))) {
3928 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3929 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3933 if (!strcmp (klass->name, "IEnumerator`1"))
3934 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3936 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3938 /* Add the T[]/InternalEnumerator class */
3939 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3943 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3944 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3948 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3949 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3953 while ((method = mono_class_get_methods (array_class, &iter))) {
3954 if (strstr (method->name, name_prefix)) {
3955 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3957 add_extra_method_with_depth (acfg, m, depth);
3961 g_free (name_prefix);
3964 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3965 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3966 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3967 MonoClass *icomparable, *gcomparer;
3968 MonoGenericContext ctx;
3969 MonoType *args [16];
3971 memset (&ctx, 0, sizeof (ctx));
3973 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3974 g_assert (icomparable);
3975 args [0] = &tclass->byval_arg;
3976 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3978 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3979 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3980 g_assert (gcomparer);
3981 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3985 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3986 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3987 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3988 MonoClass *iface, *gcomparer;
3989 MonoGenericContext ctx;
3990 MonoType *args [16];
3992 memset (&ctx, 0, sizeof (ctx));
3994 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3996 args [0] = &tclass->byval_arg;
3997 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3999 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4000 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4001 g_assert (gcomparer);
4002 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4008 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4011 MonoGenericContext ctx;
4012 MonoType *args [16];
4014 if (acfg->aot_opts.no_instances)
4017 memset (&ctx, 0, sizeof (ctx));
4019 for (i = 0; i < ninsts; ++i) {
4020 args [0] = insts [i];
4021 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4022 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4027 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4029 MonoMethodHeader *header;
4030 MonoMethodSignature *sig;
4033 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4035 sig = mono_method_signature (method);
4038 for (j = 0; j < sig->param_count; ++j)
4039 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4040 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4043 header = mono_method_get_header (method);
4046 for (j = 0; j < header->num_locals; ++j)
4047 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4048 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4050 mono_loader_clear_error ();
4055 * add_generic_instances:
4057 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4060 add_generic_instances (MonoAotCompile *acfg)
4065 MonoGenericContext *context;
4067 if (acfg->aot_opts.no_instances)
4070 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4071 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4072 method = mono_get_method (acfg->image, token, NULL);
4077 if (method->klass->image != acfg->image)
4080 context = mono_method_get_context (method);
4082 if (context && ((context->class_inst && context->class_inst->is_open)))
4086 * For open methods, create an instantiation which can be passed to the JIT.
4087 * FIXME: Handle class_inst as well.
4089 if (context && context->method_inst && context->method_inst->is_open) {
4090 MonoGenericContext shared_context;
4091 MonoGenericInst *inst;
4092 MonoType **type_argv;
4094 MonoMethod *declaring_method;
4095 gboolean supported = TRUE;
4097 /* Check that the context doesn't contain open constructed types */
4098 if (context->class_inst) {
4099 inst = context->class_inst;
4100 for (i = 0; i < inst->type_argc; ++i) {
4101 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)
4103 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4107 if (context->method_inst) {
4108 inst = context->method_inst;
4109 for (i = 0; i < inst->type_argc; ++i) {
4110 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)
4112 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4120 memset (&shared_context, 0, sizeof (MonoGenericContext));
4122 inst = context->class_inst;
4124 type_argv = g_new0 (MonoType*, inst->type_argc);
4125 for (i = 0; i < inst->type_argc; ++i) {
4126 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
4127 type_argv [i] = &mono_defaults.object_class->byval_arg;
4129 type_argv [i] = inst->type_argv [i];
4132 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4136 inst = context->method_inst;
4138 type_argv = g_new0 (MonoType*, inst->type_argc);
4139 for (i = 0; i < inst->type_argc; ++i) {
4140 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)
4141 type_argv [i] = &mono_defaults.object_class->byval_arg;
4143 type_argv [i] = inst->type_argv [i];
4146 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4150 if (method->is_generic || method->klass->generic_container)
4151 declaring_method = method;
4153 declaring_method = mono_method_get_declaring_generic_method (method);
4155 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4159 * If the method is fully sharable, it was already added in place of its
4160 * generic definition.
4162 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4166 * FIXME: Partially shared methods are not shared here, so we end up with
4167 * many identical methods.
4169 add_extra_method (acfg, method);
4172 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4175 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4177 klass = mono_class_get (acfg->image, token);
4178 if (!klass || klass->rank) {
4179 mono_loader_clear_error ();
4183 add_generic_class (acfg, klass, FALSE, "typespec");
4186 /* Add types of args/locals */
4187 for (i = 0; i < acfg->methods->len; ++i) {
4188 method = g_ptr_array_index (acfg->methods, i);
4189 add_types_from_method_header (acfg, method);
4192 if (acfg->image == mono_defaults.corlib) {
4194 MonoType *insts [256];
4197 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4198 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4199 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4200 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4201 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4202 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4203 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4204 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4205 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4206 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4207 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4208 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4210 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4211 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4213 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4214 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4216 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4218 /* Add instances of the array generic interfaces for primitive types */
4219 /* This will add instances of the InternalArray_ helper methods in Array too */
4220 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4222 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4223 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4225 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4226 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4228 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4231 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4232 * used for all instances of GetGenericValueImpl by the AOT runtime.
4235 MonoGenericContext ctx;
4236 MonoType *args [16];
4237 MonoMethod *get_method;
4238 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4240 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4243 memset (&ctx, 0, sizeof (ctx));
4244 args [0] = &mono_defaults.object_class->byval_arg;
4245 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4246 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4250 /* Same for CompareExchange<T>/Exchange<T> */
4252 MonoGenericContext ctx;
4253 MonoType *args [16];
4255 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4256 gpointer iter = NULL;
4258 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4259 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4260 memset (&ctx, 0, sizeof (ctx));
4261 args [0] = &mono_defaults.object_class->byval_arg;
4262 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4263 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4268 /* Same for Volatile.Read/Write<T> */
4270 MonoGenericContext ctx;
4271 MonoType *args [16];
4273 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4274 gpointer iter = NULL;
4276 if (volatile_klass) {
4277 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4278 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4279 memset (&ctx, 0, sizeof (ctx));
4280 args [0] = &mono_defaults.object_class->byval_arg;
4281 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4282 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4291 * is_direct_callable:
4293 * Return whenever the method identified by JI is directly callable without
4294 * going through the PLT.
4297 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4299 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4300 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4302 gboolean direct_callable = TRUE;
4304 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4305 direct_callable = FALSE;
4306 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4307 // FIXME: Maybe call the wrapper directly ?
4308 direct_callable = FALSE;
4310 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4311 /* Disable this so all calls go through load_method (), see the
4312 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4313 * mono_debugger_agent_init ().
4315 direct_callable = FALSE;
4318 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4319 /* sgen does some initialization when the allocator method is created */
4320 direct_callable = FALSE;
4322 if (direct_callable)
4325 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4326 if (acfg->aot_opts.direct_pinvoke)
4328 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4329 if (acfg->aot_opts.direct_icalls)
4338 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4340 MonoImage *image = method->klass->image;
4341 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4342 MonoTableInfo *tables = image->tables;
4343 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4344 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4345 guint32 im_cols [MONO_IMPLMAP_SIZE];
4348 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4352 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4355 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4357 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4360 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4362 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4368 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4370 if (a->native_offset == b->native_offset)
4371 return a->il_offset - b->il_offset;
4373 return a->native_offset - b->native_offset;
4377 * compute_line_numbers:
4379 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4382 static MonoDebugSourceLocation**
4383 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4385 MonoDebugMethodInfo *minfo;
4386 MonoDebugLineNumberEntry *ln_array;
4387 MonoDebugSourceLocation *loc;
4388 int i, prev_line, prev_il_offset;
4389 int *native_to_il_offset = NULL;
4390 MonoDebugSourceLocation **res;
4393 minfo = mono_debug_lookup_method (method);
4396 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4397 if (debug_info->code_size != code_size)
4400 g_assert (code_size);
4402 /* Compute the native->IL offset mapping */
4404 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4405 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4407 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4409 native_to_il_offset = g_new0 (int, code_size + 1);
4411 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4413 MonoDebugLineNumberEntry *lne = &ln_array [i];
4416 for (j = 0; j < lne->native_offset; ++j)
4417 native_to_il_offset [j] = -1;
4420 if (i < debug_info->num_line_numbers - 1) {
4421 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4423 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4424 native_to_il_offset [j] = lne->il_offset;
4426 for (j = lne->native_offset; j < code_size; ++j)
4427 native_to_il_offset [j] = lne->il_offset;
4432 /* Compute the native->line number mapping */
4433 res = g_new0 (MonoDebugSourceLocation*, code_size);
4434 prev_il_offset = -1;
4437 for (i = 0; i < code_size; ++i) {
4438 int il_offset = native_to_il_offset [i];
4440 if (il_offset == -1 || il_offset == prev_il_offset)
4442 prev_il_offset = il_offset;
4443 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4444 if (!(loc && loc->source_file))
4446 if (loc->row == prev_line) {
4447 mono_debug_symfile_free_location (loc);
4450 prev_line = loc->row;
4451 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4453 /* This will cover the prolog too */
4463 get_file_index (MonoAotCompile *acfg, const char *source_file)
4467 // FIXME: Free these
4468 if (!acfg->dwarf_ln_filenames)
4469 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4470 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4472 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4473 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4474 emit_unset_mode (acfg);
4475 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4481 * emit_and_reloc_code:
4483 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4484 * is true, calls are made through the GOT too. This is used for emitting trampolines
4485 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4486 * since trampolines are needed to make PTL work.
4489 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4491 int i, pindex, start_index, method_index;
4493 MonoJumpInfo *patch_info;
4494 MonoMethodHeader *header;
4495 MonoDebugSourceLocation **locs = NULL;
4496 gboolean skip, direct_call, external_call;
4498 const char *direct_call_target = 0;
4499 const char *direct_pinvoke;
4502 header = mono_method_get_header (method);
4504 method_index = get_method_index (acfg, method);
4507 if (acfg->gas_line_numbers && method && debug_info) {
4508 locs = compute_line_numbers (method, code_len, debug_info);
4510 int findex = get_file_index (acfg, "<unknown>");
4511 emit_unset_mode (acfg);
4512 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4516 /* Collect and sort relocations */
4517 patches = g_ptr_array_new ();
4518 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4519 g_ptr_array_add (patches, patch_info);
4520 g_ptr_array_sort (patches, compare_patches);
4523 for (i = 0; i < code_len; i++) {
4525 for (pindex = start_index; pindex < patches->len; ++pindex) {
4526 patch_info = g_ptr_array_index (patches, pindex);
4527 if (patch_info->ip.i >= i)
4531 if (locs && locs [i]) {
4532 MonoDebugSourceLocation *loc = locs [i];
4535 findex = get_file_index (acfg, loc->source_file);
4536 emit_unset_mode (acfg);
4537 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4538 mono_debug_symfile_free_location (loc);
4542 #ifdef MONO_ARCH_AOT_SUPPORTED
4543 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4544 start_index = pindex;
4546 switch (patch_info->type) {
4547 case MONO_PATCH_INFO_NONE:
4549 case MONO_PATCH_INFO_GOT_OFFSET: {
4552 arch_emit_got_offset (acfg, code + i, &code_size);
4555 patch_info->type = MONO_PATCH_INFO_NONE;
4558 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4559 int code_size, index;
4560 char *selector = (void*)patch_info->data.target;
4562 if (!acfg->objc_selector_to_index)
4563 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4564 if (!acfg->objc_selectors)
4565 acfg->objc_selectors = g_ptr_array_new ();
4566 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4570 index = acfg->objc_selector_index;
4571 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4572 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4573 acfg->objc_selector_index ++;
4576 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4579 patch_info->type = MONO_PATCH_INFO_NONE;
4584 * If this patch is a call, try emitting a direct call instead of
4585 * through a PLT entry. This is possible if the called method is in
4586 * the same assembly and requires no initialization.
4588 direct_call = FALSE;
4589 external_call = FALSE;
4590 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4591 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4592 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4593 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4595 direct_call_target = callee_cfg->asm_symbol;
4596 patch_info->type = MONO_PATCH_INFO_NONE;
4597 acfg->stats.direct_calls ++;
4600 acfg->stats.all_calls ++;
4601 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4602 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4603 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4604 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4606 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4607 if (direct_pinvoke) {
4609 g_assert (strlen (direct_pinvoke) < 1000);
4610 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4613 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4614 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4615 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4616 /* Call to a C function implementing a jit icall */
4618 external_call = TRUE;
4619 g_assert (strlen (sym) < 1000);
4620 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4622 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4623 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4624 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4625 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4626 /* Call to a jit icall without a wrapper */
4628 external_call = TRUE;
4629 g_assert (strlen (sym) < 1000);
4630 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4635 patch_info->type = MONO_PATCH_INFO_NONE;
4636 acfg->stats.direct_calls ++;
4639 if (!got_only && !direct_call) {
4640 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4642 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4644 direct_call_target = plt_entry->symbol;
4646 /* Nullify the patch */
4647 patch_info->type = MONO_PATCH_INFO_NONE;
4648 plt_entry->jit_used = TRUE;
4655 arch_emit_direct_call (acfg, direct_call_target, external_call, patch_info, &call_size);
4660 got_slot = get_got_offset (acfg, patch_info);
4662 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4669 #endif /* MONO_ARCH_AOT_SUPPORTED */
4672 /* Find next patch */
4674 for (pindex = start_index; pindex < patches->len; ++pindex) {
4675 patch_info = g_ptr_array_index (patches, pindex);
4676 if (patch_info->ip.i >= i)
4680 /* Try to emit multiple bytes at once */
4681 if (pindex < patches->len && patch_info->ip.i > i) {
4684 for (limit = i + 1; limit < patch_info->ip.i; ++limit) {
4685 if (locs && locs [limit])
4689 emit_bytes (acfg, code + i, limit - i);
4692 emit_bytes (acfg, code + i, 1);
4703 * Modify SYMBOL so it only includes characters permissible in symbols.
4706 sanitize_symbol (char *symbol)
4708 int i, len = strlen (symbol);
4710 for (i = 0; i < len; ++i)
4711 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
4716 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4718 char *name1, *name2, *cached;
4719 int i, j, len, count;
4722 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4723 if (!prefix || !*prefix)
4727 name1 = mono_method_full_name (method, TRUE);
4728 len = strlen (name1);
4729 name2 = malloc (strlen (prefix) + len + 16);
4730 memcpy (name2, prefix, strlen (prefix));
4731 j = strlen (prefix);
4732 for (i = 0; i < len; ++i) {
4733 if (isalnum (name1 [i])) {
4734 name2 [j ++] = name1 [i];
4735 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4737 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4740 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4749 while (g_hash_table_lookup (cache, name2)) {
4750 sprintf (name2 + j, "_%d", count);
4754 cached = g_strdup (name2);
4755 g_hash_table_insert (cache, cached, cached);
4761 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4766 char *debug_sym = NULL;
4767 char *symbol = NULL;
4768 int func_alignment = AOT_FUNC_ALIGNMENT;
4769 MonoMethodHeader *header;
4772 method = cfg->orig_method;
4773 code = cfg->native_code;
4774 header = cfg->header;
4776 method_index = get_method_index (acfg, method);
4777 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4780 /* Make the labels local */
4781 emit_section_change (acfg, ".text", 0);
4782 emit_alignment (acfg, func_alignment);
4784 if (acfg->global_symbols && acfg->need_no_dead_strip)
4785 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4787 emit_label (acfg, cfg->asm_symbol);
4789 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4791 * Write a C style symbol for every method, this has two uses:
4792 * - it works on platforms where the dwarf debugging info is not
4794 * - it allows the setting of breakpoints of aot-ed methods.
4796 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4798 if (acfg->need_no_dead_strip)
4799 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4800 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4801 emit_label (acfg, debug_sym);
4804 export_name = g_hash_table_lookup (acfg->export_names, method);
4806 /* Emit a global symbol for the method */
4807 emit_global_inner (acfg, export_name, TRUE);
4808 emit_label (acfg, export_name);
4811 if (cfg->verbose_level > 0)
4812 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4814 acfg->stats.code_size += cfg->code_len;
4816 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4818 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 ()));
4822 if (acfg->aot_opts.write_symbols) {
4823 emit_symbol_size (acfg, debug_sym, ".");
4827 emit_label (acfg, symbol);
4834 * Encode PATCH_INFO into its disk representation.
4837 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4841 switch (patch_info->type) {
4842 case MONO_PATCH_INFO_NONE:
4844 case MONO_PATCH_INFO_IMAGE:
4845 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4847 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4848 case MONO_PATCH_INFO_JIT_TLS_ID:
4849 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4850 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4852 case MONO_PATCH_INFO_METHOD_REL:
4853 encode_value ((gint)patch_info->data.offset, p, &p);
4855 case MONO_PATCH_INFO_SWITCH: {
4856 gpointer *table = (gpointer *)patch_info->data.table->table;
4859 encode_value (patch_info->data.table->table_size, p, &p);
4860 for (k = 0; k < patch_info->data.table->table_size; k++)
4861 encode_value ((int)(gssize)table [k], p, &p);
4864 case MONO_PATCH_INFO_METHODCONST:
4865 case MONO_PATCH_INFO_METHOD:
4866 case MONO_PATCH_INFO_METHOD_JUMP:
4867 case MONO_PATCH_INFO_ICALL_ADDR:
4868 case MONO_PATCH_INFO_METHOD_RGCTX:
4869 encode_method_ref (acfg, patch_info->data.method, p, &p);
4871 case MONO_PATCH_INFO_INTERNAL_METHOD:
4872 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4873 guint32 len = strlen (patch_info->data.name);
4875 encode_value (len, p, &p);
4877 memcpy (p, patch_info->data.name, len);
4882 case MONO_PATCH_INFO_LDSTR: {
4883 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4884 guint32 token = patch_info->data.token->token;
4885 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4886 encode_value (image_index, p, &p);
4887 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4890 case MONO_PATCH_INFO_RVA:
4891 case MONO_PATCH_INFO_DECLSEC:
4892 case MONO_PATCH_INFO_LDTOKEN:
4893 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4894 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4895 encode_value (patch_info->data.token->token, p, &p);
4896 encode_value (patch_info->data.token->has_context, p, &p);
4897 if (patch_info->data.token->has_context)
4898 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4900 case MONO_PATCH_INFO_EXC_NAME: {
4901 MonoClass *ex_class;
4904 mono_class_from_name (mono_defaults.exception_class->image,
4905 "System", patch_info->data.target);
4906 g_assert (ex_class);
4907 encode_klass_ref (acfg, ex_class, p, &p);
4910 case MONO_PATCH_INFO_R4:
4911 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4913 case MONO_PATCH_INFO_R8:
4914 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4915 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4917 case MONO_PATCH_INFO_VTABLE:
4918 case MONO_PATCH_INFO_CLASS:
4919 case MONO_PATCH_INFO_IID:
4920 case MONO_PATCH_INFO_ADJUSTED_IID:
4921 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4923 case MONO_PATCH_INFO_CLASS_INIT:
4924 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4925 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4927 case MONO_PATCH_INFO_FIELD:
4928 case MONO_PATCH_INFO_SFLDA:
4929 encode_field_info (acfg, patch_info->data.field, p, &p);
4931 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4933 case MONO_PATCH_INFO_RGCTX_FETCH: {
4934 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4939 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4940 * reference the same method, so encode the method only once.
4942 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4944 buf2 = g_malloc (1024);
4947 encode_method_ref (acfg, entry->method, p2, &p2);
4948 g_assert (p2 - buf2 < 1024);
4950 offset = add_to_blob (acfg, buf2, p2 - buf2);
4953 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4958 encode_value (offset, p, &p);
4959 g_assert ((int)entry->info_type < 256);
4960 g_assert (entry->data->type < 256);
4961 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4962 encode_patch (acfg, entry->data, p, &p);
4965 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4966 case MONO_PATCH_INFO_MONITOR_ENTER:
4967 case MONO_PATCH_INFO_MONITOR_EXIT:
4968 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4970 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4971 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4972 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4974 case MONO_PATCH_INFO_SIGNATURE:
4975 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4977 case MONO_PATCH_INFO_TLS_OFFSET:
4978 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
4980 case MONO_PATCH_INFO_GSHAREDVT_CALL:
4981 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
4982 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
4984 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
4985 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
4988 encode_method_ref (acfg, info->method, p, &p);
4989 encode_value (info->entries->len, p, &p);
4990 for (i = 0; i < info->entries->len; ++i) {
4991 MonoRuntimeGenericContextInfoTemplate *template = g_ptr_array_index (info->entries, i);
4993 encode_value (template->info_type, p, &p);
4994 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
4995 case MONO_PATCH_INFO_CLASS:
4996 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
4998 case MONO_PATCH_INFO_FIELD:
4999 encode_field_info (acfg, template->data, p, &p);
5002 g_assert_not_reached ();
5009 g_warning ("unable to handle jump info %d", patch_info->type);
5010 g_assert_not_reached ();
5017 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5020 guint32 pindex, offset;
5021 MonoJumpInfo *patch_info;
5023 encode_value (n_patches, p, &p);
5025 for (pindex = 0; pindex < patches->len; ++pindex) {
5026 patch_info = g_ptr_array_index (patches, pindex);
5028 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5032 offset = get_got_offset (acfg, patch_info);
5033 encode_value (offset, p, &p);
5040 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5044 int pindex, buf_size, n_patches;
5046 MonoJumpInfo *patch_info;
5047 MonoMethodHeader *header;
5048 guint32 method_index;
5050 guint32 first_got_offset;
5052 method = cfg->orig_method;
5053 header = mono_method_get_header (method);
5055 method_index = get_method_index (acfg, method);
5057 /* Sort relocations */
5058 patches = g_ptr_array_new ();
5059 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5060 g_ptr_array_add (patches, patch_info);
5061 g_ptr_array_sort (patches, compare_patches);
5063 first_got_offset = acfg->cfgs [method_index]->got_offset;
5065 /**********************/
5066 /* Encode method info */
5067 /**********************/
5069 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5070 p = buf = g_malloc (buf_size);
5072 if (mono_class_get_cctor (method->klass))
5073 encode_klass_ref (acfg, method->klass, p, &p);
5075 /* Not needed when loading the method */
5076 encode_value (0, p, &p);
5079 if (cfg->opt & MONO_OPT_SHARED) {
5080 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5081 for (l = cfg->ldstr_list; l; l = l->next) {
5082 encode_value ((long)l->data, p, &p);
5086 /* Used only in shared mode */
5087 g_assert (!cfg->ldstr_list);
5090 for (pindex = 0; pindex < patches->len; ++pindex) {
5091 patch_info = g_ptr_array_index (patches, pindex);
5093 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5094 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5095 patch_info->type = MONO_PATCH_INFO_NONE;
5100 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5101 /* Stored in a GOT slot initialized at module load time */
5102 patch_info->type = MONO_PATCH_INFO_NONE;
5106 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5107 /* Stored in a GOT slot initialized at module load time */
5108 patch_info->type = MONO_PATCH_INFO_NONE;
5112 if (is_plt_patch (patch_info)) {
5113 /* Calls are made through the PLT */
5114 patch_info->type = MONO_PATCH_INFO_NONE;
5122 g_assert (cfg->has_got_slots);
5124 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5126 acfg->stats.info_size += p - buf;
5128 g_assert (p - buf < buf_size);
5130 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5135 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5137 guint32 cache_index;
5140 /* Reuse the unwind module to canonize and store unwind info entries */
5141 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5143 /* Use +/- 1 to distinguish 0s from missing entries */
5144 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5152 * It would be easier to use assembler symbols, but the caller needs an
5155 offset = acfg->unwind_info_offset;
5156 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5157 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5160 encode_value (encoded_len, p, &p);
5162 acfg->unwind_info_offset += encoded_len + (p - buf);
5168 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5171 int i, k, buf_size, method_index;
5172 guint32 debug_info_size;
5174 MonoMethodHeader *header;
5175 guint8 *p, *buf, *debug_info;
5176 MonoJitInfo *jinfo = cfg->jit_info;
5178 gboolean use_unwind_ops = FALSE;
5179 MonoSeqPointInfo *seq_points;
5181 method = cfg->orig_method;
5182 code = cfg->native_code;
5183 header = cfg->header;
5185 method_index = get_method_index (acfg, method);
5187 if (!acfg->aot_opts.nodebug) {
5188 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5191 debug_info_size = 0;
5194 seq_points = cfg->seq_point_info;
5196 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
5197 p = buf = g_malloc (buf_size);
5199 use_unwind_ops = cfg->unwind_ops != NULL;
5201 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);
5203 encode_value (flags, p, &p);
5205 if (use_unwind_ops) {
5206 guint32 encoded_len;
5210 * This is a duplicate of the data in the .debug_frame section, but that
5211 * section cannot be accessed using the dl interface.
5213 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5214 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5217 encode_value (jinfo->used_regs, p, &p);
5220 /*Encode the number of holes before the number of clauses to make decoding easier*/
5221 if (jinfo->has_try_block_holes) {
5222 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5223 encode_value (table->num_holes, p, &p);
5226 /* Exception table */
5227 if (cfg->compile_llvm) {
5229 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5230 * since the information is only available to llc. Instead, we let llc save the data
5231 * into the LSDA, and read it from there at runtime.
5233 /* The assembly might be CIL stripped so emit the data ourselves */
5234 if (header->num_clauses)
5235 encode_value (header->num_clauses, p, &p);
5237 for (k = 0; k < header->num_clauses; ++k) {
5238 MonoExceptionClause *clause;
5240 clause = &header->clauses [k];
5242 encode_value (clause->flags, p, &p);
5243 if (clause->data.catch_class) {
5244 encode_value (1, p, &p);
5245 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5247 encode_value (0, p, &p);
5250 /* Emit a list of nesting clauses */
5251 for (i = 0; i < header->num_clauses; ++i) {
5253 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5255 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5257 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5258 encode_value (i, p, &p);
5260 encode_value (-1, p, &p);
5263 if (jinfo->num_clauses)
5264 encode_value (jinfo->num_clauses, p, &p);
5266 for (k = 0; k < jinfo->num_clauses; ++k) {
5267 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5269 encode_value (ei->flags, p, &p);
5270 encode_value (ei->exvar_offset, p, &p);
5272 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5273 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5275 if (ei->data.catch_class) {
5279 buf2 = g_malloc (4096);
5281 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5283 g_assert (len < 4096);
5284 encode_value (len, p, &p);
5285 memcpy (p, buf2, len);
5289 encode_value (0, p, &p);
5293 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5294 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5295 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5299 if (jinfo->has_try_block_holes) {
5300 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5301 for (i = 0; i < table->num_holes; ++i) {
5302 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5303 encode_value (hole->clause, p, &p);
5304 encode_value (hole->length, p, &p);
5305 encode_value (hole->offset, p, &p);
5309 if (jinfo->has_arch_eh_info) {
5310 MonoArchEHJitInfo *eh_info;
5312 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5313 encode_value (eh_info->stack_size, p, &p);
5316 if (jinfo->has_generic_jit_info) {
5317 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5318 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5324 encode_value (gi->nlocs, p, &p);
5326 for (i = 0; i < gi->nlocs; ++i) {
5327 MonoDwarfLocListEntry *entry = &gi->locations [i];
5329 encode_value (entry->is_reg ? 1 : 0, p, &p);
5330 encode_value (entry->reg, p, &p);
5332 encode_value (entry->offset, p, &p);
5334 g_assert (entry->from == 0);
5336 encode_value (entry->from, p, &p);
5337 encode_value (entry->to, p, &p);
5340 if (!cfg->compile_llvm) {
5341 encode_value (gi->has_this ? 1 : 0, p, &p);
5342 encode_value (gi->this_reg, p, &p);
5343 encode_value (gi->this_offset, p, &p);
5348 * Need to encode jinfo->method too, since it is not equal to 'method'
5349 * when using generic sharing.
5351 buf2 = g_malloc (4096);
5353 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5355 g_assert (len < 4096);
5356 encode_value (len, p, &p);
5357 memcpy (p, buf2, len);
5361 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5362 MonoMethodInflated *inflated;
5363 MonoGenericContext *context;
5364 MonoGenericInst *inst;
5366 g_assert (jinfo->d.method->is_inflated);
5367 inflated = (MonoMethodInflated*)jinfo->d.method;
5368 context = &inflated->context;
5370 encode_value (1, p, &p);
5371 if (context->class_inst) {
5372 inst = context->class_inst;
5374 encode_value (inst->type_argc, p, &p);
5375 for (i = 0; i < inst->type_argc; ++i)
5376 encode_value (gsctx->var_is_vt [i], p, &p);
5378 encode_value (0, p, &p);
5380 if (context->method_inst) {
5381 inst = context->method_inst;
5383 encode_value (inst->type_argc, p, &p);
5384 for (i = 0; i < inst->type_argc; ++i)
5385 encode_value (gsctx->mvar_is_vt [i], p, &p);
5387 encode_value (0, p, &p);
5390 encode_value (0, p, &p);
5395 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5397 encode_value (seq_points->len, p, &p);
5398 last_il_offset = last_native_offset = 0;
5399 for (i = 0; i < seq_points->len; ++i) {
5400 SeqPoint *sp = &seq_points->seq_points [i];
5401 il_offset = sp->il_offset;
5402 native_offset = sp->native_offset;
5403 encode_value (il_offset - last_il_offset, p, &p);
5404 encode_value (native_offset - last_native_offset, p, &p);
5405 last_il_offset = il_offset;
5406 last_native_offset = native_offset;
5408 encode_value (sp->flags, p, &p);
5409 encode_value (sp->next_len, p, &p);
5410 for (j = 0; j < sp->next_len; ++j)
5411 encode_value (sp->next [j], p, &p);
5415 g_assert (debug_info_size < buf_size);
5417 encode_value (debug_info_size, p, &p);
5418 if (debug_info_size) {
5419 memcpy (p, debug_info, debug_info_size);
5420 p += debug_info_size;
5421 g_free (debug_info);
5426 encode_value (cfg->gc_map_size, p, &p);
5427 /* The GC map requires 4 bytes of alignment */
5428 while ((gsize)p % 4)
5430 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5431 p += cfg->gc_map_size;
5434 acfg->stats.ex_info_size += p - buf;
5436 g_assert (p - buf < buf_size);
5439 /* The GC Map requires 4 byte alignment */
5440 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5445 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5447 MonoClass *klass = mono_class_get (acfg->image, token);
5449 int i, buf_size, res;
5450 gboolean no_special_static, cant_encode;
5451 gpointer iter = NULL;
5454 mono_loader_clear_error ();
5458 p = buf = g_malloc (buf_size);
5460 /* Mark as unusable */
5461 encode_value (-1, p, &p);
5463 res = add_to_blob (acfg, buf, p - buf);
5469 buf_size = 10240 + (klass->vtable_size * 16);
5470 p = buf = g_malloc (buf_size);
5474 mono_class_init (klass);
5476 mono_class_get_nested_types (klass, &iter);
5477 g_assert (klass->nested_classes_inited);
5479 mono_class_setup_vtable (klass);
5482 * Emit all the information which is required for creating vtables so
5483 * the runtime does not need to create the MonoMethod structures which
5484 * take up a lot of space.
5487 no_special_static = !mono_class_has_special_static_fields (klass);
5489 /* Check whenever we have enough info to encode the vtable */
5490 cant_encode = FALSE;
5491 for (i = 0; i < klass->vtable_size; ++i) {
5492 MonoMethod *cm = klass->vtable [i];
5494 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5498 mono_class_has_finalizer (klass);
5500 if (klass->generic_container || cant_encode) {
5501 encode_value (-1, p, &p);
5503 encode_value (klass->vtable_size, p, &p);
5504 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);
5505 if (klass->has_cctor)
5506 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5507 if (klass->has_finalize)
5508 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5510 encode_value (klass->instance_size, p, &p);
5511 encode_value (mono_class_data_size (klass), p, &p);
5512 encode_value (klass->packing_size, p, &p);
5513 encode_value (klass->min_align, p, &p);
5515 for (i = 0; i < klass->vtable_size; ++i) {
5516 MonoMethod *cm = klass->vtable [i];
5519 encode_method_ref (acfg, cm, p, &p);
5521 encode_value (0, p, &p);
5525 acfg->stats.class_info_size += p - buf;
5527 g_assert (p - buf < buf_size);
5528 res = add_to_blob (acfg, buf, p - buf);
5535 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5537 char *debug_sym = NULL;
5540 case MONO_PATCH_INFO_METHOD:
5541 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5543 case MONO_PATCH_INFO_INTERNAL_METHOD:
5544 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5546 case MONO_PATCH_INFO_CLASS_INIT:
5547 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
5548 sanitize_symbol (debug_sym);
5550 case MONO_PATCH_INFO_RGCTX_FETCH:
5551 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5553 case MONO_PATCH_INFO_ICALL_ADDR: {
5554 char *s = get_debug_sym (ji->data.method, "", cache);
5556 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5560 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5561 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5563 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5564 debug_sym = g_strdup_printf ("plt__generic_class_init");
5574 * Calls made from AOTed code are routed through a table of jumps similar to the
5575 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5576 * control to the AOT runtime through a trampoline.
5579 emit_plt (MonoAotCompile *acfg)
5585 sprintf (symbol, "plt");
5587 emit_section_change (acfg, ".text", 0);
5588 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5589 emit_label (acfg, symbol);
5590 emit_label (acfg, acfg->plt_symbol);
5592 for (i = 0; i < acfg->plt_offset; ++i) {
5593 char *debug_sym = NULL;
5594 MonoPltEntry *plt_entry = NULL;
5599 * The first plt entry is unused.
5603 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5608 * If the target is directly callable, alias the plt symbol to point to
5610 * FIXME: Use this to simplify emit_and_reloc_code ().
5611 * FIXME: Avoid the got slot.
5612 * FIXME: Add support to the binary writer.
5614 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5615 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5618 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5619 /* LLVM calls the PLT entries using bl, so emit a stub */
5620 emit_set_thumb_mode (acfg);
5621 fprintf (acfg->fp, "\n.thumb_func\n");
5622 emit_label (acfg, plt_entry->llvm_symbol);
5623 fprintf (acfg->fp, "bx pc\n");
5624 fprintf (acfg->fp, "nop\n");
5625 emit_set_arm_mode (acfg);
5626 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5628 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5635 debug_sym = plt_entry->debug_sym;
5637 if (acfg->thumb_mixed && !plt_entry->jit_used)
5638 /* Emit only a thumb version */
5641 if (acfg->llvm && !acfg->thumb_mixed)
5642 emit_label (acfg, plt_entry->llvm_symbol);
5645 if (acfg->need_no_dead_strip) {
5646 emit_unset_mode (acfg);
5647 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5649 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5650 emit_label (acfg, debug_sym);
5653 emit_label (acfg, plt_entry->symbol);
5655 arch_emit_plt_entry (acfg, i);
5658 emit_symbol_size (acfg, debug_sym, ".");
5661 if (acfg->thumb_mixed) {
5662 /* Make sure the ARM symbols don't alias the thumb ones */
5663 emit_zero_bytes (acfg, 16);
5666 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5669 for (i = 0; i < acfg->plt_offset; ++i) {
5670 char *debug_sym = NULL;
5671 MonoPltEntry *plt_entry = NULL;
5677 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5680 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5683 /* Skip plt entries not actually called by LLVM code */
5684 if (!plt_entry->llvm_used)
5687 if (acfg->aot_opts.write_symbols) {
5688 if (plt_entry->debug_sym)
5689 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5693 #if defined(TARGET_MACH)
5694 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5695 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5697 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5698 emit_label (acfg, debug_sym);
5700 fprintf (acfg->fp, "\n.thumb_func\n");
5702 emit_label (acfg, plt_entry->llvm_symbol);
5704 arch_emit_llvm_plt_entry (acfg, i);
5707 emit_symbol_size (acfg, debug_sym, ".");
5713 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5715 sprintf (symbol, "plt_end");
5716 emit_label (acfg, symbol);
5720 * emit_trampoline_full:
5722 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5723 * create_jit_info_for_trampoline ().
5725 static G_GNUC_UNUSED void
5726 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5728 char start_symbol [256];
5729 char end_symbol [256];
5731 guint32 buf_size, info_offset;
5732 MonoJumpInfo *patch_info;
5745 code_size = info->code_size;
5747 unwind_ops = info->unwind_ops;
5749 #ifdef __native_client_codegen__
5750 mono_nacl_fix_patches (code, ji);
5755 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5757 emit_section_change (acfg, ".text", 0);
5758 emit_global (acfg, start_symbol, TRUE);
5759 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5760 emit_label (acfg, start_symbol);
5762 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5763 emit_label (acfg, symbol);
5766 * The code should access everything through the GOT, so we pass
5769 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5771 emit_symbol_size (acfg, start_symbol, ".");
5774 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5775 emit_label (acfg, end_symbol);
5780 /* Sort relocations */
5781 patches = g_ptr_array_new ();
5782 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5783 if (patch_info->type != MONO_PATCH_INFO_NONE)
5784 g_ptr_array_add (patches, patch_info);
5785 g_ptr_array_sort (patches, compare_patches);
5787 buf_size = patches->len * 128 + 128;
5788 buf = g_malloc (buf_size);
5791 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5792 g_assert (p - buf < buf_size);
5794 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5796 info_offset = add_to_blob (acfg, buf, p - buf);
5798 emit_section_change (acfg, RODATA_SECT, 0);
5799 emit_global (acfg, symbol, FALSE);
5800 emit_label (acfg, symbol);
5802 emit_int32 (acfg, info_offset);
5806 guint32 encoded_len;
5810 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5812 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5813 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5816 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5817 emit_int32 (acfg, uw_offset);
5820 /* Emit debug info */
5824 sprintf (symbol, "%s", name);
5825 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5828 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5832 static G_GNUC_UNUSED void
5833 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5835 emit_trampoline_full (acfg, got_offset, info, FALSE);
5839 emit_trampolines (MonoAotCompile *acfg)
5842 char end_symbol [256];
5843 int i, tramp_got_offset;
5844 MonoAotTrampoline ntype;
5845 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5849 if (!acfg->aot_opts.full_aot)
5852 g_assert (acfg->image->assembly);
5854 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5855 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5856 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5857 MonoTrampInfo *info;
5860 * Emit the generic trampolines.
5862 * We could save some code by treating the generic trampolines as a wrapper
5863 * method, but that approach has its own complexities, so we choose the simpler
5866 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5867 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5868 #ifdef DISABLE_REMOTING
5869 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5872 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5873 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5876 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5877 emit_trampoline (acfg, acfg->got_offset, info);
5880 mono_arch_get_nullified_class_init_trampoline (&info);
5881 emit_trampoline (acfg, acfg->got_offset, info);
5882 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5883 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5884 emit_trampoline (acfg, acfg->got_offset, info);
5885 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5886 emit_trampoline (acfg, acfg->got_offset, info);
5889 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5890 emit_trampoline (acfg, acfg->got_offset, info);
5892 /* Emit the exception related code pieces */
5893 mono_arch_get_restore_context (&info, TRUE);
5894 emit_trampoline (acfg, acfg->got_offset, info);
5895 mono_arch_get_call_filter (&info, TRUE);
5896 emit_trampoline (acfg, acfg->got_offset, info);
5897 mono_arch_get_throw_exception (&info, TRUE);
5898 emit_trampoline (acfg, acfg->got_offset, info);
5899 mono_arch_get_rethrow_exception (&info, TRUE);
5900 emit_trampoline (acfg, acfg->got_offset, info);
5901 mono_arch_get_throw_corlib_exception (&info, TRUE);
5902 emit_trampoline (acfg, acfg->got_offset, info);
5904 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5905 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5907 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5909 /* Create a separate out trampoline for more information in stack traces */
5910 info->name = g_strdup ("gsharedvt_out_trampoline");
5911 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5915 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5917 GSList *l = mono_arch_get_trampolines (TRUE);
5920 MonoTrampInfo *info = l->data;
5922 emit_trampoline (acfg, acfg->got_offset, info);
5928 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5931 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5932 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5933 emit_trampoline (acfg, acfg->got_offset, info);
5935 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5936 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5937 emit_trampoline (acfg, acfg->got_offset, info);
5940 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
5941 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
5942 emit_trampoline (acfg, acfg->got_offset, info);
5948 /* delegate_invoke_impl trampolines */
5949 l = mono_arch_get_delegate_invoke_impls ();
5951 MonoTrampInfo *info = l->data;
5953 emit_trampoline (acfg, acfg->got_offset, info);
5958 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5960 /* Emit trampolines which are numerous */
5963 * These include the following:
5964 * - specific trampolines
5965 * - static rgctx invoke trampolines
5967 * These trampolines have the same code, they are parameterized by GOT
5969 * They are defined in this file, in the arch_... routines instead of
5970 * in tramp-<ARCH>.c, since it is easier to do it this way.
5974 * When running in aot-only mode, we can't create specific trampolines at
5975 * runtime, so we create a few, and save them in the AOT file.
5976 * Normal trampolines embed their argument as a literal inside the
5977 * trampoline code, we can't do that here, so instead we embed an offset
5978 * which needs to be added to the trampoline address to get the address of
5979 * the GOT slot which contains the argument value.
5980 * The generated trampolines jump to the generic trampolines using another
5981 * GOT slot, which will be setup by the AOT loader to point to the
5982 * generic trampoline code of the given type.
5986 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5990 emit_section_change (acfg, ".text", 0);
5992 tramp_got_offset = acfg->got_offset;
5994 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5996 case MONO_AOT_TRAMP_SPECIFIC:
5997 sprintf (symbol, "specific_trampolines");
5999 case MONO_AOT_TRAMP_STATIC_RGCTX:
6000 sprintf (symbol, "static_rgctx_trampolines");
6002 case MONO_AOT_TRAMP_IMT_THUNK:
6003 sprintf (symbol, "imt_thunks");
6005 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6006 sprintf (symbol, "gsharedvt_arg_trampolines");
6009 g_assert_not_reached ();
6012 sprintf (end_symbol, "%s_e", symbol);
6014 if (acfg->aot_opts.write_symbols)
6015 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6017 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6018 emit_label (acfg, symbol);
6020 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6022 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6026 case MONO_AOT_TRAMP_SPECIFIC:
6027 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6028 tramp_got_offset += 2;
6030 case MONO_AOT_TRAMP_STATIC_RGCTX:
6031 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6032 tramp_got_offset += 2;
6034 case MONO_AOT_TRAMP_IMT_THUNK:
6035 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6036 tramp_got_offset += 1;
6038 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6039 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6040 tramp_got_offset += 2;
6043 g_assert_not_reached ();
6045 #ifdef __native_client_codegen__
6046 /* align to avoid 32-byte boundary crossings */
6047 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6050 if (!acfg->trampoline_size [ntype]) {
6051 g_assert (tramp_size);
6052 acfg->trampoline_size [ntype] = tramp_size;
6056 emit_label (acfg, end_symbol);
6057 emit_int32 (acfg, 0);
6060 arch_emit_specific_trampoline_pages (acfg);
6062 /* Reserve some entries at the end of the GOT for our use */
6063 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6066 acfg->got_offset += acfg->num_trampoline_got_entries;
6070 str_begins_with (const char *str1, const char *str2)
6072 int len = strlen (str2);
6073 return strncmp (str1, str2, len) == 0;
6077 mono_aot_readonly_field_override (MonoClassField *field)
6080 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6081 char *p = rdv->name;
6083 len = strlen (field->parent->name_space);
6084 if (strncmp (p, field->parent->name_space, len))
6089 len = strlen (field->parent->name);
6090 if (strncmp (p, field->parent->name, len))
6095 if (strcmp (p, field->name))
6097 switch (rdv->type) {
6099 return &rdv->value.i1;
6101 return &rdv->value.i2;
6103 return &rdv->value.i4;
6112 add_readonly_value (MonoAotOptions *opts, const char *val)
6117 /* the format of val is:
6118 * namespace.typename.fieldname=type/value
6119 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6121 fval = strrchr (val, '/');
6123 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6126 tval = strrchr (val, '=');
6128 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6131 rdv = g_new0 (ReadOnlyValue, 1);
6132 rdv->name = g_malloc0 (tval - val + 1);
6133 memcpy (rdv->name, val, tval - val);
6136 if (strncmp (tval, "i1", 2) == 0) {
6137 rdv->value.i1 = atoi (fval);
6138 rdv->type = MONO_TYPE_I1;
6139 } else if (strncmp (tval, "i2", 2) == 0) {
6140 rdv->value.i2 = atoi (fval);
6141 rdv->type = MONO_TYPE_I2;
6142 } else if (strncmp (tval, "i4", 2) == 0) {
6143 rdv->value.i4 = atoi (fval);
6144 rdv->type = MONO_TYPE_I4;
6146 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6149 rdv->next = readonly_values;
6150 readonly_values = rdv;
6154 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6156 gchar **args, **ptr;
6158 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6159 for (ptr = args; ptr && *ptr; ptr ++) {
6160 const char *arg = *ptr;
6162 if (str_begins_with (arg, "outfile=")) {
6163 opts->outfile = g_strdup (arg + strlen ("outfile="));
6164 } else if (str_begins_with (arg, "save-temps")) {
6165 opts->save_temps = TRUE;
6166 } else if (str_begins_with (arg, "keep-temps")) {
6167 opts->save_temps = TRUE;
6168 } else if (str_begins_with (arg, "write-symbols")) {
6169 opts->write_symbols = TRUE;
6170 } else if (str_begins_with (arg, "no-write-symbols")) {
6171 opts->write_symbols = FALSE;
6172 } else if (str_begins_with (arg, "metadata-only")) {
6173 opts->metadata_only = TRUE;
6174 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6175 opts->bind_to_runtime_version = TRUE;
6176 } else if (str_begins_with (arg, "full")) {
6177 opts->full_aot = TRUE;
6178 } else if (str_begins_with (arg, "threads=")) {
6179 opts->nthreads = atoi (arg + strlen ("threads="));
6180 } else if (str_begins_with (arg, "static")) {
6181 opts->static_link = TRUE;
6182 opts->no_dlsym = TRUE;
6183 } else if (str_begins_with (arg, "asmonly")) {
6184 opts->asm_only = TRUE;
6185 } else if (str_begins_with (arg, "asmwriter")) {
6186 opts->asm_writer = TRUE;
6187 } else if (str_begins_with (arg, "nodebug")) {
6188 opts->nodebug = TRUE;
6189 } else if (str_begins_with (arg, "dwarfdebug")) {
6190 opts->dwarf_debug = TRUE;
6191 } else if (str_begins_with (arg, "nopagetrampolines")) {
6192 opts->use_trampolines_page = FALSE;
6193 } else if (str_begins_with (arg, "ntrampolines=")) {
6194 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6195 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6196 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6197 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6198 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6199 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6200 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6201 } else if (str_begins_with (arg, "autoreg")) {
6202 opts->autoreg = TRUE;
6203 } else if (str_begins_with (arg, "tool-prefix=")) {
6204 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6205 } else if (str_begins_with (arg, "soft-debug")) {
6206 opts->soft_debug = TRUE;
6207 } else if (str_begins_with (arg, "direct-pinvoke")) {
6208 opts->direct_pinvoke = TRUE;
6209 } else if (str_begins_with (arg, "direct-icalls")) {
6210 opts->direct_icalls = TRUE;
6211 #if defined(TARGET_ARM)
6212 } else if (str_begins_with (arg, "iphone-abi")) {
6213 // older full-aot users did depend on this.
6215 } else if (str_begins_with (arg, "no-direct-calls")) {
6216 opts->no_direct_calls = TRUE;
6217 } else if (str_begins_with (arg, "print-skipped")) {
6218 opts->print_skipped_methods = TRUE;
6219 } else if (str_begins_with (arg, "stats")) {
6221 } else if (str_begins_with (arg, "no-instances")) {
6222 opts->no_instances = TRUE;
6223 } else if (str_begins_with (arg, "log-generics")) {
6224 opts->log_generics = TRUE;
6225 } else if (str_begins_with (arg, "mtriple=")) {
6226 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6227 } else if (str_begins_with (arg, "llvm-path=")) {
6228 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6229 } else if (str_begins_with (arg, "readonly-value=")) {
6230 add_readonly_value (opts, arg + strlen ("readonly-value="));
6231 } else if (str_begins_with (arg, "info")) {
6232 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6234 } else if (str_begins_with (arg, "gc-maps")) {
6235 mini_gc_enable_gc_maps_for_aot ();
6236 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6237 printf ("Supported options for --aot:\n");
6238 printf (" outfile=\n");
6239 printf (" save-temps\n");
6240 printf (" keep-temps\n");
6241 printf (" write-symbols\n");
6242 printf (" metadata-only\n");
6243 printf (" bind-to-runtime-version\n");
6245 printf (" threads=\n");
6246 printf (" static\n");
6247 printf (" asmonly\n");
6248 printf (" asmwriter\n");
6249 printf (" nodebug\n");
6250 printf (" dwarfdebug\n");
6251 printf (" ntrampolines=\n");
6252 printf (" nrgctx-trampolines=\n");
6253 printf (" nimt-trampolines=\n");
6254 printf (" ngsharedvt-trampolines=\n");
6255 printf (" autoreg\n");
6256 printf (" tool-prefix=\n");
6257 printf (" readonly-value=\n");
6258 printf (" soft-debug\n");
6259 printf (" gc-maps\n");
6260 printf (" print-skipped\n");
6261 printf (" no-instances\n");
6262 printf (" stats\n");
6264 printf (" help/?\n");
6267 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6272 if (opts->use_trampolines_page) {
6273 opts->ntrampolines = 0;
6274 opts->nrgctx_trampolines = 0;
6275 opts->nimt_trampolines = 0;
6276 opts->ngsharedvt_arg_trampolines = 0;
6282 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6284 MonoMethod *method = (MonoMethod*)key;
6285 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6286 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6287 MonoAotCompile *acfg = user_data;
6289 new_ji->image = ji->image;
6290 new_ji->token = ji->token;
6291 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6295 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6297 if (klass->type_token)
6299 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6302 return can_encode_class (acfg, klass->element_class);
6307 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6309 if (method->wrapper_type) {
6310 switch (method->wrapper_type) {
6311 case MONO_WRAPPER_NONE:
6312 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6313 case MONO_WRAPPER_XDOMAIN_INVOKE:
6314 case MONO_WRAPPER_STFLD:
6315 case MONO_WRAPPER_LDFLD:
6316 case MONO_WRAPPER_LDFLDA:
6317 case MONO_WRAPPER_LDFLD_REMOTE:
6318 case MONO_WRAPPER_STFLD_REMOTE:
6319 case MONO_WRAPPER_STELEMREF:
6320 case MONO_WRAPPER_ISINST:
6321 case MONO_WRAPPER_PROXY_ISINST:
6322 case MONO_WRAPPER_ALLOC:
6323 case MONO_WRAPPER_REMOTING_INVOKE:
6324 case MONO_WRAPPER_UNKNOWN:
6325 case MONO_WRAPPER_WRITE_BARRIER:
6326 case MONO_WRAPPER_DELEGATE_INVOKE:
6327 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6328 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6329 case MONO_WRAPPER_SYNCHRONIZED:
6331 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6332 case MONO_WRAPPER_CASTCLASS: {
6333 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6342 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6346 if (!method->token) {
6347 /* The method is part of a constructed type like Int[,].Set (). */
6348 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6349 if (method->klass->rank)
6359 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6361 switch (patch_info->type) {
6362 case MONO_PATCH_INFO_METHOD:
6363 case MONO_PATCH_INFO_METHODCONST: {
6364 MonoMethod *method = patch_info->data.method;
6366 return can_encode_method (acfg, method);
6368 case MONO_PATCH_INFO_VTABLE:
6369 case MONO_PATCH_INFO_CLASS_INIT:
6370 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6371 case MONO_PATCH_INFO_CLASS:
6372 case MONO_PATCH_INFO_IID:
6373 case MONO_PATCH_INFO_ADJUSTED_IID:
6374 if (!can_encode_class (acfg, patch_info->data.klass)) {
6375 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6379 case MONO_PATCH_INFO_RGCTX_FETCH: {
6380 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6382 if (!can_encode_method (acfg, entry->method))
6384 if (!can_encode_patch (acfg, entry->data))
6398 * AOT compile a given method.
6399 * This function might be called by multiple threads, so it must be thread-safe.
6402 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6405 MonoJumpInfo *patch_info;
6408 MonoMethod *wrapped;
6410 if (acfg->aot_opts.metadata_only)
6413 mono_acfg_lock (acfg);
6414 index = get_method_index (acfg, method);
6415 mono_acfg_unlock (acfg);
6417 /* fixme: maybe we can also precompile wrapper methods */
6418 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6419 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6420 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6421 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6425 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6428 wrapped = mono_marshal_method_from_wrapper (method);
6429 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6430 // FIXME: The wrapper should be generic too, but it is not
6433 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6436 InterlockedIncrement (&acfg->stats.mcount);
6439 if (method->is_generic || method->klass->generic_container) {
6440 InterlockedIncrement (&acfg->stats.genericcount);
6445 //acfg->aot_opts.print_skipped_methods = TRUE;
6448 * Since these methods are the only ones which are compiled with
6449 * AOT support, and they are not used by runtime startup/shutdown code,
6450 * the runtime will not see AOT methods during AOT compilation,so it
6451 * does not need to support them by creating a fake GOT etc.
6453 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
6454 mono_loader_clear_error ();
6456 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6457 if (acfg->aot_opts.print_skipped_methods)
6458 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6459 InterlockedIncrement (&acfg->stats.genericcount);
6462 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6463 if (acfg->aot_opts.print_skipped_methods)
6464 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6465 /* Let the exception happen at runtime */
6469 if (cfg->disable_aot) {
6470 if (acfg->aot_opts.print_skipped_methods)
6471 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6472 InterlockedIncrement (&acfg->stats.ocount);
6473 mono_destroy_compile (cfg);
6476 cfg->method_index = index;
6478 /* Nullify patches which need no aot processing */
6479 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6480 switch (patch_info->type) {
6481 case MONO_PATCH_INFO_LABEL:
6482 case MONO_PATCH_INFO_BB:
6483 patch_info->type = MONO_PATCH_INFO_NONE;
6490 /* Collect method->token associations from the cfg */
6491 mono_acfg_lock (acfg);
6492 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6493 mono_acfg_unlock (acfg);
6496 * Check for absolute addresses.
6499 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6500 switch (patch_info->type) {
6501 case MONO_PATCH_INFO_ABS:
6502 /* unable to handle this */
6511 if (acfg->aot_opts.print_skipped_methods)
6512 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6513 InterlockedIncrement (&acfg->stats.abscount);
6514 mono_destroy_compile (cfg);
6518 /* Lock for the rest of the code */
6519 mono_acfg_lock (acfg);
6522 * Check for methods/klasses we can't encode.
6525 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6526 if (!can_encode_patch (acfg, patch_info))
6531 if (acfg->aot_opts.print_skipped_methods)
6532 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6533 acfg->stats.ocount++;
6534 mono_destroy_compile (cfg);
6535 mono_acfg_unlock (acfg);
6539 /* Adds generic instances referenced by this method */
6541 * The depth is used to avoid infinite loops when generic virtual recursion is
6544 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6545 if (!acfg->aot_opts.no_instances && depth < 32) {
6546 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6547 switch (patch_info->type) {
6548 case MONO_PATCH_INFO_METHOD: {
6549 MonoMethod *m = patch_info->data.method;
6550 if (m->is_inflated) {
6551 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6552 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6553 !method_has_type_vars (m)) {
6554 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6555 if (acfg->aot_opts.full_aot)
6556 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6558 add_extra_method_with_depth (acfg, m, depth + 1);
6559 add_types_from_method_header (acfg, m);
6562 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6564 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6565 add_extra_method_with_depth (acfg, m, depth + 1);
6568 case MONO_PATCH_INFO_VTABLE: {
6569 MonoClass *klass = patch_info->data.klass;
6571 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6572 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6575 case MONO_PATCH_INFO_SFLDA: {
6576 MonoClass *klass = patch_info->data.field->parent;
6578 /* The .cctor needs to run at runtime. */
6579 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6580 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6589 /* Determine whenever the method has GOT slots */
6590 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6591 switch (patch_info->type) {
6592 case MONO_PATCH_INFO_GOT_OFFSET:
6593 case MONO_PATCH_INFO_NONE:
6594 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6596 case MONO_PATCH_INFO_IMAGE:
6597 /* The assembly is stored in GOT slot 0 */
6598 if (patch_info->data.image != acfg->image)
6599 cfg->has_got_slots = TRUE;
6602 if (!is_plt_patch (patch_info))
6603 cfg->has_got_slots = TRUE;
6608 if (!cfg->has_got_slots)
6609 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6612 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6614 /* Make a copy of the patch info which is in the mempool */
6616 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6618 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6619 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6622 patches = new_patch_info;
6624 patches_end->next = new_patch_info;
6625 patches_end = new_patch_info;
6627 cfg->patch_info = patches;
6629 /* Make a copy of the unwind info */
6631 GSList *l, *unwind_ops;
6635 for (l = cfg->unwind_ops; l; l = l->next) {
6636 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6637 memcpy (op, l->data, sizeof (MonoUnwindOp));
6638 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6640 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6642 /* Make a copy of the argument/local info */
6644 MonoInst **args, **locals;
6645 MonoMethodSignature *sig;
6646 MonoMethodHeader *header;
6649 sig = mono_method_signature (method);
6650 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6651 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6652 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6653 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6657 header = mono_method_get_header (method);
6658 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6659 for (i = 0; i < header->num_locals; ++i) {
6660 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6661 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6663 cfg->locals = locals;
6666 /* Free some fields used by cfg to conserve memory */
6667 mono_mempool_destroy (cfg->mempool);
6668 cfg->mempool = NULL;
6669 g_free (cfg->varinfo);
6670 cfg->varinfo = NULL;
6674 mono_regstate_free (cfg->rs);
6678 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6680 while (index >= acfg->cfgs_size) {
6681 MonoCompile **new_cfgs;
6684 new_size = acfg->cfgs_size * 2;
6685 new_cfgs = g_new0 (MonoCompile*, new_size);
6686 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6687 g_free (acfg->cfgs);
6688 acfg->cfgs = new_cfgs;
6689 acfg->cfgs_size = new_size;
6691 acfg->cfgs [index] = cfg;
6693 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6696 if (cfg->orig_method->wrapper_type)
6697 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6700 mono_acfg_unlock (acfg);
6702 InterlockedIncrement (&acfg->stats.ccount);
6706 compile_thread_main (gpointer *user_data)
6708 MonoDomain *domain = user_data [0];
6709 MonoAotCompile *acfg = user_data [1];
6710 GPtrArray *methods = user_data [2];
6713 mono_thread_attach (domain);
6715 for (i = 0; i < methods->len; ++i)
6716 compile_method (acfg, g_ptr_array_index (methods, i));
6720 load_profile_files (MonoAotCompile *acfg)
6724 int file_index, res, method_index, i;
6727 GList *unordered, *l;
6732 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6734 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6739 infile = fopen (tmp, "r");
6742 printf ("Using profile data file '%s'\n", tmp);
6747 res = fscanf (infile, "%32s\n", ver);
6748 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6749 printf ("Profile file has wrong version or invalid.\n");
6756 MonoMethodDesc *desc;
6759 if (fgets (name, 1023, infile) == NULL)
6762 /* Kill the newline */
6763 if (strlen (name) > 0)
6764 name [strlen (name) - 1] = '\0';
6766 desc = mono_method_desc_new (name, TRUE);
6768 method = mono_method_desc_search_in_image (desc, acfg->image);
6770 if (method && mono_method_get_token (method)) {
6771 token = mono_method_get_token (method);
6772 method_index = mono_metadata_token_index (token) - 1;
6775 for (i = 0; i < acfg->method_order->len; ++i) {
6776 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6782 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6784 //printf ("No method found matching '%s'.\n", name);
6790 /* Add missing methods */
6792 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6794 for (i = 0; i < acfg->method_order->len; ++i) {
6795 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6801 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6803 unordered = g_list_reverse (unordered);
6804 for (l = unordered; l; l = l->next)
6805 g_ptr_array_add (acfg->method_order, l->data);
6808 /* Used by the LLVM backend */
6810 mono_aot_get_got_offset (MonoJumpInfo *ji)
6812 return get_got_offset (llvm_acfg, ji);
6816 mono_aot_get_method_name (MonoCompile *cfg)
6818 if (llvm_acfg->aot_opts.static_link)
6819 /* Include the assembly name too to avoid duplicate symbol errors */
6820 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6822 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6826 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6828 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6829 MonoPltEntry *plt_entry;
6832 ji->data.target = data;
6834 if (!can_encode_patch (llvm_acfg, ji))
6837 plt_entry = get_plt_entry (llvm_acfg, ji);
6838 plt_entry->llvm_used = TRUE;
6840 #if defined(TARGET_MACH)
6841 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6843 return g_strdup_printf (plt_entry->llvm_symbol);
6848 mono_aot_get_method_index (MonoMethod *method)
6850 g_assert (llvm_acfg);
6851 return get_method_index (llvm_acfg, method);
6855 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6859 mono_acfg_lock (llvm_acfg);
6860 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6861 mono_acfg_unlock (llvm_acfg);
6871 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6875 emit_llvm_file (MonoAotCompile *acfg)
6877 char *command, *opts, *tempbc;
6879 MonoJumpInfo *patch_info;
6882 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6886 /* Compute the final size of the got */
6887 for (i = 0; i < acfg->nmethods; ++i) {
6888 if (acfg->cfgs [i]) {
6889 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6890 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6891 if (!is_plt_patch (patch_info))
6892 get_got_offset (acfg, patch_info);
6894 get_plt_entry (acfg, patch_info);
6900 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6902 if (acfg->aot_opts.full_aot) {
6906 * Need to add the got entries used by the trampolines.
6907 * This is only a conservative approximation.
6909 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6910 /* For the generic + rgctx trampolines */
6911 acfg->final_got_size += 400;
6912 /* For the specific trampolines */
6913 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6914 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6919 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
6920 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6924 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6925 * a lot of time, and doesn't seem to save much space.
6926 * The following optimizations cannot be enabled:
6928 * - 'jump-threading' changes our blockaddress references to int constants.
6929 * - 'basiccg' fails because it contains:
6930 * if (CS && !isa<IntrinsicInst>(II)) {
6931 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
6932 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
6933 * The opt list below was produced by taking the output of:
6934 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
6935 * then removing tailcallelim + the global opts.
6936 * strip-dead-prototypes deletes unused intrinsics definitions.
6938 opts = g_strdup ("-instcombine -simplifycfg");
6939 //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");
6940 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");
6942 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
6943 printf ("Executing opt: %s\n", command);
6944 if (system (command) != 0) {
6950 if (!acfg->llc_args)
6951 acfg->llc_args = g_string_new ("");
6953 /* Verbose asm slows down llc greatly */
6954 g_string_append (acfg->llc_args, " -asm-verbose=false");
6956 if (acfg->aot_opts.mtriple)
6957 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
6959 #if defined(TARGET_MACH) && defined(TARGET_ARM)
6960 /* ios requires PIC code now */
6961 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6963 if (llvm_acfg->aot_opts.static_link)
6964 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
6966 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6968 unlink (acfg->tmpfname);
6970 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpbasename);
6972 printf ("Executing llc: %s\n", command);
6974 if (system (command) != 0) {
6981 emit_code (MonoAotCompile *acfg)
6983 int oindex, i, prev_index;
6986 #if defined(TARGET_POWERPC64)
6987 sprintf (symbol, ".Lgot_addr");
6988 emit_section_change (acfg, ".text", 0);
6989 emit_alignment (acfg, 8);
6990 emit_label (acfg, symbol);
6991 emit_pointer (acfg, acfg->got_symbol);
6995 * This global symbol is used to compute the address of each method using the
6996 * code_offsets array. It is also used to compute the memory ranges occupied by
6997 * AOT code, so it must be equal to the address of the first emitted method.
6999 emit_section_change (acfg, ".text", 0);
7000 emit_alignment (acfg, 8);
7002 for (i = 0; i < acfg->nmethods; ++i) {
7003 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7004 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7009 if (!acfg->methods_symbol) {
7010 sprintf (symbol, "methods");
7011 emit_label (acfg, symbol);
7012 acfg->methods_symbol = g_strdup (symbol);
7016 * Emit some padding so the local symbol for the first method doesn't have the
7017 * same address as 'methods'.
7019 #if defined(__default_codegen__)
7020 emit_zero_bytes (acfg, 16);
7021 #elif defined(__native_client_codegen__)
7023 const int kPaddingSize = 16;
7024 guint8 pad_buffer[kPaddingSize];
7025 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7026 emit_bytes (acfg, pad_buffer, kPaddingSize);
7030 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7034 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7036 cfg = acfg->cfgs [i];
7041 method = cfg->orig_method;
7043 /* Emit unbox trampoline */
7044 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7045 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7047 emit_section_change (acfg, ".text", 0);
7048 #ifdef __native_client_codegen__
7049 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7052 if (acfg->thumb_mixed && cfg->compile_llvm) {
7053 emit_set_thumb_mode (acfg);
7054 fprintf (acfg->fp, "\n.thumb_func\n");
7057 emit_label (acfg, symbol);
7059 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7061 if (acfg->thumb_mixed && cfg->compile_llvm) {
7062 emit_set_arm_mode (acfg);
7066 if (cfg->compile_llvm)
7067 acfg->stats.llvm_count ++;
7069 emit_method_code (acfg, cfg);
7072 sprintf (symbol, "methods_end");
7073 emit_section_change (acfg, ".text", 0);
7074 emit_alignment (acfg, 8);
7075 emit_label (acfg, symbol);
7076 /* To distinguish it from the next symbol */
7077 emit_int32 (acfg, 0);
7080 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7081 * from optimizing them away, since it doesn't see that code_offsets references them.
7082 * JITted methods don't need this since they are referenced using assembler local
7084 * FIXME: This is why write-symbols doesn't work on OSX ?
7086 if (acfg->llvm && acfg->need_no_dead_strip) {
7087 fprintf (acfg->fp, "\n");
7088 for (i = 0; i < acfg->nmethods; ++i) {
7089 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7090 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7095 if (acfg->direct_method_addresses) {
7096 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7099 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7100 * This is PIE code, and the linker can update it if needed.
7102 sprintf (symbol, "method_addresses");
7103 emit_section_change (acfg, ".text", 1);
7104 emit_alignment (acfg, 8);
7105 emit_label (acfg, symbol);
7106 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7107 emit_unset_mode (acfg);
7108 if (acfg->need_no_dead_strip)
7109 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7111 for (i = 0; i < acfg->nmethods; ++i) {
7112 if (acfg->cfgs [i]) {
7113 if (acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm)
7114 fprintf (acfg->fp, "\tblx %s\n", acfg->cfgs [i]->asm_symbol);
7116 fprintf (acfg->fp, "\tbl %s\n", acfg->cfgs [i]->asm_symbol);
7118 fprintf (acfg->fp, "\tbl method_addresses\n");
7122 sprintf (symbol, "method_addresses_end");
7123 emit_label (acfg, symbol);
7126 sprintf (symbol, "code_offsets");
7127 emit_section_change (acfg, RODATA_SECT, 1);
7128 emit_alignment (acfg, 8);
7129 emit_label (acfg, symbol);
7130 emit_int32 (acfg, 0);
7132 sprintf (symbol, "code_offsets");
7133 emit_section_change (acfg, RODATA_SECT, 1);
7134 emit_alignment (acfg, 8);
7135 emit_label (acfg, symbol);
7137 acfg->stats.offsets_size += acfg->nmethods * 4;
7139 for (i = 0; i < acfg->nmethods; ++i) {
7140 if (acfg->cfgs [i]) {
7141 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7143 emit_int32 (acfg, 0xffffffff);
7148 sprintf (symbol, "code_offsets");
7149 emit_section_change (acfg, RODATA_SECT, 1);
7150 emit_alignment (acfg, 8);
7151 emit_label (acfg, symbol);
7153 acfg->stats.offsets_size += acfg->nmethods * 4;
7155 for (i = 0; i < acfg->nmethods; ++i) {
7156 if (acfg->cfgs [i]) {
7157 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7159 emit_int32 (acfg, 0xffffffff);
7165 /* Emit a sorted table mapping methods to their unbox trampolines */
7166 sprintf (symbol, "unbox_trampolines");
7167 if (acfg->direct_method_addresses)
7168 emit_section_change (acfg, ".text", 0);
7170 emit_section_change (acfg, RODATA_SECT, 0);
7171 emit_alignment (acfg, 8);
7172 emit_label (acfg, symbol);
7175 for (i = 0; i < acfg->nmethods; ++i) {
7180 cfg = acfg->cfgs [i];
7184 method = cfg->orig_method;
7186 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7187 index = get_method_index (acfg, method);
7188 sprintf (symbol, "ut_%d", index);
7190 emit_int32 (acfg, index);
7191 if (acfg->direct_method_addresses) {
7192 emit_unset_mode (acfg);
7193 if (acfg->thumb_mixed && cfg->compile_llvm)
7194 fprintf (acfg->fp, "\n\tblx %s\n", symbol);
7196 fprintf (acfg->fp, "\n\tbl %s\n", symbol);
7198 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7200 /* Make sure the table is sorted by index */
7201 g_assert (index > prev_index);
7205 sprintf (symbol, "unbox_trampolines_end");
7206 emit_label (acfg, symbol);
7207 emit_int32 (acfg, 0);
7211 emit_info (MonoAotCompile *acfg)
7217 offsets = g_new0 (gint32, acfg->nmethods);
7219 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7220 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7222 if (acfg->cfgs [i]) {
7223 emit_method_info (acfg, acfg->cfgs [i]);
7224 offsets [i] = acfg->cfgs [i]->method_info_offset;
7230 sprintf (symbol, "method_info_offsets");
7231 emit_section_change (acfg, RODATA_SECT, 1);
7232 emit_alignment (acfg, 8);
7233 emit_label (acfg, symbol);
7235 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7240 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7242 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7243 #define mix(a,b,c) { \
7244 a -= c; a ^= rot(c, 4); c += b; \
7245 b -= a; b ^= rot(a, 6); a += c; \
7246 c -= b; c ^= rot(b, 8); b += a; \
7247 a -= c; a ^= rot(c,16); c += b; \
7248 b -= a; b ^= rot(a,19); a += c; \
7249 c -= b; c ^= rot(b, 4); b += a; \
7251 #define final(a,b,c) { \
7252 c ^= b; c -= rot(b,14); \
7253 a ^= c; a -= rot(c,11); \
7254 b ^= a; b -= rot(a,25); \
7255 c ^= b; c -= rot(b,16); \
7256 a ^= c; a -= rot(c,4); \
7257 b ^= a; b -= rot(a,14); \
7258 c ^= b; c -= rot(b,24); \
7262 mono_aot_type_hash (MonoType *t1)
7264 guint hash = t1->type;
7266 hash |= t1->byref << 6; /* do not collide with t1->type values */
7268 case MONO_TYPE_VALUETYPE:
7269 case MONO_TYPE_CLASS:
7270 case MONO_TYPE_SZARRAY:
7271 /* check if the distribution is good enough */
7272 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7274 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7275 case MONO_TYPE_ARRAY:
7276 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7277 case MONO_TYPE_GENERICINST:
7278 return ((hash << 5) - hash) ^ 0;
7285 * mono_aot_method_hash:
7287 * Return a hash code for methods which only depends on metadata.
7290 mono_aot_method_hash (MonoMethod *method)
7292 MonoMethodSignature *sig;
7296 guint32 *hashes_start, *hashes;
7298 MonoGenericInst *ginst = NULL;
7300 /* Similar to the hash in mono_method_get_imt_slot () */
7302 sig = mono_method_signature (method);
7304 if (method->is_inflated)
7305 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7307 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7308 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7309 hashes = hashes_start;
7311 /* Some wrappers are assigned to random classes */
7312 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7313 klass = method->klass;
7315 klass = mono_defaults.object_class;
7317 if (!method->wrapper_type) {
7318 char *full_name = mono_type_full_name (&klass->byval_arg);
7320 hashes [0] = mono_metadata_str_hash (full_name);
7324 hashes [0] = mono_metadata_str_hash (klass->name);
7325 hashes [1] = mono_metadata_str_hash (klass->name_space);
7327 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7328 /* The method name includes a stringified pointer */
7331 hashes [2] = mono_metadata_str_hash (method->name);
7332 hashes [3] = method->wrapper_type;
7333 hashes [4] = mono_aot_type_hash (sig->ret);
7335 for (i = 0; i < sig->param_count; i++) {
7336 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7339 for (i = 0; i < ginst->type_argc; ++i)
7340 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7342 g_assert (hindex == hashes_count);
7344 /* Setup internal state */
7345 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7347 /* Handle most of the hashes */
7348 while (hashes_count > 3) {
7357 /* Handle the last 3 hashes (all the case statements fall through) */
7358 switch (hashes_count) {
7359 case 3 : c += hashes [2];
7360 case 2 : b += hashes [1];
7361 case 1 : a += hashes [0];
7363 case 0: /* nothing left to add */
7367 free (hashes_start);
7376 * mono_aot_get_array_helper_from_wrapper;
7378 * Get the helper method in Array called by an array wrapper method.
7381 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7385 MonoGenericContext ctx;
7386 MonoType *args [16];
7387 char *mname, *iname, *s, *s2, *helper_name = NULL;
7389 prefix = "System.Collections.Generic";
7390 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7391 s2 = strstr (s, "`1.");
7397 //printf ("X: %s %s\n", iname, mname);
7399 if (!strcmp (iname, "IList"))
7400 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7402 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7403 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7405 g_free (helper_name);
7408 if (m->is_generic) {
7409 memset (&ctx, 0, sizeof (ctx));
7410 args [0] = &method->klass->element_class->byval_arg;
7411 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7412 m = mono_class_inflate_generic_method (m, &ctx);
7418 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7420 typedef struct HashEntry {
7421 guint32 key, value, index;
7422 struct HashEntry *next;
7426 * emit_extra_methods:
7428 * Emit methods which are not in the METHOD table, like wrappers.
7431 emit_extra_methods (MonoAotCompile *acfg)
7433 int i, table_size, buf_size;
7436 guint32 *info_offsets;
7439 HashEntry *entry, *new_entry;
7440 int nmethods, max_chain_length;
7443 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7445 /* Emit method info */
7447 for (i = 0; i < acfg->extra_methods->len; ++i) {
7448 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7449 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7455 p = buf = g_malloc (buf_size);
7459 method = cfg->method_to_register;
7461 encode_method_ref (acfg, method, p, &p);
7463 g_assert ((p - buf) < buf_size);
7465 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7470 * Construct a chained hash table for mapping indexes in extra_method_info to
7473 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7474 table = g_ptr_array_sized_new (table_size);
7475 for (i = 0; i < table_size; ++i)
7476 g_ptr_array_add (table, NULL);
7477 chain_lengths = g_new0 (int, table_size);
7478 max_chain_length = 0;
7479 for (i = 0; i < acfg->extra_methods->len; ++i) {
7480 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7481 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7487 key = info_offsets [i];
7488 value = get_method_index (acfg, method);
7490 hash = mono_aot_method_hash (method) % table_size;
7491 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7493 chain_lengths [hash] ++;
7494 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7496 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7497 new_entry->key = key;
7498 new_entry->value = value;
7500 entry = g_ptr_array_index (table, hash);
7501 if (entry == NULL) {
7502 new_entry->index = hash;
7503 g_ptr_array_index (table, hash) = new_entry;
7506 entry = entry->next;
7508 entry->next = new_entry;
7509 new_entry->index = table->len;
7510 g_ptr_array_add (table, new_entry);
7514 //printf ("MAX: %d\n", max_chain_length);
7516 /* Emit the table */
7517 sprintf (symbol, "extra_method_table");
7518 emit_section_change (acfg, RODATA_SECT, 0);
7519 emit_alignment (acfg, 8);
7520 emit_label (acfg, symbol);
7522 emit_int32 (acfg, table_size);
7523 for (i = 0; i < table->len; ++i) {
7524 HashEntry *entry = g_ptr_array_index (table, i);
7526 if (entry == NULL) {
7527 emit_int32 (acfg, 0);
7528 emit_int32 (acfg, 0);
7529 emit_int32 (acfg, 0);
7531 //g_assert (entry->key > 0);
7532 emit_int32 (acfg, entry->key);
7533 emit_int32 (acfg, entry->value);
7535 emit_int32 (acfg, entry->next->index);
7537 emit_int32 (acfg, 0);
7542 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7543 * This is used by mono_aot_find_jit_info ().
7545 sprintf (symbol, "extra_method_info_offsets");
7546 emit_section_change (acfg, RODATA_SECT, 0);
7547 emit_alignment (acfg, 8);
7548 emit_label (acfg, symbol);
7550 emit_int32 (acfg, acfg->extra_methods->len);
7551 for (i = 0; i < acfg->extra_methods->len; ++i) {
7552 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7554 emit_int32 (acfg, get_method_index (acfg, method));
7555 emit_int32 (acfg, info_offsets [i]);
7560 emit_exception_info (MonoAotCompile *acfg)
7566 offsets = g_new0 (gint32, acfg->nmethods);
7567 for (i = 0; i < acfg->nmethods; ++i) {
7568 if (acfg->cfgs [i]) {
7569 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7570 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7576 sprintf (symbol, "ex_info_offsets");
7577 emit_section_change (acfg, RODATA_SECT, 1);
7578 emit_alignment (acfg, 8);
7579 emit_label (acfg, symbol);
7581 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7586 emit_unwind_info (MonoAotCompile *acfg)
7592 * The unwind info contains a lot of duplicates so we emit each unique
7593 * entry once, and only store the offset from the start of the table in the
7597 sprintf (symbol, "unwind_info");
7598 emit_section_change (acfg, RODATA_SECT, 1);
7599 emit_alignment (acfg, 8);
7600 emit_label (acfg, symbol);
7602 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7603 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7604 guint8 *unwind_info;
7605 guint32 unwind_info_len;
7609 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7612 encode_value (unwind_info_len, p, &p);
7613 emit_bytes (acfg, buf, p - buf);
7614 emit_bytes (acfg, unwind_info, unwind_info_len);
7616 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7621 emit_class_info (MonoAotCompile *acfg)
7627 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7628 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7629 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7631 sprintf (symbol, "class_info_offsets");
7632 emit_section_change (acfg, RODATA_SECT, 1);
7633 emit_alignment (acfg, 8);
7634 emit_label (acfg, symbol);
7636 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7640 typedef struct ClassNameTableEntry {
7641 guint32 token, index;
7642 struct ClassNameTableEntry *next;
7643 } ClassNameTableEntry;
7646 emit_class_name_table (MonoAotCompile *acfg)
7649 guint32 token, hash;
7654 ClassNameTableEntry *entry, *new_entry;
7657 * Construct a chained hash table for mapping class names to typedef tokens.
7659 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7660 table = g_ptr_array_sized_new (table_size);
7661 for (i = 0; i < table_size; ++i)
7662 g_ptr_array_add (table, NULL);
7663 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7664 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7665 klass = mono_class_get (acfg->image, token);
7667 mono_loader_clear_error ();
7670 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7671 hash = mono_metadata_str_hash (full_name) % table_size;
7674 /* FIXME: Allocate from the mempool */
7675 new_entry = g_new0 (ClassNameTableEntry, 1);
7676 new_entry->token = token;
7678 entry = g_ptr_array_index (table, hash);
7679 if (entry == NULL) {
7680 new_entry->index = hash;
7681 g_ptr_array_index (table, hash) = new_entry;
7684 entry = entry->next;
7686 entry->next = new_entry;
7687 new_entry->index = table->len;
7688 g_ptr_array_add (table, new_entry);
7692 /* Emit the table */
7693 sprintf (symbol, "class_name_table");
7694 emit_section_change (acfg, RODATA_SECT, 0);
7695 emit_alignment (acfg, 8);
7696 emit_label (acfg, symbol);
7698 /* FIXME: Optimize memory usage */
7699 g_assert (table_size < 65000);
7700 emit_int16 (acfg, table_size);
7701 g_assert (table->len < 65000);
7702 for (i = 0; i < table->len; ++i) {
7703 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7705 if (entry == NULL) {
7706 emit_int16 (acfg, 0);
7707 emit_int16 (acfg, 0);
7709 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7711 emit_int16 (acfg, entry->next->index);
7713 emit_int16 (acfg, 0);
7719 emit_image_table (MonoAotCompile *acfg)
7725 * The image table is small but referenced in a lot of places.
7726 * So we emit it at once, and reference its elements by an index.
7729 sprintf (symbol, "image_table");
7730 emit_section_change (acfg, RODATA_SECT, 1);
7731 emit_alignment (acfg, 8);
7732 emit_label (acfg, symbol);
7734 emit_int32 (acfg, acfg->image_table->len);
7735 for (i = 0; i < acfg->image_table->len; i++) {
7736 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7737 MonoAssemblyName *aname = &image->assembly->aname;
7739 /* FIXME: Support multi-module assemblies */
7740 g_assert (image->assembly->image == image);
7742 emit_string (acfg, image->assembly_name);
7743 emit_string (acfg, image->guid);
7744 emit_string (acfg, aname->culture ? aname->culture : "");
7745 emit_string (acfg, (const char*)aname->public_key_token);
7747 emit_alignment (acfg, 8);
7748 emit_int32 (acfg, aname->flags);
7749 emit_int32 (acfg, aname->major);
7750 emit_int32 (acfg, aname->minor);
7751 emit_int32 (acfg, aname->build);
7752 emit_int32 (acfg, aname->revision);
7757 emit_got_info (MonoAotCompile *acfg)
7760 int i, first_plt_got_patch, buf_size;
7762 guint32 *got_info_offsets;
7764 /* Add the patches needed by the PLT to the GOT */
7765 acfg->plt_got_offset_base = acfg->got_offset;
7766 first_plt_got_patch = acfg->got_patches->len;
7767 for (i = 1; i < acfg->plt_offset; ++i) {
7768 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7770 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7772 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7775 acfg->got_offset += acfg->plt_offset;
7779 * - optimize offsets table.
7780 * - reduce number of exported symbols.
7781 * - emit info for a klass only once.
7782 * - determine when a method uses a GOT slot which is guaranteed to be already
7784 * - clean up and document the code.
7785 * - use String.Empty in class libs.
7788 /* Encode info required to decode shared GOT entries */
7789 buf_size = acfg->got_patches->len * 128;
7790 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7791 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7792 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7794 if (acfg->plt_offset)
7795 acfg->plt_got_info_offsets [0] = 0;
7796 for (i = 0; i < acfg->got_patches->len; ++i) {
7797 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7802 encode_value (ji->type, p, &p);
7804 encode_patch (acfg, ji, p, &p);
7805 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7806 g_assert (p - buf <= buf_size);
7807 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7809 if (i >= first_plt_got_patch)
7810 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7811 acfg->stats.got_info_size += p - buf;
7814 /* Emit got_info_offsets table */
7815 sprintf (symbol, "got_info_offsets");
7816 emit_section_change (acfg, RODATA_SECT, 1);
7817 emit_alignment (acfg, 8);
7818 emit_label (acfg, symbol);
7820 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7821 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7825 emit_got (MonoAotCompile *acfg)
7830 /* Don't make GOT global so accesses to it don't need relocations */
7831 sprintf (symbol, "%s", acfg->got_symbol);
7832 emit_section_change (acfg, ".bss", 0);
7833 emit_alignment (acfg, 8);
7834 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7835 emit_label (acfg, symbol);
7836 if (acfg->got_offset > 0)
7837 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7839 sprintf (symbol, "got_end");
7840 emit_label (acfg, symbol);
7844 typedef struct GlobalsTableEntry {
7845 guint32 value, index;
7846 struct GlobalsTableEntry *next;
7847 } GlobalsTableEntry;
7850 emit_globals (MonoAotCompile *acfg)
7856 GlobalsTableEntry *entry, *new_entry;
7858 if (!acfg->aot_opts.static_link)
7862 * When static linking, we emit a table containing our globals.
7866 * Construct a chained hash table for mapping global names to their index in
7867 * the globals table.
7869 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7870 table = g_ptr_array_sized_new (table_size);
7871 for (i = 0; i < table_size; ++i)
7872 g_ptr_array_add (table, NULL);
7873 for (i = 0; i < acfg->globals->len; ++i) {
7874 char *name = g_ptr_array_index (acfg->globals, i);
7876 hash = mono_metadata_str_hash (name) % table_size;
7878 /* FIXME: Allocate from the mempool */
7879 new_entry = g_new0 (GlobalsTableEntry, 1);
7880 new_entry->value = i;
7882 entry = g_ptr_array_index (table, hash);
7883 if (entry == NULL) {
7884 new_entry->index = hash;
7885 g_ptr_array_index (table, hash) = new_entry;
7888 entry = entry->next;
7890 entry->next = new_entry;
7891 new_entry->index = table->len;
7892 g_ptr_array_add (table, new_entry);
7896 /* Emit the table */
7897 sprintf (symbol, ".Lglobals_hash");
7898 emit_section_change (acfg, RODATA_SECT, 0);
7899 emit_alignment (acfg, 8);
7900 emit_label (acfg, symbol);
7902 /* FIXME: Optimize memory usage */
7903 g_assert (table_size < 65000);
7904 emit_int16 (acfg, table_size);
7905 for (i = 0; i < table->len; ++i) {
7906 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7908 if (entry == NULL) {
7909 emit_int16 (acfg, 0);
7910 emit_int16 (acfg, 0);
7912 emit_int16 (acfg, entry->value + 1);
7914 emit_int16 (acfg, entry->next->index);
7916 emit_int16 (acfg, 0);
7920 /* Emit the names */
7921 for (i = 0; i < acfg->globals->len; ++i) {
7922 char *name = g_ptr_array_index (acfg->globals, i);
7924 sprintf (symbol, "name_%d", i);
7925 emit_section_change (acfg, RODATA_SECT, 1);
7927 emit_alignment (acfg, 4);
7929 emit_label (acfg, symbol);
7930 emit_string (acfg, name);
7933 /* Emit the globals table */
7934 sprintf (symbol, "globals");
7935 emit_section_change (acfg, ".data", 0);
7936 /* This is not a global, since it is accessed by the init function */
7937 emit_alignment (acfg, 8);
7938 emit_label (acfg, symbol);
7940 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
7941 emit_pointer (acfg, symbol);
7943 for (i = 0; i < acfg->globals->len; ++i) {
7944 char *name = g_ptr_array_index (acfg->globals, i);
7946 sprintf (symbol, "name_%d", i);
7947 emit_pointer (acfg, symbol);
7949 sprintf (symbol, "%s", name);
7950 emit_pointer (acfg, symbol);
7952 /* Null terminate the table */
7953 emit_int32 (acfg, 0);
7954 emit_int32 (acfg, 0);
7958 emit_autoreg (MonoAotCompile *acfg)
7963 * Emit a function into the .ctor section which will be called by the ELF
7964 * loader to register this module with the runtime.
7966 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
7969 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
7971 arch_emit_autoreg (acfg, symbol);
7977 emit_mem_end (MonoAotCompile *acfg)
7981 sprintf (symbol, "mem_end");
7982 emit_section_change (acfg, ".text", 1);
7983 emit_alignment (acfg, 8);
7984 emit_label (acfg, symbol);
7988 * Emit a structure containing all the information not stored elsewhere.
7991 emit_file_info (MonoAotCompile *acfg)
7996 const char *gc_name;
7999 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8001 if (acfg->aot_opts.bind_to_runtime_version) {
8002 build_info = mono_get_runtime_build_info ();
8003 emit_string_symbol (acfg, "runtime_version", build_info);
8004 g_free (build_info);
8006 emit_string_symbol (acfg, "runtime_version", "");
8009 /* Emit a string holding the assembly name */
8010 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8013 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8016 gc_name = mono_gc_get_gc_name ();
8017 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8019 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8020 emit_section_change (acfg, ".data", 0);
8021 emit_alignment (acfg, 8);
8022 emit_label (acfg, symbol);
8023 if (!acfg->aot_opts.static_link)
8024 emit_global (acfg, symbol, FALSE);
8026 /* The data emitted here must match MonoAotFileInfo. */
8028 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8029 emit_int32 (acfg, 0);
8032 * We emit pointers to our data structures instead of emitting global symbols which
8033 * point to them, to reduce the number of globals, and because using globals leads to
8034 * various problems (i.e. arm/thumb).
8036 emit_pointer (acfg, acfg->got_symbol);
8037 emit_pointer (acfg, acfg->methods_symbol);
8040 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8042 emit_pointer (acfg, "mono_eh_frame");
8044 emit_pointer (acfg, NULL);
8046 emit_pointer (acfg, "blob");
8047 emit_pointer (acfg, "class_name_table");
8048 emit_pointer (acfg, "class_info_offsets");
8049 emit_pointer (acfg, "method_info_offsets");
8050 emit_pointer (acfg, "ex_info_offsets");
8051 emit_pointer (acfg, "code_offsets");
8052 if (acfg->direct_method_addresses)
8053 emit_pointer (acfg, "method_addresses");
8055 emit_pointer (acfg, NULL);
8056 emit_pointer (acfg, "extra_method_info_offsets");
8057 emit_pointer (acfg, "extra_method_table");
8058 emit_pointer (acfg, "got_info_offsets");
8059 emit_pointer (acfg, "methods_end");
8060 emit_pointer (acfg, "unwind_info");
8061 emit_pointer (acfg, "mem_end");
8062 emit_pointer (acfg, "image_table");
8063 emit_pointer (acfg, "plt");
8064 emit_pointer (acfg, "plt_end");
8065 emit_pointer (acfg, "assembly_guid");
8066 emit_pointer (acfg, "runtime_version");
8067 if (acfg->num_trampoline_got_entries) {
8068 emit_pointer (acfg, "specific_trampolines");
8069 emit_pointer (acfg, "static_rgctx_trampolines");
8070 emit_pointer (acfg, "imt_thunks");
8071 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8073 emit_pointer (acfg, NULL);
8074 emit_pointer (acfg, NULL);
8075 emit_pointer (acfg, NULL);
8076 emit_pointer (acfg, NULL);
8078 if (acfg->thumb_mixed) {
8079 emit_pointer (acfg, "thumb_end");
8081 emit_pointer (acfg, NULL);
8083 if (acfg->aot_opts.static_link) {
8084 emit_pointer (acfg, "globals");
8086 emit_pointer (acfg, NULL);
8088 emit_pointer (acfg, "assembly_name");
8089 emit_pointer (acfg, "unbox_trampolines");
8090 emit_pointer (acfg, "unbox_trampolines_end");
8092 emit_int32 (acfg, acfg->plt_got_offset_base);
8093 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8094 emit_int32 (acfg, acfg->plt_offset);
8095 emit_int32 (acfg, acfg->nmethods);
8096 emit_int32 (acfg, acfg->flags);
8097 emit_int32 (acfg, acfg->opts);
8098 emit_int32 (acfg, acfg->simd_opts);
8099 emit_int32 (acfg, gc_name_offset);
8101 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8102 emit_int32 (acfg, acfg->num_trampolines [i]);
8103 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8104 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8105 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8106 emit_int32 (acfg, acfg->trampoline_size [i]);
8107 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8109 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8114 memset (&t, 0, sizeof (MonoType));
8115 t.type = MONO_TYPE_R8;
8116 mono_type_size (&t, &align);
8117 emit_int32 (acfg, align);
8119 memset (&t, 0, sizeof (MonoType));
8120 t.type = MONO_TYPE_I8;
8121 mono_type_size (&t, &align);
8123 emit_int32 (acfg, align);
8126 emit_int32 (acfg, __alignof__ (double));
8127 emit_int32 (acfg, __alignof__ (gint64));
8129 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8130 emit_int32 (acfg, acfg->tramp_page_size);
8131 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8132 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8134 if (acfg->aot_opts.static_link) {
8138 * Emit a global symbol which can be passed by an embedding app to
8139 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8142 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8144 /* Get rid of characters which cannot occur in symbols */
8146 for (p = symbol; *p; ++p) {
8147 if (!(isalnum (*p) || *p == '_'))
8150 acfg->static_linking_symbol = g_strdup (symbol);
8151 emit_global_inner (acfg, symbol, FALSE);
8152 emit_alignment (acfg, sizeof (gpointer));
8153 emit_label (acfg, symbol);
8154 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8159 emit_blob (MonoAotCompile *acfg)
8163 sprintf (symbol, "blob");
8164 emit_section_change (acfg, RODATA_SECT, 1);
8165 emit_alignment (acfg, 8);
8166 emit_label (acfg, symbol);
8168 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8172 emit_objc_selectors (MonoAotCompile *acfg)
8176 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8181 * cat > foo.m << EOF
8184 * return @selector(print:);
8189 img_writer_emit_unset_mode (acfg->w);
8190 g_assert (acfg->fp);
8191 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8192 fprintf (acfg->fp, ".align 2\n");
8193 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8194 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8195 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8197 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8198 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8199 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8200 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8203 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8204 fprintf (acfg->fp, ".align 2\n");
8205 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8206 fprintf (acfg->fp, ".long 0\n");
8207 fprintf (acfg->fp, ".long 16\n");
8211 emit_dwarf_info (MonoAotCompile *acfg)
8213 #ifdef EMIT_DWARF_INFO
8217 /* DIEs for methods */
8218 for (i = 0; i < acfg->nmethods; ++i) {
8219 MonoCompile *cfg = acfg->cfgs [i];
8224 // FIXME: LLVM doesn't define .Lme_...
8225 if (cfg->compile_llvm)
8228 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8230 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 ()));
8236 collect_methods (MonoAotCompile *acfg)
8239 MonoImage *image = acfg->image;
8241 /* Collect methods */
8242 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8244 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8246 method = mono_get_method (acfg->image, token, NULL);
8249 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8253 /* Load all methods eagerly to skip the slower lazy loading code */
8254 mono_class_setup_methods (method->klass);
8256 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8257 /* Compile the wrapper instead */
8258 /* We do this here instead of add_wrappers () because it is easy to do it here */
8259 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8263 /* FIXME: Some mscorlib methods don't have debug info */
8265 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8266 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8267 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8268 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8269 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8270 if (!mono_debug_lookup_method (method)) {
8271 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8278 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8279 add_method_with_index (acfg, method, i, FALSE);
8280 acfg->method_index ++;
8283 /* gsharedvt methods */
8284 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8286 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8288 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8291 method = mono_get_method (acfg->image, token, NULL);
8295 if (strcmp (method->name, "gshared2"))
8299 if (!strstr (method->klass->image->name, "mini"))
8302 if (method->is_generic || method->klass->generic_container) {
8303 MonoMethod *gshared;
8305 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8306 add_extra_method (acfg, gshared);
8310 add_generic_instances (acfg);
8312 if (acfg->aot_opts.full_aot)
8313 add_wrappers (acfg);
8317 compile_methods (MonoAotCompile *acfg)
8321 if (acfg->aot_opts.nthreads > 0) {
8326 gpointer *user_data;
8327 MonoMethod **methods;
8329 methods_len = acfg->methods->len;
8331 len = acfg->methods->len / acfg->aot_opts.nthreads;
8334 * Partition the list of methods into fragments, and hand it to threads to
8337 threads = g_ptr_array_new ();
8338 /* Make a copy since acfg->methods is modified by compile_method () */
8339 methods = g_new0 (MonoMethod*, methods_len);
8340 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8341 for (i = 0; i < methods_len; ++i)
8342 methods [i] = g_ptr_array_index (acfg->methods, i);
8344 while (i < methods_len) {
8345 frag = g_ptr_array_new ();
8346 for (j = 0; j < len; ++j) {
8347 if (i < methods_len) {
8348 g_ptr_array_add (frag, methods [i]);
8353 user_data = g_new0 (gpointer, 3);
8354 user_data [0] = mono_domain_get ();
8355 user_data [1] = acfg;
8356 user_data [2] = frag;
8358 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
8359 g_ptr_array_add (threads, handle);
8363 for (i = 0; i < threads->len; ++i) {
8364 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8370 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8371 for (i = methods_len; i < acfg->methods->len; ++i) {
8372 /* This can new methods to acfg->methods */
8373 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8378 compile_asm (MonoAotCompile *acfg)
8380 char *command, *objfile;
8381 char *outfile_name, *tmp_outfile_name;
8382 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8384 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8385 #define AS_OPTIONS "--64"
8386 #elif defined(TARGET_POWERPC64)
8387 #define AS_OPTIONS "-a64 -mppc64"
8388 #define LD_OPTIONS "-m elf64ppc"
8389 #elif defined(sparc) && SIZEOF_VOID_P == 8
8390 #define AS_OPTIONS "-xarch=v9"
8391 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8392 #define AS_OPTIONS "-arch i386 -W"
8394 #define AS_OPTIONS ""
8397 #ifdef __native_client_codegen__
8398 #if defined(TARGET_AMD64)
8399 #define AS_NAME "nacl64-as"
8401 #define AS_NAME "nacl-as"
8403 #elif defined(TARGET_OSX)
8404 #define AS_NAME "clang -c -x assembler"
8406 #define AS_NAME "as"
8410 #define LD_OPTIONS ""
8414 #define LD_NAME "ld -shared -G"
8415 #elif defined(__ppc__) && defined(TARGET_MACH)
8416 #define LD_NAME "gcc -dynamiclib"
8417 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8418 #define LD_NAME "clang --shared"
8419 #elif defined(HOST_WIN32)
8420 #define LD_NAME "gcc -shared --dll"
8421 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8422 #define LD_NAME "clang -m32 -dynamiclib"
8425 if (acfg->aot_opts.asm_only) {
8426 printf ("Output file: '%s'.\n", acfg->tmpfname);
8427 if (acfg->aot_opts.static_link)
8428 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8432 if (acfg->aot_opts.static_link) {
8433 if (acfg->aot_opts.outfile)
8434 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8436 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8438 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8440 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);
8441 printf ("Executing the native assembler: %s\n", command);
8442 if (system (command) != 0) {
8450 if (acfg->aot_opts.static_link) {
8451 printf ("Output file: '%s'.\n", objfile);
8452 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8457 if (acfg->aot_opts.outfile)
8458 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8460 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8462 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8465 command = g_strdup_printf ("%s -o %s %s.o", LD_NAME, tmp_outfile_name, acfg->tmpfname);
8467 command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8469 printf ("Executing the native linker: %s\n", command);
8470 if (system (command) != 0) {
8471 g_free (tmp_outfile_name);
8472 g_free (outfile_name);
8480 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8481 printf ("Stripping the binary: %s\n", com);
8485 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8487 * gas generates 'mapping symbols' each time code and data is mixed, which
8488 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8490 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8491 printf ("Stripping the binary: %s\n", command);
8492 if (system (command) != 0) {
8493 g_free (tmp_outfile_name);
8494 g_free (outfile_name);
8501 rename (tmp_outfile_name, outfile_name);
8503 #if defined(TARGET_MACH)
8504 command = g_strdup_printf ("dsymutil %s", outfile_name);
8505 printf ("Executing dsymutil: %s\n", command);
8506 if (system (command) != 0) {
8511 if (!acfg->aot_opts.save_temps)
8514 g_free (tmp_outfile_name);
8515 g_free (outfile_name);
8518 if (acfg->aot_opts.save_temps)
8519 printf ("Retained input file.\n");
8521 unlink (acfg->tmpfname);
8526 static MonoAotCompile*
8527 acfg_create (MonoAssembly *ass, guint32 opts)
8529 MonoImage *image = ass->image;
8530 MonoAotCompile *acfg;
8533 acfg = g_new0 (MonoAotCompile, 1);
8534 acfg->methods = g_ptr_array_new ();
8535 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8536 acfg->method_depth = g_hash_table_new (NULL, NULL);
8537 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8538 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8539 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8540 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8541 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8542 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8543 acfg->got_patches = g_ptr_array_new ();
8544 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8545 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8546 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8547 acfg->image_hash = g_hash_table_new (NULL, NULL);
8548 acfg->image_table = g_ptr_array_new ();
8549 acfg->globals = g_ptr_array_new ();
8550 acfg->image = image;
8552 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8553 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8554 acfg->mempool = mono_mempool_new ();
8555 acfg->extra_methods = g_ptr_array_new ();
8556 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8557 acfg->unwind_ops = g_ptr_array_new ();
8558 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8559 acfg->method_order = g_ptr_array_new ();
8560 acfg->export_names = g_hash_table_new (NULL, NULL);
8561 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8562 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8563 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8564 InitializeCriticalSection (&acfg->mutex);
8570 acfg_free (MonoAotCompile *acfg)
8574 img_writer_destroy (acfg->w);
8575 for (i = 0; i < acfg->nmethods; ++i)
8577 g_free (acfg->cfgs [i]);
8578 g_free (acfg->cfgs);
8579 g_free (acfg->static_linking_symbol);
8580 g_free (acfg->got_symbol);
8581 g_free (acfg->plt_symbol);
8582 g_ptr_array_free (acfg->methods, TRUE);
8583 g_ptr_array_free (acfg->got_patches, TRUE);
8584 g_ptr_array_free (acfg->image_table, TRUE);
8585 g_ptr_array_free (acfg->globals, TRUE);
8586 g_ptr_array_free (acfg->unwind_ops, TRUE);
8587 g_hash_table_destroy (acfg->method_indexes);
8588 g_hash_table_destroy (acfg->method_depth);
8589 g_hash_table_destroy (acfg->plt_offset_to_entry);
8590 g_hash_table_destroy (acfg->patch_to_plt_entry);
8591 g_hash_table_destroy (acfg->patch_to_got_offset);
8592 g_hash_table_destroy (acfg->method_to_cfg);
8593 g_hash_table_destroy (acfg->token_info_hash);
8594 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8595 g_hash_table_destroy (acfg->image_hash);
8596 g_hash_table_destroy (acfg->unwind_info_offsets);
8597 g_hash_table_destroy (acfg->method_label_hash);
8598 g_hash_table_destroy (acfg->export_names);
8599 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8600 g_hash_table_destroy (acfg->klass_blob_hash);
8601 g_hash_table_destroy (acfg->method_blob_hash);
8602 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8603 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8604 g_free (acfg->patch_to_got_offset_by_type);
8605 mono_mempool_destroy (acfg->mempool);
8610 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8612 MonoImage *image = ass->image;
8614 MonoAotCompile *acfg;
8615 char *outfile_name, *tmp_outfile_name, *p;
8616 char llvm_stats_msg [256];
8620 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || (!defined(MONO_EXTENSIONS) && !defined(MONOTOUCH))
8621 if (opts & MONO_OPT_GSHAREDVT) {
8622 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8627 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8629 acfg = acfg_create (ass, opts);
8631 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8632 acfg->aot_opts.write_symbols = TRUE;
8633 acfg->aot_opts.ntrampolines = 1024;
8634 acfg->aot_opts.nrgctx_trampolines = 1024;
8635 acfg->aot_opts.nimt_trampolines = 128;
8636 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8637 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8638 acfg->aot_opts.llvm_path = g_strdup ("");
8640 acfg->aot_opts.use_trampolines_page = TRUE;
8643 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8645 if (acfg->aot_opts.static_link)
8646 acfg->aot_opts.autoreg = TRUE;
8648 //acfg->aot_opts.print_skipped_methods = TRUE;
8650 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8651 if (acfg->aot_opts.full_aot) {
8652 printf ("--aot=full is not supported on this platform.\n");
8657 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8658 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8662 if (acfg->aot_opts.static_link)
8663 acfg->aot_opts.asm_writer = TRUE;
8665 if (acfg->aot_opts.soft_debug) {
8666 MonoDebugOptions *opt = mini_get_debug_options ();
8668 opt->mdb_optimizations = TRUE;
8669 opt->gen_seq_points = TRUE;
8671 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8672 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8675 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8678 if (mono_use_llvm) {
8680 acfg->aot_opts.asm_writer = TRUE;
8681 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8683 if (acfg->aot_opts.soft_debug) {
8684 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8689 if (acfg->aot_opts.full_aot)
8690 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8692 load_profile_files (acfg);
8694 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8695 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8696 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8698 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8699 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8700 if (acfg->opts & MONO_OPT_GSHAREDVT)
8701 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8704 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8708 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8709 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8710 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8712 /* Get rid of characters which cannot occur in symbols */
8713 for (p = acfg->got_symbol_base; *p; ++p) {
8714 if (!(isalnum (*p) || *p == '_'))
8717 for (p = acfg->plt_symbol; *p; ++p) {
8718 if (!(isalnum (*p) || *p == '_'))
8721 for (p = acfg->assembly_name_sym; *p; ++p) {
8722 if (!(isalnum (*p) || *p == '_'))
8726 acfg->method_index = 1;
8730 if (acfg->aot_opts.full_aot)
8731 mono_set_partial_sharing_supported (TRUE);
8734 collect_methods (acfg);
8736 acfg->cfgs_size = acfg->methods->len + 32;
8737 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8739 /* PLT offset 0 is reserved for the PLT trampoline */
8740 acfg->plt_offset = 1;
8745 mono_llvm_create_aot_module (acfg->got_symbol_base);
8749 /* GOT offset 0 is reserved for the address of the current assembly */
8753 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8754 ji->type = MONO_PATCH_INFO_IMAGE;
8755 ji->data.image = acfg->image;
8757 get_got_offset (acfg, ji);
8759 /* Slot 1 is reserved for the mscorlib got addr */
8760 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8761 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8762 get_got_offset (acfg, ji);
8764 /* This is very common */
8765 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8766 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8767 get_got_offset (acfg, ji);
8769 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8770 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8771 get_got_offset (acfg, ji);
8776 compile_methods (acfg);
8780 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8786 if (acfg->aot_opts.asm_only) {
8787 if (acfg->aot_opts.outfile) {
8788 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8789 acfg->tmpbasename = g_strdup (acfg->tmpfname);
8791 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
8792 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8795 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
8796 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8799 emit_llvm_file (acfg);
8803 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8804 if (acfg->aot_opts.outfile)
8805 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8807 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8810 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8811 * it might be in another file system so the rename () won't work.
8813 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8815 acfg->fp = fopen (tmp_outfile_name, "w");
8817 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8821 acfg->w = img_writer_create (acfg->fp, TRUE);
8822 acfg->use_bin_writer = TRUE;
8825 /* Append to the .s file created by llvm */
8826 /* FIXME: Use multiple files instead */
8827 acfg->fp = fopen (acfg->tmpfname, "a+");
8829 if (acfg->aot_opts.asm_only) {
8830 if (acfg->aot_opts.outfile)
8831 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8833 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8834 acfg->fp = fopen (acfg->tmpfname, "w+");
8836 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8837 acfg->fp = fdopen (i, "w+");
8840 if (acfg->fp == 0) {
8841 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8844 acfg->w = img_writer_create (acfg->fp, FALSE);
8846 tmp_outfile_name = NULL;
8847 outfile_name = NULL;
8850 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8852 /* Compute symbols for methods */
8853 for (i = 0; i < acfg->nmethods; ++i) {
8854 if (acfg->cfgs [i]) {
8855 MonoCompile *cfg = acfg->cfgs [i];
8856 int method_index = get_method_index (acfg, cfg->orig_method);
8858 if (COMPILE_LLVM (cfg))
8859 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8860 else if (acfg->global_symbols)
8861 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8863 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8867 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
8869 * CLANG supports GAS .file/.loc directives, so emit line number information this way
8871 acfg->gas_line_numbers = TRUE;
8874 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8875 if (acfg->aot_opts.dwarf_debug && mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8876 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8879 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
8882 img_writer_emit_start (acfg->w);
8885 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
8887 if (acfg->thumb_mixed) {
8890 * This global symbol marks the end of THUMB code, and the beginning of ARM
8891 * code generated by our JIT.
8893 sprintf (symbol, "thumb_end");
8894 emit_section_change (acfg, ".text", 0);
8895 emit_alignment (acfg, 8);
8896 emit_label (acfg, symbol);
8897 emit_zero_bytes (acfg, 16);
8899 fprintf (acfg->fp, ".arm\n");
8906 emit_extra_methods (acfg);
8908 emit_trampolines (acfg);
8910 emit_class_name_table (acfg);
8912 emit_got_info (acfg);
8914 emit_exception_info (acfg);
8916 emit_unwind_info (acfg);
8918 emit_class_info (acfg);
8922 emit_image_table (acfg);
8926 emit_file_info (acfg);
8930 emit_objc_selectors (acfg);
8932 emit_globals (acfg);
8934 emit_autoreg (acfg);
8937 emit_dwarf_info (acfg);
8938 mono_dwarf_writer_close (acfg->dwarf);
8941 emit_mem_end (acfg);
8943 if (acfg->need_pt_gnu_stack) {
8944 /* This is required so the .so doesn't have an executable stack */
8945 /* The bin writer already emits this */
8946 if (!acfg->use_bin_writer)
8947 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
8952 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
8955 g_assert (acfg->got_offset <= acfg->final_got_size);
8958 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
8960 strcpy (llvm_stats_msg, "");
8961 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);
8962 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
8963 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
8965 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
8966 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
8967 if (acfg->stats.genericcount)
8968 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
8969 if (acfg->stats.abscount)
8970 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
8971 if (acfg->stats.lmfcount)
8972 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
8973 if (acfg->stats.ocount)
8974 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
8977 res = img_writer_emit_writeout (acfg->w);
8982 if (acfg->use_bin_writer) {
8983 int err = rename (tmp_outfile_name, outfile_name);
8986 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
8990 res = compile_asm (acfg);
8997 acfg->stats.link_time = TV_ELAPSED (atv, btv);
8999 if (acfg->aot_opts.stats) {
9002 printf ("GOT slot distribution:\n");
9003 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9004 if (acfg->stats.got_slot_types [i])
9005 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9008 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);
9020 mono_aot_readonly_field_override (MonoClassField *field)
9026 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)