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)
643 g_string_append (acfg->llc_args, " -march=x86-64");
647 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
648 g_string_append (acfg->llc_args, "-mattr=+v6");
651 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
652 g_string_append (acfg->as_args, " -mfpu=vfp3");
654 g_string_append (acfg->llc_args, " -soft-float");
657 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
658 acfg->thumb_mixed = TRUE;
660 if (acfg->aot_opts.mtriple)
661 mono_arch_set_target (acfg->aot_opts.mtriple);
665 acfg->user_symbol_prefix = "_";
666 acfg->llvm_label_prefix = "_";
667 acfg->need_no_dead_strip = TRUE;
668 acfg->aot_opts.gnu_asm = TRUE;
671 #if defined(__linux__) && !defined(TARGET_ARM)
672 acfg->need_pt_gnu_stack = TRUE;
676 acfg->direct_method_addresses = TRUE;
677 acfg->global_symbols = TRUE;
682 * arch_emit_direct_call:
684 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
688 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, MonoJumpInfo *ji, int *call_size)
690 #if defined(TARGET_X86) || defined(TARGET_AMD64)
691 /* Need to make sure this is exactly 5 bytes long */
692 if (external && !acfg->use_bin_writer) {
693 emit_unset_mode (acfg);
694 fprintf (acfg->fp, "call %s\n", target);
696 emit_byte (acfg, '\xe8');
697 emit_symbol_diff (acfg, target, ".", -4);
700 #elif defined(TARGET_ARM)
701 if (acfg->use_bin_writer) {
708 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
709 emit_bytes (acfg, buf, 4);
711 emit_unset_mode (acfg);
712 fprintf (acfg->fp, "bl %s\n", target);
715 #elif defined(TARGET_POWERPC)
716 if (acfg->use_bin_writer) {
717 g_assert_not_reached ();
719 emit_unset_mode (acfg);
720 fprintf (acfg->fp, "bl %s\n", target);
724 g_assert_not_reached ();
730 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
732 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
733 * in in the 2. slot of every GOT, and require every method to place the GOT
734 * address in r30, even when it doesn't access the GOT otherwise. This way,
735 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
740 * PPC64 uses function descriptors which greatly complicate all code, since
741 * these are used very inconsistently in the runtime. Some functions like
742 * mono_compile_method () return ftn descriptors, while others like the
743 * trampoline creation functions do not.
744 * We assume that all GOT slots contain function descriptors, and create
745 * descriptors in aot-runtime.c when needed.
746 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
747 * from function descriptors, we could do the same, but it would require
748 * rewriting all the ppc/aot code to handle function descriptors properly.
749 * So instead, we use the same approach as on PPC32.
750 * This is a horrible mess, but fixing it would probably lead to an even bigger
756 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
759 #ifdef MONO_ARCH_AOT_SUPPORTED
761 * arch_emit_got_offset:
763 * The memory pointed to by CODE should hold native code for computing the GOT
764 * address. Emit this code while patching it with the offset between code and
765 * the GOT. CODE_SIZE is set to the number of bytes emitted.
768 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
770 #if defined(TARGET_POWERPC64)
771 g_assert (!acfg->use_bin_writer);
772 emit_unset_mode (acfg);
774 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
775 * unsupported relocations. So we store the got address into the .Lgot_addr
776 * symbol which is in the text segment, compute its address, and load it.
778 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
779 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
780 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
781 fprintf (acfg->fp, "add 30, 30, 0\n");
782 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
783 acfg->label_generator ++;
785 #elif defined(TARGET_POWERPC)
786 g_assert (!acfg->use_bin_writer);
787 emit_unset_mode (acfg);
788 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
789 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
790 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
791 acfg->label_generator ++;
794 guint32 offset = mono_arch_get_patch_offset (code);
795 emit_bytes (acfg, code, offset);
796 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
798 *code_size = offset + 4;
803 * arch_emit_got_access:
805 * The memory pointed to by CODE should hold native code for loading a GOT
806 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
807 * CODE_SIZE is set to the number of bytes emitted.
810 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
812 /* Emit beginning of instruction */
813 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
815 /* Emit the offset */
817 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
818 *code_size = mono_arch_get_patch_offset (code) + 4;
819 #elif defined(TARGET_X86)
820 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
821 *code_size = mono_arch_get_patch_offset (code) + 4;
822 #elif defined(TARGET_ARM)
823 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
824 *code_size = mono_arch_get_patch_offset (code) + 4;
825 #elif defined(TARGET_POWERPC)
831 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
832 g_assert (code - buf == 8);
833 emit_bytes (acfg, buf, code - buf);
834 *code_size = code - buf;
837 g_assert_not_reached ();
844 * arch_emit_objc_selector_ref:
846 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
849 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
851 #if defined(TARGET_ARM)
854 int lindex = acfg->objc_selector_index_2 ++;
857 emit_bytes (acfg, code, 8);
859 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
860 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
862 emit_label (acfg, symbol1);
863 img_writer_emit_unset_mode (acfg->w);
864 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
868 g_assert_not_reached ();
873 * arch_emit_plt_entry:
875 * Emit code for the PLT entry with index INDEX.
878 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
880 #if defined(TARGET_X86)
881 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
882 #if defined(__default_codegen__)
883 /* jmp *<offset>(%ebx) */
884 emit_byte (acfg, 0xff);
885 emit_byte (acfg, 0xa3);
886 emit_int32 (acfg, offset);
887 /* Used by mono_aot_get_plt_info_offset */
888 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
889 #elif defined(__native_client_codegen__)
890 const guint8 kSizeOfNaClJmp = 11;
891 guint8 bytes[kSizeOfNaClJmp];
892 guint8 *pbytes = &bytes[0];
894 x86_jump_membase32 (pbytes, X86_EBX, offset);
895 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
896 /* four bytes of data, used by mono_arch_patch_plt_entry */
897 /* For Native Client, make this work with data embedded in push. */
898 emit_byte (acfg, 0x68); /* hide data in a push */
899 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
900 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
901 #endif /*__native_client_codegen__*/
902 #elif defined(TARGET_AMD64)
903 #if defined(__default_codegen__)
905 * We can't emit jumps because they are 32 bits only so they can't be patched.
906 * So we make indirect calls through GOT entries which are patched by the AOT
907 * loader to point to .Lpd entries.
909 /* jmpq *<offset>(%rip) */
910 emit_byte (acfg, '\xff');
911 emit_byte (acfg, '\x25');
912 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
913 /* Used by mono_aot_get_plt_info_offset */
914 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
915 #elif defined(__native_client_codegen__)
917 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
918 guint8 *code = buf_aligned;
920 /* mov <OFFSET>(%rip), %r11d */
921 emit_byte (acfg, '\x45');
922 emit_byte (acfg, '\x8b');
923 emit_byte (acfg, '\x1d');
924 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
926 amd64_jump_reg (code, AMD64_R11);
927 /* This should be constant for the plt patch */
928 g_assert ((size_t)(code-buf_aligned) == 10);
929 emit_bytes (acfg, buf_aligned, code - buf_aligned);
931 /* Hide data in a push imm32 so it passes validation */
932 emit_byte (acfg, 0x68); /* push */
933 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
934 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
935 #endif /*__native_client_codegen__*/
936 #elif defined(TARGET_ARM)
941 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
942 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
943 emit_bytes (acfg, buf, code - buf);
944 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
945 /* Used by mono_aot_get_plt_info_offset */
946 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
947 #elif defined(TARGET_POWERPC)
948 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
950 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
951 g_assert (!acfg->use_bin_writer);
952 emit_unset_mode (acfg);
953 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
954 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
955 fprintf (acfg->fp, "add 11, 11, 30\n");
956 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
957 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
958 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
959 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
961 fprintf (acfg->fp, "mtctr 11\n");
962 fprintf (acfg->fp, "bctr\n");
963 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
965 g_assert_not_reached ();
970 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
972 #if defined(TARGET_ARM)
974 /* LLVM calls the PLT entries using bl, so emit a stub */
975 /* FIXME: Too much overhead on every call */
976 fprintf (acfg->fp, ".thumb_func\n");
977 fprintf (acfg->fp, "bx pc\n");
978 fprintf (acfg->fp, "nop\n");
979 fprintf (acfg->fp, ".arm\n");
981 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
982 /* The caller already transitioned to thumb */
983 /* The code below should be 12 bytes long */
984 /* clang has trouble encoding these instructions, so emit the binary */
986 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
987 /* thumb can't encode ld pc, [pc, ip] */
988 fprintf (acfg->fp, "add ip, pc, ip\n");
989 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
990 fprintf (acfg->fp, "bx ip\n");
992 emit_set_thumb_mode (acfg);
993 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
994 fprintf (acfg->fp, ".2byte 0x44fc\n");
995 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
996 fprintf (acfg->fp, ".2byte 0x4760\n");
997 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
998 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
999 emit_unset_mode (acfg);
1000 emit_set_arm_mode (acfg);
1002 g_assert_not_reached ();
1007 * arch_emit_specific_trampoline_pages:
1009 * Emits a page full of trampolines: each trampoline uses its own address to
1010 * lookup both the generic trampoline code and the data argument.
1011 * This page can be remapped in process multiple times so we can get an
1012 * unlimited number of trampolines.
1013 * Specifically this implementation uses the following trick: two memory pages
1014 * are allocated, with the first containing the data and the second containing the trampolines.
1015 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1016 * implementation does all the lifting.
1017 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1018 * on the arm 32 bit system.
1021 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1023 #if defined(TARGET_ARM)
1026 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1028 #define COMMON_TRAMP_SIZE 16
1029 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1030 int imm8, rot_amount;
1033 if (!acfg->aot_opts.use_trampolines_page)
1036 acfg->tramp_page_size = mono_pagesize ();
1038 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1039 emit_alignment (acfg, mono_pagesize ());
1040 emit_global (acfg, symbol, TRUE);
1041 emit_label (acfg, symbol);
1043 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1045 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1046 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1047 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1048 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1050 g_assert (code - buf == COMMON_TRAMP_SIZE);
1053 emit_bytes (acfg, buf, code - buf);
1055 for (i = 0; i < count; ++i) {
1057 ARM_PUSH (code, 0x5fff);
1059 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1060 g_assert (code - buf == 8);
1061 emit_bytes (acfg, buf, code - buf);
1064 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1065 * the instruction pointer address, so the generic trampoline at the start of the page
1066 * subtracts 4096 to get to the data page and loads the values
1067 * We again fit the generic trampiline in 16 bytes.
1069 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1070 emit_global (acfg, symbol, TRUE);
1071 emit_label (acfg, symbol);
1073 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1074 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1075 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1076 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1078 g_assert (code - buf == COMMON_TRAMP_SIZE);
1081 emit_bytes (acfg, buf, code - buf);
1083 for (i = 0; i < count; ++i) {
1085 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1087 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1088 g_assert (code - buf == 8);
1089 emit_bytes (acfg, buf, code - buf);
1093 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1095 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1096 emit_global (acfg, symbol, TRUE);
1097 emit_label (acfg, symbol);
1099 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1100 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1101 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1102 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1103 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1104 g_assert (code - buf == COMMON_TRAMP_SIZE);
1106 emit_bytes (acfg, buf, code - buf);
1108 for (i = 0; i < count; ++i) {
1110 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1112 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1113 g_assert (code - buf == 8);
1114 emit_bytes (acfg, buf, code - buf);
1117 /* now the imt trampolines: each specific trampolines puts in the ip register
1118 * the instruction pointer address, so the generic trampoline at the start of the page
1119 * subtracts 4096 to get to the data page and loads the values
1120 * We again fit the generic trampiline in 16 bytes.
1122 #define IMT_TRAMP_SIZE 72
1123 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1124 emit_global (acfg, symbol, TRUE);
1125 emit_label (acfg, symbol);
1127 /* Need at least two free registers, plus a slot for storing the pc */
1128 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1130 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1131 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1132 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1134 /* The IMT method is in v5, r0 has the imt array address */
1137 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1138 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1139 imt_found_check = code;
1140 ARM_B_COND (code, ARMCOND_EQ, 0);
1142 /* End-of-loop check */
1143 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1144 loop_end_check = code;
1145 ARM_B_COND (code, ARMCOND_EQ, 0);
1148 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1149 loop_branch_back = code;
1151 arm_patch (loop_branch_back, loop_start);
1154 arm_patch (imt_found_check, code);
1155 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1156 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1157 /* Save it to the third stack slot */
1158 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1159 /* Restore the registers and branch */
1160 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1163 arm_patch (loop_end_check, code);
1164 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1165 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1166 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1170 g_assert (code - buf == IMT_TRAMP_SIZE);
1171 emit_bytes (acfg, buf, code - buf);
1173 for (i = 0; i < count; ++i) {
1175 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1177 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1178 g_assert (code - buf == 8);
1179 emit_bytes (acfg, buf, code - buf);
1185 * arch_emit_specific_trampoline:
1187 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1188 * two GOT slots which contain the generic trampoline address and the trampoline
1189 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1192 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1195 * The trampolines created here are variations of the specific
1196 * trampolines created in mono_arch_create_specific_trampoline (). The
1198 * - the generic trampoline address is taken from a got slot.
1199 * - the offset of the got slot where the trampoline argument is stored
1200 * is embedded in the instruction stream, and the generic trampoline
1201 * can load the argument by loading the offset, adding it to the
1202 * address of the trampoline to get the address of the got slot, and
1203 * loading the argument from there.
1204 * - all the trampolines should be of the same length.
1206 #if defined(TARGET_AMD64)
1207 #if defined(__default_codegen__)
1208 /* This should be exactly 16 bytes long */
1210 /* call *<offset>(%rip) */
1211 emit_byte (acfg, '\x41');
1212 emit_byte (acfg, '\xff');
1213 emit_byte (acfg, '\x15');
1214 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1215 /* This should be relative to the start of the trampoline */
1216 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1217 emit_zero_bytes (acfg, 5);
1218 #elif defined(__native_client_codegen__)
1220 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1221 guint8 *code = buf_aligned;
1226 /* Emit this call in 'code' so we can find out how long it is. */
1227 amd64_call_reg (code, AMD64_R11);
1228 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1229 call_len = code - call_start;
1231 /* The tramp_size is twice the NaCl alignment because it starts with */
1232 /* a call which needs to be aligned to the end of the boundary. */
1233 *tramp_size = kNaClAlignment*2;
1235 /* Emit nops to align call site below which is 7 bytes plus */
1236 /* the length of the call sequence emitted above. */
1237 /* Note: this requires the specific trampoline starts on a */
1238 /* kNaclAlignedment aligned address, which it does because */
1239 /* it's its own function that is aligned. */
1240 guint8 nop_buf[256];
1241 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1242 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1243 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1245 /* The trampoline is stored at the offset'th pointer, the -4 is */
1246 /* present because RIP relative addressing starts at the end of */
1247 /* the current instruction, while the label "." is relative to */
1248 /* the beginning of the current asm location, which in this case */
1249 /* is not the mov instruction, but the offset itself, due to the */
1250 /* way the bytes and ints are emitted here. */
1251 got_offset = (offset * sizeof(gpointer)) - 4;
1253 /* mov <OFFSET>(%rip), %r11d */
1254 emit_byte (acfg, '\x45');
1255 emit_byte (acfg, '\x8b');
1256 emit_byte (acfg, '\x1d');
1257 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1260 emit_bytes (acfg, call_start, call_len);
1262 /* The arg is stored at the offset+1 pointer, relative to beginning */
1263 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1264 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1266 /* We can't emit this data directly, hide in a "push imm32" */
1267 emit_byte (acfg, '\x68'); /* push */
1268 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1269 emit_alignment (acfg, kNaClAlignment);
1270 #endif /*__native_client_codegen__*/
1271 #elif defined(TARGET_ARM)
1275 /* This should be exactly 20 bytes long */
1278 ARM_PUSH (code, 0x5fff);
1279 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1280 /* Load the value from the GOT */
1281 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1283 ARM_BLX_REG (code, ARMREG_R1);
1285 g_assert (code - buf == 16);
1288 emit_bytes (acfg, buf, code - buf);
1290 * Only one offset is needed, since the second one would be equal to the
1293 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1294 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1295 #elif defined(TARGET_POWERPC)
1302 g_assert (!acfg->use_bin_writer);
1305 * PPC has no ip relative addressing, so we need to compute the address
1306 * of the mscorlib got. That is slow and complex, so instead, we store it
1307 * in the second got slot of every aot image. The caller already computed
1308 * the address of its got and placed it into r30.
1310 emit_unset_mode (acfg);
1311 /* Load mscorlib got address */
1312 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1313 /* Load generic trampoline address */
1314 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1315 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1316 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1317 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1318 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1320 fprintf (acfg->fp, "mtctr 11\n");
1321 /* Load trampoline argument */
1322 /* On ppc, we pass it normally to the generic trampoline */
1323 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1324 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1325 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1326 /* Branch to generic trampoline */
1327 fprintf (acfg->fp, "bctr\n");
1329 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1330 *tramp_size = 10 * 4;
1332 *tramp_size = 9 * 4;
1334 #elif defined(TARGET_X86)
1338 /* Similar to the PPC code above */
1340 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1342 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1343 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1344 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1348 /* Load mscorlib got address */
1349 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1350 /* Push trampoline argument */
1351 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1352 /* Load generic trampoline address */
1353 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1354 /* Branch to generic trampoline */
1355 x86_jump_reg (code, X86_ECX);
1357 #ifdef __native_client_codegen__
1359 /* emit nops to next 32 byte alignment */
1360 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1361 while (code < (buf + a)) x86_nop(code);
1364 emit_bytes (acfg, buf, code - buf);
1366 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1367 g_assert (code - buf == *tramp_size);
1369 g_assert_not_reached ();
1374 * arch_emit_unbox_trampoline:
1376 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1377 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1380 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1382 #if defined(TARGET_AMD64)
1387 this_reg = mono_arch_get_this_arg_reg (NULL);
1389 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1391 emit_bytes (acfg, buf, code - buf);
1393 emit_byte (acfg, '\xe9');
1394 emit_symbol_diff (acfg, call_target, ".", -4);
1395 #elif defined(TARGET_X86)
1402 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1404 emit_bytes (acfg, buf, code - buf);
1407 emit_byte (acfg, '\xe9');
1408 emit_symbol_diff (acfg, call_target, ".", -4);
1409 #elif defined(TARGET_ARM)
1413 if (acfg->thumb_mixed && cfg->compile_llvm) {
1414 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1415 fprintf (acfg->fp, "b %s\n", call_target);
1416 fprintf (acfg->fp, ".arm\n");
1417 fprintf (acfg->fp, ".align 2\n");
1423 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1425 emit_bytes (acfg, buf, code - buf);
1426 /* jump to method */
1427 if (acfg->use_bin_writer) {
1434 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1435 emit_bytes (acfg, buf, 4);
1437 if (acfg->thumb_mixed && cfg->compile_llvm)
1438 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1440 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1442 #elif defined(TARGET_POWERPC)
1445 g_assert (!acfg->use_bin_writer);
1447 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1448 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1450 g_assert_not_reached ();
1455 * arch_emit_static_rgctx_trampoline:
1457 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1458 * two GOT slots which contain the rgctx argument, and the method to jump to.
1459 * TRAMP_SIZE is set to the size of the emitted trampoline.
1460 * These kinds of trampolines cannot be enumerated statically, since there could
1461 * be one trampoline per method instantiation, so we emit the same code for all
1462 * trampolines, and parameterize them using two GOT slots.
1465 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1467 #if defined(TARGET_AMD64)
1468 #if defined(__default_codegen__)
1469 /* This should be exactly 13 bytes long */
1472 /* mov <OFFSET>(%rip), %r10 */
1473 emit_byte (acfg, '\x4d');
1474 emit_byte (acfg, '\x8b');
1475 emit_byte (acfg, '\x15');
1476 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1478 /* jmp *<offset>(%rip) */
1479 emit_byte (acfg, '\xff');
1480 emit_byte (acfg, '\x25');
1481 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1482 #elif defined(__native_client_codegen__)
1484 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1485 guint8 *code = buf_aligned;
1487 /* mov <OFFSET>(%rip), %r10d */
1488 emit_byte (acfg, '\x45');
1489 emit_byte (acfg, '\x8b');
1490 emit_byte (acfg, '\x15');
1491 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1493 /* mov <OFFSET>(%rip), %r11d */
1494 emit_byte (acfg, '\x45');
1495 emit_byte (acfg, '\x8b');
1496 emit_byte (acfg, '\x1d');
1497 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1500 amd64_jump_reg (code, AMD64_R11);
1501 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1503 emit_alignment (acfg, kNaClAlignment);
1504 *tramp_size = kNaClAlignment;
1505 #endif /*__native_client_codegen__*/
1507 #elif defined(TARGET_ARM)
1511 /* This should be exactly 24 bytes long */
1514 /* Load rgctx value */
1515 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1516 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1517 /* Load branch addr + branch */
1518 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1519 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1521 g_assert (code - buf == 16);
1524 emit_bytes (acfg, buf, code - buf);
1525 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1526 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1527 #elif defined(TARGET_POWERPC)
1534 g_assert (!acfg->use_bin_writer);
1537 * PPC has no ip relative addressing, so we need to compute the address
1538 * of the mscorlib got. That is slow and complex, so instead, we store it
1539 * in the second got slot of every aot image. The caller already computed
1540 * the address of its got and placed it into r30.
1542 emit_unset_mode (acfg);
1543 /* Load mscorlib got address */
1544 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1546 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1547 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1548 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1549 /* Load target address */
1550 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1551 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1552 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1553 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1554 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1555 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1557 fprintf (acfg->fp, "mtctr 11\n");
1558 /* Branch to the target address */
1559 fprintf (acfg->fp, "bctr\n");
1561 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1562 *tramp_size = 11 * 4;
1564 *tramp_size = 9 * 4;
1567 #elif defined(TARGET_X86)
1571 /* Similar to the PPC code above */
1573 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1576 /* Load mscorlib got address */
1577 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1579 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1580 /* Branch to the target address */
1581 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1583 #ifdef __native_client_codegen__
1585 /* emit nops to next 32 byte alignment */
1586 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1587 while (code < (buf + a)) x86_nop(code);
1591 emit_bytes (acfg, buf, code - buf);
1593 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1594 g_assert (code - buf == *tramp_size);
1596 g_assert_not_reached ();
1601 * arch_emit_imt_thunk:
1603 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1604 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1605 * key is the IMT key, and ptr holds the address of a memory location holding
1606 * the address to branch to if the IMT arg matches the key. The array is
1607 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1609 * TRAMP_SIZE is set to the size of the emitted trampoline.
1612 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1614 #if defined(TARGET_AMD64)
1616 #if defined(__native_client_codegen__)
1619 guint8 *labels [16];
1621 guint8 *mov_buf_ptr = mov_buf;
1623 const int kSizeOfMove = 7;
1624 #if defined(__default_codegen__)
1625 code = buf = g_malloc (256);
1626 #elif defined(__native_client_codegen__)
1627 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1628 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1629 /* The RIP relative move below is emitted first */
1634 /* FIXME: Optimize this, i.e. use binary search etc. */
1635 /* Maybe move the body into a separate function (slower, but much smaller) */
1637 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1640 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1642 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1645 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1647 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1650 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1651 amd64_jump_code (code, labels [0]);
1654 mono_amd64_patch (labels [2], code);
1655 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1656 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1659 mono_amd64_patch (labels [1], code);
1660 /* Load fail tramp */
1661 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1662 /* Check if there is a fail tramp */
1663 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1665 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1666 /* Jump to fail tramp */
1667 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1670 mono_amd64_patch (labels [3], code);
1671 x86_breakpoint (code);
1673 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1674 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1675 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1676 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1677 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1678 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1680 emit_bytes (acfg, buf, code - buf);
1682 *tramp_size = code - buf + kSizeOfMove;
1683 #if defined(__native_client_codegen__)
1684 /* The tramp will be padded to the next kNaClAlignment bundle. */
1685 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1688 #if defined(__default_codegen__)
1690 #elif defined(__native_client_codegen__)
1694 #elif defined(TARGET_X86)
1696 #ifdef __native_client_codegen__
1699 guint8 *labels [16];
1701 #if defined(__default_codegen__)
1702 code = buf = g_malloc (256);
1703 #elif defined(__native_client_codegen__)
1704 buf_alloc = g_malloc (256 + kNaClAlignment);
1705 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1708 /* Allocate a temporary stack slot */
1709 x86_push_reg (code, X86_EAX);
1711 x86_push_reg (code, X86_EAX);
1713 /* Load mscorlib got address */
1714 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1716 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1719 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1721 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1724 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1726 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1729 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1730 x86_jump_code (code, labels [0]);
1733 mono_x86_patch (labels [2], code);
1734 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1735 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1736 /* Save the target address to the temporary stack location */
1737 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1739 x86_pop_reg (code, X86_EAX);
1740 /* Jump to the target address */
1744 mono_x86_patch (labels [1], code);
1745 /* Load fail tramp */
1746 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1747 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1749 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1750 /* Jump to fail tramp */
1751 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1752 x86_pop_reg (code, X86_EAX);
1756 mono_x86_patch (labels [3], code);
1757 x86_breakpoint (code);
1759 #ifdef __native_client_codegen__
1761 /* emit nops to next 32 byte alignment */
1762 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1763 while (code < (buf + a)) x86_nop(code);
1766 emit_bytes (acfg, buf, code - buf);
1768 *tramp_size = code - buf;
1770 #if defined(__default_codegen__)
1772 #elif defined(__native_client_codegen__)
1776 #elif defined(TARGET_ARM)
1778 guint8 *code, *code2, *labels [16];
1782 /* The IMT method is in v5 */
1784 /* Need at least two free registers, plus a slot for storing the pc */
1785 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1787 /* Load the parameter from the GOT */
1788 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1789 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1792 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1793 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1795 ARM_B_COND (code, ARMCOND_EQ, 0);
1797 /* End-of-loop check */
1798 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1800 ARM_B_COND (code, ARMCOND_EQ, 0);
1803 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1806 arm_patch (labels [4], labels [1]);
1809 arm_patch (labels [2], code);
1810 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1811 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1812 /* Save it to the third stack slot */
1813 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1814 /* Restore the registers and branch */
1815 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1818 arm_patch (labels [3], code);
1819 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1820 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1821 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1825 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1827 emit_bytes (acfg, buf, code - buf);
1828 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1830 *tramp_size = code - buf + 4;
1831 #elif defined(TARGET_POWERPC)
1833 guint8 *code, *labels [16];
1837 /* Load the mscorlib got address */
1838 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1839 /* Load the parameter from the GOT */
1840 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1841 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1843 /* Load and check key */
1845 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1846 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1848 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1850 /* End-of-loop check */
1851 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1853 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1856 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1859 mono_ppc_patch (labels [4], labels [1]);
1862 mono_ppc_patch (labels [2], code);
1863 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1864 /* r11 now contains the value of the vtable slot */
1865 /* this is not a function descriptor on ppc64 */
1866 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1867 ppc_mtctr (code, ppc_r11);
1868 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1871 mono_ppc_patch (labels [3], code);
1875 *tramp_size = code - buf;
1877 emit_bytes (acfg, buf, code - buf);
1879 g_assert_not_reached ();
1884 * arch_emit_gsharedvt_arg_trampoline:
1886 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1887 * two GOT slots which contain the argument, and the code to jump to.
1888 * TRAMP_SIZE is set to the size of the emitted trampoline.
1889 * These kinds of trampolines cannot be enumerated statically, since there could
1890 * be one trampoline per method instantiation, so we emit the same code for all
1891 * trampolines, and parameterize them using two GOT slots.
1894 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1896 #if defined(TARGET_X86)
1900 /* Similar to the PPC code above */
1902 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1905 /* Load mscorlib got address */
1906 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1908 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1909 /* Branch to the target address */
1910 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1912 #ifdef __native_client_codegen__
1914 /* emit nops to next 32 byte alignment */
1915 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1916 while (code < (buf + a)) x86_nop(code);
1920 emit_bytes (acfg, buf, code - buf);
1922 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1923 g_assert (code - buf == *tramp_size);
1924 #elif defined(TARGET_ARM)
1928 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1929 /* Similar to arch_emit_specific_trampoline () */
1932 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1933 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1934 /* Load the arg value from the GOT */
1935 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1936 /* Load the addr from the GOT */
1937 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1939 ARM_BX (code, ARMREG_R1);
1941 g_assert (code - buf == 20);
1944 emit_bytes (acfg, buf, code - buf);
1945 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1947 g_assert_not_reached ();
1952 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1954 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1955 /* Based on code generated by gcc */
1956 emit_unset_mode (acfg);
1959 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1960 ".section .ctors,\"aw\",@progbits\n"
1964 ".section .opd,\"aw\"\n"
1967 ".long .%s,.TOC.@tocbase32\n"
1970 ".type .%s,@function\n"
1972 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1974 ".section .ctors,\"aw\",@progbits\n"
1978 ".section .opd,\"aw\"\n"
1981 ".long .%1$s,.TOC.@tocbase32\n"
1982 ".size %1$s,.-%1$s\n"
1984 ".type .%1$s,@function\n"
1986 ".%1$s:\n", symbol);
1997 "lis 3, .Lglobals@h\n"
1998 "ori 3, 3, .Lglobals@l\n"
1999 "bl .mono_aot_register_module\n"
2007 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2009 ".size .%s,.-.%s\n", symbol, symbol);
2012 ".size .%1$s,.-.%1$s\n", symbol);
2018 /* END OF ARCH SPECIFIC CODE */
2021 mono_get_field_token (MonoClassField *field)
2023 MonoClass *klass = field->parent;
2026 for (i = 0; i < klass->field.count; ++i) {
2027 if (field == &klass->fields [i])
2028 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2031 g_assert_not_reached ();
2036 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2040 //printf ("ENCODE: %d 0x%x.\n", value, value);
2043 * Same encoding as the one used in the metadata, extended to handle values
2044 * greater than 0x1fffffff.
2046 if ((value >= 0) && (value <= 127))
2048 else if ((value >= 0) && (value <= 16383)) {
2049 p [0] = 0x80 | (value >> 8);
2050 p [1] = value & 0xff;
2052 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2053 p [0] = (value >> 24) | 0xc0;
2054 p [1] = (value >> 16) & 0xff;
2055 p [2] = (value >> 8) & 0xff;
2056 p [3] = value & 0xff;
2061 p [1] = (value >> 24) & 0xff;
2062 p [2] = (value >> 16) & 0xff;
2063 p [3] = (value >> 8) & 0xff;
2064 p [4] = value & 0xff;
2072 stream_init (MonoDynamicStream *sh)
2075 sh->alloc_size = 4096;
2076 sh->data = g_malloc (4096);
2078 /* So offsets are > 0 */
2084 make_room_in_stream (MonoDynamicStream *stream, int size)
2086 if (size <= stream->alloc_size)
2089 while (stream->alloc_size <= size) {
2090 if (stream->alloc_size < 4096)
2091 stream->alloc_size = 4096;
2093 stream->alloc_size *= 2;
2096 stream->data = g_realloc (stream->data, stream->alloc_size);
2100 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2104 make_room_in_stream (stream, stream->index + len);
2105 memcpy (stream->data + stream->index, data, len);
2106 idx = stream->index;
2107 stream->index += len;
2114 * Add data to the binary blob inside the aot image. Returns the offset inside the
2115 * blob where the data was stored.
2118 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2120 if (acfg->blob.alloc_size == 0)
2121 stream_init (&acfg->blob);
2123 return add_stream_data (&acfg->blob, (char*)data, data_len);
2127 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2132 if (acfg->blob.alloc_size == 0)
2133 stream_init (&acfg->blob);
2135 count = acfg->blob.index % align;
2137 /* we assume the stream data will be aligned */
2139 add_stream_data (&acfg->blob, buf, 4 - count);
2141 return add_stream_data (&acfg->blob, (char*)data, data_len);
2145 * emit_offset_table:
2147 * Emit a table of increasing offsets in a compact form using differential encoding.
2148 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2149 * group size, the more compact the table becomes, but the slower it becomes to compute
2150 * a given entry. Returns the size of the table.
2153 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2155 gint32 current_offset;
2156 int i, buf_size, ngroups, index_entry_size;
2158 guint32 *index_offsets;
2160 ngroups = (noffsets + (group_size - 1)) / group_size;
2162 index_offsets = g_new0 (guint32, ngroups);
2164 buf_size = noffsets * 4;
2165 p = buf = g_malloc0 (buf_size);
2168 for (i = 0; i < noffsets; ++i) {
2169 //printf ("D: %d -> %d\n", i, offsets [i]);
2170 if ((i % group_size) == 0) {
2171 index_offsets [i / group_size] = p - buf;
2172 /* Emit the full value for these entries */
2173 encode_value (offsets [i], p, &p);
2175 /* The offsets are allowed to be non-increasing */
2176 //g_assert (offsets [i] >= current_offset);
2177 encode_value (offsets [i] - current_offset, p, &p);
2179 current_offset = offsets [i];
2182 if (ngroups && index_offsets [ngroups - 1] < 65000)
2183 index_entry_size = 2;
2185 index_entry_size = 4;
2187 /* Emit the header */
2188 emit_int32 (acfg, noffsets);
2189 emit_int32 (acfg, group_size);
2190 emit_int32 (acfg, ngroups);
2191 emit_int32 (acfg, index_entry_size);
2193 /* Emit the index */
2194 for (i = 0; i < ngroups; ++i) {
2195 if (index_entry_size == 2)
2196 emit_int16 (acfg, index_offsets [i]);
2198 emit_int32 (acfg, index_offsets [i]);
2202 emit_bytes (acfg, buf, p - buf);
2204 return (int)(p - buf) + (ngroups * 4);
2208 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2212 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2216 index = g_hash_table_size (cfg->image_hash);
2217 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2218 g_ptr_array_add (cfg->image_table, image);
2224 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2227 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2229 /* FIXME: Search referenced images as well */
2230 if (!acfg->typespec_classes) {
2231 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2232 for (i = 0; i < len; ++i) {
2233 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2236 for (i = 0; i < len; ++i) {
2237 if (acfg->typespec_classes [i] == klass)
2242 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2248 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2251 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2254 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2257 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2260 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2265 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2269 if (klass->generic_class) {
2271 g_assert (klass->type_token);
2273 /* Find a typespec for a class if possible */
2274 token = find_typespec_for_class (acfg, klass);
2276 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2277 encode_value (token, p, &p);
2279 MonoClass *gclass = klass->generic_class->container_class;
2280 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2281 static int count = 0;
2284 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2285 encode_klass_ref (acfg, gclass, p, &p);
2286 encode_ginst (acfg, inst, p, &p);
2290 } else if (klass->type_token) {
2291 int iindex = get_image_index (acfg, klass->image);
2293 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2295 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2296 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2298 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2299 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2300 encode_value (get_image_index (acfg, klass->image), p, &p);
2302 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2303 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2304 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2306 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2307 encode_value (klass->byval_arg.type, p, &p);
2308 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2310 encode_value (container ? 1 : 0, p, &p);
2312 encode_value (container->is_method, p, &p);
2313 g_assert (par->serial == 0);
2314 if (container->is_method)
2315 encode_method_ref (acfg, container->owner.method, p, &p);
2317 encode_klass_ref (acfg, container->owner.klass, p, &p);
2319 encode_value (par->serial, p, &p);
2321 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2322 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2323 encode_type (acfg, &klass->byval_arg, p, &p);
2326 g_assert (klass->rank > 0);
2327 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2328 encode_value (klass->rank, p, &p);
2329 encode_klass_ref (acfg, klass->element_class, p, &p);
2337 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2338 * standard metadata encoding.
2341 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2343 gboolean shared = FALSE;
2346 * The encoding of generic instances is large so emit them only once.
2348 if (klass->generic_class) {
2350 g_assert (klass->type_token);
2352 /* Find a typespec for a class if possible */
2353 token = find_typespec_for_class (acfg, klass);
2356 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2361 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2365 buf2 = g_malloc (1024);
2368 encode_klass_ref_inner (acfg, klass, p, &p);
2369 g_assert (p - buf2 < 1024);
2371 offset = add_to_blob (acfg, buf2, p - buf2);
2374 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2380 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2381 encode_value (offset, p, &p);
2386 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2390 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2392 guint32 token = mono_get_field_token (field);
2395 encode_klass_ref (cfg, field->parent, p, &p);
2396 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2397 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2402 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2407 encode_value (inst->type_argc, p, &p);
2408 for (i = 0; i < inst->type_argc; ++i)
2409 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2414 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2417 MonoGenericInst *inst;
2419 inst = context->class_inst;
2421 g_assert (inst->type_argc);
2422 encode_ginst (acfg, inst, p, &p);
2424 encode_value (0, p, &p);
2426 inst = context->method_inst;
2428 g_assert (inst->type_argc);
2429 encode_ginst (acfg, inst, p, &p);
2431 encode_value (0, p, &p);
2437 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2441 g_assert (t->num_mods == 0);
2442 /* t->attrs can be ignored */
2443 //g_assert (t->attrs == 0);
2446 *p = MONO_TYPE_PINNED;
2450 *p = MONO_TYPE_BYREF;
2458 case MONO_TYPE_VOID:
2459 case MONO_TYPE_BOOLEAN:
2460 case MONO_TYPE_CHAR:
2473 case MONO_TYPE_STRING:
2474 case MONO_TYPE_OBJECT:
2475 case MONO_TYPE_TYPEDBYREF:
2477 case MONO_TYPE_VALUETYPE:
2478 case MONO_TYPE_CLASS:
2479 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2481 case MONO_TYPE_SZARRAY:
2482 encode_klass_ref (acfg, t->data.klass, p, &p);
2485 encode_type (acfg, t->data.type, p, &p);
2487 case MONO_TYPE_GENERICINST: {
2488 MonoClass *gclass = t->data.generic_class->container_class;
2489 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2491 encode_klass_ref (acfg, gclass, p, &p);
2492 encode_ginst (acfg, inst, p, &p);
2495 case MONO_TYPE_ARRAY: {
2496 MonoArrayType *array = t->data.array;
2499 encode_klass_ref (acfg, array->eklass, p, &p);
2500 encode_value (array->rank, p, &p);
2501 encode_value (array->numsizes, p, &p);
2502 for (i = 0; i < array->numsizes; ++i)
2503 encode_value (array->sizes [i], p, &p);
2504 encode_value (array->numlobounds, p, &p);
2505 for (i = 0; i < array->numlobounds; ++i)
2506 encode_value (array->lobounds [i], p, &p);
2510 case MONO_TYPE_MVAR:
2511 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2514 g_assert_not_reached ();
2521 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2527 /* Similar to the metadata encoding */
2528 if (sig->generic_param_count)
2532 if (sig->explicit_this)
2534 flags |= (sig->call_convention & 0x0F);
2538 if (sig->generic_param_count)
2539 encode_value (sig->generic_param_count, p, &p);
2540 encode_value (sig->param_count, p, &p);
2542 encode_type (acfg, sig->ret, p, &p);
2543 for (i = 0; i < sig->param_count; ++i) {
2544 if (sig->sentinelpos == i) {
2545 *p = MONO_TYPE_SENTINEL;
2548 encode_type (acfg, sig->params [i], p, &p);
2554 #define MAX_IMAGE_INDEX 250
2557 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2559 guint32 image_index = get_image_index (acfg, method->klass->image);
2560 guint32 token = method->token;
2561 MonoJumpInfoToken *ji;
2565 * The encoding for most methods is as follows:
2566 * - image index encoded as a leb128
2567 * - token index encoded as a leb128
2568 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2569 * types of method encodings.
2572 /* Mark methods which can't use aot trampolines because they need the further
2573 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2575 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2576 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2577 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2579 if (method->wrapper_type) {
2580 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2582 encode_value (method->wrapper_type, p, &p);
2584 switch (method->wrapper_type) {
2585 case MONO_WRAPPER_REMOTING_INVOKE:
2586 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2587 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2590 m = mono_marshal_method_from_wrapper (method);
2592 encode_method_ref (acfg, m, p, &p);
2595 case MONO_WRAPPER_PROXY_ISINST:
2596 case MONO_WRAPPER_LDFLD:
2597 case MONO_WRAPPER_LDFLDA:
2598 case MONO_WRAPPER_STFLD:
2599 case MONO_WRAPPER_ISINST: {
2600 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2601 encode_klass_ref (acfg, proxy_class, p, &p);
2604 case MONO_WRAPPER_LDFLD_REMOTE:
2605 case MONO_WRAPPER_STFLD_REMOTE:
2607 case MONO_WRAPPER_ALLOC: {
2608 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2610 /* The GC name is saved once in MonoAotFileInfo */
2611 g_assert (info->alloc_type != -1);
2612 encode_value (info->alloc_type, p, &p);
2615 case MONO_WRAPPER_WRITE_BARRIER:
2617 case MONO_WRAPPER_STELEMREF: {
2618 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2621 encode_value (info->subtype, p, &p);
2622 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2623 encode_value (info->d.virtual_stelemref.kind, p, &p);
2626 case MONO_WRAPPER_UNKNOWN: {
2627 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2630 encode_value (info->subtype, p, &p);
2631 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2632 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2633 encode_klass_ref (acfg, method->klass, p, &p);
2634 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2635 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2636 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2637 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2640 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2641 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2644 encode_value (info->subtype, p, &p);
2645 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2646 strcpy ((char*)p, method->name);
2647 p += strlen (method->name) + 1;
2648 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2649 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2651 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2652 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2656 case MONO_WRAPPER_SYNCHRONIZED: {
2659 m = mono_marshal_method_from_wrapper (method);
2661 g_assert (m != method);
2662 encode_method_ref (acfg, m, p, &p);
2665 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2666 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2669 encode_value (info->subtype, p, &p);
2671 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2672 encode_value (info->d.element_addr.rank, p, &p);
2673 encode_value (info->d.element_addr.elem_size, p, &p);
2674 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2675 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2677 g_assert_not_reached ();
2681 case MONO_WRAPPER_CASTCLASS: {
2682 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2685 encode_value (info->subtype, p, &p);
2688 case MONO_WRAPPER_RUNTIME_INVOKE: {
2689 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2692 encode_value (info->subtype, p, &p);
2693 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2694 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2695 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2696 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2699 case MONO_WRAPPER_DELEGATE_INVOKE:
2700 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2701 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2702 if (method->is_inflated) {
2703 /* These wrappers are identified by their class */
2704 encode_value (1, p, &p);
2705 encode_klass_ref (acfg, method->klass, p, &p);
2707 MonoMethodSignature *sig = mono_method_signature (method);
2708 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2710 encode_value (0, p, &p);
2711 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2712 encode_value (info ? info->subtype : 0, p, &p);
2713 encode_signature (acfg, sig, p, &p);
2717 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2718 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2721 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2722 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2726 g_assert_not_reached ();
2728 } else if (mono_method_signature (method)->is_inflated) {
2730 * This is a generic method, find the original token which referenced it and
2732 * Obtain the token from information recorded by the JIT.
2734 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2736 image_index = get_image_index (acfg, ji->image);
2737 g_assert (image_index < MAX_IMAGE_INDEX);
2740 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2741 encode_value (image_index, p, &p);
2742 encode_value (token, p, &p);
2744 MonoMethod *declaring;
2745 MonoGenericContext *context = mono_method_get_context (method);
2747 g_assert (method->is_inflated);
2748 declaring = ((MonoMethodInflated*)method)->declaring;
2751 * This might be a non-generic method of a generic instance, which
2752 * doesn't have a token since the reference is generated by the JIT
2753 * like Nullable:Box/Unbox, or by generic sharing.
2755 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2756 /* Encode the klass */
2757 encode_klass_ref (acfg, method->klass, p, &p);
2758 /* Encode the method */
2759 image_index = get_image_index (acfg, method->klass->image);
2760 g_assert (image_index < MAX_IMAGE_INDEX);
2761 g_assert (declaring->token);
2762 token = declaring->token;
2763 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2764 encode_value (image_index, p, &p);
2765 encode_value (token, p, &p);
2766 encode_generic_context (acfg, context, p, &p);
2768 } else if (token == 0) {
2769 /* This might be a method of a constructed type like int[,].Set */
2770 /* Obtain the token from information recorded by the JIT */
2771 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2773 image_index = get_image_index (acfg, ji->image);
2774 g_assert (image_index < MAX_IMAGE_INDEX);
2777 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2778 encode_value (image_index, p, &p);
2779 encode_value (token, p, &p);
2782 g_assert (method->klass->rank);
2784 /* Encode directly */
2785 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2786 encode_klass_ref (acfg, method->klass, p, &p);
2787 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2788 encode_value (0, p, &p);
2789 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2790 encode_value (1, p, &p);
2791 else if (!strcmp (method->name, "Get"))
2792 encode_value (2, p, &p);
2793 else if (!strcmp (method->name, "Address"))
2794 encode_value (3, p, &p);
2795 else if (!strcmp (method->name, "Set"))
2796 encode_value (4, p, &p);
2798 g_assert_not_reached ();
2801 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2803 if (image_index >= MONO_AOT_METHODREF_MIN) {
2804 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2805 encode_value (image_index, p, &p);
2806 encode_value (mono_metadata_token_index (token), p, &p);
2808 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2815 compare_patches (gconstpointer a, gconstpointer b)
2819 i = (*(MonoJumpInfo**)a)->ip.i;
2820 j = (*(MonoJumpInfo**)b)->ip.i;
2831 static G_GNUC_UNUSED char*
2832 patch_to_string (MonoJumpInfo *patch_info)
2836 str = g_string_new ("");
2838 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2840 switch (patch_info->type) {
2841 case MONO_PATCH_INFO_VTABLE:
2842 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2847 g_string_append_printf (str, ")");
2848 return g_string_free (str, FALSE);
2854 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2857 static inline gboolean
2858 is_plt_patch (MonoJumpInfo *patch_info)
2860 switch (patch_info->type) {
2861 case MONO_PATCH_INFO_METHOD:
2862 case MONO_PATCH_INFO_INTERNAL_METHOD:
2863 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2864 case MONO_PATCH_INFO_ICALL_ADDR:
2865 case MONO_PATCH_INFO_CLASS_INIT:
2866 case MONO_PATCH_INFO_RGCTX_FETCH:
2867 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2868 case MONO_PATCH_INFO_MONITOR_ENTER:
2869 case MONO_PATCH_INFO_MONITOR_EXIT:
2870 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2880 * Return the symbol identifying the plt entry PLT_OFFSET.
2883 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2887 * The Apple linker reorganizes object files, so it doesn't like branches to local
2888 * labels, since those have no relocations.
2890 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2892 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2899 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2901 static MonoPltEntry*
2902 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2906 if (!is_plt_patch (patch_info))
2909 if (!acfg->patch_to_plt_entry [patch_info->type])
2910 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
2911 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
2913 // FIXME: This breaks the calculation of final_got_size
2914 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2916 * Allocate a separate PLT slot for each such patch, since some plt
2917 * entries will refer to the method itself, and some will refer to the
2924 MonoJumpInfo *new_ji;
2926 g_assert (!acfg->final_got_size);
2928 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2930 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2931 res->plt_offset = acfg->plt_offset;
2933 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2934 if (acfg->aot_opts.write_symbols)
2935 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2937 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2939 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2941 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
2943 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2945 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2946 //mono_print_ji (patch_info); printf ("\n");
2947 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2949 acfg->plt_offset ++;
2958 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2959 * JI could be found if it exists, otherwise allocates a new one.
2962 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2966 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2968 return got_offset - 1;
2970 got_offset = acfg->got_offset;
2971 acfg->got_offset ++;
2973 if (acfg->final_got_size)
2974 g_assert (got_offset < acfg->final_got_size);
2976 acfg->stats.got_slots ++;
2977 acfg->stats.got_slot_types [ji->type] ++;
2979 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2980 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2981 g_ptr_array_add (acfg->got_patches, ji);
2986 /* Add a method to the list of methods which need to be emitted */
2988 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2991 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2992 g_ptr_array_add (acfg->methods, method);
2993 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2994 acfg->nmethods = acfg->methods->len + 1;
2997 if (method->wrapper_type || extra)
2998 g_ptr_array_add (acfg->extra_methods, method);
3002 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3004 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3012 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3016 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3020 index = acfg->method_index;
3021 add_method_with_index (acfg, method, index, extra);
3023 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3025 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3027 acfg->method_index ++;
3033 add_method (MonoAotCompile *acfg, MonoMethod *method)
3035 return add_method_full (acfg, method, FALSE, 0);
3039 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3041 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3042 method = mini_get_shared_method (method);
3044 if (acfg->aot_opts.log_generics)
3045 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3047 add_method_full (acfg, method, TRUE, depth);
3051 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3053 add_extra_method_with_depth (acfg, method, 0);
3057 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3059 MonoAotCompile *acfg = user_data;
3060 MonoJitICallInfo *callinfo = value;
3061 MonoMethod *wrapper;
3067 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3068 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3071 add_method (acfg, wrapper);
3075 get_runtime_invoke_sig (MonoMethodSignature *sig)
3077 MonoMethodBuilder *mb;
3080 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3081 m = mono_mb_create_method (mb, sig, 16);
3082 return mono_marshal_get_runtime_invoke (m, FALSE);
3086 can_marshal_struct (MonoClass *klass)
3088 MonoClassField *field;
3089 gboolean can_marshal = TRUE;
3090 gpointer iter = NULL;
3091 MonoMarshalType *info;
3094 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3097 info = mono_marshal_load_type_info (klass);
3099 /* Only allow a few field types to avoid asserts in the marshalling code */
3100 while ((field = mono_class_get_fields (klass, &iter))) {
3101 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3104 switch (field->type->type) {
3109 case MONO_TYPE_BOOLEAN:
3112 case MONO_TYPE_CHAR:
3120 case MONO_TYPE_STRING:
3122 case MONO_TYPE_VALUETYPE:
3123 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3124 can_marshal = FALSE;
3126 case MONO_TYPE_SZARRAY: {
3127 gboolean has_mspec = FALSE;
3130 for (i = 0; i < info->num_fields; ++i) {
3131 if (info->fields [i].field == field && info->fields [i].mspec)
3136 can_marshal = FALSE;
3140 can_marshal = FALSE;
3146 /* Its hard to compute whenever these can be marshalled or not */
3147 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3154 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3156 /* Create a vtype instantiation */
3157 MonoGenericContext shared_context;
3159 MonoGenericInst *inst;
3160 MonoGenericContainer *container;
3161 MonoClass **constraints;
3164 memset (ctx, 0, sizeof (MonoGenericContext));
3166 if (method->klass->generic_container) {
3167 shared_context = method->klass->generic_container->context;
3168 inst = shared_context.class_inst;
3170 args = g_new0 (MonoType*, inst->type_argc);
3171 for (i = 0; i < inst->type_argc; ++i) {
3172 args [i] = &mono_defaults.int_class->byval_arg;
3174 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3176 if (method->is_generic) {
3177 container = mono_method_get_generic_container (method);
3178 shared_context = container->context;
3179 inst = shared_context.method_inst;
3181 args = g_new0 (MonoType*, inst->type_argc);
3182 for (i = 0; i < container->type_argc; ++i) {
3183 MonoGenericParamInfo *info = &container->type_params [i].info;
3184 gboolean ref_only = FALSE;
3186 if (info && info->constraints) {
3187 constraints = info->constraints;
3189 while (*constraints) {
3190 MonoClass *cklass = *constraints;
3191 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3192 /* Inflaring the method with our vtype would not be valid */
3199 args [i] = &mono_defaults.object_class->byval_arg;
3201 args [i] = &mono_defaults.int_class->byval_arg;
3203 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3208 add_wrappers (MonoAotCompile *acfg)
3210 MonoMethod *method, *m;
3212 MonoMethodSignature *sig, *csig;
3216 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3217 * so there is only one wrapper of a given type, or inlining their contents into their
3220 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3222 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3223 gboolean skip = FALSE;
3225 method = mono_get_method (acfg->image, token, NULL);
3227 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3228 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3229 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3232 /* Skip methods which can not be handled by get_runtime_invoke () */
3233 sig = mono_method_signature (method);
3236 if ((sig->ret->type == MONO_TYPE_PTR) ||
3237 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3239 if (mono_class_is_open_constructed_type (sig->ret))
3242 for (j = 0; j < sig->param_count; j++) {
3243 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3245 if (mono_class_is_open_constructed_type (sig->params [j]))
3249 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3250 if (!mono_class_is_contextbound (method->klass)) {
3251 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3252 gboolean has_nullable = FALSE;
3254 for (j = 0; j < sig->param_count; j++) {
3255 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3256 has_nullable = TRUE;
3259 if (info && !has_nullable) {
3260 /* Supported by the dynamic runtime-invoke wrapper */
3268 //printf ("%s\n", mono_method_full_name (method, TRUE));
3269 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3273 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3274 MonoMethodDesc *desc;
3275 MonoMethod *orig_method;
3278 /* Runtime invoke wrappers */
3280 /* void runtime-invoke () [.cctor] */
3281 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3282 csig->ret = &mono_defaults.void_class->byval_arg;
3283 add_method (acfg, get_runtime_invoke_sig (csig));
3285 /* void runtime-invoke () [Finalize] */
3286 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3288 csig->ret = &mono_defaults.void_class->byval_arg;
3289 add_method (acfg, get_runtime_invoke_sig (csig));
3291 /* void runtime-invoke (string) [exception ctor] */
3292 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3294 csig->ret = &mono_defaults.void_class->byval_arg;
3295 csig->params [0] = &mono_defaults.string_class->byval_arg;
3296 add_method (acfg, get_runtime_invoke_sig (csig));
3298 /* void runtime-invoke (string, string) [exception ctor] */
3299 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3301 csig->ret = &mono_defaults.void_class->byval_arg;
3302 csig->params [0] = &mono_defaults.string_class->byval_arg;
3303 csig->params [1] = &mono_defaults.string_class->byval_arg;
3304 add_method (acfg, get_runtime_invoke_sig (csig));
3306 /* string runtime-invoke () [Exception.ToString ()] */
3307 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3309 csig->ret = &mono_defaults.string_class->byval_arg;
3310 add_method (acfg, get_runtime_invoke_sig (csig));
3312 /* void runtime-invoke (string, Exception) [exception ctor] */
3313 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3315 csig->ret = &mono_defaults.void_class->byval_arg;
3316 csig->params [0] = &mono_defaults.string_class->byval_arg;
3317 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3318 add_method (acfg, get_runtime_invoke_sig (csig));
3320 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3321 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3323 csig->ret = &(mono_class_from_name (
3324 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3325 csig->params [0] = &mono_defaults.string_class->byval_arg;
3326 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3327 add_method (acfg, get_runtime_invoke_sig (csig));
3329 /* runtime-invoke used by finalizers */
3330 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3332 /* This is used by mono_runtime_capture_context () */
3333 method = mono_get_context_capture_method ();
3335 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3337 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3338 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3342 add_method (acfg, mono_marshal_get_stelemref ());
3344 if (MONO_ARCH_HAVE_TLS_GET) {
3345 /* Managed Allocators */
3346 nallocators = mono_gc_get_managed_allocator_types ();
3347 for (i = 0; i < nallocators; ++i) {
3348 m = mono_gc_get_managed_allocator_by_type (i);
3350 add_method (acfg, m);
3353 /* Monitor Enter/Exit */
3354 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3355 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3356 /* This is a v4 method */
3358 method = mono_monitor_get_fast_path (orig_method);
3360 add_method (acfg, method);
3362 mono_method_desc_free (desc);
3364 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3365 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3366 g_assert (orig_method);
3367 mono_method_desc_free (desc);
3368 method = mono_monitor_get_fast_path (orig_method);
3370 add_method (acfg, method);
3373 /* Stelemref wrappers */
3375 MonoMethod **wrappers;
3378 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3379 for (i = 0; i < nwrappers; ++i)
3380 add_method (acfg, wrappers [i]);
3384 /* castclass_with_check wrapper */
3385 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3386 /* isinst_with_check wrapper */
3387 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3389 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3391 MonoMethodDesc *desc;
3394 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3395 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3396 mono_method_desc_free (desc);
3398 m = mono_monitor_get_fast_path (m);
3400 add_method (acfg, m);
3405 /* JIT icall wrappers */
3406 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3407 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3411 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3412 * we use the original method instead at runtime.
3413 * Since full-aot doesn't support remoting, this is not a problem.
3416 /* remoting-invoke wrappers */
3417 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3418 MonoMethodSignature *sig;
3420 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3421 method = mono_get_method (acfg->image, token, NULL);
3423 sig = mono_method_signature (method);
3425 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3426 m = mono_marshal_get_remoting_invoke_with_check (method);
3428 add_method (acfg, m);
3433 /* delegate-invoke wrappers */
3434 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3436 MonoCustomAttrInfo *cattr;
3438 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3439 klass = mono_class_get (acfg->image, token);
3442 mono_loader_clear_error ();
3446 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3449 if (!klass->generic_container) {
3450 method = mono_get_delegate_invoke (klass);
3452 m = mono_marshal_get_delegate_invoke (method, NULL);
3454 add_method (acfg, m);
3456 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3458 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3460 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3462 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3464 cattr = mono_custom_attrs_from_class (klass);
3469 for (j = 0; j < cattr->num_attrs; ++j)
3470 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3472 if (j < cattr->num_attrs)
3473 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3475 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3476 MonoGenericContext ctx;
3477 MonoMethod *inst, *gshared;
3480 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3483 method = mono_get_delegate_invoke (klass);
3484 create_gsharedvt_inst (acfg, method, &ctx);
3486 inst = mono_class_inflate_generic_method (method, &ctx);
3488 m = mono_marshal_get_delegate_invoke (inst, NULL);
3489 g_assert (m->is_inflated);
3491 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3492 add_extra_method (acfg, gshared);
3495 method = mono_get_delegate_begin_invoke (klass);
3496 create_gsharedvt_inst (acfg, method, &ctx);
3498 inst = mono_class_inflate_generic_method (method, &ctx);
3500 m = mono_marshal_get_delegate_begin_invoke (inst);
3501 g_assert (m->is_inflated);
3503 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3504 add_extra_method (acfg, gshared);
3507 method = mono_get_delegate_end_invoke (klass);
3508 create_gsharedvt_inst (acfg, method, &ctx);
3510 inst = mono_class_inflate_generic_method (method, &ctx);
3512 m = mono_marshal_get_delegate_end_invoke (inst);
3513 g_assert (m->is_inflated);
3515 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3516 add_extra_method (acfg, gshared);
3521 /* array access wrappers */
3522 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3525 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3526 klass = mono_class_get (acfg->image, token);
3529 mono_loader_clear_error ();
3533 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3534 MonoMethod *m, *wrapper;
3536 /* Add runtime-invoke wrappers too */
3538 m = mono_class_get_method_from_name (klass, "Get", -1);
3540 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3541 add_extra_method (acfg, wrapper);
3542 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3544 m = mono_class_get_method_from_name (klass, "Set", -1);
3546 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3547 add_extra_method (acfg, wrapper);
3548 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3552 /* Synchronized wrappers */
3553 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3554 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3555 method = mono_get_method (acfg->image, token, NULL);
3557 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3558 if (method->is_generic) {
3560 } else if (method->klass->generic_container) {
3561 MonoGenericContext ctx;
3562 MonoMethod *inst, *gshared, *m;
3565 * Create a generic wrapper for a generic instance, and AOT that.
3567 create_gsharedvt_inst (acfg, method, &ctx);
3568 inst = mono_class_inflate_generic_method (method, &ctx);
3569 m = mono_marshal_get_synchronized_wrapper (inst);
3570 g_assert (m->is_inflated);
3571 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3572 add_method (acfg, gshared);
3574 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3579 /* pinvoke wrappers */
3580 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3582 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3584 method = mono_get_method (acfg->image, token, NULL);
3586 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3587 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3588 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3592 /* native-to-managed wrappers */
3593 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3595 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3596 MonoCustomAttrInfo *cattr;
3599 method = mono_get_method (acfg->image, token, NULL);
3602 * Only generate native-to-managed wrappers for methods which have an
3603 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3604 * name to avoid defining a new assembly to contain it.
3606 cattr = mono_custom_attrs_from_method (method);
3609 for (j = 0; j < cattr->num_attrs; ++j)
3610 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3612 if (j < cattr->num_attrs) {
3613 MonoCustomAttrEntry *e = &cattr->attrs [j];
3614 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3615 const char *p = (const char*)e->data;
3617 int slen, num_named, named_type, data_type;
3621 char *export_name = NULL;
3622 MonoMethod *wrapper;
3624 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3625 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3626 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3627 mono_method_full_name (method, TRUE));
3631 g_assert (sig->param_count == 1);
3632 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3635 * Decode the cattr manually since we can't create objects
3636 * during aot compilation.
3642 /* From load_cattr_value () in reflection.c */
3643 slen = mono_metadata_decode_value (p, &p);
3644 n = g_memdup (p, slen + 1);
3646 t = mono_reflection_type_from_name (n, acfg->image);
3650 klass = mono_class_from_mono_type (t);
3651 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3655 num_named = read16 (p);
3658 g_assert (num_named < 2);
3659 if (num_named == 1) {
3662 MonoType *prop_type;
3664 /* parse ExportSymbol attribute */
3666 named_type = *named;
3671 name_len = mono_metadata_decode_blob_size (named, &named);
3672 name = g_malloc (name_len + 1);
3673 memcpy (name, named, name_len);
3674 name [name_len] = 0;
3677 g_assert (named_type == 0x54);
3678 g_assert (!strcmp (name, "ExportSymbol"));
3680 prop_type = &mono_defaults.string_class->byval_arg;
3682 /* load_cattr_value (), string case */
3683 g_assert (*named != (char)0xff);
3684 slen = mono_metadata_decode_value (named, &named);
3685 export_name = g_malloc (slen + 1);
3686 memcpy (export_name, named, slen);
3687 export_name [slen] = 0;
3691 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3692 add_method (acfg, wrapper);
3694 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3698 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3699 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3700 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3704 /* StructureToPtr/PtrToStructure wrappers */
3705 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3708 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3709 klass = mono_class_get (acfg->image, token);
3712 mono_loader_clear_error ();
3716 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3717 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3718 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3719 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3725 has_type_vars (MonoClass *klass)
3727 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3730 return has_type_vars (klass->element_class);
3731 if (klass->generic_class) {
3732 MonoGenericContext *context = &klass->generic_class->context;
3733 if (context->class_inst) {
3736 for (i = 0; i < context->class_inst->type_argc; ++i)
3737 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3741 if (klass->generic_container)
3747 is_vt_inst (MonoGenericInst *inst)
3751 for (i = 0; i < inst->type_argc; ++i) {
3752 MonoType *t = inst->type_argv [i];
3753 if (t->type == MONO_TYPE_VALUETYPE)
3760 method_has_type_vars (MonoMethod *method)
3762 if (has_type_vars (method->klass))
3765 if (method->is_inflated) {
3766 MonoGenericContext *context = mono_method_get_context (method);
3767 if (context->method_inst) {
3770 for (i = 0; i < context->method_inst->type_argc; ++i)
3771 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3778 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3781 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3783 /* This might lead to a huge code blowup so only do it if neccesary */
3784 if (!acfg->aot_opts.full_aot && !force)
3787 add_generic_class_with_depth (acfg, klass, 0, ref);
3791 check_type_depth (MonoType *t, int depth)
3799 case MONO_TYPE_GENERICINST: {
3800 MonoGenericClass *gklass = t->data.generic_class;
3801 MonoGenericInst *ginst = gklass->context.class_inst;
3804 for (i = 0; i < ginst->type_argc; ++i) {
3805 if (check_type_depth (ginst->type_argv [i], depth + 1))
3819 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3822 * add_generic_class:
3824 * Add all methods of a generic class.
3827 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3830 MonoClassField *field;
3832 gboolean use_gsharedvt = FALSE;
3834 if (!acfg->ginst_hash)
3835 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3837 mono_class_init (klass);
3839 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3842 if (has_type_vars (klass))
3845 if (!klass->generic_class && !klass->rank)
3848 if (klass->exception_type)
3851 if (!acfg->ginst_hash)
3852 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3854 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3857 if (check_type_depth (&klass->byval_arg, 0))
3860 if (acfg->aot_opts.log_generics)
3861 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3863 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3866 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3867 * Enable this only for some classes since gsharedvt might not support all methods.
3869 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")))
3870 use_gsharedvt = TRUE;
3873 while ((method = mono_class_get_methods (klass, &iter))) {
3874 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3876 * This is partial sharing, and we can't handle it yet
3881 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
3883 add_types_from_method_header (acfg, method);
3887 if (method->is_generic)
3892 * FIXME: Instances which are referenced by these methods are not added,
3893 * for example Array.Resize<int> for List<int>.Add ().
3895 add_extra_method_with_depth (acfg, method, depth + 1);
3899 while ((field = mono_class_get_fields (klass, &iter))) {
3900 if (field->type->type == MONO_TYPE_GENERICINST)
3901 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3904 if (klass->delegate) {
3905 method = mono_get_delegate_invoke (klass);
3907 method = mono_marshal_get_delegate_invoke (method, NULL);
3909 if (acfg->aot_opts.log_generics)
3910 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3912 add_method (acfg, method);
3915 /* Add superclasses */
3917 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3920 * For ICollection<T>, add instances of the helper methods
3921 * in Array, since a T[] could be cast to ICollection<T>.
3923 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3924 (!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"))) {
3925 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3926 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3930 if (!strcmp (klass->name, "IEnumerator`1"))
3931 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3933 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3935 /* Add the T[]/InternalEnumerator class */
3936 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3940 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3941 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3945 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3946 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3950 while ((method = mono_class_get_methods (array_class, &iter))) {
3951 if (strstr (method->name, name_prefix)) {
3952 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3954 add_extra_method_with_depth (acfg, m, depth);
3958 g_free (name_prefix);
3961 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3962 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3963 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3964 MonoClass *icomparable, *gcomparer;
3965 MonoGenericContext ctx;
3966 MonoType *args [16];
3968 memset (&ctx, 0, sizeof (ctx));
3970 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3971 g_assert (icomparable);
3972 args [0] = &tclass->byval_arg;
3973 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3975 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3976 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3977 g_assert (gcomparer);
3978 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3982 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3983 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3984 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3985 MonoClass *iface, *gcomparer;
3986 MonoGenericContext ctx;
3987 MonoType *args [16];
3989 memset (&ctx, 0, sizeof (ctx));
3991 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3993 args [0] = &tclass->byval_arg;
3994 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3996 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3997 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3998 g_assert (gcomparer);
3999 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4005 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4008 MonoGenericContext ctx;
4009 MonoType *args [16];
4011 if (acfg->aot_opts.no_instances)
4014 memset (&ctx, 0, sizeof (ctx));
4016 for (i = 0; i < ninsts; ++i) {
4017 args [0] = insts [i];
4018 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4019 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4024 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4026 MonoMethodHeader *header;
4027 MonoMethodSignature *sig;
4030 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4032 sig = mono_method_signature (method);
4035 for (j = 0; j < sig->param_count; ++j)
4036 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4037 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4040 header = mono_method_get_header (method);
4043 for (j = 0; j < header->num_locals; ++j)
4044 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4045 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4047 mono_loader_clear_error ();
4052 * add_generic_instances:
4054 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4057 add_generic_instances (MonoAotCompile *acfg)
4062 MonoGenericContext *context;
4064 if (acfg->aot_opts.no_instances)
4067 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4068 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4069 method = mono_get_method (acfg->image, token, NULL);
4074 if (method->klass->image != acfg->image)
4077 context = mono_method_get_context (method);
4079 if (context && ((context->class_inst && context->class_inst->is_open)))
4083 * For open methods, create an instantiation which can be passed to the JIT.
4084 * FIXME: Handle class_inst as well.
4086 if (context && context->method_inst && context->method_inst->is_open) {
4087 MonoGenericContext shared_context;
4088 MonoGenericInst *inst;
4089 MonoType **type_argv;
4091 MonoMethod *declaring_method;
4092 gboolean supported = TRUE;
4094 /* Check that the context doesn't contain open constructed types */
4095 if (context->class_inst) {
4096 inst = context->class_inst;
4097 for (i = 0; i < inst->type_argc; ++i) {
4098 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)
4100 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4104 if (context->method_inst) {
4105 inst = context->method_inst;
4106 for (i = 0; i < inst->type_argc; ++i) {
4107 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)
4109 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4117 memset (&shared_context, 0, sizeof (MonoGenericContext));
4119 inst = context->class_inst;
4121 type_argv = g_new0 (MonoType*, inst->type_argc);
4122 for (i = 0; i < inst->type_argc; ++i) {
4123 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)
4124 type_argv [i] = &mono_defaults.object_class->byval_arg;
4126 type_argv [i] = inst->type_argv [i];
4129 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4133 inst = context->method_inst;
4135 type_argv = g_new0 (MonoType*, inst->type_argc);
4136 for (i = 0; i < inst->type_argc; ++i) {
4137 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
4138 type_argv [i] = &mono_defaults.object_class->byval_arg;
4140 type_argv [i] = inst->type_argv [i];
4143 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4147 if (method->is_generic || method->klass->generic_container)
4148 declaring_method = method;
4150 declaring_method = mono_method_get_declaring_generic_method (method);
4152 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4156 * If the method is fully sharable, it was already added in place of its
4157 * generic definition.
4159 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4163 * FIXME: Partially shared methods are not shared here, so we end up with
4164 * many identical methods.
4166 add_extra_method (acfg, method);
4169 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4172 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4174 klass = mono_class_get (acfg->image, token);
4175 if (!klass || klass->rank) {
4176 mono_loader_clear_error ();
4180 add_generic_class (acfg, klass, FALSE, "typespec");
4183 /* Add types of args/locals */
4184 for (i = 0; i < acfg->methods->len; ++i) {
4185 method = g_ptr_array_index (acfg->methods, i);
4186 add_types_from_method_header (acfg, method);
4189 if (acfg->image == mono_defaults.corlib) {
4191 MonoType *insts [256];
4194 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4195 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4196 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4197 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4198 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4199 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4200 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4201 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4202 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4203 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4204 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4205 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4207 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4208 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4210 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4211 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4213 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4215 /* Add instances of the array generic interfaces for primitive types */
4216 /* This will add instances of the InternalArray_ helper methods in Array too */
4217 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4219 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4220 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4222 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4223 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4225 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4228 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4229 * used for all instances of GetGenericValueImpl by the AOT runtime.
4232 MonoGenericContext ctx;
4233 MonoType *args [16];
4234 MonoMethod *get_method;
4235 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4237 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4240 memset (&ctx, 0, sizeof (ctx));
4241 args [0] = &mono_defaults.object_class->byval_arg;
4242 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4243 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4247 /* Same for CompareExchange<T>/Exchange<T> */
4249 MonoGenericContext ctx;
4250 MonoType *args [16];
4252 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4253 gpointer iter = NULL;
4255 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4256 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4257 memset (&ctx, 0, sizeof (ctx));
4258 args [0] = &mono_defaults.object_class->byval_arg;
4259 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4260 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4265 /* Same for Volatile.Read/Write<T> */
4267 MonoGenericContext ctx;
4268 MonoType *args [16];
4270 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4271 gpointer iter = NULL;
4273 if (volatile_klass) {
4274 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4275 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4276 memset (&ctx, 0, sizeof (ctx));
4277 args [0] = &mono_defaults.object_class->byval_arg;
4278 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4279 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4288 * is_direct_callable:
4290 * Return whenever the method identified by JI is directly callable without
4291 * going through the PLT.
4294 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4296 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4297 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4299 gboolean direct_callable = TRUE;
4301 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4302 direct_callable = FALSE;
4303 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4304 // FIXME: Maybe call the wrapper directly ?
4305 direct_callable = FALSE;
4307 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4308 /* Disable this so all calls go through load_method (), see the
4309 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4310 * mono_debugger_agent_init ().
4312 direct_callable = FALSE;
4315 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4316 /* sgen does some initialization when the allocator method is created */
4317 direct_callable = FALSE;
4319 if (direct_callable)
4322 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4323 if (acfg->aot_opts.direct_pinvoke)
4325 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4326 if (acfg->aot_opts.direct_icalls)
4335 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4337 MonoImage *image = method->klass->image;
4338 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4339 MonoTableInfo *tables = image->tables;
4340 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4341 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4342 guint32 im_cols [MONO_IMPLMAP_SIZE];
4345 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4349 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4352 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4354 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4357 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4359 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4365 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4367 if (a->native_offset == b->native_offset)
4368 return a->il_offset - b->il_offset;
4370 return a->native_offset - b->native_offset;
4374 * compute_line_numbers:
4376 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4379 static MonoDebugSourceLocation**
4380 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4382 MonoDebugMethodInfo *minfo;
4383 MonoDebugLineNumberEntry *ln_array;
4384 MonoDebugSourceLocation *loc;
4385 int i, prev_line, prev_il_offset;
4386 int *native_to_il_offset = NULL;
4387 MonoDebugSourceLocation **res;
4390 minfo = mono_debug_lookup_method (method);
4393 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4394 if (debug_info->code_size != code_size)
4397 g_assert (code_size);
4399 /* Compute the native->IL offset mapping */
4401 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4402 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4404 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4406 native_to_il_offset = g_new0 (int, code_size + 1);
4408 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4410 MonoDebugLineNumberEntry *lne = &ln_array [i];
4413 for (j = 0; j < lne->native_offset; ++j)
4414 native_to_il_offset [j] = -1;
4417 if (i < debug_info->num_line_numbers - 1) {
4418 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4420 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4421 native_to_il_offset [j] = lne->il_offset;
4423 for (j = lne->native_offset; j < code_size; ++j)
4424 native_to_il_offset [j] = lne->il_offset;
4429 /* Compute the native->line number mapping */
4430 res = g_new0 (MonoDebugSourceLocation*, code_size);
4431 prev_il_offset = -1;
4434 for (i = 0; i < code_size; ++i) {
4435 int il_offset = native_to_il_offset [i];
4437 if (il_offset == -1 || il_offset == prev_il_offset)
4439 prev_il_offset = il_offset;
4440 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4441 if (!(loc && loc->source_file))
4443 if (loc->row == prev_line) {
4444 mono_debug_symfile_free_location (loc);
4447 prev_line = loc->row;
4448 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4450 /* This will cover the prolog too */
4460 get_file_index (MonoAotCompile *acfg, const char *source_file)
4464 // FIXME: Free these
4465 if (!acfg->dwarf_ln_filenames)
4466 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4467 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4469 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4470 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4471 emit_unset_mode (acfg);
4472 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4478 * emit_and_reloc_code:
4480 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4481 * is true, calls are made through the GOT too. This is used for emitting trampolines
4482 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4483 * since trampolines are needed to make PTL work.
4486 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4488 int i, pindex, start_index, method_index;
4490 MonoJumpInfo *patch_info;
4491 MonoMethodHeader *header;
4492 MonoDebugSourceLocation **locs = NULL;
4493 gboolean skip, direct_call, external_call;
4495 const char *direct_call_target = 0;
4496 const char *direct_pinvoke;
4499 header = mono_method_get_header (method);
4501 method_index = get_method_index (acfg, method);
4504 if (acfg->gas_line_numbers && method && debug_info) {
4505 locs = compute_line_numbers (method, code_len, debug_info);
4507 int findex = get_file_index (acfg, "<unknown>");
4508 emit_unset_mode (acfg);
4509 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4513 /* Collect and sort relocations */
4514 patches = g_ptr_array_new ();
4515 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4516 g_ptr_array_add (patches, patch_info);
4517 g_ptr_array_sort (patches, compare_patches);
4520 for (i = 0; i < code_len; i++) {
4522 for (pindex = start_index; pindex < patches->len; ++pindex) {
4523 patch_info = g_ptr_array_index (patches, pindex);
4524 if (patch_info->ip.i >= i)
4528 if (locs && locs [i]) {
4529 MonoDebugSourceLocation *loc = locs [i];
4532 findex = get_file_index (acfg, loc->source_file);
4533 emit_unset_mode (acfg);
4534 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4535 mono_debug_symfile_free_location (loc);
4539 #ifdef MONO_ARCH_AOT_SUPPORTED
4540 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4541 start_index = pindex;
4543 switch (patch_info->type) {
4544 case MONO_PATCH_INFO_NONE:
4546 case MONO_PATCH_INFO_GOT_OFFSET: {
4549 arch_emit_got_offset (acfg, code + i, &code_size);
4552 patch_info->type = MONO_PATCH_INFO_NONE;
4555 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4556 int code_size, index;
4557 char *selector = (void*)patch_info->data.target;
4559 if (!acfg->objc_selector_to_index)
4560 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4561 if (!acfg->objc_selectors)
4562 acfg->objc_selectors = g_ptr_array_new ();
4563 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4567 index = acfg->objc_selector_index;
4568 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4569 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4570 acfg->objc_selector_index ++;
4573 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4576 patch_info->type = MONO_PATCH_INFO_NONE;
4581 * If this patch is a call, try emitting a direct call instead of
4582 * through a PLT entry. This is possible if the called method is in
4583 * the same assembly and requires no initialization.
4585 direct_call = FALSE;
4586 external_call = FALSE;
4587 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4588 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4589 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4590 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4592 direct_call_target = callee_cfg->asm_symbol;
4593 patch_info->type = MONO_PATCH_INFO_NONE;
4594 acfg->stats.direct_calls ++;
4597 acfg->stats.all_calls ++;
4598 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4599 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4600 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4601 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4603 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4604 if (direct_pinvoke) {
4606 g_assert (strlen (direct_pinvoke) < 1000);
4607 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4610 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4611 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4612 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4613 /* Call to a C function implementing a jit icall */
4615 external_call = TRUE;
4616 g_assert (strlen (sym) < 1000);
4617 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4619 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4620 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4621 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4622 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4623 /* Call to a jit icall without a wrapper */
4625 external_call = TRUE;
4626 g_assert (strlen (sym) < 1000);
4627 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4632 patch_info->type = MONO_PATCH_INFO_NONE;
4633 acfg->stats.direct_calls ++;
4636 if (!got_only && !direct_call) {
4637 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4639 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4641 direct_call_target = plt_entry->symbol;
4643 /* Nullify the patch */
4644 patch_info->type = MONO_PATCH_INFO_NONE;
4645 plt_entry->jit_used = TRUE;
4652 arch_emit_direct_call (acfg, direct_call_target, external_call, patch_info, &call_size);
4657 got_slot = get_got_offset (acfg, patch_info);
4659 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4666 #endif /* MONO_ARCH_AOT_SUPPORTED */
4669 /* Find next patch */
4671 for (pindex = start_index; pindex < patches->len; ++pindex) {
4672 patch_info = g_ptr_array_index (patches, pindex);
4673 if (patch_info->ip.i >= i)
4677 /* Try to emit multiple bytes at once */
4678 if (pindex < patches->len && patch_info->ip.i > i) {
4681 for (limit = i + 1; limit < patch_info->ip.i; ++limit) {
4682 if (locs && locs [limit])
4686 emit_bytes (acfg, code + i, limit - i);
4689 emit_bytes (acfg, code + i, 1);
4700 * Return a modified version of S which only includes characters permissible in symbols.
4703 sanitize_symbol (MonoAotCompile *acfg, char *s)
4705 gboolean process = FALSE;
4714 for (i = 0; i < len; ++i)
4715 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4720 gs = g_string_sized_new (len);
4721 for (i = 0; i < len; ++i) {
4723 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4724 g_string_append_c (gs, c);
4725 } else if (c > 0x7f) {
4726 /* multi-byte utf8 */
4727 g_string_append_printf (gs, "_0x%x", c);
4730 while (c >> 6 == 0x2) {
4731 g_string_append_printf (gs, "%x", c);
4735 g_string_append_printf (gs, "_");
4738 g_string_append_c (gs, '_');
4742 res = mono_mempool_strdup (acfg->mempool, gs->str);
4743 g_string_free (gs, TRUE);
4748 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4750 char *name1, *name2, *cached;
4751 int i, j, len, count;
4754 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4755 if (!prefix || !*prefix)
4759 name1 = mono_method_full_name (method, TRUE);
4760 len = strlen (name1);
4761 name2 = malloc (strlen (prefix) + len + 16);
4762 memcpy (name2, prefix, strlen (prefix));
4763 j = strlen (prefix);
4764 for (i = 0; i < len; ++i) {
4765 if (isalnum (name1 [i])) {
4766 name2 [j ++] = name1 [i];
4767 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4769 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4772 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4781 while (g_hash_table_lookup (cache, name2)) {
4782 sprintf (name2 + j, "_%d", count);
4786 cached = g_strdup (name2);
4787 g_hash_table_insert (cache, cached, cached);
4793 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4798 char *debug_sym = NULL;
4799 char *symbol = NULL;
4800 int func_alignment = AOT_FUNC_ALIGNMENT;
4801 MonoMethodHeader *header;
4804 method = cfg->orig_method;
4805 code = cfg->native_code;
4806 header = cfg->header;
4808 method_index = get_method_index (acfg, method);
4809 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4812 /* Make the labels local */
4813 emit_section_change (acfg, ".text", 0);
4814 emit_alignment (acfg, func_alignment);
4816 if (acfg->global_symbols && acfg->need_no_dead_strip)
4817 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4819 emit_label (acfg, cfg->asm_symbol);
4821 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4823 * Write a C style symbol for every method, this has two uses:
4824 * - it works on platforms where the dwarf debugging info is not
4826 * - it allows the setting of breakpoints of aot-ed methods.
4828 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4830 if (acfg->need_no_dead_strip)
4831 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4832 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4833 emit_label (acfg, debug_sym);
4836 export_name = g_hash_table_lookup (acfg->export_names, method);
4838 /* Emit a global symbol for the method */
4839 emit_global_inner (acfg, export_name, TRUE);
4840 emit_label (acfg, export_name);
4843 if (cfg->verbose_level > 0)
4844 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4846 acfg->stats.code_size += cfg->code_len;
4848 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4850 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 ()));
4854 if (acfg->aot_opts.write_symbols) {
4855 emit_symbol_size (acfg, debug_sym, ".");
4859 emit_label (acfg, symbol);
4866 * Encode PATCH_INFO into its disk representation.
4869 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4873 switch (patch_info->type) {
4874 case MONO_PATCH_INFO_NONE:
4876 case MONO_PATCH_INFO_IMAGE:
4877 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4879 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4880 case MONO_PATCH_INFO_JIT_TLS_ID:
4881 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4882 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4883 case MONO_PATCH_INFO_NURSERY_START_SHIFTED:
4884 case MONO_PATCH_INFO_NURSERY_SHIFT:
4886 case MONO_PATCH_INFO_METHOD_REL:
4887 encode_value ((gint)patch_info->data.offset, p, &p);
4889 case MONO_PATCH_INFO_SWITCH: {
4890 gpointer *table = (gpointer *)patch_info->data.table->table;
4893 encode_value (patch_info->data.table->table_size, p, &p);
4894 for (k = 0; k < patch_info->data.table->table_size; k++)
4895 encode_value ((int)(gssize)table [k], p, &p);
4898 case MONO_PATCH_INFO_METHODCONST:
4899 case MONO_PATCH_INFO_METHOD:
4900 case MONO_PATCH_INFO_METHOD_JUMP:
4901 case MONO_PATCH_INFO_ICALL_ADDR:
4902 case MONO_PATCH_INFO_METHOD_RGCTX:
4903 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
4904 encode_method_ref (acfg, patch_info->data.method, p, &p);
4906 case MONO_PATCH_INFO_INTERNAL_METHOD:
4907 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4908 guint32 len = strlen (patch_info->data.name);
4910 encode_value (len, p, &p);
4912 memcpy (p, patch_info->data.name, len);
4917 case MONO_PATCH_INFO_LDSTR: {
4918 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4919 guint32 token = patch_info->data.token->token;
4920 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4921 encode_value (image_index, p, &p);
4922 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4925 case MONO_PATCH_INFO_RVA:
4926 case MONO_PATCH_INFO_DECLSEC:
4927 case MONO_PATCH_INFO_LDTOKEN:
4928 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4929 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4930 encode_value (patch_info->data.token->token, p, &p);
4931 encode_value (patch_info->data.token->has_context, p, &p);
4932 if (patch_info->data.token->has_context)
4933 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4935 case MONO_PATCH_INFO_EXC_NAME: {
4936 MonoClass *ex_class;
4939 mono_class_from_name (mono_defaults.exception_class->image,
4940 "System", patch_info->data.target);
4941 g_assert (ex_class);
4942 encode_klass_ref (acfg, ex_class, p, &p);
4945 case MONO_PATCH_INFO_R4:
4946 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4948 case MONO_PATCH_INFO_R8:
4949 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4950 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4952 case MONO_PATCH_INFO_VTABLE:
4953 case MONO_PATCH_INFO_CLASS:
4954 case MONO_PATCH_INFO_IID:
4955 case MONO_PATCH_INFO_ADJUSTED_IID:
4956 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4958 case MONO_PATCH_INFO_CLASS_INIT:
4959 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4960 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4962 case MONO_PATCH_INFO_FIELD:
4963 case MONO_PATCH_INFO_SFLDA:
4964 encode_field_info (acfg, patch_info->data.field, p, &p);
4966 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4968 case MONO_PATCH_INFO_RGCTX_FETCH: {
4969 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4974 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4975 * reference the same method, so encode the method only once.
4977 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4979 buf2 = g_malloc (1024);
4982 encode_method_ref (acfg, entry->method, p2, &p2);
4983 g_assert (p2 - buf2 < 1024);
4985 offset = add_to_blob (acfg, buf2, p2 - buf2);
4988 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4993 encode_value (offset, p, &p);
4994 g_assert ((int)entry->info_type < 256);
4995 g_assert (entry->data->type < 256);
4996 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4997 encode_patch (acfg, entry->data, p, &p);
5000 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5001 case MONO_PATCH_INFO_MONITOR_ENTER:
5002 case MONO_PATCH_INFO_MONITOR_EXIT:
5003 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5005 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5006 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5007 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5009 case MONO_PATCH_INFO_SIGNATURE:
5010 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5012 case MONO_PATCH_INFO_TLS_OFFSET:
5013 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5015 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5016 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5017 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5019 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5020 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5023 encode_method_ref (acfg, info->method, p, &p);
5024 encode_value (info->num_entries, p, &p);
5025 for (i = 0; i < info->num_entries; ++i) {
5026 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5028 encode_value (template->info_type, p, &p);
5029 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5030 case MONO_PATCH_INFO_CLASS:
5031 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5033 case MONO_PATCH_INFO_FIELD:
5034 encode_field_info (acfg, template->data, p, &p);
5037 g_assert_not_reached ();
5044 g_warning ("unable to handle jump info %d", patch_info->type);
5045 g_assert_not_reached ();
5052 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5055 guint32 pindex, offset;
5056 MonoJumpInfo *patch_info;
5058 encode_value (n_patches, p, &p);
5060 for (pindex = 0; pindex < patches->len; ++pindex) {
5061 patch_info = g_ptr_array_index (patches, pindex);
5063 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5067 offset = get_got_offset (acfg, patch_info);
5068 encode_value (offset, p, &p);
5075 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5079 int pindex, buf_size, n_patches;
5081 MonoJumpInfo *patch_info;
5082 MonoMethodHeader *header;
5083 guint32 method_index;
5085 guint32 first_got_offset;
5087 method = cfg->orig_method;
5088 header = mono_method_get_header (method);
5090 method_index = get_method_index (acfg, method);
5092 /* Sort relocations */
5093 patches = g_ptr_array_new ();
5094 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5095 g_ptr_array_add (patches, patch_info);
5096 g_ptr_array_sort (patches, compare_patches);
5098 first_got_offset = acfg->cfgs [method_index]->got_offset;
5100 /**********************/
5101 /* Encode method info */
5102 /**********************/
5104 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5105 p = buf = g_malloc (buf_size);
5107 if (mono_class_get_cctor (method->klass))
5108 encode_klass_ref (acfg, method->klass, p, &p);
5110 /* Not needed when loading the method */
5111 encode_value (0, p, &p);
5114 if (cfg->opt & MONO_OPT_SHARED) {
5115 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5116 for (l = cfg->ldstr_list; l; l = l->next) {
5117 encode_value ((long)l->data, p, &p);
5121 /* Used only in shared mode */
5122 g_assert (!cfg->ldstr_list);
5125 for (pindex = 0; pindex < patches->len; ++pindex) {
5126 patch_info = g_ptr_array_index (patches, pindex);
5128 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5129 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5130 patch_info->type = MONO_PATCH_INFO_NONE;
5135 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5136 /* Stored in a GOT slot initialized at module load time */
5137 patch_info->type = MONO_PATCH_INFO_NONE;
5141 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5142 /* Stored in a GOT slot initialized at module load time */
5143 patch_info->type = MONO_PATCH_INFO_NONE;
5147 if (is_plt_patch (patch_info)) {
5148 /* Calls are made through the PLT */
5149 patch_info->type = MONO_PATCH_INFO_NONE;
5157 g_assert (cfg->has_got_slots);
5159 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5161 acfg->stats.info_size += p - buf;
5163 g_assert (p - buf < buf_size);
5165 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5170 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5172 guint32 cache_index;
5175 /* Reuse the unwind module to canonize and store unwind info entries */
5176 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5178 /* Use +/- 1 to distinguish 0s from missing entries */
5179 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5187 * It would be easier to use assembler symbols, but the caller needs an
5190 offset = acfg->unwind_info_offset;
5191 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5192 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5195 encode_value (encoded_len, p, &p);
5197 acfg->unwind_info_offset += encoded_len + (p - buf);
5203 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5206 int i, k, buf_size, method_index;
5207 guint32 debug_info_size;
5209 MonoMethodHeader *header;
5210 guint8 *p, *buf, *debug_info;
5211 MonoJitInfo *jinfo = cfg->jit_info;
5213 gboolean use_unwind_ops = FALSE;
5214 MonoSeqPointInfo *seq_points;
5216 method = cfg->orig_method;
5217 code = cfg->native_code;
5218 header = cfg->header;
5220 method_index = get_method_index (acfg, method);
5222 if (!acfg->aot_opts.nodebug) {
5223 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5226 debug_info_size = 0;
5229 seq_points = cfg->seq_point_info;
5231 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 128) : 0) + cfg->gc_map_size;
5232 p = buf = g_malloc (buf_size);
5234 use_unwind_ops = cfg->unwind_ops != NULL;
5236 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);
5238 encode_value (flags, p, &p);
5240 if (use_unwind_ops) {
5241 guint32 encoded_len;
5245 * This is a duplicate of the data in the .debug_frame section, but that
5246 * section cannot be accessed using the dl interface.
5248 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5249 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5252 encode_value (jinfo->used_regs, p, &p);
5255 /*Encode the number of holes before the number of clauses to make decoding easier*/
5256 if (jinfo->has_try_block_holes) {
5257 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5258 encode_value (table->num_holes, p, &p);
5261 /* Exception table */
5262 if (cfg->compile_llvm) {
5264 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5265 * since the information is only available to llc. Instead, we let llc save the data
5266 * into the LSDA, and read it from there at runtime.
5268 /* The assembly might be CIL stripped so emit the data ourselves */
5269 if (header->num_clauses)
5270 encode_value (header->num_clauses, p, &p);
5272 for (k = 0; k < header->num_clauses; ++k) {
5273 MonoExceptionClause *clause;
5275 clause = &header->clauses [k];
5277 encode_value (clause->flags, p, &p);
5278 if (clause->data.catch_class) {
5279 encode_value (1, p, &p);
5280 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5282 encode_value (0, p, &p);
5285 /* Emit a list of nesting clauses */
5286 for (i = 0; i < header->num_clauses; ++i) {
5288 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5290 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5292 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5293 encode_value (i, p, &p);
5295 encode_value (-1, p, &p);
5298 if (jinfo->num_clauses)
5299 encode_value (jinfo->num_clauses, p, &p);
5301 for (k = 0; k < jinfo->num_clauses; ++k) {
5302 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5304 encode_value (ei->flags, p, &p);
5305 encode_value (ei->exvar_offset, p, &p);
5307 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5308 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5310 if (ei->data.catch_class) {
5314 buf2 = g_malloc (4096);
5316 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5318 g_assert (len < 4096);
5319 encode_value (len, p, &p);
5320 memcpy (p, buf2, len);
5324 encode_value (0, p, &p);
5328 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5329 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5330 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5334 if (jinfo->has_try_block_holes) {
5335 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5336 for (i = 0; i < table->num_holes; ++i) {
5337 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5338 encode_value (hole->clause, p, &p);
5339 encode_value (hole->length, p, &p);
5340 encode_value (hole->offset, p, &p);
5344 if (jinfo->has_arch_eh_info) {
5345 MonoArchEHJitInfo *eh_info;
5347 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5348 encode_value (eh_info->stack_size, p, &p);
5351 if (jinfo->has_generic_jit_info) {
5352 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5353 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5359 encode_value (gi->nlocs, p, &p);
5361 for (i = 0; i < gi->nlocs; ++i) {
5362 MonoDwarfLocListEntry *entry = &gi->locations [i];
5364 encode_value (entry->is_reg ? 1 : 0, p, &p);
5365 encode_value (entry->reg, p, &p);
5367 encode_value (entry->offset, p, &p);
5369 g_assert (entry->from == 0);
5371 encode_value (entry->from, p, &p);
5372 encode_value (entry->to, p, &p);
5375 if (!cfg->compile_llvm) {
5376 encode_value (gi->has_this ? 1 : 0, p, &p);
5377 encode_value (gi->this_reg, p, &p);
5378 encode_value (gi->this_offset, p, &p);
5383 * Need to encode jinfo->method too, since it is not equal to 'method'
5384 * when using generic sharing.
5386 buf2 = g_malloc (4096);
5388 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5390 g_assert (len < 4096);
5391 encode_value (len, p, &p);
5392 memcpy (p, buf2, len);
5396 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5397 MonoMethodInflated *inflated;
5398 MonoGenericContext *context;
5399 MonoGenericInst *inst;
5401 g_assert (jinfo->d.method->is_inflated);
5402 inflated = (MonoMethodInflated*)jinfo->d.method;
5403 context = &inflated->context;
5405 encode_value (1, p, &p);
5406 if (context->class_inst) {
5407 inst = context->class_inst;
5409 encode_value (inst->type_argc, p, &p);
5410 for (i = 0; i < inst->type_argc; ++i)
5411 encode_value (gsctx->var_is_vt [i], p, &p);
5413 encode_value (0, p, &p);
5415 if (context->method_inst) {
5416 inst = context->method_inst;
5418 encode_value (inst->type_argc, p, &p);
5419 for (i = 0; i < inst->type_argc; ++i)
5420 encode_value (gsctx->mvar_is_vt [i], p, &p);
5422 encode_value (0, p, &p);
5425 encode_value (0, p, &p);
5430 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5432 encode_value (seq_points->len, p, &p);
5433 last_il_offset = last_native_offset = 0;
5434 for (i = 0; i < seq_points->len; ++i) {
5435 SeqPoint *sp = &seq_points->seq_points [i];
5436 il_offset = sp->il_offset;
5437 native_offset = sp->native_offset;
5438 encode_value (il_offset - last_il_offset, p, &p);
5439 encode_value (native_offset - last_native_offset, p, &p);
5440 last_il_offset = il_offset;
5441 last_native_offset = native_offset;
5443 encode_value (sp->flags, p, &p);
5444 encode_value (sp->next_len, p, &p);
5445 for (j = 0; j < sp->next_len; ++j)
5446 encode_value (sp->next [j], p, &p);
5450 g_assert (debug_info_size < buf_size);
5452 encode_value (debug_info_size, p, &p);
5453 if (debug_info_size) {
5454 memcpy (p, debug_info, debug_info_size);
5455 p += debug_info_size;
5456 g_free (debug_info);
5461 encode_value (cfg->gc_map_size, p, &p);
5462 /* The GC map requires 4 bytes of alignment */
5463 while ((gsize)p % 4)
5465 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5466 p += cfg->gc_map_size;
5469 acfg->stats.ex_info_size += p - buf;
5471 g_assert (p - buf < buf_size);
5474 /* The GC Map requires 4 byte alignment */
5475 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5480 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5482 MonoClass *klass = mono_class_get (acfg->image, token);
5484 int i, buf_size, res;
5485 gboolean no_special_static, cant_encode;
5486 gpointer iter = NULL;
5489 mono_loader_clear_error ();
5493 p = buf = g_malloc (buf_size);
5495 /* Mark as unusable */
5496 encode_value (-1, p, &p);
5498 res = add_to_blob (acfg, buf, p - buf);
5504 buf_size = 10240 + (klass->vtable_size * 16);
5505 p = buf = g_malloc (buf_size);
5509 mono_class_init (klass);
5511 mono_class_get_nested_types (klass, &iter);
5512 g_assert (klass->nested_classes_inited);
5514 mono_class_setup_vtable (klass);
5517 * Emit all the information which is required for creating vtables so
5518 * the runtime does not need to create the MonoMethod structures which
5519 * take up a lot of space.
5522 no_special_static = !mono_class_has_special_static_fields (klass);
5524 /* Check whenever we have enough info to encode the vtable */
5525 cant_encode = FALSE;
5526 for (i = 0; i < klass->vtable_size; ++i) {
5527 MonoMethod *cm = klass->vtable [i];
5529 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5533 mono_class_has_finalizer (klass);
5535 if (klass->generic_container || cant_encode) {
5536 encode_value (-1, p, &p);
5538 encode_value (klass->vtable_size, p, &p);
5539 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);
5540 if (klass->has_cctor)
5541 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5542 if (klass->has_finalize)
5543 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5545 encode_value (klass->instance_size, p, &p);
5546 encode_value (mono_class_data_size (klass), p, &p);
5547 encode_value (klass->packing_size, p, &p);
5548 encode_value (klass->min_align, p, &p);
5550 for (i = 0; i < klass->vtable_size; ++i) {
5551 MonoMethod *cm = klass->vtable [i];
5554 encode_method_ref (acfg, cm, p, &p);
5556 encode_value (0, p, &p);
5560 acfg->stats.class_info_size += p - buf;
5562 g_assert (p - buf < buf_size);
5563 res = add_to_blob (acfg, buf, p - buf);
5570 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5572 char *debug_sym = NULL;
5576 case MONO_PATCH_INFO_METHOD:
5577 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5579 case MONO_PATCH_INFO_INTERNAL_METHOD:
5580 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5582 case MONO_PATCH_INFO_CLASS_INIT:
5583 s = mono_type_get_name (&ji->data.klass->byval_arg);
5584 debug_sym = g_strdup_printf ("plt__class_init_%s", s);
5587 case MONO_PATCH_INFO_RGCTX_FETCH:
5588 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5590 case MONO_PATCH_INFO_ICALL_ADDR: {
5591 char *s = get_debug_sym (ji->data.method, "", cache);
5593 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5597 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5598 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5600 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5601 debug_sym = g_strdup_printf ("plt__generic_class_init");
5607 return sanitize_symbol (acfg, debug_sym);
5611 * Calls made from AOTed code are routed through a table of jumps similar to the
5612 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5613 * control to the AOT runtime through a trampoline.
5616 emit_plt (MonoAotCompile *acfg)
5622 sprintf (symbol, "plt");
5624 emit_section_change (acfg, ".text", 0);
5625 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5626 emit_label (acfg, symbol);
5627 emit_label (acfg, acfg->plt_symbol);
5629 for (i = 0; i < acfg->plt_offset; ++i) {
5630 char *debug_sym = NULL;
5631 MonoPltEntry *plt_entry = NULL;
5636 * The first plt entry is unused.
5640 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5645 * If the target is directly callable, alias the plt symbol to point to
5647 * FIXME: Use this to simplify emit_and_reloc_code ().
5648 * FIXME: Avoid the got slot.
5649 * FIXME: Add support to the binary writer.
5651 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5652 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5655 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5656 /* LLVM calls the PLT entries using bl, so emit a stub */
5657 emit_set_thumb_mode (acfg);
5658 fprintf (acfg->fp, "\n.thumb_func\n");
5659 emit_label (acfg, plt_entry->llvm_symbol);
5660 fprintf (acfg->fp, "bx pc\n");
5661 fprintf (acfg->fp, "nop\n");
5662 emit_set_arm_mode (acfg);
5663 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5665 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5672 debug_sym = plt_entry->debug_sym;
5674 if (acfg->thumb_mixed && !plt_entry->jit_used)
5675 /* Emit only a thumb version */
5678 if (acfg->llvm && !acfg->thumb_mixed)
5679 emit_label (acfg, plt_entry->llvm_symbol);
5682 if (acfg->need_no_dead_strip) {
5683 emit_unset_mode (acfg);
5684 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5686 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5687 emit_label (acfg, debug_sym);
5690 emit_label (acfg, plt_entry->symbol);
5692 arch_emit_plt_entry (acfg, i);
5695 emit_symbol_size (acfg, debug_sym, ".");
5698 if (acfg->thumb_mixed) {
5699 /* Make sure the ARM symbols don't alias the thumb ones */
5700 emit_zero_bytes (acfg, 16);
5703 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5706 for (i = 0; i < acfg->plt_offset; ++i) {
5707 char *debug_sym = NULL;
5708 MonoPltEntry *plt_entry = NULL;
5714 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5717 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5720 /* Skip plt entries not actually called by LLVM code */
5721 if (!plt_entry->llvm_used)
5724 if (acfg->aot_opts.write_symbols) {
5725 if (plt_entry->debug_sym)
5726 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5730 #if defined(TARGET_MACH)
5731 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5732 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5734 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5735 emit_label (acfg, debug_sym);
5737 fprintf (acfg->fp, "\n.thumb_func\n");
5739 emit_label (acfg, plt_entry->llvm_symbol);
5741 arch_emit_llvm_plt_entry (acfg, i);
5744 emit_symbol_size (acfg, debug_sym, ".");
5750 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5752 sprintf (symbol, "plt_end");
5753 emit_label (acfg, symbol);
5757 * emit_trampoline_full:
5759 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5760 * create_jit_info_for_trampoline ().
5762 static G_GNUC_UNUSED void
5763 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5765 char start_symbol [256];
5766 char end_symbol [256];
5768 guint32 buf_size, info_offset;
5769 MonoJumpInfo *patch_info;
5782 code_size = info->code_size;
5784 unwind_ops = info->unwind_ops;
5786 #ifdef __native_client_codegen__
5787 mono_nacl_fix_patches (code, ji);
5792 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5794 emit_section_change (acfg, ".text", 0);
5795 emit_global (acfg, start_symbol, TRUE);
5796 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5797 emit_label (acfg, start_symbol);
5799 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5800 emit_label (acfg, symbol);
5803 * The code should access everything through the GOT, so we pass
5806 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5808 emit_symbol_size (acfg, start_symbol, ".");
5811 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5812 emit_label (acfg, end_symbol);
5817 /* Sort relocations */
5818 patches = g_ptr_array_new ();
5819 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5820 if (patch_info->type != MONO_PATCH_INFO_NONE)
5821 g_ptr_array_add (patches, patch_info);
5822 g_ptr_array_sort (patches, compare_patches);
5824 buf_size = patches->len * 128 + 128;
5825 buf = g_malloc (buf_size);
5828 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5829 g_assert (p - buf < buf_size);
5831 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5833 info_offset = add_to_blob (acfg, buf, p - buf);
5835 emit_section_change (acfg, RODATA_SECT, 0);
5836 emit_global (acfg, symbol, FALSE);
5837 emit_label (acfg, symbol);
5839 emit_int32 (acfg, info_offset);
5843 guint32 encoded_len;
5847 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5849 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5850 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5853 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5854 emit_int32 (acfg, uw_offset);
5857 /* Emit debug info */
5861 sprintf (symbol, "%s", name);
5862 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5865 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5869 static G_GNUC_UNUSED void
5870 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5872 emit_trampoline_full (acfg, got_offset, info, FALSE);
5876 emit_trampolines (MonoAotCompile *acfg)
5879 char end_symbol [256];
5880 int i, tramp_got_offset;
5881 MonoAotTrampoline ntype;
5882 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5886 if (!acfg->aot_opts.full_aot)
5889 g_assert (acfg->image->assembly);
5891 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5892 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5893 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5894 MonoTrampInfo *info;
5897 * Emit the generic trampolines.
5899 * We could save some code by treating the generic trampolines as a wrapper
5900 * method, but that approach has its own complexities, so we choose the simpler
5903 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5904 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5905 #ifdef DISABLE_REMOTING
5906 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5909 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5910 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5913 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5914 emit_trampoline (acfg, acfg->got_offset, info);
5917 mono_arch_get_nullified_class_init_trampoline (&info);
5918 emit_trampoline (acfg, acfg->got_offset, info);
5919 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5920 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5921 emit_trampoline (acfg, acfg->got_offset, info);
5922 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5923 emit_trampoline (acfg, acfg->got_offset, info);
5926 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5927 emit_trampoline (acfg, acfg->got_offset, info);
5929 /* Emit the exception related code pieces */
5930 mono_arch_get_restore_context (&info, TRUE);
5931 emit_trampoline (acfg, acfg->got_offset, info);
5932 mono_arch_get_call_filter (&info, TRUE);
5933 emit_trampoline (acfg, acfg->got_offset, info);
5934 mono_arch_get_throw_exception (&info, TRUE);
5935 emit_trampoline (acfg, acfg->got_offset, info);
5936 mono_arch_get_rethrow_exception (&info, TRUE);
5937 emit_trampoline (acfg, acfg->got_offset, info);
5938 mono_arch_get_throw_corlib_exception (&info, TRUE);
5939 emit_trampoline (acfg, acfg->got_offset, info);
5941 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5942 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5944 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5946 /* Create a separate out trampoline for more information in stack traces */
5947 info->name = g_strdup ("gsharedvt_out_trampoline");
5948 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5952 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5954 GSList *l = mono_arch_get_trampolines (TRUE);
5957 MonoTrampInfo *info = l->data;
5959 emit_trampoline (acfg, acfg->got_offset, info);
5965 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5968 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5969 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5970 emit_trampoline (acfg, acfg->got_offset, info);
5972 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5973 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5974 emit_trampoline (acfg, acfg->got_offset, info);
5977 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
5978 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
5979 emit_trampoline (acfg, acfg->got_offset, info);
5985 /* delegate_invoke_impl trampolines */
5986 l = mono_arch_get_delegate_invoke_impls ();
5988 MonoTrampInfo *info = l->data;
5990 emit_trampoline (acfg, acfg->got_offset, info);
5995 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5997 /* Emit trampolines which are numerous */
6000 * These include the following:
6001 * - specific trampolines
6002 * - static rgctx invoke trampolines
6004 * These trampolines have the same code, they are parameterized by GOT
6006 * They are defined in this file, in the arch_... routines instead of
6007 * in tramp-<ARCH>.c, since it is easier to do it this way.
6011 * When running in aot-only mode, we can't create specific trampolines at
6012 * runtime, so we create a few, and save them in the AOT file.
6013 * Normal trampolines embed their argument as a literal inside the
6014 * trampoline code, we can't do that here, so instead we embed an offset
6015 * which needs to be added to the trampoline address to get the address of
6016 * the GOT slot which contains the argument value.
6017 * The generated trampolines jump to the generic trampolines using another
6018 * GOT slot, which will be setup by the AOT loader to point to the
6019 * generic trampoline code of the given type.
6023 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6027 emit_section_change (acfg, ".text", 0);
6029 tramp_got_offset = acfg->got_offset;
6031 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6033 case MONO_AOT_TRAMP_SPECIFIC:
6034 sprintf (symbol, "specific_trampolines");
6036 case MONO_AOT_TRAMP_STATIC_RGCTX:
6037 sprintf (symbol, "static_rgctx_trampolines");
6039 case MONO_AOT_TRAMP_IMT_THUNK:
6040 sprintf (symbol, "imt_thunks");
6042 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6043 sprintf (symbol, "gsharedvt_arg_trampolines");
6046 g_assert_not_reached ();
6049 sprintf (end_symbol, "%s_e", symbol);
6051 if (acfg->aot_opts.write_symbols)
6052 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6054 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6055 emit_label (acfg, symbol);
6057 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6059 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6063 case MONO_AOT_TRAMP_SPECIFIC:
6064 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6065 tramp_got_offset += 2;
6067 case MONO_AOT_TRAMP_STATIC_RGCTX:
6068 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6069 tramp_got_offset += 2;
6071 case MONO_AOT_TRAMP_IMT_THUNK:
6072 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6073 tramp_got_offset += 1;
6075 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6076 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6077 tramp_got_offset += 2;
6080 g_assert_not_reached ();
6082 #ifdef __native_client_codegen__
6083 /* align to avoid 32-byte boundary crossings */
6084 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6087 if (!acfg->trampoline_size [ntype]) {
6088 g_assert (tramp_size);
6089 acfg->trampoline_size [ntype] = tramp_size;
6093 emit_label (acfg, end_symbol);
6094 emit_int32 (acfg, 0);
6097 arch_emit_specific_trampoline_pages (acfg);
6099 /* Reserve some entries at the end of the GOT for our use */
6100 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6103 acfg->got_offset += acfg->num_trampoline_got_entries;
6107 str_begins_with (const char *str1, const char *str2)
6109 int len = strlen (str2);
6110 return strncmp (str1, str2, len) == 0;
6114 mono_aot_readonly_field_override (MonoClassField *field)
6117 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6118 char *p = rdv->name;
6120 len = strlen (field->parent->name_space);
6121 if (strncmp (p, field->parent->name_space, len))
6126 len = strlen (field->parent->name);
6127 if (strncmp (p, field->parent->name, len))
6132 if (strcmp (p, field->name))
6134 switch (rdv->type) {
6136 return &rdv->value.i1;
6138 return &rdv->value.i2;
6140 return &rdv->value.i4;
6149 add_readonly_value (MonoAotOptions *opts, const char *val)
6154 /* the format of val is:
6155 * namespace.typename.fieldname=type/value
6156 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6158 fval = strrchr (val, '/');
6160 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6163 tval = strrchr (val, '=');
6165 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6168 rdv = g_new0 (ReadOnlyValue, 1);
6169 rdv->name = g_malloc0 (tval - val + 1);
6170 memcpy (rdv->name, val, tval - val);
6173 if (strncmp (tval, "i1", 2) == 0) {
6174 rdv->value.i1 = atoi (fval);
6175 rdv->type = MONO_TYPE_I1;
6176 } else if (strncmp (tval, "i2", 2) == 0) {
6177 rdv->value.i2 = atoi (fval);
6178 rdv->type = MONO_TYPE_I2;
6179 } else if (strncmp (tval, "i4", 2) == 0) {
6180 rdv->value.i4 = atoi (fval);
6181 rdv->type = MONO_TYPE_I4;
6183 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6186 rdv->next = readonly_values;
6187 readonly_values = rdv;
6191 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6193 gchar **args, **ptr;
6195 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6196 for (ptr = args; ptr && *ptr; ptr ++) {
6197 const char *arg = *ptr;
6199 if (str_begins_with (arg, "outfile=")) {
6200 opts->outfile = g_strdup (arg + strlen ("outfile="));
6201 } else if (str_begins_with (arg, "save-temps")) {
6202 opts->save_temps = TRUE;
6203 } else if (str_begins_with (arg, "keep-temps")) {
6204 opts->save_temps = TRUE;
6205 } else if (str_begins_with (arg, "write-symbols")) {
6206 opts->write_symbols = TRUE;
6207 } else if (str_begins_with (arg, "no-write-symbols")) {
6208 opts->write_symbols = FALSE;
6209 } else if (str_begins_with (arg, "metadata-only")) {
6210 opts->metadata_only = TRUE;
6211 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6212 opts->bind_to_runtime_version = TRUE;
6213 } else if (str_begins_with (arg, "full")) {
6214 opts->full_aot = TRUE;
6215 } else if (str_begins_with (arg, "threads=")) {
6216 opts->nthreads = atoi (arg + strlen ("threads="));
6217 } else if (str_begins_with (arg, "static")) {
6218 opts->static_link = TRUE;
6219 opts->no_dlsym = TRUE;
6220 } else if (str_begins_with (arg, "asmonly")) {
6221 opts->asm_only = TRUE;
6222 } else if (str_begins_with (arg, "asmwriter")) {
6223 opts->asm_writer = TRUE;
6224 } else if (str_begins_with (arg, "nodebug")) {
6225 opts->nodebug = TRUE;
6226 } else if (str_begins_with (arg, "dwarfdebug")) {
6227 opts->dwarf_debug = TRUE;
6228 } else if (str_begins_with (arg, "nopagetrampolines")) {
6229 opts->use_trampolines_page = FALSE;
6230 } else if (str_begins_with (arg, "ntrampolines=")) {
6231 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6232 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6233 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6234 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6235 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6236 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6237 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6238 } else if (str_begins_with (arg, "autoreg")) {
6239 opts->autoreg = TRUE;
6240 } else if (str_begins_with (arg, "tool-prefix=")) {
6241 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6242 } else if (str_begins_with (arg, "soft-debug")) {
6243 opts->soft_debug = TRUE;
6244 } else if (str_begins_with (arg, "direct-pinvoke")) {
6245 opts->direct_pinvoke = TRUE;
6246 } else if (str_begins_with (arg, "direct-icalls")) {
6247 opts->direct_icalls = TRUE;
6248 #if defined(TARGET_ARM)
6249 } else if (str_begins_with (arg, "iphone-abi")) {
6250 // older full-aot users did depend on this.
6252 } else if (str_begins_with (arg, "no-direct-calls")) {
6253 opts->no_direct_calls = TRUE;
6254 } else if (str_begins_with (arg, "print-skipped")) {
6255 opts->print_skipped_methods = TRUE;
6256 } else if (str_begins_with (arg, "stats")) {
6258 } else if (str_begins_with (arg, "no-instances")) {
6259 opts->no_instances = TRUE;
6260 } else if (str_begins_with (arg, "log-generics")) {
6261 opts->log_generics = TRUE;
6262 } else if (str_begins_with (arg, "mtriple=")) {
6263 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6264 } else if (str_begins_with (arg, "llvm-path=")) {
6265 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6266 } else if (str_begins_with (arg, "readonly-value=")) {
6267 add_readonly_value (opts, arg + strlen ("readonly-value="));
6268 } else if (str_begins_with (arg, "info")) {
6269 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6271 } else if (str_begins_with (arg, "gc-maps")) {
6272 mini_gc_enable_gc_maps_for_aot ();
6273 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6274 printf ("Supported options for --aot:\n");
6275 printf (" outfile=\n");
6276 printf (" save-temps\n");
6277 printf (" keep-temps\n");
6278 printf (" write-symbols\n");
6279 printf (" metadata-only\n");
6280 printf (" bind-to-runtime-version\n");
6282 printf (" threads=\n");
6283 printf (" static\n");
6284 printf (" asmonly\n");
6285 printf (" asmwriter\n");
6286 printf (" nodebug\n");
6287 printf (" dwarfdebug\n");
6288 printf (" ntrampolines=\n");
6289 printf (" nrgctx-trampolines=\n");
6290 printf (" nimt-trampolines=\n");
6291 printf (" ngsharedvt-trampolines=\n");
6292 printf (" autoreg\n");
6293 printf (" tool-prefix=\n");
6294 printf (" readonly-value=\n");
6295 printf (" soft-debug\n");
6296 printf (" gc-maps\n");
6297 printf (" print-skipped\n");
6298 printf (" no-instances\n");
6299 printf (" stats\n");
6301 printf (" help/?\n");
6304 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6309 if (opts->use_trampolines_page) {
6310 opts->ntrampolines = 0;
6311 opts->nrgctx_trampolines = 0;
6312 opts->nimt_trampolines = 0;
6313 opts->ngsharedvt_arg_trampolines = 0;
6319 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6321 MonoMethod *method = (MonoMethod*)key;
6322 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6323 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6324 MonoAotCompile *acfg = user_data;
6326 new_ji->image = ji->image;
6327 new_ji->token = ji->token;
6328 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6332 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6334 if (klass->type_token)
6336 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6339 return can_encode_class (acfg, klass->element_class);
6344 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6346 if (method->wrapper_type) {
6347 switch (method->wrapper_type) {
6348 case MONO_WRAPPER_NONE:
6349 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6350 case MONO_WRAPPER_XDOMAIN_INVOKE:
6351 case MONO_WRAPPER_STFLD:
6352 case MONO_WRAPPER_LDFLD:
6353 case MONO_WRAPPER_LDFLDA:
6354 case MONO_WRAPPER_LDFLD_REMOTE:
6355 case MONO_WRAPPER_STFLD_REMOTE:
6356 case MONO_WRAPPER_STELEMREF:
6357 case MONO_WRAPPER_ISINST:
6358 case MONO_WRAPPER_PROXY_ISINST:
6359 case MONO_WRAPPER_ALLOC:
6360 case MONO_WRAPPER_REMOTING_INVOKE:
6361 case MONO_WRAPPER_UNKNOWN:
6362 case MONO_WRAPPER_WRITE_BARRIER:
6363 case MONO_WRAPPER_DELEGATE_INVOKE:
6364 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6365 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6366 case MONO_WRAPPER_SYNCHRONIZED:
6368 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6369 case MONO_WRAPPER_CASTCLASS: {
6370 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6379 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6383 if (!method->token) {
6384 /* The method is part of a constructed type like Int[,].Set (). */
6385 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6386 if (method->klass->rank)
6396 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6398 switch (patch_info->type) {
6399 case MONO_PATCH_INFO_METHOD:
6400 case MONO_PATCH_INFO_METHODCONST:
6401 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6402 MonoMethod *method = patch_info->data.method;
6404 return can_encode_method (acfg, method);
6406 case MONO_PATCH_INFO_VTABLE:
6407 case MONO_PATCH_INFO_CLASS_INIT:
6408 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6409 case MONO_PATCH_INFO_CLASS:
6410 case MONO_PATCH_INFO_IID:
6411 case MONO_PATCH_INFO_ADJUSTED_IID:
6412 if (!can_encode_class (acfg, patch_info->data.klass)) {
6413 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6417 case MONO_PATCH_INFO_RGCTX_FETCH: {
6418 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6420 if (!can_encode_method (acfg, entry->method))
6422 if (!can_encode_patch (acfg, entry->data))
6436 * AOT compile a given method.
6437 * This function might be called by multiple threads, so it must be thread-safe.
6440 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6443 MonoJumpInfo *patch_info;
6446 MonoMethod *wrapped;
6448 if (acfg->aot_opts.metadata_only)
6451 mono_acfg_lock (acfg);
6452 index = get_method_index (acfg, method);
6453 mono_acfg_unlock (acfg);
6455 /* fixme: maybe we can also precompile wrapper methods */
6456 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6457 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6458 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6459 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6463 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6466 wrapped = mono_marshal_method_from_wrapper (method);
6467 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6468 // FIXME: The wrapper should be generic too, but it is not
6471 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6474 InterlockedIncrement (&acfg->stats.mcount);
6477 if (method->is_generic || method->klass->generic_container) {
6478 InterlockedIncrement (&acfg->stats.genericcount);
6483 //acfg->aot_opts.print_skipped_methods = TRUE;
6486 * Since these methods are the only ones which are compiled with
6487 * AOT support, and they are not used by runtime startup/shutdown code,
6488 * the runtime will not see AOT methods during AOT compilation,so it
6489 * does not need to support them by creating a fake GOT etc.
6491 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), acfg->aot_opts.full_aot ? (JIT_FLAG_AOT|JIT_FLAG_FULL_AOT) : (JIT_FLAG_AOT), 0);
6492 mono_loader_clear_error ();
6494 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6495 if (acfg->aot_opts.print_skipped_methods)
6496 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6497 InterlockedIncrement (&acfg->stats.genericcount);
6500 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6501 if (acfg->aot_opts.print_skipped_methods)
6502 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6503 /* Let the exception happen at runtime */
6507 if (cfg->disable_aot) {
6508 if (acfg->aot_opts.print_skipped_methods)
6509 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6510 InterlockedIncrement (&acfg->stats.ocount);
6511 mono_destroy_compile (cfg);
6514 cfg->method_index = index;
6516 /* Nullify patches which need no aot processing */
6517 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6518 switch (patch_info->type) {
6519 case MONO_PATCH_INFO_LABEL:
6520 case MONO_PATCH_INFO_BB:
6521 patch_info->type = MONO_PATCH_INFO_NONE;
6528 /* Collect method->token associations from the cfg */
6529 mono_acfg_lock (acfg);
6530 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6531 mono_acfg_unlock (acfg);
6534 * Check for absolute addresses.
6537 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6538 switch (patch_info->type) {
6539 case MONO_PATCH_INFO_ABS:
6540 /* unable to handle this */
6549 if (acfg->aot_opts.print_skipped_methods)
6550 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6551 InterlockedIncrement (&acfg->stats.abscount);
6552 mono_destroy_compile (cfg);
6556 /* Lock for the rest of the code */
6557 mono_acfg_lock (acfg);
6560 * Check for methods/klasses we can't encode.
6563 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6564 if (!can_encode_patch (acfg, patch_info))
6569 if (acfg->aot_opts.print_skipped_methods)
6570 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6571 acfg->stats.ocount++;
6572 mono_destroy_compile (cfg);
6573 mono_acfg_unlock (acfg);
6577 /* Adds generic instances referenced by this method */
6579 * The depth is used to avoid infinite loops when generic virtual recursion is
6582 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6583 if (!acfg->aot_opts.no_instances && depth < 32) {
6584 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6585 switch (patch_info->type) {
6586 case MONO_PATCH_INFO_METHOD: {
6587 MonoMethod *m = patch_info->data.method;
6588 if (m->is_inflated) {
6589 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6590 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6591 !method_has_type_vars (m)) {
6592 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6593 if (acfg->aot_opts.full_aot)
6594 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6596 add_extra_method_with_depth (acfg, m, depth + 1);
6597 add_types_from_method_header (acfg, m);
6600 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6602 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6603 add_extra_method_with_depth (acfg, m, depth + 1);
6606 case MONO_PATCH_INFO_VTABLE: {
6607 MonoClass *klass = patch_info->data.klass;
6609 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6610 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6613 case MONO_PATCH_INFO_SFLDA: {
6614 MonoClass *klass = patch_info->data.field->parent;
6616 /* The .cctor needs to run at runtime. */
6617 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6618 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6627 /* Determine whenever the method has GOT slots */
6628 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6629 switch (patch_info->type) {
6630 case MONO_PATCH_INFO_GOT_OFFSET:
6631 case MONO_PATCH_INFO_NONE:
6632 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6634 case MONO_PATCH_INFO_IMAGE:
6635 /* The assembly is stored in GOT slot 0 */
6636 if (patch_info->data.image != acfg->image)
6637 cfg->has_got_slots = TRUE;
6640 if (!is_plt_patch (patch_info))
6641 cfg->has_got_slots = TRUE;
6646 if (!cfg->has_got_slots)
6647 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6650 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6652 /* Make a copy of the patch info which is in the mempool */
6654 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6656 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6657 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6660 patches = new_patch_info;
6662 patches_end->next = new_patch_info;
6663 patches_end = new_patch_info;
6665 cfg->patch_info = patches;
6667 /* Make a copy of the unwind info */
6669 GSList *l, *unwind_ops;
6673 for (l = cfg->unwind_ops; l; l = l->next) {
6674 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6675 memcpy (op, l->data, sizeof (MonoUnwindOp));
6676 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6678 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6680 /* Make a copy of the argument/local info */
6682 MonoInst **args, **locals;
6683 MonoMethodSignature *sig;
6684 MonoMethodHeader *header;
6687 sig = mono_method_signature (method);
6688 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6689 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6690 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6691 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6695 header = mono_method_get_header (method);
6696 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6697 for (i = 0; i < header->num_locals; ++i) {
6698 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6699 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6701 cfg->locals = locals;
6704 /* Free some fields used by cfg to conserve memory */
6705 mono_mempool_destroy (cfg->mempool);
6706 cfg->mempool = NULL;
6707 g_free (cfg->varinfo);
6708 cfg->varinfo = NULL;
6712 mono_regstate_free (cfg->rs);
6716 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6718 while (index >= acfg->cfgs_size) {
6719 MonoCompile **new_cfgs;
6722 new_size = acfg->cfgs_size * 2;
6723 new_cfgs = g_new0 (MonoCompile*, new_size);
6724 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6725 g_free (acfg->cfgs);
6726 acfg->cfgs = new_cfgs;
6727 acfg->cfgs_size = new_size;
6729 acfg->cfgs [index] = cfg;
6731 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6734 if (cfg->orig_method->wrapper_type)
6735 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6738 mono_acfg_unlock (acfg);
6740 InterlockedIncrement (&acfg->stats.ccount);
6744 compile_thread_main (gpointer *user_data)
6746 MonoDomain *domain = user_data [0];
6747 MonoAotCompile *acfg = user_data [1];
6748 GPtrArray *methods = user_data [2];
6751 mono_thread_attach (domain);
6753 for (i = 0; i < methods->len; ++i)
6754 compile_method (acfg, g_ptr_array_index (methods, i));
6758 load_profile_files (MonoAotCompile *acfg)
6762 int file_index, res, method_index, i;
6765 GList *unordered, *l;
6770 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6772 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6777 infile = fopen (tmp, "r");
6780 printf ("Using profile data file '%s'\n", tmp);
6785 res = fscanf (infile, "%32s\n", ver);
6786 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6787 printf ("Profile file has wrong version or invalid.\n");
6794 MonoMethodDesc *desc;
6797 if (fgets (name, 1023, infile) == NULL)
6800 /* Kill the newline */
6801 if (strlen (name) > 0)
6802 name [strlen (name) - 1] = '\0';
6804 desc = mono_method_desc_new (name, TRUE);
6806 method = mono_method_desc_search_in_image (desc, acfg->image);
6808 if (method && mono_method_get_token (method)) {
6809 token = mono_method_get_token (method);
6810 method_index = mono_metadata_token_index (token) - 1;
6813 for (i = 0; i < acfg->method_order->len; ++i) {
6814 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6820 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6822 //printf ("No method found matching '%s'.\n", name);
6828 /* Add missing methods */
6830 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6832 for (i = 0; i < acfg->method_order->len; ++i) {
6833 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6839 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6841 unordered = g_list_reverse (unordered);
6842 for (l = unordered; l; l = l->next)
6843 g_ptr_array_add (acfg->method_order, l->data);
6846 /* Used by the LLVM backend */
6848 mono_aot_get_got_offset (MonoJumpInfo *ji)
6850 return get_got_offset (llvm_acfg, ji);
6854 mono_aot_get_method_name (MonoCompile *cfg)
6856 if (llvm_acfg->aot_opts.static_link)
6857 /* Include the assembly name too to avoid duplicate symbol errors */
6858 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6860 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6864 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6866 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6867 MonoPltEntry *plt_entry;
6870 ji->data.target = data;
6872 if (!can_encode_patch (llvm_acfg, ji))
6875 plt_entry = get_plt_entry (llvm_acfg, ji);
6876 plt_entry->llvm_used = TRUE;
6878 #if defined(TARGET_MACH)
6879 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6881 return g_strdup_printf (plt_entry->llvm_symbol);
6886 mono_aot_get_method_index (MonoMethod *method)
6888 g_assert (llvm_acfg);
6889 return get_method_index (llvm_acfg, method);
6893 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6897 mono_acfg_lock (llvm_acfg);
6898 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6899 mono_acfg_unlock (llvm_acfg);
6909 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6913 emit_llvm_file (MonoAotCompile *acfg)
6915 char *command, *opts, *tempbc;
6917 MonoJumpInfo *patch_info;
6920 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6924 /* Compute the final size of the got */
6925 for (i = 0; i < acfg->nmethods; ++i) {
6926 if (acfg->cfgs [i]) {
6927 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6928 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6929 if (!is_plt_patch (patch_info))
6930 get_got_offset (acfg, patch_info);
6932 get_plt_entry (acfg, patch_info);
6938 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6940 if (acfg->aot_opts.full_aot) {
6944 * Need to add the got entries used by the trampolines.
6945 * This is only a conservative approximation.
6947 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6948 /* For the generic + rgctx trampolines */
6949 acfg->final_got_size += 400;
6950 /* For the specific trampolines */
6951 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6952 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6957 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
6958 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6962 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6963 * a lot of time, and doesn't seem to save much space.
6964 * The following optimizations cannot be enabled:
6966 * - 'jump-threading' changes our blockaddress references to int constants.
6967 * - 'basiccg' fails because it contains:
6968 * if (CS && !isa<IntrinsicInst>(II)) {
6969 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
6970 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
6971 * The opt list below was produced by taking the output of:
6972 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
6973 * then removing tailcallelim + the global opts.
6974 * strip-dead-prototypes deletes unused intrinsics definitions.
6976 opts = g_strdup ("-instcombine -simplifycfg");
6977 //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");
6978 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -dse -adce -simplifycfg -instcombine -strip-dead-prototypes -preverify -domtree -verify");
6980 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
6981 printf ("Executing opt: %s\n", command);
6982 if (system (command) != 0) {
6988 if (!acfg->llc_args)
6989 acfg->llc_args = g_string_new ("");
6991 /* Verbose asm slows down llc greatly */
6992 g_string_append (acfg->llc_args, " -asm-verbose=false");
6994 if (acfg->aot_opts.mtriple)
6995 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
6997 #if defined(TARGET_MACH) && defined(TARGET_ARM)
6998 /* ios requires PIC code now */
6999 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7001 if (llvm_acfg->aot_opts.static_link)
7002 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7004 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7006 unlink (acfg->tmpfname);
7008 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);
7010 printf ("Executing llc: %s\n", command);
7012 if (system (command) != 0) {
7019 emit_code (MonoAotCompile *acfg)
7021 int oindex, i, prev_index;
7024 #if defined(TARGET_POWERPC64)
7025 sprintf (symbol, ".Lgot_addr");
7026 emit_section_change (acfg, ".text", 0);
7027 emit_alignment (acfg, 8);
7028 emit_label (acfg, symbol);
7029 emit_pointer (acfg, acfg->got_symbol);
7033 * This global symbol is used to compute the address of each method using the
7034 * code_offsets array. It is also used to compute the memory ranges occupied by
7035 * AOT code, so it must be equal to the address of the first emitted method.
7037 emit_section_change (acfg, ".text", 0);
7038 emit_alignment (acfg, 8);
7040 for (i = 0; i < acfg->nmethods; ++i) {
7041 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7042 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7047 if (!acfg->methods_symbol) {
7048 sprintf (symbol, "methods");
7049 emit_label (acfg, symbol);
7050 acfg->methods_symbol = g_strdup (symbol);
7054 * Emit some padding so the local symbol for the first method doesn't have the
7055 * same address as 'methods'.
7057 #if defined(__default_codegen__)
7058 emit_zero_bytes (acfg, 16);
7059 #elif defined(__native_client_codegen__)
7061 const int kPaddingSize = 16;
7062 guint8 pad_buffer[kPaddingSize];
7063 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7064 emit_bytes (acfg, pad_buffer, kPaddingSize);
7068 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7072 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7074 cfg = acfg->cfgs [i];
7079 method = cfg->orig_method;
7081 /* Emit unbox trampoline */
7082 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7083 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7085 emit_section_change (acfg, ".text", 0);
7086 #ifdef __native_client_codegen__
7087 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7090 if (acfg->thumb_mixed && cfg->compile_llvm) {
7091 emit_set_thumb_mode (acfg);
7092 fprintf (acfg->fp, "\n.thumb_func\n");
7095 emit_label (acfg, symbol);
7097 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7099 if (acfg->thumb_mixed && cfg->compile_llvm) {
7100 emit_set_arm_mode (acfg);
7104 if (cfg->compile_llvm)
7105 acfg->stats.llvm_count ++;
7107 emit_method_code (acfg, cfg);
7110 sprintf (symbol, "methods_end");
7111 emit_section_change (acfg, ".text", 0);
7112 emit_alignment (acfg, 8);
7113 emit_label (acfg, symbol);
7114 /* To distinguish it from the next symbol */
7115 emit_int32 (acfg, 0);
7118 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7119 * from optimizing them away, since it doesn't see that code_offsets references them.
7120 * JITted methods don't need this since they are referenced using assembler local
7122 * FIXME: This is why write-symbols doesn't work on OSX ?
7124 if (acfg->llvm && acfg->need_no_dead_strip) {
7125 fprintf (acfg->fp, "\n");
7126 for (i = 0; i < acfg->nmethods; ++i) {
7127 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7128 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7133 if (acfg->direct_method_addresses) {
7134 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7137 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7138 * This is PIE code, and the linker can update it if needed.
7140 sprintf (symbol, "method_addresses");
7141 emit_section_change (acfg, ".text", 1);
7142 emit_alignment (acfg, 8);
7143 emit_label (acfg, symbol);
7144 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7145 emit_unset_mode (acfg);
7146 if (acfg->need_no_dead_strip)
7147 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7149 for (i = 0; i < acfg->nmethods; ++i) {
7150 if (acfg->cfgs [i]) {
7151 if (acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm)
7152 fprintf (acfg->fp, "\tblx %s\n", acfg->cfgs [i]->asm_symbol);
7154 fprintf (acfg->fp, "\tbl %s\n", acfg->cfgs [i]->asm_symbol);
7156 fprintf (acfg->fp, "\tbl method_addresses\n");
7160 sprintf (symbol, "method_addresses_end");
7161 emit_label (acfg, symbol);
7164 sprintf (symbol, "code_offsets");
7165 emit_section_change (acfg, RODATA_SECT, 1);
7166 emit_alignment (acfg, 8);
7167 emit_label (acfg, symbol);
7168 emit_int32 (acfg, 0);
7170 sprintf (symbol, "code_offsets");
7171 emit_section_change (acfg, RODATA_SECT, 1);
7172 emit_alignment (acfg, 8);
7173 emit_label (acfg, symbol);
7175 acfg->stats.offsets_size += acfg->nmethods * 4;
7177 for (i = 0; i < acfg->nmethods; ++i) {
7178 if (acfg->cfgs [i]) {
7179 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7181 emit_int32 (acfg, 0xffffffff);
7186 sprintf (symbol, "code_offsets");
7187 emit_section_change (acfg, RODATA_SECT, 1);
7188 emit_alignment (acfg, 8);
7189 emit_label (acfg, symbol);
7191 acfg->stats.offsets_size += acfg->nmethods * 4;
7193 for (i = 0; i < acfg->nmethods; ++i) {
7194 if (acfg->cfgs [i]) {
7195 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7197 emit_int32 (acfg, 0xffffffff);
7203 /* Emit a sorted table mapping methods to their unbox trampolines */
7204 sprintf (symbol, "unbox_trampolines");
7205 if (acfg->direct_method_addresses)
7206 emit_section_change (acfg, ".text", 0);
7208 emit_section_change (acfg, RODATA_SECT, 0);
7209 emit_alignment (acfg, 8);
7210 emit_label (acfg, symbol);
7213 for (i = 0; i < acfg->nmethods; ++i) {
7218 cfg = acfg->cfgs [i];
7222 method = cfg->orig_method;
7224 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7225 index = get_method_index (acfg, method);
7226 sprintf (symbol, "ut_%d", index);
7228 emit_int32 (acfg, index);
7229 if (acfg->direct_method_addresses) {
7230 emit_unset_mode (acfg);
7231 if (acfg->thumb_mixed && cfg->compile_llvm)
7232 fprintf (acfg->fp, "\n\tblx %s\n", symbol);
7234 fprintf (acfg->fp, "\n\tbl %s\n", symbol);
7236 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7238 /* Make sure the table is sorted by index */
7239 g_assert (index > prev_index);
7243 sprintf (symbol, "unbox_trampolines_end");
7244 emit_label (acfg, symbol);
7245 emit_int32 (acfg, 0);
7249 emit_info (MonoAotCompile *acfg)
7255 offsets = g_new0 (gint32, acfg->nmethods);
7257 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7258 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7260 if (acfg->cfgs [i]) {
7261 emit_method_info (acfg, acfg->cfgs [i]);
7262 offsets [i] = acfg->cfgs [i]->method_info_offset;
7268 sprintf (symbol, "method_info_offsets");
7269 emit_section_change (acfg, RODATA_SECT, 1);
7270 emit_alignment (acfg, 8);
7271 emit_label (acfg, symbol);
7273 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7278 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7280 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7281 #define mix(a,b,c) { \
7282 a -= c; a ^= rot(c, 4); c += b; \
7283 b -= a; b ^= rot(a, 6); a += c; \
7284 c -= b; c ^= rot(b, 8); b += a; \
7285 a -= c; a ^= rot(c,16); c += b; \
7286 b -= a; b ^= rot(a,19); a += c; \
7287 c -= b; c ^= rot(b, 4); b += a; \
7289 #define final(a,b,c) { \
7290 c ^= b; c -= rot(b,14); \
7291 a ^= c; a -= rot(c,11); \
7292 b ^= a; b -= rot(a,25); \
7293 c ^= b; c -= rot(b,16); \
7294 a ^= c; a -= rot(c,4); \
7295 b ^= a; b -= rot(a,14); \
7296 c ^= b; c -= rot(b,24); \
7300 mono_aot_type_hash (MonoType *t1)
7302 guint hash = t1->type;
7304 hash |= t1->byref << 6; /* do not collide with t1->type values */
7306 case MONO_TYPE_VALUETYPE:
7307 case MONO_TYPE_CLASS:
7308 case MONO_TYPE_SZARRAY:
7309 /* check if the distribution is good enough */
7310 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7312 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7313 case MONO_TYPE_ARRAY:
7314 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7315 case MONO_TYPE_GENERICINST:
7316 return ((hash << 5) - hash) ^ 0;
7323 * mono_aot_method_hash:
7325 * Return a hash code for methods which only depends on metadata.
7328 mono_aot_method_hash (MonoMethod *method)
7330 MonoMethodSignature *sig;
7334 guint32 *hashes_start, *hashes;
7336 MonoGenericInst *ginst = NULL;
7338 /* Similar to the hash in mono_method_get_imt_slot () */
7340 sig = mono_method_signature (method);
7342 if (method->is_inflated)
7343 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7345 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7346 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7347 hashes = hashes_start;
7349 /* Some wrappers are assigned to random classes */
7350 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7351 klass = method->klass;
7353 klass = mono_defaults.object_class;
7355 if (!method->wrapper_type) {
7356 char *full_name = mono_type_full_name (&klass->byval_arg);
7358 hashes [0] = mono_metadata_str_hash (full_name);
7362 hashes [0] = mono_metadata_str_hash (klass->name);
7363 hashes [1] = mono_metadata_str_hash (klass->name_space);
7365 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7366 /* The method name includes a stringified pointer */
7369 hashes [2] = mono_metadata_str_hash (method->name);
7370 hashes [3] = method->wrapper_type;
7371 hashes [4] = mono_aot_type_hash (sig->ret);
7373 for (i = 0; i < sig->param_count; i++) {
7374 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7377 for (i = 0; i < ginst->type_argc; ++i)
7378 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7380 g_assert (hindex == hashes_count);
7382 /* Setup internal state */
7383 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7385 /* Handle most of the hashes */
7386 while (hashes_count > 3) {
7395 /* Handle the last 3 hashes (all the case statements fall through) */
7396 switch (hashes_count) {
7397 case 3 : c += hashes [2];
7398 case 2 : b += hashes [1];
7399 case 1 : a += hashes [0];
7401 case 0: /* nothing left to add */
7405 free (hashes_start);
7414 * mono_aot_get_array_helper_from_wrapper;
7416 * Get the helper method in Array called by an array wrapper method.
7419 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7423 MonoGenericContext ctx;
7424 MonoType *args [16];
7425 char *mname, *iname, *s, *s2, *helper_name = NULL;
7427 prefix = "System.Collections.Generic";
7428 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7429 s2 = strstr (s, "`1.");
7435 //printf ("X: %s %s\n", iname, mname);
7437 if (!strcmp (iname, "IList"))
7438 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7440 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7441 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7443 g_free (helper_name);
7446 if (m->is_generic) {
7447 memset (&ctx, 0, sizeof (ctx));
7448 args [0] = &method->klass->element_class->byval_arg;
7449 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7450 m = mono_class_inflate_generic_method (m, &ctx);
7456 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7458 typedef struct HashEntry {
7459 guint32 key, value, index;
7460 struct HashEntry *next;
7464 * emit_extra_methods:
7466 * Emit methods which are not in the METHOD table, like wrappers.
7469 emit_extra_methods (MonoAotCompile *acfg)
7471 int i, table_size, buf_size;
7474 guint32 *info_offsets;
7477 HashEntry *entry, *new_entry;
7478 int nmethods, max_chain_length;
7481 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7483 /* Emit method info */
7485 for (i = 0; i < acfg->extra_methods->len; ++i) {
7486 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7487 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7493 p = buf = g_malloc (buf_size);
7497 method = cfg->method_to_register;
7499 encode_method_ref (acfg, method, p, &p);
7501 g_assert ((p - buf) < buf_size);
7503 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7508 * Construct a chained hash table for mapping indexes in extra_method_info to
7511 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7512 table = g_ptr_array_sized_new (table_size);
7513 for (i = 0; i < table_size; ++i)
7514 g_ptr_array_add (table, NULL);
7515 chain_lengths = g_new0 (int, table_size);
7516 max_chain_length = 0;
7517 for (i = 0; i < acfg->extra_methods->len; ++i) {
7518 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7519 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7525 key = info_offsets [i];
7526 value = get_method_index (acfg, method);
7528 hash = mono_aot_method_hash (method) % table_size;
7529 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7531 chain_lengths [hash] ++;
7532 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7534 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7535 new_entry->key = key;
7536 new_entry->value = value;
7538 entry = g_ptr_array_index (table, hash);
7539 if (entry == NULL) {
7540 new_entry->index = hash;
7541 g_ptr_array_index (table, hash) = new_entry;
7544 entry = entry->next;
7546 entry->next = new_entry;
7547 new_entry->index = table->len;
7548 g_ptr_array_add (table, new_entry);
7552 //printf ("MAX: %d\n", max_chain_length);
7554 /* Emit the table */
7555 sprintf (symbol, "extra_method_table");
7556 emit_section_change (acfg, RODATA_SECT, 0);
7557 emit_alignment (acfg, 8);
7558 emit_label (acfg, symbol);
7560 emit_int32 (acfg, table_size);
7561 for (i = 0; i < table->len; ++i) {
7562 HashEntry *entry = g_ptr_array_index (table, i);
7564 if (entry == NULL) {
7565 emit_int32 (acfg, 0);
7566 emit_int32 (acfg, 0);
7567 emit_int32 (acfg, 0);
7569 //g_assert (entry->key > 0);
7570 emit_int32 (acfg, entry->key);
7571 emit_int32 (acfg, entry->value);
7573 emit_int32 (acfg, entry->next->index);
7575 emit_int32 (acfg, 0);
7580 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7581 * This is used by mono_aot_find_jit_info ().
7583 sprintf (symbol, "extra_method_info_offsets");
7584 emit_section_change (acfg, RODATA_SECT, 0);
7585 emit_alignment (acfg, 8);
7586 emit_label (acfg, symbol);
7588 emit_int32 (acfg, acfg->extra_methods->len);
7589 for (i = 0; i < acfg->extra_methods->len; ++i) {
7590 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7592 emit_int32 (acfg, get_method_index (acfg, method));
7593 emit_int32 (acfg, info_offsets [i]);
7598 emit_exception_info (MonoAotCompile *acfg)
7604 offsets = g_new0 (gint32, acfg->nmethods);
7605 for (i = 0; i < acfg->nmethods; ++i) {
7606 if (acfg->cfgs [i]) {
7607 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7608 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7614 sprintf (symbol, "ex_info_offsets");
7615 emit_section_change (acfg, RODATA_SECT, 1);
7616 emit_alignment (acfg, 8);
7617 emit_label (acfg, symbol);
7619 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7624 emit_unwind_info (MonoAotCompile *acfg)
7630 * The unwind info contains a lot of duplicates so we emit each unique
7631 * entry once, and only store the offset from the start of the table in the
7635 sprintf (symbol, "unwind_info");
7636 emit_section_change (acfg, RODATA_SECT, 1);
7637 emit_alignment (acfg, 8);
7638 emit_label (acfg, symbol);
7640 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7641 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7642 guint8 *unwind_info;
7643 guint32 unwind_info_len;
7647 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7650 encode_value (unwind_info_len, p, &p);
7651 emit_bytes (acfg, buf, p - buf);
7652 emit_bytes (acfg, unwind_info, unwind_info_len);
7654 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7659 emit_class_info (MonoAotCompile *acfg)
7665 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7666 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7667 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7669 sprintf (symbol, "class_info_offsets");
7670 emit_section_change (acfg, RODATA_SECT, 1);
7671 emit_alignment (acfg, 8);
7672 emit_label (acfg, symbol);
7674 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7678 typedef struct ClassNameTableEntry {
7679 guint32 token, index;
7680 struct ClassNameTableEntry *next;
7681 } ClassNameTableEntry;
7684 emit_class_name_table (MonoAotCompile *acfg)
7687 guint32 token, hash;
7692 ClassNameTableEntry *entry, *new_entry;
7695 * Construct a chained hash table for mapping class names to typedef tokens.
7697 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7698 table = g_ptr_array_sized_new (table_size);
7699 for (i = 0; i < table_size; ++i)
7700 g_ptr_array_add (table, NULL);
7701 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7702 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7703 klass = mono_class_get (acfg->image, token);
7705 mono_loader_clear_error ();
7708 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7709 hash = mono_metadata_str_hash (full_name) % table_size;
7712 /* FIXME: Allocate from the mempool */
7713 new_entry = g_new0 (ClassNameTableEntry, 1);
7714 new_entry->token = token;
7716 entry = g_ptr_array_index (table, hash);
7717 if (entry == NULL) {
7718 new_entry->index = hash;
7719 g_ptr_array_index (table, hash) = new_entry;
7722 entry = entry->next;
7724 entry->next = new_entry;
7725 new_entry->index = table->len;
7726 g_ptr_array_add (table, new_entry);
7730 /* Emit the table */
7731 sprintf (symbol, "class_name_table");
7732 emit_section_change (acfg, RODATA_SECT, 0);
7733 emit_alignment (acfg, 8);
7734 emit_label (acfg, symbol);
7736 /* FIXME: Optimize memory usage */
7737 g_assert (table_size < 65000);
7738 emit_int16 (acfg, table_size);
7739 g_assert (table->len < 65000);
7740 for (i = 0; i < table->len; ++i) {
7741 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7743 if (entry == NULL) {
7744 emit_int16 (acfg, 0);
7745 emit_int16 (acfg, 0);
7747 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7749 emit_int16 (acfg, entry->next->index);
7751 emit_int16 (acfg, 0);
7757 emit_image_table (MonoAotCompile *acfg)
7763 * The image table is small but referenced in a lot of places.
7764 * So we emit it at once, and reference its elements by an index.
7767 sprintf (symbol, "image_table");
7768 emit_section_change (acfg, RODATA_SECT, 1);
7769 emit_alignment (acfg, 8);
7770 emit_label (acfg, symbol);
7772 emit_int32 (acfg, acfg->image_table->len);
7773 for (i = 0; i < acfg->image_table->len; i++) {
7774 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7775 MonoAssemblyName *aname = &image->assembly->aname;
7777 /* FIXME: Support multi-module assemblies */
7778 g_assert (image->assembly->image == image);
7780 emit_string (acfg, image->assembly_name);
7781 emit_string (acfg, image->guid);
7782 emit_string (acfg, aname->culture ? aname->culture : "");
7783 emit_string (acfg, (const char*)aname->public_key_token);
7785 emit_alignment (acfg, 8);
7786 emit_int32 (acfg, aname->flags);
7787 emit_int32 (acfg, aname->major);
7788 emit_int32 (acfg, aname->minor);
7789 emit_int32 (acfg, aname->build);
7790 emit_int32 (acfg, aname->revision);
7795 emit_got_info (MonoAotCompile *acfg)
7798 int i, first_plt_got_patch, buf_size;
7800 guint32 *got_info_offsets;
7802 /* Add the patches needed by the PLT to the GOT */
7803 acfg->plt_got_offset_base = acfg->got_offset;
7804 first_plt_got_patch = acfg->got_patches->len;
7805 for (i = 1; i < acfg->plt_offset; ++i) {
7806 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7808 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7810 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7813 acfg->got_offset += acfg->plt_offset;
7817 * - optimize offsets table.
7818 * - reduce number of exported symbols.
7819 * - emit info for a klass only once.
7820 * - determine when a method uses a GOT slot which is guaranteed to be already
7822 * - clean up and document the code.
7823 * - use String.Empty in class libs.
7826 /* Encode info required to decode shared GOT entries */
7827 buf_size = acfg->got_patches->len * 128;
7828 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7829 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7830 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7832 if (acfg->plt_offset)
7833 acfg->plt_got_info_offsets [0] = 0;
7834 for (i = 0; i < acfg->got_patches->len; ++i) {
7835 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7840 encode_value (ji->type, p, &p);
7842 encode_patch (acfg, ji, p, &p);
7843 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7844 g_assert (p - buf <= buf_size);
7845 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7847 if (i >= first_plt_got_patch)
7848 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7849 acfg->stats.got_info_size += p - buf;
7852 /* Emit got_info_offsets table */
7853 sprintf (symbol, "got_info_offsets");
7854 emit_section_change (acfg, RODATA_SECT, 1);
7855 emit_alignment (acfg, 8);
7856 emit_label (acfg, symbol);
7858 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7859 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7863 emit_got (MonoAotCompile *acfg)
7868 /* Don't make GOT global so accesses to it don't need relocations */
7869 sprintf (symbol, "%s", acfg->got_symbol);
7870 emit_section_change (acfg, ".bss", 0);
7871 emit_alignment (acfg, 8);
7872 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7873 emit_label (acfg, symbol);
7874 if (acfg->got_offset > 0)
7875 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7877 sprintf (symbol, "got_end");
7878 emit_label (acfg, symbol);
7882 typedef struct GlobalsTableEntry {
7883 guint32 value, index;
7884 struct GlobalsTableEntry *next;
7885 } GlobalsTableEntry;
7888 emit_globals (MonoAotCompile *acfg)
7894 GlobalsTableEntry *entry, *new_entry;
7896 if (!acfg->aot_opts.static_link)
7900 * When static linking, we emit a table containing our globals.
7904 * Construct a chained hash table for mapping global names to their index in
7905 * the globals table.
7907 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7908 table = g_ptr_array_sized_new (table_size);
7909 for (i = 0; i < table_size; ++i)
7910 g_ptr_array_add (table, NULL);
7911 for (i = 0; i < acfg->globals->len; ++i) {
7912 char *name = g_ptr_array_index (acfg->globals, i);
7914 hash = mono_metadata_str_hash (name) % table_size;
7916 /* FIXME: Allocate from the mempool */
7917 new_entry = g_new0 (GlobalsTableEntry, 1);
7918 new_entry->value = i;
7920 entry = g_ptr_array_index (table, hash);
7921 if (entry == NULL) {
7922 new_entry->index = hash;
7923 g_ptr_array_index (table, hash) = new_entry;
7926 entry = entry->next;
7928 entry->next = new_entry;
7929 new_entry->index = table->len;
7930 g_ptr_array_add (table, new_entry);
7934 /* Emit the table */
7935 sprintf (symbol, ".Lglobals_hash");
7936 emit_section_change (acfg, RODATA_SECT, 0);
7937 emit_alignment (acfg, 8);
7938 emit_label (acfg, symbol);
7940 /* FIXME: Optimize memory usage */
7941 g_assert (table_size < 65000);
7942 emit_int16 (acfg, table_size);
7943 for (i = 0; i < table->len; ++i) {
7944 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7946 if (entry == NULL) {
7947 emit_int16 (acfg, 0);
7948 emit_int16 (acfg, 0);
7950 emit_int16 (acfg, entry->value + 1);
7952 emit_int16 (acfg, entry->next->index);
7954 emit_int16 (acfg, 0);
7958 /* Emit the names */
7959 for (i = 0; i < acfg->globals->len; ++i) {
7960 char *name = g_ptr_array_index (acfg->globals, i);
7962 sprintf (symbol, "name_%d", i);
7963 emit_section_change (acfg, RODATA_SECT, 1);
7965 emit_alignment (acfg, 4);
7967 emit_label (acfg, symbol);
7968 emit_string (acfg, name);
7971 /* Emit the globals table */
7972 sprintf (symbol, "globals");
7973 emit_section_change (acfg, ".data", 0);
7974 /* This is not a global, since it is accessed by the init function */
7975 emit_alignment (acfg, 8);
7976 emit_label (acfg, symbol);
7978 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
7979 emit_pointer (acfg, symbol);
7981 for (i = 0; i < acfg->globals->len; ++i) {
7982 char *name = g_ptr_array_index (acfg->globals, i);
7984 sprintf (symbol, "name_%d", i);
7985 emit_pointer (acfg, symbol);
7987 sprintf (symbol, "%s", name);
7988 emit_pointer (acfg, symbol);
7990 /* Null terminate the table */
7991 emit_int32 (acfg, 0);
7992 emit_int32 (acfg, 0);
7996 emit_autoreg (MonoAotCompile *acfg)
8001 * Emit a function into the .ctor section which will be called by the ELF
8002 * loader to register this module with the runtime.
8004 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8007 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8009 arch_emit_autoreg (acfg, symbol);
8015 emit_mem_end (MonoAotCompile *acfg)
8019 sprintf (symbol, "mem_end");
8020 emit_section_change (acfg, ".text", 1);
8021 emit_alignment (acfg, 8);
8022 emit_label (acfg, symbol);
8026 * Emit a structure containing all the information not stored elsewhere.
8029 emit_file_info (MonoAotCompile *acfg)
8034 const char *gc_name;
8037 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8039 if (acfg->aot_opts.bind_to_runtime_version) {
8040 build_info = mono_get_runtime_build_info ();
8041 emit_string_symbol (acfg, "runtime_version", build_info);
8042 g_free (build_info);
8044 emit_string_symbol (acfg, "runtime_version", "");
8047 /* Emit a string holding the assembly name */
8048 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8051 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8054 gc_name = mono_gc_get_gc_name ();
8055 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8057 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8058 emit_section_change (acfg, ".data", 0);
8059 emit_alignment (acfg, 8);
8060 emit_label (acfg, symbol);
8061 if (!acfg->aot_opts.static_link)
8062 emit_global (acfg, symbol, FALSE);
8064 /* The data emitted here must match MonoAotFileInfo. */
8066 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8067 emit_int32 (acfg, 0);
8070 * We emit pointers to our data structures instead of emitting global symbols which
8071 * point to them, to reduce the number of globals, and because using globals leads to
8072 * various problems (i.e. arm/thumb).
8074 emit_pointer (acfg, acfg->got_symbol);
8075 emit_pointer (acfg, acfg->methods_symbol);
8078 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8080 emit_pointer (acfg, "mono_eh_frame");
8082 emit_pointer (acfg, NULL);
8084 emit_pointer (acfg, "blob");
8085 emit_pointer (acfg, "class_name_table");
8086 emit_pointer (acfg, "class_info_offsets");
8087 emit_pointer (acfg, "method_info_offsets");
8088 emit_pointer (acfg, "ex_info_offsets");
8089 emit_pointer (acfg, "code_offsets");
8090 if (acfg->direct_method_addresses)
8091 emit_pointer (acfg, "method_addresses");
8093 emit_pointer (acfg, NULL);
8094 emit_pointer (acfg, "extra_method_info_offsets");
8095 emit_pointer (acfg, "extra_method_table");
8096 emit_pointer (acfg, "got_info_offsets");
8097 emit_pointer (acfg, "methods_end");
8098 emit_pointer (acfg, "unwind_info");
8099 emit_pointer (acfg, "mem_end");
8100 emit_pointer (acfg, "image_table");
8101 emit_pointer (acfg, "plt");
8102 emit_pointer (acfg, "plt_end");
8103 emit_pointer (acfg, "assembly_guid");
8104 emit_pointer (acfg, "runtime_version");
8105 if (acfg->num_trampoline_got_entries) {
8106 emit_pointer (acfg, "specific_trampolines");
8107 emit_pointer (acfg, "static_rgctx_trampolines");
8108 emit_pointer (acfg, "imt_thunks");
8109 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8111 emit_pointer (acfg, NULL);
8112 emit_pointer (acfg, NULL);
8113 emit_pointer (acfg, NULL);
8114 emit_pointer (acfg, NULL);
8116 if (acfg->thumb_mixed) {
8117 emit_pointer (acfg, "thumb_end");
8119 emit_pointer (acfg, NULL);
8121 if (acfg->aot_opts.static_link) {
8122 emit_pointer (acfg, "globals");
8124 emit_pointer (acfg, NULL);
8126 emit_pointer (acfg, "assembly_name");
8127 emit_pointer (acfg, "unbox_trampolines");
8128 emit_pointer (acfg, "unbox_trampolines_end");
8130 emit_int32 (acfg, acfg->plt_got_offset_base);
8131 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8132 emit_int32 (acfg, acfg->plt_offset);
8133 emit_int32 (acfg, acfg->nmethods);
8134 emit_int32 (acfg, acfg->flags);
8135 emit_int32 (acfg, acfg->opts);
8136 emit_int32 (acfg, acfg->simd_opts);
8137 emit_int32 (acfg, gc_name_offset);
8139 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8140 emit_int32 (acfg, acfg->num_trampolines [i]);
8141 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8142 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8143 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8144 emit_int32 (acfg, acfg->trampoline_size [i]);
8145 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8147 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8152 memset (&t, 0, sizeof (MonoType));
8153 t.type = MONO_TYPE_R8;
8154 mono_type_size (&t, &align);
8155 emit_int32 (acfg, align);
8157 memset (&t, 0, sizeof (MonoType));
8158 t.type = MONO_TYPE_I8;
8159 mono_type_size (&t, &align);
8161 emit_int32 (acfg, align);
8164 emit_int32 (acfg, __alignof__ (double));
8165 emit_int32 (acfg, __alignof__ (gint64));
8167 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8168 emit_int32 (acfg, acfg->tramp_page_size);
8169 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8170 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8172 if (acfg->aot_opts.static_link) {
8176 * Emit a global symbol which can be passed by an embedding app to
8177 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8180 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8182 /* Get rid of characters which cannot occur in symbols */
8184 for (p = symbol; *p; ++p) {
8185 if (!(isalnum (*p) || *p == '_'))
8188 acfg->static_linking_symbol = g_strdup (symbol);
8189 emit_global_inner (acfg, symbol, FALSE);
8190 emit_alignment (acfg, sizeof (gpointer));
8191 emit_label (acfg, symbol);
8192 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8197 emit_blob (MonoAotCompile *acfg)
8201 sprintf (symbol, "blob");
8202 emit_section_change (acfg, RODATA_SECT, 1);
8203 emit_alignment (acfg, 8);
8204 emit_label (acfg, symbol);
8206 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8210 emit_objc_selectors (MonoAotCompile *acfg)
8214 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8219 * cat > foo.m << EOF
8222 * return @selector(print:);
8227 img_writer_emit_unset_mode (acfg->w);
8228 g_assert (acfg->fp);
8229 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8230 fprintf (acfg->fp, ".align 2\n");
8231 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8232 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8233 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8235 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8236 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8237 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8238 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8241 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8242 fprintf (acfg->fp, ".align 2\n");
8243 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8244 fprintf (acfg->fp, ".long 0\n");
8245 fprintf (acfg->fp, ".long 16\n");
8249 emit_dwarf_info (MonoAotCompile *acfg)
8251 #ifdef EMIT_DWARF_INFO
8255 /* DIEs for methods */
8256 for (i = 0; i < acfg->nmethods; ++i) {
8257 MonoCompile *cfg = acfg->cfgs [i];
8262 // FIXME: LLVM doesn't define .Lme_...
8263 if (cfg->compile_llvm)
8266 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8268 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 ()));
8274 collect_methods (MonoAotCompile *acfg)
8277 MonoImage *image = acfg->image;
8279 /* Collect methods */
8280 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8282 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8284 method = mono_get_method (acfg->image, token, NULL);
8287 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8288 printf ("Run with MONO_LOG_LEVEL=debug for more information.\n");
8292 /* Load all methods eagerly to skip the slower lazy loading code */
8293 mono_class_setup_methods (method->klass);
8295 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8296 /* Compile the wrapper instead */
8297 /* We do this here instead of add_wrappers () because it is easy to do it here */
8298 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8302 /* FIXME: Some mscorlib methods don't have debug info */
8304 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8305 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8306 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8307 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8308 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8309 if (!mono_debug_lookup_method (method)) {
8310 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8317 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8318 add_method_with_index (acfg, method, i, FALSE);
8319 acfg->method_index ++;
8322 /* gsharedvt methods */
8323 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8325 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8327 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8330 method = mono_get_method (acfg->image, token, NULL);
8334 if (strcmp (method->name, "gshared2"))
8338 if (!strstr (method->klass->image->name, "mini"))
8341 if (method->is_generic || method->klass->generic_container) {
8342 MonoMethod *gshared;
8344 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8345 add_extra_method (acfg, gshared);
8349 add_generic_instances (acfg);
8351 if (acfg->aot_opts.full_aot)
8352 add_wrappers (acfg);
8356 compile_methods (MonoAotCompile *acfg)
8360 if (acfg->aot_opts.nthreads > 0) {
8365 gpointer *user_data;
8366 MonoMethod **methods;
8368 methods_len = acfg->methods->len;
8370 len = acfg->methods->len / acfg->aot_opts.nthreads;
8373 * Partition the list of methods into fragments, and hand it to threads to
8376 threads = g_ptr_array_new ();
8377 /* Make a copy since acfg->methods is modified by compile_method () */
8378 methods = g_new0 (MonoMethod*, methods_len);
8379 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8380 for (i = 0; i < methods_len; ++i)
8381 methods [i] = g_ptr_array_index (acfg->methods, i);
8383 while (i < methods_len) {
8384 frag = g_ptr_array_new ();
8385 for (j = 0; j < len; ++j) {
8386 if (i < methods_len) {
8387 g_ptr_array_add (frag, methods [i]);
8392 user_data = g_new0 (gpointer, 3);
8393 user_data [0] = mono_domain_get ();
8394 user_data [1] = acfg;
8395 user_data [2] = frag;
8397 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8398 g_ptr_array_add (threads, handle);
8402 for (i = 0; i < threads->len; ++i) {
8403 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8409 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8410 for (i = methods_len; i < acfg->methods->len; ++i) {
8411 /* This can new methods to acfg->methods */
8412 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8417 compile_asm (MonoAotCompile *acfg)
8419 char *command, *objfile;
8420 char *outfile_name, *tmp_outfile_name;
8421 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8423 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8424 #define AS_OPTIONS "--64"
8425 #elif defined(TARGET_POWERPC64)
8426 #define AS_OPTIONS "-a64 -mppc64"
8427 #define LD_OPTIONS "-m elf64ppc"
8428 #elif defined(sparc) && SIZEOF_VOID_P == 8
8429 #define AS_OPTIONS "-xarch=v9"
8430 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8431 #define AS_OPTIONS "-arch i386"
8433 #define AS_OPTIONS ""
8436 #ifdef __native_client_codegen__
8437 #if defined(TARGET_AMD64)
8438 #define AS_NAME "nacl64-as"
8440 #define AS_NAME "nacl-as"
8442 #elif defined(TARGET_OSX)
8443 #define AS_NAME "clang -c -x assembler"
8445 #define AS_NAME "as"
8449 #define LD_OPTIONS ""
8453 #define LD_NAME "ld -shared -G"
8454 #elif defined(__ppc__) && defined(TARGET_MACH)
8455 #define LD_NAME "gcc -dynamiclib"
8456 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8457 #define LD_NAME "clang --shared"
8458 #elif defined(HOST_WIN32)
8459 #define LD_NAME "gcc -shared --dll"
8460 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8461 #define LD_NAME "clang -m32 -dynamiclib"
8464 if (acfg->aot_opts.asm_only) {
8465 printf ("Output file: '%s'.\n", acfg->tmpfname);
8466 if (acfg->aot_opts.static_link)
8467 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8471 if (acfg->aot_opts.static_link) {
8472 if (acfg->aot_opts.outfile)
8473 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8475 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8477 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8479 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);
8480 printf ("Executing the native assembler: %s\n", command);
8481 if (system (command) != 0) {
8489 if (acfg->aot_opts.static_link) {
8490 printf ("Output file: '%s'.\n", objfile);
8491 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8496 if (acfg->aot_opts.outfile)
8497 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8499 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8501 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8504 command = g_strdup_printf ("%s -o %s %s.o", LD_NAME, tmp_outfile_name, acfg->tmpfname);
8506 command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8508 printf ("Executing the native linker: %s\n", command);
8509 if (system (command) != 0) {
8510 g_free (tmp_outfile_name);
8511 g_free (outfile_name);
8519 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8520 printf ("Stripping the binary: %s\n", com);
8524 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8526 * gas generates 'mapping symbols' each time code and data is mixed, which
8527 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8529 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8530 printf ("Stripping the binary: %s\n", command);
8531 if (system (command) != 0) {
8532 g_free (tmp_outfile_name);
8533 g_free (outfile_name);
8540 rename (tmp_outfile_name, outfile_name);
8542 #if defined(TARGET_MACH)
8543 command = g_strdup_printf ("dsymutil %s", outfile_name);
8544 printf ("Executing dsymutil: %s\n", command);
8545 if (system (command) != 0) {
8550 if (!acfg->aot_opts.save_temps)
8553 g_free (tmp_outfile_name);
8554 g_free (outfile_name);
8557 if (acfg->aot_opts.save_temps)
8558 printf ("Retained input file.\n");
8560 unlink (acfg->tmpfname);
8565 static MonoAotCompile*
8566 acfg_create (MonoAssembly *ass, guint32 opts)
8568 MonoImage *image = ass->image;
8569 MonoAotCompile *acfg;
8572 acfg = g_new0 (MonoAotCompile, 1);
8573 acfg->methods = g_ptr_array_new ();
8574 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8575 acfg->method_depth = g_hash_table_new (NULL, NULL);
8576 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8577 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8578 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8579 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8580 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8581 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8582 acfg->got_patches = g_ptr_array_new ();
8583 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8584 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8585 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8586 acfg->image_hash = g_hash_table_new (NULL, NULL);
8587 acfg->image_table = g_ptr_array_new ();
8588 acfg->globals = g_ptr_array_new ();
8589 acfg->image = image;
8591 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8592 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8593 acfg->mempool = mono_mempool_new ();
8594 acfg->extra_methods = g_ptr_array_new ();
8595 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8596 acfg->unwind_ops = g_ptr_array_new ();
8597 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8598 acfg->method_order = g_ptr_array_new ();
8599 acfg->export_names = g_hash_table_new (NULL, NULL);
8600 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8601 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8602 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8603 InitializeCriticalSection (&acfg->mutex);
8609 acfg_free (MonoAotCompile *acfg)
8613 img_writer_destroy (acfg->w);
8614 for (i = 0; i < acfg->nmethods; ++i)
8616 g_free (acfg->cfgs [i]);
8617 g_free (acfg->cfgs);
8618 g_free (acfg->static_linking_symbol);
8619 g_free (acfg->got_symbol);
8620 g_free (acfg->plt_symbol);
8621 g_ptr_array_free (acfg->methods, TRUE);
8622 g_ptr_array_free (acfg->got_patches, TRUE);
8623 g_ptr_array_free (acfg->image_table, TRUE);
8624 g_ptr_array_free (acfg->globals, TRUE);
8625 g_ptr_array_free (acfg->unwind_ops, TRUE);
8626 g_hash_table_destroy (acfg->method_indexes);
8627 g_hash_table_destroy (acfg->method_depth);
8628 g_hash_table_destroy (acfg->plt_offset_to_entry);
8629 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8630 if (acfg->patch_to_plt_entry [i])
8631 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8633 g_free (acfg->patch_to_plt_entry);
8634 g_hash_table_destroy (acfg->patch_to_got_offset);
8635 g_hash_table_destroy (acfg->method_to_cfg);
8636 g_hash_table_destroy (acfg->token_info_hash);
8637 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8638 g_hash_table_destroy (acfg->image_hash);
8639 g_hash_table_destroy (acfg->unwind_info_offsets);
8640 g_hash_table_destroy (acfg->method_label_hash);
8641 g_hash_table_destroy (acfg->export_names);
8642 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8643 g_hash_table_destroy (acfg->klass_blob_hash);
8644 g_hash_table_destroy (acfg->method_blob_hash);
8645 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8646 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8647 g_free (acfg->patch_to_got_offset_by_type);
8648 mono_mempool_destroy (acfg->mempool);
8653 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8655 MonoImage *image = ass->image;
8657 MonoAotCompile *acfg;
8658 char *outfile_name, *tmp_outfile_name, *p;
8659 char llvm_stats_msg [256];
8663 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8664 if (opts & MONO_OPT_GSHAREDVT) {
8665 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8670 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8672 acfg = acfg_create (ass, opts);
8674 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8675 acfg->aot_opts.write_symbols = TRUE;
8676 acfg->aot_opts.ntrampolines = 1024;
8677 acfg->aot_opts.nrgctx_trampolines = 1024;
8678 acfg->aot_opts.nimt_trampolines = 128;
8679 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8680 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8681 acfg->aot_opts.llvm_path = g_strdup ("");
8683 acfg->aot_opts.use_trampolines_page = TRUE;
8686 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8688 if (acfg->aot_opts.static_link)
8689 acfg->aot_opts.autoreg = TRUE;
8691 //acfg->aot_opts.print_skipped_methods = TRUE;
8693 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8694 if (acfg->aot_opts.full_aot) {
8695 printf ("--aot=full is not supported on this platform.\n");
8700 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8701 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8705 if (acfg->aot_opts.static_link)
8706 acfg->aot_opts.asm_writer = TRUE;
8708 if (acfg->aot_opts.soft_debug) {
8709 MonoDebugOptions *opt = mini_get_debug_options ();
8711 opt->mdb_optimizations = TRUE;
8712 opt->gen_seq_points = TRUE;
8714 if (!mono_debug_enabled ()) {
8715 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8718 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8721 if (mono_use_llvm) {
8723 acfg->aot_opts.asm_writer = TRUE;
8724 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8726 if (acfg->aot_opts.soft_debug) {
8727 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8732 if (acfg->aot_opts.full_aot)
8733 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8735 load_profile_files (acfg);
8737 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8738 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8739 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8741 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8742 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8743 if (acfg->opts & MONO_OPT_GSHAREDVT)
8744 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8747 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8751 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8752 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8753 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8755 /* Get rid of characters which cannot occur in symbols */
8756 for (p = acfg->got_symbol_base; *p; ++p) {
8757 if (!(isalnum (*p) || *p == '_'))
8760 for (p = acfg->plt_symbol; *p; ++p) {
8761 if (!(isalnum (*p) || *p == '_'))
8764 for (p = acfg->assembly_name_sym; *p; ++p) {
8765 if (!(isalnum (*p) || *p == '_'))
8769 acfg->method_index = 1;
8773 if (acfg->aot_opts.full_aot)
8774 mono_set_partial_sharing_supported (TRUE);
8777 collect_methods (acfg);
8779 acfg->cfgs_size = acfg->methods->len + 32;
8780 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8782 /* PLT offset 0 is reserved for the PLT trampoline */
8783 acfg->plt_offset = 1;
8788 mono_llvm_create_aot_module (acfg->got_symbol_base);
8792 /* GOT offset 0 is reserved for the address of the current assembly */
8796 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8797 ji->type = MONO_PATCH_INFO_IMAGE;
8798 ji->data.image = acfg->image;
8800 get_got_offset (acfg, ji);
8802 /* Slot 1 is reserved for the mscorlib got addr */
8803 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8804 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8805 get_got_offset (acfg, ji);
8807 /* This is very common */
8808 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8809 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8810 get_got_offset (acfg, ji);
8812 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8813 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8814 get_got_offset (acfg, ji);
8819 compile_methods (acfg);
8823 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8829 if (acfg->aot_opts.asm_only) {
8830 if (acfg->aot_opts.outfile) {
8831 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8832 acfg->tmpbasename = g_strdup (acfg->tmpfname);
8834 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
8835 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8838 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
8839 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8842 emit_llvm_file (acfg);
8846 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8847 if (acfg->aot_opts.outfile)
8848 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8850 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8853 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8854 * it might be in another file system so the rename () won't work.
8856 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8858 acfg->fp = fopen (tmp_outfile_name, "w");
8860 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8864 acfg->w = img_writer_create (acfg->fp, TRUE);
8865 acfg->use_bin_writer = TRUE;
8868 /* Append to the .s file created by llvm */
8869 /* FIXME: Use multiple files instead */
8870 acfg->fp = fopen (acfg->tmpfname, "a+");
8872 if (acfg->aot_opts.asm_only) {
8873 if (acfg->aot_opts.outfile)
8874 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8876 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8877 acfg->fp = fopen (acfg->tmpfname, "w+");
8879 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8880 acfg->fp = fdopen (i, "w+");
8883 if (acfg->fp == 0) {
8884 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8887 acfg->w = img_writer_create (acfg->fp, FALSE);
8889 tmp_outfile_name = NULL;
8890 outfile_name = NULL;
8893 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8895 /* Compute symbols for methods */
8896 for (i = 0; i < acfg->nmethods; ++i) {
8897 if (acfg->cfgs [i]) {
8898 MonoCompile *cfg = acfg->cfgs [i];
8899 int method_index = get_method_index (acfg, cfg->orig_method);
8901 if (COMPILE_LLVM (cfg))
8902 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8903 else if (acfg->global_symbols)
8904 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8906 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8910 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
8912 * CLANG supports GAS .file/.loc directives, so emit line number information this way
8913 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
8916 //acfg->gas_line_numbers = TRUE;
8919 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8920 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
8921 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8924 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
8927 img_writer_emit_start (acfg->w);
8930 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
8932 if (acfg->thumb_mixed) {
8935 * This global symbol marks the end of THUMB code, and the beginning of ARM
8936 * code generated by our JIT.
8938 sprintf (symbol, "thumb_end");
8939 emit_section_change (acfg, ".text", 0);
8940 emit_alignment (acfg, 8);
8941 emit_label (acfg, symbol);
8942 emit_zero_bytes (acfg, 16);
8944 fprintf (acfg->fp, ".arm\n");
8951 emit_extra_methods (acfg);
8953 emit_trampolines (acfg);
8955 emit_class_name_table (acfg);
8957 emit_got_info (acfg);
8959 emit_exception_info (acfg);
8961 emit_unwind_info (acfg);
8963 emit_class_info (acfg);
8967 emit_image_table (acfg);
8971 emit_file_info (acfg);
8975 emit_objc_selectors (acfg);
8977 emit_globals (acfg);
8979 emit_autoreg (acfg);
8982 emit_dwarf_info (acfg);
8983 mono_dwarf_writer_close (acfg->dwarf);
8986 emit_mem_end (acfg);
8988 if (acfg->need_pt_gnu_stack) {
8989 /* This is required so the .so doesn't have an executable stack */
8990 /* The bin writer already emits this */
8991 if (!acfg->use_bin_writer)
8992 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
8997 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9000 g_assert (acfg->got_offset <= acfg->final_got_size);
9003 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9005 strcpy (llvm_stats_msg, "");
9006 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);
9007 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9008 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9010 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9011 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9012 if (acfg->stats.genericcount)
9013 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9014 if (acfg->stats.abscount)
9015 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9016 if (acfg->stats.lmfcount)
9017 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9018 if (acfg->stats.ocount)
9019 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9022 res = img_writer_emit_writeout (acfg->w);
9027 if (acfg->use_bin_writer) {
9028 int err = rename (tmp_outfile_name, outfile_name);
9031 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9035 res = compile_asm (acfg);
9042 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9044 if (acfg->aot_opts.stats) {
9047 printf ("GOT slot distribution:\n");
9048 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9049 if (acfg->stats.got_slot_types [i])
9050 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9053 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);
9065 mono_aot_readonly_field_override (MonoClassField *field)
9071 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)