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;
192 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
193 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
194 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
196 MonoAotOptions aot_opts;
200 MonoMemPool *mempool;
203 char *static_linking_symbol;
204 CRITICAL_SECTION mutex;
205 gboolean use_bin_writer;
206 gboolean gas_line_numbers;
208 MonoDwarfWriter *dwarf;
212 GHashTable *unwind_info_offsets;
213 GPtrArray *unwind_ops;
214 guint32 unwind_info_offset;
215 char *got_symbol_base;
218 GHashTable *method_label_hash;
219 const char *temp_prefix;
220 const char *user_symbol_prefix;
221 const char *llvm_label_prefix;
222 guint32 label_generator;
224 MonoAotFileFlags flags;
225 MonoDynamicStream blob;
226 MonoClass **typespec_classes;
229 char *assembly_name_sym;
230 GHashTable *plt_entry_debug_sym_cache;
231 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
232 GHashTable *ginst_hash;
233 GHashTable *dwarf_ln_filenames;
234 gboolean global_symbols;
235 gboolean direct_method_addresses;
240 char *symbol, *llvm_symbol, *debug_sym;
242 gboolean jit_used, llvm_used;
245 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
246 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
248 /* This points to the current acfg in LLVM mode */
249 static MonoAotCompile *llvm_acfg;
251 #ifdef HAVE_ARRAY_ELEM_INIT
252 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
253 #define MSGSTRFIELD1(line) str##line
254 static const struct msgstr_t {
255 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
256 #include "patch-info.h"
259 #define PATCH_INFO(a,b) b,
260 #include "patch-info.h"
263 static const gint16 opidx [] = {
264 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
265 #include "patch-info.h"
269 static G_GNUC_UNUSED const char*
270 get_patch_name (int info)
272 return (const char*)&opstr + opidx [info];
276 #define PATCH_INFO(a,b) b,
277 static const char* const
278 patch_types [MONO_PATCH_INFO_NUM + 1] = {
279 #include "patch-info.h"
283 static G_GNUC_UNUSED const char*
284 get_patch_name (int info)
286 return patch_types [info];
292 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
294 /* Wrappers around the image writer functions */
297 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
299 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
303 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
305 img_writer_emit_push_section (acfg->w, section_name, subsection);
309 emit_pop_section (MonoAotCompile *acfg)
311 img_writer_emit_pop_section (acfg->w);
315 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
317 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
321 emit_label (MonoAotCompile *acfg, const char *name)
323 img_writer_emit_label (acfg->w, name);
327 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
329 img_writer_emit_bytes (acfg->w, buf, size);
333 emit_string (MonoAotCompile *acfg, const char *value)
335 img_writer_emit_string (acfg->w, value);
339 emit_line (MonoAotCompile *acfg)
341 img_writer_emit_line (acfg->w);
345 emit_alignment (MonoAotCompile *acfg, int size)
347 img_writer_emit_alignment (acfg->w, size);
351 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
353 img_writer_emit_pointer_unaligned (acfg->w, target);
357 emit_pointer (MonoAotCompile *acfg, const char *target)
359 img_writer_emit_pointer (acfg->w, target);
363 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
365 if (prefix [0] != '\0') {
366 char *s = g_strdup_printf ("%s%s", prefix, target);
367 img_writer_emit_pointer (acfg->w, s);
370 img_writer_emit_pointer (acfg->w, target);
375 emit_int16 (MonoAotCompile *acfg, int value)
377 img_writer_emit_int16 (acfg->w, value);
381 emit_int32 (MonoAotCompile *acfg, int value)
383 img_writer_emit_int32 (acfg->w, value);
387 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
389 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
393 emit_zero_bytes (MonoAotCompile *acfg, int num)
395 img_writer_emit_zero_bytes (acfg->w, num);
399 emit_byte (MonoAotCompile *acfg, guint8 val)
401 img_writer_emit_byte (acfg->w, val);
404 #ifdef __native_client_codegen__
406 emit_nacl_call_alignment (MonoAotCompile *acfg)
408 img_writer_emit_nacl_call_alignment (acfg->w);
412 static G_GNUC_UNUSED void
413 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
415 img_writer_emit_global (acfg->w, name, func);
419 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
421 if (acfg->aot_opts.no_dlsym) {
422 g_ptr_array_add (acfg->globals, g_strdup (name));
423 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
425 img_writer_emit_global (acfg->w, name, func);
430 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
432 img_writer_emit_symbol_size (acfg->w, name, end_label);
436 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
438 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
440 /* On apple, all symbols need to be aligned to avoid warnings from ld */
441 emit_alignment (acfg, 4);
443 img_writer_emit_label (acfg->w, name);
444 img_writer_emit_string (acfg->w, value);
447 static G_GNUC_UNUSED void
448 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
451 guint8 b = value & 0x7f;
453 if (value != 0) /* more bytes to come */
459 static G_GNUC_UNUSED void
460 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
463 gboolean negative = (value < 0);
470 /* the following is unnecessary if the
471 * implementation of >>= uses an arithmetic rather
472 * than logical shift for a signed left operand
476 value |= - ((gint64)1 <<(size - 7));
477 /* sign bit of byte is second high order bit (0x40) */
478 if ((value == 0 && !(byte & 0x40)) ||
479 (value == -1 && (byte & 0x40)))
483 emit_byte (acfg, byte);
487 static G_GNUC_UNUSED void
488 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
493 guint8 b = value & 0x7f;
495 if (value != 0) /* more bytes to come */
503 static G_GNUC_UNUSED void
504 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
507 gboolean negative = (value < 0);
515 /* the following is unnecessary if the
516 * implementation of >>= uses an arithmetic rather
517 * than logical shift for a signed left operand
521 value |= - (1 <<(size - 7));
522 /* sign bit of byte is second high order bit (0x40) */
523 if ((value == 0 && !(byte & 0x40)) ||
524 (value == -1 && (byte & 0x40)))
535 emit_unset_mode (MonoAotCompile *acfg)
537 img_writer_emit_unset_mode (acfg->w);
540 static G_GNUC_UNUSED void
541 emit_set_thumb_mode (MonoAotCompile *acfg)
543 emit_unset_mode (acfg);
544 fprintf (acfg->fp, ".code 16\n");
547 static G_GNUC_UNUSED void
548 emit_set_arm_mode (MonoAotCompile *acfg)
550 emit_unset_mode (acfg);
551 fprintf (acfg->fp, ".code 32\n");
554 /* ARCHITECTURE SPECIFIC CODE */
556 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
557 #define EMIT_DWARF_INFO 1
560 #if defined(TARGET_ARM)
561 #define AOT_FUNC_ALIGNMENT 4
563 #define AOT_FUNC_ALIGNMENT 16
565 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
566 #undef AOT_FUNC_ALIGNMENT
567 #define AOT_FUNC_ALIGNMENT 32
570 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
571 #define PPC_LD_OP "ld"
572 #define PPC_LDX_OP "ldx"
574 #define PPC_LD_OP "lwz"
575 #define PPC_LDX_OP "lwzx"
579 #define AOT_TARGET_STR "AMD64"
584 #define AOT_TARGET_STR "ARM (MACH)"
586 #define AOT_TARGET_STR "ARM (!MACH)"
590 #ifdef TARGET_POWERPC64
591 #ifdef __mono_ilp32__
592 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
594 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
597 #ifdef TARGET_POWERPC
598 #ifdef __mono_ilp32__
599 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
601 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
608 #define AOT_TARGET_STR "X86 (WIN32)"
609 #elif defined(__native_client_codegen__)
610 #define AOT_TARGET_STR "X86 (native client codegen)"
612 #define AOT_TARGET_STR "X86 (!native client codegen)"
616 #ifndef AOT_TARGET_STR
617 #define AOT_TARGET_STR ""
621 arch_init (MonoAotCompile *acfg)
623 acfg->llc_args = g_string_new ("");
624 acfg->as_args = g_string_new ("");
627 * The prefix LLVM likes to put in front of symbol names on darwin.
628 * The mach-os specs require this for globals, but LLVM puts them in front of all
629 * symbols. We need to handle this, since we need to refer to LLVM generated
632 acfg->llvm_label_prefix = "";
633 acfg->user_symbol_prefix = "";
635 #if defined(TARGET_AMD64) && defined(TARGET_MACH)
636 /* osx contains an old as which doesn't support avx opcodes */
637 g_string_append (acfg->llc_args, "-mattr=-avx");
641 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
642 g_string_append (acfg->llc_args, "-mattr=+v6");
645 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
646 g_string_append (acfg->as_args, " -mfpu=vfp3");
648 g_string_append (acfg->llc_args, " -soft-float");
651 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
652 acfg->thumb_mixed = TRUE;
654 if (acfg->aot_opts.mtriple)
655 mono_arch_set_target (acfg->aot_opts.mtriple);
659 acfg->user_symbol_prefix = "_";
660 acfg->llvm_label_prefix = "_";
661 acfg->need_no_dead_strip = TRUE;
662 acfg->aot_opts.gnu_asm = TRUE;
665 #if defined(__linux__) && !defined(TARGET_ARM)
666 acfg->need_pt_gnu_stack = TRUE;
670 acfg->direct_method_addresses = TRUE;
671 acfg->global_symbols = TRUE;
676 * arch_emit_direct_call:
678 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
682 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, int *call_size)
684 #if defined(TARGET_X86) || defined(TARGET_AMD64)
685 /* Need to make sure this is exactly 5 bytes long */
686 if (external && !acfg->use_bin_writer) {
687 emit_unset_mode (acfg);
688 fprintf (acfg->fp, "call %s\n", target);
690 emit_byte (acfg, '\xe8');
691 emit_symbol_diff (acfg, target, ".", -4);
694 #elif defined(TARGET_ARM)
695 if (acfg->use_bin_writer) {
702 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
703 emit_bytes (acfg, buf, 4);
705 emit_unset_mode (acfg);
706 fprintf (acfg->fp, "bl %s\n", target);
709 #elif defined(TARGET_POWERPC)
710 if (acfg->use_bin_writer) {
711 g_assert_not_reached ();
713 emit_unset_mode (acfg);
714 fprintf (acfg->fp, "bl %s\n", target);
718 g_assert_not_reached ();
724 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
726 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
727 * in in the 2. slot of every GOT, and require every method to place the GOT
728 * address in r30, even when it doesn't access the GOT otherwise. This way,
729 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
734 * PPC64 uses function descriptors which greatly complicate all code, since
735 * these are used very inconsistently in the runtime. Some functions like
736 * mono_compile_method () return ftn descriptors, while others like the
737 * trampoline creation functions do not.
738 * We assume that all GOT slots contain function descriptors, and create
739 * descriptors in aot-runtime.c when needed.
740 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
741 * from function descriptors, we could do the same, but it would require
742 * rewriting all the ppc/aot code to handle function descriptors properly.
743 * So instead, we use the same approach as on PPC32.
744 * This is a horrible mess, but fixing it would probably lead to an even bigger
750 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
753 #ifdef MONO_ARCH_AOT_SUPPORTED
755 * arch_emit_got_offset:
757 * The memory pointed to by CODE should hold native code for computing the GOT
758 * address. Emit this code while patching it with the offset between code and
759 * the GOT. CODE_SIZE is set to the number of bytes emitted.
762 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
764 #if defined(TARGET_POWERPC64)
765 g_assert (!acfg->use_bin_writer);
766 emit_unset_mode (acfg);
768 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
769 * unsupported relocations. So we store the got address into the .Lgot_addr
770 * symbol which is in the text segment, compute its address, and load it.
772 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
773 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
774 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
775 fprintf (acfg->fp, "add 30, 30, 0\n");
776 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
777 acfg->label_generator ++;
779 #elif defined(TARGET_POWERPC)
780 g_assert (!acfg->use_bin_writer);
781 emit_unset_mode (acfg);
782 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
783 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
784 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
785 acfg->label_generator ++;
788 guint32 offset = mono_arch_get_patch_offset (code);
789 emit_bytes (acfg, code, offset);
790 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
792 *code_size = offset + 4;
797 * arch_emit_got_access:
799 * The memory pointed to by CODE should hold native code for loading a GOT
800 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
801 * CODE_SIZE is set to the number of bytes emitted.
804 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
806 /* Emit beginning of instruction */
807 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
809 /* Emit the offset */
811 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
812 *code_size = mono_arch_get_patch_offset (code) + 4;
813 #elif defined(TARGET_X86)
814 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
815 *code_size = mono_arch_get_patch_offset (code) + 4;
816 #elif defined(TARGET_ARM)
817 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
818 *code_size = mono_arch_get_patch_offset (code) + 4;
819 #elif defined(TARGET_POWERPC)
825 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
826 g_assert (code - buf == 8);
827 emit_bytes (acfg, buf, code - buf);
828 *code_size = code - buf;
831 g_assert_not_reached ();
838 * arch_emit_plt_entry:
840 * Emit code for the PLT entry with index INDEX.
843 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
845 #if defined(TARGET_X86)
846 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
847 #if defined(__default_codegen__)
848 /* jmp *<offset>(%ebx) */
849 emit_byte (acfg, 0xff);
850 emit_byte (acfg, 0xa3);
851 emit_int32 (acfg, offset);
852 /* Used by mono_aot_get_plt_info_offset */
853 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
854 #elif defined(__native_client_codegen__)
855 const guint8 kSizeOfNaClJmp = 11;
856 guint8 bytes[kSizeOfNaClJmp];
857 guint8 *pbytes = &bytes[0];
859 x86_jump_membase32 (pbytes, X86_EBX, offset);
860 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
861 /* four bytes of data, used by mono_arch_patch_plt_entry */
862 /* For Native Client, make this work with data embedded in push. */
863 emit_byte (acfg, 0x68); /* hide data in a push */
864 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
865 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
866 #endif /*__native_client_codegen__*/
867 #elif defined(TARGET_AMD64)
868 #if defined(__default_codegen__)
870 * We can't emit jumps because they are 32 bits only so they can't be patched.
871 * So we make indirect calls through GOT entries which are patched by the AOT
872 * loader to point to .Lpd entries.
874 /* jmpq *<offset>(%rip) */
875 emit_byte (acfg, '\xff');
876 emit_byte (acfg, '\x25');
877 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
878 /* Used by mono_aot_get_plt_info_offset */
879 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
880 #elif defined(__native_client_codegen__)
882 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
883 guint8 *code = buf_aligned;
885 /* mov <OFFSET>(%rip), %r11d */
886 emit_byte (acfg, '\x45');
887 emit_byte (acfg, '\x8b');
888 emit_byte (acfg, '\x1d');
889 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
891 amd64_jump_reg (code, AMD64_R11);
892 /* This should be constant for the plt patch */
893 g_assert ((size_t)(code-buf_aligned) == 10);
894 emit_bytes (acfg, buf_aligned, code - buf_aligned);
896 /* Hide data in a push imm32 so it passes validation */
897 emit_byte (acfg, 0x68); /* push */
898 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
899 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
900 #endif /*__native_client_codegen__*/
901 #elif defined(TARGET_ARM)
906 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
907 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
908 emit_bytes (acfg, buf, code - buf);
909 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
910 /* Used by mono_aot_get_plt_info_offset */
911 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
912 #elif defined(TARGET_POWERPC)
913 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
915 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
916 g_assert (!acfg->use_bin_writer);
917 emit_unset_mode (acfg);
918 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
919 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
920 fprintf (acfg->fp, "add 11, 11, 30\n");
921 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
922 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
923 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
924 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
926 fprintf (acfg->fp, "mtctr 11\n");
927 fprintf (acfg->fp, "bctr\n");
928 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
930 g_assert_not_reached ();
935 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
937 #if defined(TARGET_ARM)
939 /* LLVM calls the PLT entries using bl, so emit a stub */
940 /* FIXME: Too much overhead on every call */
941 fprintf (acfg->fp, ".thumb_func\n");
942 fprintf (acfg->fp, "bx pc\n");
943 fprintf (acfg->fp, "nop\n");
944 fprintf (acfg->fp, ".arm\n");
946 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
947 /* The caller already transitioned to thumb */
948 /* The code below should be 12 bytes long */
949 /* clang has trouble encoding these instructions, so emit the binary */
951 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
952 /* thumb can't encode ld pc, [pc, ip] */
953 fprintf (acfg->fp, "add ip, pc, ip\n");
954 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
955 fprintf (acfg->fp, "bx ip\n");
957 emit_set_thumb_mode (acfg);
958 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
959 fprintf (acfg->fp, ".2byte 0x44fc\n");
960 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
961 fprintf (acfg->fp, ".2byte 0x4760\n");
962 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
963 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
964 emit_unset_mode (acfg);
965 emit_set_arm_mode (acfg);
967 g_assert_not_reached ();
972 * arch_emit_specific_trampoline_pages:
974 * Emits a page full of trampolines: each trampoline uses its own address to
975 * lookup both the generic trampoline code and the data argument.
976 * This page can be remapped in process multiple times so we can get an
977 * unlimited number of trampolines.
978 * Specifically this implementation uses the following trick: two memory pages
979 * are allocated, with the first containing the data and the second containing the trampolines.
980 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
981 * implementation does all the lifting.
982 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
983 * on the arm 32 bit system.
986 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
988 #if defined(TARGET_ARM)
991 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
993 #define COMMON_TRAMP_SIZE 16
994 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
995 int imm8, rot_amount;
998 if (!acfg->aot_opts.use_trampolines_page)
1001 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1002 emit_alignment (acfg, mono_pagesize ());
1003 emit_global (acfg, symbol, TRUE);
1004 emit_label (acfg, symbol);
1006 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1008 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1009 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1010 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1011 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1013 g_assert (code - buf == COMMON_TRAMP_SIZE);
1016 emit_bytes (acfg, buf, code - buf);
1018 for (i = 0; i < count; ++i) {
1020 ARM_PUSH (code, 0x5fff);
1022 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1023 g_assert (code - buf == 8);
1024 emit_bytes (acfg, buf, code - buf);
1027 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1028 * the instruction pointer address, so the generic trampoline at the start of the page
1029 * subtracts 4096 to get to the data page and loads the values
1030 * We again fit the generic trampiline in 16 bytes.
1032 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1033 emit_global (acfg, symbol, TRUE);
1034 emit_label (acfg, symbol);
1036 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1037 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1038 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1039 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1041 g_assert (code - buf == COMMON_TRAMP_SIZE);
1044 emit_bytes (acfg, buf, code - buf);
1046 for (i = 0; i < count; ++i) {
1048 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1050 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1051 g_assert (code - buf == 8);
1052 emit_bytes (acfg, buf, code - buf);
1056 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1058 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1059 emit_global (acfg, symbol, TRUE);
1060 emit_label (acfg, symbol);
1062 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1063 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1064 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1065 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1066 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1067 g_assert (code - buf == COMMON_TRAMP_SIZE);
1069 emit_bytes (acfg, buf, code - buf);
1071 for (i = 0; i < count; ++i) {
1073 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1075 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1076 g_assert (code - buf == 8);
1077 emit_bytes (acfg, buf, code - buf);
1080 /* now the imt trampolines: each specific trampolines puts in the ip register
1081 * the instruction pointer address, so the generic trampoline at the start of the page
1082 * subtracts 4096 to get to the data page and loads the values
1083 * We again fit the generic trampiline in 16 bytes.
1085 #define IMT_TRAMP_SIZE 72
1086 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1087 emit_global (acfg, symbol, TRUE);
1088 emit_label (acfg, symbol);
1090 /* Need at least two free registers, plus a slot for storing the pc */
1091 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1093 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1094 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1095 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1097 /* The IMT method is in v5, r0 has the imt array address */
1100 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1101 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1102 imt_found_check = code;
1103 ARM_B_COND (code, ARMCOND_EQ, 0);
1105 /* End-of-loop check */
1106 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1107 loop_end_check = code;
1108 ARM_B_COND (code, ARMCOND_EQ, 0);
1111 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1112 loop_branch_back = code;
1114 arm_patch (loop_branch_back, loop_start);
1117 arm_patch (imt_found_check, code);
1118 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1119 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1120 /* Save it to the third stack slot */
1121 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1122 /* Restore the registers and branch */
1123 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1126 arm_patch (loop_end_check, code);
1127 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1128 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1129 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1133 g_assert (code - buf == IMT_TRAMP_SIZE);
1134 emit_bytes (acfg, buf, code - buf);
1136 for (i = 0; i < count; ++i) {
1138 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1140 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1141 g_assert (code - buf == 8);
1142 emit_bytes (acfg, buf, code - buf);
1148 * arch_emit_specific_trampoline:
1150 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1151 * two GOT slots which contain the generic trampoline address and the trampoline
1152 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1155 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1158 * The trampolines created here are variations of the specific
1159 * trampolines created in mono_arch_create_specific_trampoline (). The
1161 * - the generic trampoline address is taken from a got slot.
1162 * - the offset of the got slot where the trampoline argument is stored
1163 * is embedded in the instruction stream, and the generic trampoline
1164 * can load the argument by loading the offset, adding it to the
1165 * address of the trampoline to get the address of the got slot, and
1166 * loading the argument from there.
1167 * - all the trampolines should be of the same length.
1169 #if defined(TARGET_AMD64)
1170 #if defined(__default_codegen__)
1171 /* This should be exactly 16 bytes long */
1173 /* call *<offset>(%rip) */
1174 emit_byte (acfg, '\x41');
1175 emit_byte (acfg, '\xff');
1176 emit_byte (acfg, '\x15');
1177 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1178 /* This should be relative to the start of the trampoline */
1179 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1180 emit_zero_bytes (acfg, 5);
1181 #elif defined(__native_client_codegen__)
1183 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1184 guint8 *code = buf_aligned;
1189 /* Emit this call in 'code' so we can find out how long it is. */
1190 amd64_call_reg (code, AMD64_R11);
1191 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1192 call_len = code - call_start;
1194 /* The tramp_size is twice the NaCl alignment because it starts with */
1195 /* a call which needs to be aligned to the end of the boundary. */
1196 *tramp_size = kNaClAlignment*2;
1198 /* Emit nops to align call site below which is 7 bytes plus */
1199 /* the length of the call sequence emitted above. */
1200 /* Note: this requires the specific trampoline starts on a */
1201 /* kNaclAlignedment aligned address, which it does because */
1202 /* it's its own function that is aligned. */
1203 guint8 nop_buf[256];
1204 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1205 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1206 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1208 /* The trampoline is stored at the offset'th pointer, the -4 is */
1209 /* present because RIP relative addressing starts at the end of */
1210 /* the current instruction, while the label "." is relative to */
1211 /* the beginning of the current asm location, which in this case */
1212 /* is not the mov instruction, but the offset itself, due to the */
1213 /* way the bytes and ints are emitted here. */
1214 got_offset = (offset * sizeof(gpointer)) - 4;
1216 /* mov <OFFSET>(%rip), %r11d */
1217 emit_byte (acfg, '\x45');
1218 emit_byte (acfg, '\x8b');
1219 emit_byte (acfg, '\x1d');
1220 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1223 emit_bytes (acfg, call_start, call_len);
1225 /* The arg is stored at the offset+1 pointer, relative to beginning */
1226 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1227 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1229 /* We can't emit this data directly, hide in a "push imm32" */
1230 emit_byte (acfg, '\x68'); /* push */
1231 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1232 emit_alignment (acfg, kNaClAlignment);
1233 #endif /*__native_client_codegen__*/
1234 #elif defined(TARGET_ARM)
1238 /* This should be exactly 20 bytes long */
1241 ARM_PUSH (code, 0x5fff);
1242 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1243 /* Load the value from the GOT */
1244 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1246 ARM_BLX_REG (code, ARMREG_R1);
1248 g_assert (code - buf == 16);
1251 emit_bytes (acfg, buf, code - buf);
1253 * Only one offset is needed, since the second one would be equal to the
1256 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1257 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1258 #elif defined(TARGET_POWERPC)
1265 g_assert (!acfg->use_bin_writer);
1268 * PPC has no ip relative addressing, so we need to compute the address
1269 * of the mscorlib got. That is slow and complex, so instead, we store it
1270 * in the second got slot of every aot image. The caller already computed
1271 * the address of its got and placed it into r30.
1273 emit_unset_mode (acfg);
1274 /* Load mscorlib got address */
1275 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1276 /* Load generic trampoline address */
1277 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1278 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1279 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1280 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1281 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1283 fprintf (acfg->fp, "mtctr 11\n");
1284 /* Load trampoline argument */
1285 /* On ppc, we pass it normally to the generic trampoline */
1286 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1287 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1288 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1289 /* Branch to generic trampoline */
1290 fprintf (acfg->fp, "bctr\n");
1292 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1293 *tramp_size = 10 * 4;
1295 *tramp_size = 9 * 4;
1297 #elif defined(TARGET_X86)
1301 /* Similar to the PPC code above */
1303 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1305 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1306 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1307 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1311 /* Load mscorlib got address */
1312 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1313 /* Push trampoline argument */
1314 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1315 /* Load generic trampoline address */
1316 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1317 /* Branch to generic trampoline */
1318 x86_jump_reg (code, X86_ECX);
1320 #ifdef __native_client_codegen__
1322 /* emit nops to next 32 byte alignment */
1323 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1324 while (code < (buf + a)) x86_nop(code);
1327 emit_bytes (acfg, buf, code - buf);
1329 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1330 g_assert (code - buf == *tramp_size);
1332 g_assert_not_reached ();
1337 * arch_emit_unbox_trampoline:
1339 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1340 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1343 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1345 #if defined(TARGET_AMD64)
1350 this_reg = mono_arch_get_this_arg_reg (NULL);
1352 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1354 emit_bytes (acfg, buf, code - buf);
1356 emit_byte (acfg, '\xe9');
1357 emit_symbol_diff (acfg, call_target, ".", -4);
1358 #elif defined(TARGET_X86)
1365 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1367 emit_bytes (acfg, buf, code - buf);
1370 emit_byte (acfg, '\xe9');
1371 emit_symbol_diff (acfg, call_target, ".", -4);
1372 #elif defined(TARGET_ARM)
1376 if (acfg->thumb_mixed && cfg->compile_llvm) {
1377 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1378 fprintf (acfg->fp, "b %s\n", call_target);
1379 fprintf (acfg->fp, ".arm\n");
1380 fprintf (acfg->fp, ".align 2\n");
1386 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1388 emit_bytes (acfg, buf, code - buf);
1389 /* jump to method */
1390 if (acfg->use_bin_writer) {
1397 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1398 emit_bytes (acfg, buf, 4);
1400 if (acfg->thumb_mixed && cfg->compile_llvm)
1401 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1403 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1405 #elif defined(TARGET_POWERPC)
1408 g_assert (!acfg->use_bin_writer);
1410 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1411 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1413 g_assert_not_reached ();
1418 * arch_emit_static_rgctx_trampoline:
1420 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1421 * two GOT slots which contain the rgctx argument, and the method to jump to.
1422 * TRAMP_SIZE is set to the size of the emitted trampoline.
1423 * These kinds of trampolines cannot be enumerated statically, since there could
1424 * be one trampoline per method instantiation, so we emit the same code for all
1425 * trampolines, and parameterize them using two GOT slots.
1428 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1430 #if defined(TARGET_AMD64)
1431 #if defined(__default_codegen__)
1432 /* This should be exactly 13 bytes long */
1435 /* mov <OFFSET>(%rip), %r10 */
1436 emit_byte (acfg, '\x4d');
1437 emit_byte (acfg, '\x8b');
1438 emit_byte (acfg, '\x15');
1439 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1441 /* jmp *<offset>(%rip) */
1442 emit_byte (acfg, '\xff');
1443 emit_byte (acfg, '\x25');
1444 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1445 #elif defined(__native_client_codegen__)
1447 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1448 guint8 *code = buf_aligned;
1450 /* mov <OFFSET>(%rip), %r10d */
1451 emit_byte (acfg, '\x45');
1452 emit_byte (acfg, '\x8b');
1453 emit_byte (acfg, '\x15');
1454 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1456 /* mov <OFFSET>(%rip), %r11d */
1457 emit_byte (acfg, '\x45');
1458 emit_byte (acfg, '\x8b');
1459 emit_byte (acfg, '\x1d');
1460 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1463 amd64_jump_reg (code, AMD64_R11);
1464 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1466 emit_alignment (acfg, kNaClAlignment);
1467 *tramp_size = kNaClAlignment;
1468 #endif /*__native_client_codegen__*/
1470 #elif defined(TARGET_ARM)
1474 /* This should be exactly 24 bytes long */
1477 /* Load rgctx value */
1478 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1479 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1480 /* Load branch addr + branch */
1481 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1482 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1484 g_assert (code - buf == 16);
1487 emit_bytes (acfg, buf, code - buf);
1488 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1489 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1490 #elif defined(TARGET_POWERPC)
1497 g_assert (!acfg->use_bin_writer);
1500 * PPC has no ip relative addressing, so we need to compute the address
1501 * of the mscorlib got. That is slow and complex, so instead, we store it
1502 * in the second got slot of every aot image. The caller already computed
1503 * the address of its got and placed it into r30.
1505 emit_unset_mode (acfg);
1506 /* Load mscorlib got address */
1507 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1509 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1510 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1511 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1512 /* Load target address */
1513 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1514 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1515 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1516 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1517 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1518 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1520 fprintf (acfg->fp, "mtctr 11\n");
1521 /* Branch to the target address */
1522 fprintf (acfg->fp, "bctr\n");
1524 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1525 *tramp_size = 11 * 4;
1527 *tramp_size = 9 * 4;
1530 #elif defined(TARGET_X86)
1534 /* Similar to the PPC code above */
1536 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1539 /* Load mscorlib got address */
1540 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1542 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1543 /* Branch to the target address */
1544 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1546 #ifdef __native_client_codegen__
1548 /* emit nops to next 32 byte alignment */
1549 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1550 while (code < (buf + a)) x86_nop(code);
1554 emit_bytes (acfg, buf, code - buf);
1556 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1557 g_assert (code - buf == *tramp_size);
1559 g_assert_not_reached ();
1564 * arch_emit_imt_thunk:
1566 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1567 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1568 * key is the IMT key, and ptr holds the address of a memory location holding
1569 * the address to branch to if the IMT arg matches the key. The array is
1570 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1572 * TRAMP_SIZE is set to the size of the emitted trampoline.
1575 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1577 #if defined(TARGET_AMD64)
1579 #if defined(__native_client_codegen__)
1582 guint8 *labels [16];
1584 guint8 *mov_buf_ptr = mov_buf;
1586 const int kSizeOfMove = 7;
1587 #if defined(__default_codegen__)
1588 code = buf = g_malloc (256);
1589 #elif defined(__native_client_codegen__)
1590 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1591 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1592 /* The RIP relative move below is emitted first */
1597 /* FIXME: Optimize this, i.e. use binary search etc. */
1598 /* Maybe move the body into a separate function (slower, but much smaller) */
1600 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1603 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1605 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1608 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1610 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1613 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1614 amd64_jump_code (code, labels [0]);
1617 mono_amd64_patch (labels [2], code);
1618 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1619 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1622 mono_amd64_patch (labels [1], code);
1623 /* Load fail tramp */
1624 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1625 /* Check if there is a fail tramp */
1626 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1628 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1629 /* Jump to fail tramp */
1630 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1633 mono_amd64_patch (labels [3], code);
1634 x86_breakpoint (code);
1636 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1637 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1638 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1639 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1640 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1641 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1643 emit_bytes (acfg, buf, code - buf);
1645 *tramp_size = code - buf + kSizeOfMove;
1646 #if defined(__native_client_codegen__)
1647 /* The tramp will be padded to the next kNaClAlignment bundle. */
1648 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1651 #if defined(__default_codegen__)
1653 #elif defined(__native_client_codegen__)
1657 #elif defined(TARGET_X86)
1659 #ifdef __native_client_codegen__
1662 guint8 *labels [16];
1664 #if defined(__default_codegen__)
1665 code = buf = g_malloc (256);
1666 #elif defined(__native_client_codegen__)
1667 buf_alloc = g_malloc (256 + kNaClAlignment);
1668 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1671 /* Allocate a temporary stack slot */
1672 x86_push_reg (code, X86_EAX);
1674 x86_push_reg (code, X86_EAX);
1676 /* Load mscorlib got address */
1677 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1679 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1682 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1684 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1687 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1689 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1692 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1693 x86_jump_code (code, labels [0]);
1696 mono_x86_patch (labels [2], code);
1697 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1698 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1699 /* Save the target address to the temporary stack location */
1700 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1702 x86_pop_reg (code, X86_EAX);
1703 /* Jump to the target address */
1707 mono_x86_patch (labels [1], code);
1708 /* Load fail tramp */
1709 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1710 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1712 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1713 /* Jump to fail tramp */
1714 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1715 x86_pop_reg (code, X86_EAX);
1719 mono_x86_patch (labels [3], code);
1720 x86_breakpoint (code);
1722 #ifdef __native_client_codegen__
1724 /* emit nops to next 32 byte alignment */
1725 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1726 while (code < (buf + a)) x86_nop(code);
1729 emit_bytes (acfg, buf, code - buf);
1731 *tramp_size = code - buf;
1733 #if defined(__default_codegen__)
1735 #elif defined(__native_client_codegen__)
1739 #elif defined(TARGET_ARM)
1741 guint8 *code, *code2, *labels [16];
1745 /* The IMT method is in v5 */
1747 /* Need at least two free registers, plus a slot for storing the pc */
1748 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1750 /* Load the parameter from the GOT */
1751 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1752 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1755 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1756 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1758 ARM_B_COND (code, ARMCOND_EQ, 0);
1760 /* End-of-loop check */
1761 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1763 ARM_B_COND (code, ARMCOND_EQ, 0);
1766 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1769 arm_patch (labels [4], labels [1]);
1772 arm_patch (labels [2], code);
1773 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1774 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1775 /* Save it to the third stack slot */
1776 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1777 /* Restore the registers and branch */
1778 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1781 arm_patch (labels [3], code);
1782 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1783 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1784 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1788 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1790 emit_bytes (acfg, buf, code - buf);
1791 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1793 *tramp_size = code - buf + 4;
1794 #elif defined(TARGET_POWERPC)
1796 guint8 *code, *labels [16];
1800 /* Load the mscorlib got address */
1801 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1802 /* Load the parameter from the GOT */
1803 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1804 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1806 /* Load and check key */
1808 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1809 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1811 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1813 /* End-of-loop check */
1814 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1816 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1819 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1822 mono_ppc_patch (labels [4], labels [1]);
1825 mono_ppc_patch (labels [2], code);
1826 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1827 /* r11 now contains the value of the vtable slot */
1828 /* this is not a function descriptor on ppc64 */
1829 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1830 ppc_mtctr (code, ppc_r11);
1831 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1834 mono_ppc_patch (labels [3], code);
1838 *tramp_size = code - buf;
1840 emit_bytes (acfg, buf, code - buf);
1842 g_assert_not_reached ();
1847 * arch_emit_gsharedvt_arg_trampoline:
1849 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1850 * two GOT slots which contain the argument, and the code to jump to.
1851 * TRAMP_SIZE is set to the size of the emitted trampoline.
1852 * These kinds of trampolines cannot be enumerated statically, since there could
1853 * be one trampoline per method instantiation, so we emit the same code for all
1854 * trampolines, and parameterize them using two GOT slots.
1857 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1859 #if defined(TARGET_X86)
1863 /* Similar to the PPC code above */
1865 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1868 /* Load mscorlib got address */
1869 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1871 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1872 /* Branch to the target address */
1873 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1875 #ifdef __native_client_codegen__
1877 /* emit nops to next 32 byte alignment */
1878 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1879 while (code < (buf + a)) x86_nop(code);
1883 emit_bytes (acfg, buf, code - buf);
1885 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1886 g_assert (code - buf == *tramp_size);
1887 #elif defined(TARGET_ARM)
1891 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1892 /* Similar to arch_emit_specific_trampoline () */
1895 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1896 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1897 /* Load the arg value from the GOT */
1898 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1899 /* Load the addr from the GOT */
1900 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1902 ARM_BX (code, ARMREG_R1);
1904 g_assert (code - buf == 20);
1907 emit_bytes (acfg, buf, code - buf);
1908 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1910 g_assert_not_reached ();
1915 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1917 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1918 /* Based on code generated by gcc */
1919 emit_unset_mode (acfg);
1922 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1923 ".section .ctors,\"aw\",@progbits\n"
1927 ".section .opd,\"aw\"\n"
1930 ".long .%s,.TOC.@tocbase32\n"
1933 ".type .%s,@function\n"
1935 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1937 ".section .ctors,\"aw\",@progbits\n"
1941 ".section .opd,\"aw\"\n"
1944 ".long .%1$s,.TOC.@tocbase32\n"
1945 ".size %1$s,.-%1$s\n"
1947 ".type .%1$s,@function\n"
1949 ".%1$s:\n", symbol);
1960 "lis 3, .Lglobals@h\n"
1961 "ori 3, 3, .Lglobals@l\n"
1962 "bl .mono_aot_register_module\n"
1970 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1972 ".size .%s,.-.%s\n", symbol, symbol);
1975 ".size .%1$s,.-.%1$s\n", symbol);
1981 /* END OF ARCH SPECIFIC CODE */
1984 mono_get_field_token (MonoClassField *field)
1986 MonoClass *klass = field->parent;
1989 for (i = 0; i < klass->field.count; ++i) {
1990 if (field == &klass->fields [i])
1991 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1994 g_assert_not_reached ();
1999 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2003 //printf ("ENCODE: %d 0x%x.\n", value, value);
2006 * Same encoding as the one used in the metadata, extended to handle values
2007 * greater than 0x1fffffff.
2009 if ((value >= 0) && (value <= 127))
2011 else if ((value >= 0) && (value <= 16383)) {
2012 p [0] = 0x80 | (value >> 8);
2013 p [1] = value & 0xff;
2015 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2016 p [0] = (value >> 24) | 0xc0;
2017 p [1] = (value >> 16) & 0xff;
2018 p [2] = (value >> 8) & 0xff;
2019 p [3] = value & 0xff;
2024 p [1] = (value >> 24) & 0xff;
2025 p [2] = (value >> 16) & 0xff;
2026 p [3] = (value >> 8) & 0xff;
2027 p [4] = value & 0xff;
2035 stream_init (MonoDynamicStream *sh)
2038 sh->alloc_size = 4096;
2039 sh->data = g_malloc (4096);
2041 /* So offsets are > 0 */
2047 make_room_in_stream (MonoDynamicStream *stream, int size)
2049 if (size <= stream->alloc_size)
2052 while (stream->alloc_size <= size) {
2053 if (stream->alloc_size < 4096)
2054 stream->alloc_size = 4096;
2056 stream->alloc_size *= 2;
2059 stream->data = g_realloc (stream->data, stream->alloc_size);
2063 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2067 make_room_in_stream (stream, stream->index + len);
2068 memcpy (stream->data + stream->index, data, len);
2069 idx = stream->index;
2070 stream->index += len;
2077 * Add data to the binary blob inside the aot image. Returns the offset inside the
2078 * blob where the data was stored.
2081 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2083 if (acfg->blob.alloc_size == 0)
2084 stream_init (&acfg->blob);
2086 return add_stream_data (&acfg->blob, (char*)data, data_len);
2090 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2095 if (acfg->blob.alloc_size == 0)
2096 stream_init (&acfg->blob);
2098 count = acfg->blob.index % align;
2100 /* we assume the stream data will be aligned */
2102 add_stream_data (&acfg->blob, buf, 4 - count);
2104 return add_stream_data (&acfg->blob, (char*)data, data_len);
2108 * emit_offset_table:
2110 * Emit a table of increasing offsets in a compact form using differential encoding.
2111 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2112 * group size, the more compact the table becomes, but the slower it becomes to compute
2113 * a given entry. Returns the size of the table.
2116 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2118 gint32 current_offset;
2119 int i, buf_size, ngroups, index_entry_size;
2121 guint32 *index_offsets;
2123 ngroups = (noffsets + (group_size - 1)) / group_size;
2125 index_offsets = g_new0 (guint32, ngroups);
2127 buf_size = noffsets * 4;
2128 p = buf = g_malloc0 (buf_size);
2131 for (i = 0; i < noffsets; ++i) {
2132 //printf ("D: %d -> %d\n", i, offsets [i]);
2133 if ((i % group_size) == 0) {
2134 index_offsets [i / group_size] = p - buf;
2135 /* Emit the full value for these entries */
2136 encode_value (offsets [i], p, &p);
2138 /* The offsets are allowed to be non-increasing */
2139 //g_assert (offsets [i] >= current_offset);
2140 encode_value (offsets [i] - current_offset, p, &p);
2142 current_offset = offsets [i];
2145 if (ngroups && index_offsets [ngroups - 1] < 65000)
2146 index_entry_size = 2;
2148 index_entry_size = 4;
2150 /* Emit the header */
2151 emit_int32 (acfg, noffsets);
2152 emit_int32 (acfg, group_size);
2153 emit_int32 (acfg, ngroups);
2154 emit_int32 (acfg, index_entry_size);
2156 /* Emit the index */
2157 for (i = 0; i < ngroups; ++i) {
2158 if (index_entry_size == 2)
2159 emit_int16 (acfg, index_offsets [i]);
2161 emit_int32 (acfg, index_offsets [i]);
2165 emit_bytes (acfg, buf, p - buf);
2167 return (int)(p - buf) + (ngroups * 4);
2171 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2175 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2179 index = g_hash_table_size (cfg->image_hash);
2180 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2181 g_ptr_array_add (cfg->image_table, image);
2187 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2190 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2192 /* FIXME: Search referenced images as well */
2193 if (!acfg->typespec_classes) {
2194 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2195 for (i = 0; i < len; ++i) {
2196 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2199 for (i = 0; i < len; ++i) {
2200 if (acfg->typespec_classes [i] == klass)
2205 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2211 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2214 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2217 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2220 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2223 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2228 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2232 if (klass->generic_class) {
2234 g_assert (klass->type_token);
2236 /* Find a typespec for a class if possible */
2237 token = find_typespec_for_class (acfg, klass);
2239 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2240 encode_value (token, p, &p);
2242 MonoClass *gclass = klass->generic_class->container_class;
2243 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2244 static int count = 0;
2247 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2248 encode_klass_ref (acfg, gclass, p, &p);
2249 encode_ginst (acfg, inst, p, &p);
2253 } else if (klass->type_token) {
2254 int iindex = get_image_index (acfg, klass->image);
2256 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2258 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2259 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2261 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2262 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2263 encode_value (get_image_index (acfg, klass->image), p, &p);
2265 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2266 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2267 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2269 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2270 encode_value (klass->byval_arg.type, p, &p);
2271 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2273 encode_value (container ? 1 : 0, p, &p);
2275 encode_value (container->is_method, p, &p);
2276 g_assert (par->serial == 0);
2277 if (container->is_method)
2278 encode_method_ref (acfg, container->owner.method, p, &p);
2280 encode_klass_ref (acfg, container->owner.klass, p, &p);
2282 encode_value (par->serial, p, &p);
2284 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2285 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2286 encode_type (acfg, &klass->byval_arg, p, &p);
2289 g_assert (klass->rank > 0);
2290 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2291 encode_value (klass->rank, p, &p);
2292 encode_klass_ref (acfg, klass->element_class, p, &p);
2300 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2301 * standard metadata encoding.
2304 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2306 gboolean shared = FALSE;
2309 * The encoding of generic instances is large so emit them only once.
2311 if (klass->generic_class) {
2313 g_assert (klass->type_token);
2315 /* Find a typespec for a class if possible */
2316 token = find_typespec_for_class (acfg, klass);
2319 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2324 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2328 buf2 = g_malloc (1024);
2331 encode_klass_ref_inner (acfg, klass, p, &p);
2332 g_assert (p - buf2 < 1024);
2334 offset = add_to_blob (acfg, buf2, p - buf2);
2337 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2343 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2344 encode_value (offset, p, &p);
2349 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2353 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2355 guint32 token = mono_get_field_token (field);
2358 encode_klass_ref (cfg, field->parent, p, &p);
2359 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2360 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2365 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2370 encode_value (inst->type_argc, p, &p);
2371 for (i = 0; i < inst->type_argc; ++i)
2372 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2377 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2380 MonoGenericInst *inst;
2382 inst = context->class_inst;
2384 g_assert (inst->type_argc);
2385 encode_ginst (acfg, inst, p, &p);
2387 encode_value (0, p, &p);
2389 inst = context->method_inst;
2391 g_assert (inst->type_argc);
2392 encode_ginst (acfg, inst, p, &p);
2394 encode_value (0, p, &p);
2400 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2404 g_assert (t->num_mods == 0);
2405 /* t->attrs can be ignored */
2406 //g_assert (t->attrs == 0);
2409 *p = MONO_TYPE_PINNED;
2413 *p = MONO_TYPE_BYREF;
2421 case MONO_TYPE_VOID:
2422 case MONO_TYPE_BOOLEAN:
2423 case MONO_TYPE_CHAR:
2436 case MONO_TYPE_STRING:
2437 case MONO_TYPE_OBJECT:
2438 case MONO_TYPE_TYPEDBYREF:
2440 case MONO_TYPE_VALUETYPE:
2441 case MONO_TYPE_CLASS:
2442 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2444 case MONO_TYPE_SZARRAY:
2445 encode_klass_ref (acfg, t->data.klass, p, &p);
2448 encode_type (acfg, t->data.type, p, &p);
2450 case MONO_TYPE_GENERICINST: {
2451 MonoClass *gclass = t->data.generic_class->container_class;
2452 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2454 encode_klass_ref (acfg, gclass, p, &p);
2455 encode_ginst (acfg, inst, p, &p);
2458 case MONO_TYPE_ARRAY: {
2459 MonoArrayType *array = t->data.array;
2462 encode_klass_ref (acfg, array->eklass, p, &p);
2463 encode_value (array->rank, p, &p);
2464 encode_value (array->numsizes, p, &p);
2465 for (i = 0; i < array->numsizes; ++i)
2466 encode_value (array->sizes [i], p, &p);
2467 encode_value (array->numlobounds, p, &p);
2468 for (i = 0; i < array->numlobounds; ++i)
2469 encode_value (array->lobounds [i], p, &p);
2473 case MONO_TYPE_MVAR:
2474 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2477 g_assert_not_reached ();
2484 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2490 /* Similar to the metadata encoding */
2491 if (sig->generic_param_count)
2495 if (sig->explicit_this)
2497 flags |= (sig->call_convention & 0x0F);
2501 if (sig->generic_param_count)
2502 encode_value (sig->generic_param_count, p, &p);
2503 encode_value (sig->param_count, p, &p);
2505 encode_type (acfg, sig->ret, p, &p);
2506 for (i = 0; i < sig->param_count; ++i) {
2507 if (sig->sentinelpos == i) {
2508 *p = MONO_TYPE_SENTINEL;
2511 encode_type (acfg, sig->params [i], p, &p);
2517 #define MAX_IMAGE_INDEX 250
2520 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2522 guint32 image_index = get_image_index (acfg, method->klass->image);
2523 guint32 token = method->token;
2524 MonoJumpInfoToken *ji;
2528 * The encoding for most methods is as follows:
2529 * - image index encoded as a leb128
2530 * - token index encoded as a leb128
2531 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2532 * types of method encodings.
2535 /* Mark methods which can't use aot trampolines because they need the further
2536 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2538 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2539 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2540 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2542 if (method->wrapper_type) {
2543 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2545 encode_value (method->wrapper_type, p, &p);
2547 switch (method->wrapper_type) {
2548 case MONO_WRAPPER_REMOTING_INVOKE:
2549 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2550 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2553 m = mono_marshal_method_from_wrapper (method);
2555 encode_method_ref (acfg, m, p, &p);
2558 case MONO_WRAPPER_PROXY_ISINST:
2559 case MONO_WRAPPER_LDFLD:
2560 case MONO_WRAPPER_LDFLDA:
2561 case MONO_WRAPPER_STFLD:
2562 case MONO_WRAPPER_ISINST: {
2563 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2564 encode_klass_ref (acfg, proxy_class, p, &p);
2567 case MONO_WRAPPER_LDFLD_REMOTE:
2568 case MONO_WRAPPER_STFLD_REMOTE:
2570 case MONO_WRAPPER_ALLOC: {
2571 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2573 /* The GC name is saved once in MonoAotFileInfo */
2574 g_assert (info->alloc_type != -1);
2575 encode_value (info->alloc_type, p, &p);
2578 case MONO_WRAPPER_WRITE_BARRIER:
2580 case MONO_WRAPPER_STELEMREF: {
2581 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2584 encode_value (info->subtype, p, &p);
2585 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2586 encode_value (info->d.virtual_stelemref.kind, p, &p);
2589 case MONO_WRAPPER_UNKNOWN: {
2590 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2593 encode_value (info->subtype, p, &p);
2594 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2595 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2596 encode_klass_ref (acfg, method->klass, p, &p);
2597 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2598 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2599 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2600 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2603 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2604 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2607 encode_value (info->subtype, p, &p);
2608 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2609 strcpy ((char*)p, method->name);
2610 p += strlen (method->name) + 1;
2611 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2612 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2614 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2615 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2619 case MONO_WRAPPER_SYNCHRONIZED: {
2622 m = mono_marshal_method_from_wrapper (method);
2624 g_assert (m != method);
2625 encode_method_ref (acfg, m, p, &p);
2628 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2629 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2632 encode_value (info->subtype, p, &p);
2634 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2635 encode_value (info->d.element_addr.rank, p, &p);
2636 encode_value (info->d.element_addr.elem_size, p, &p);
2637 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2638 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2640 g_assert_not_reached ();
2644 case MONO_WRAPPER_CASTCLASS: {
2645 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2648 encode_value (info->subtype, p, &p);
2651 case MONO_WRAPPER_RUNTIME_INVOKE: {
2652 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2655 encode_value (info->subtype, p, &p);
2656 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2657 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2658 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2659 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2662 case MONO_WRAPPER_DELEGATE_INVOKE:
2663 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2664 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2665 if (method->is_inflated) {
2666 /* These wrappers are identified by their class */
2667 encode_value (1, p, &p);
2668 encode_klass_ref (acfg, method->klass, p, &p);
2670 MonoMethodSignature *sig = mono_method_signature (method);
2671 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2673 encode_value (0, p, &p);
2674 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2675 encode_value (info ? info->subtype : 0, p, &p);
2676 encode_signature (acfg, sig, p, &p);
2680 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2681 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2684 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2685 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2689 g_assert_not_reached ();
2691 } else if (mono_method_signature (method)->is_inflated) {
2693 * This is a generic method, find the original token which referenced it and
2695 * Obtain the token from information recorded by the JIT.
2697 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2699 image_index = get_image_index (acfg, ji->image);
2700 g_assert (image_index < MAX_IMAGE_INDEX);
2703 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2704 encode_value (image_index, p, &p);
2705 encode_value (token, p, &p);
2707 MonoMethod *declaring;
2708 MonoGenericContext *context = mono_method_get_context (method);
2710 g_assert (method->is_inflated);
2711 declaring = ((MonoMethodInflated*)method)->declaring;
2714 * This might be a non-generic method of a generic instance, which
2715 * doesn't have a token since the reference is generated by the JIT
2716 * like Nullable:Box/Unbox, or by generic sharing.
2718 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2719 /* Encode the klass */
2720 encode_klass_ref (acfg, method->klass, p, &p);
2721 /* Encode the method */
2722 image_index = get_image_index (acfg, method->klass->image);
2723 g_assert (image_index < MAX_IMAGE_INDEX);
2724 g_assert (declaring->token);
2725 token = declaring->token;
2726 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2727 encode_value (image_index, p, &p);
2728 encode_value (token, p, &p);
2729 encode_generic_context (acfg, context, p, &p);
2731 } else if (token == 0) {
2732 /* This might be a method of a constructed type like int[,].Set */
2733 /* 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);
2745 g_assert (method->klass->rank);
2747 /* Encode directly */
2748 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2749 encode_klass_ref (acfg, method->klass, p, &p);
2750 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2751 encode_value (0, p, &p);
2752 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2753 encode_value (1, p, &p);
2754 else if (!strcmp (method->name, "Get"))
2755 encode_value (2, p, &p);
2756 else if (!strcmp (method->name, "Address"))
2757 encode_value (3, p, &p);
2758 else if (!strcmp (method->name, "Set"))
2759 encode_value (4, p, &p);
2761 g_assert_not_reached ();
2764 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2766 if (image_index >= MONO_AOT_METHODREF_MIN) {
2767 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2768 encode_value (image_index, p, &p);
2769 encode_value (mono_metadata_token_index (token), p, &p);
2771 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2778 compare_patches (gconstpointer a, gconstpointer b)
2782 i = (*(MonoJumpInfo**)a)->ip.i;
2783 j = (*(MonoJumpInfo**)b)->ip.i;
2794 static G_GNUC_UNUSED char*
2795 patch_to_string (MonoJumpInfo *patch_info)
2799 str = g_string_new ("");
2801 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2803 switch (patch_info->type) {
2804 case MONO_PATCH_INFO_VTABLE:
2805 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2810 g_string_append_printf (str, ")");
2811 return g_string_free (str, FALSE);
2817 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2820 static inline gboolean
2821 is_plt_patch (MonoJumpInfo *patch_info)
2823 switch (patch_info->type) {
2824 case MONO_PATCH_INFO_METHOD:
2825 case MONO_PATCH_INFO_INTERNAL_METHOD:
2826 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2827 case MONO_PATCH_INFO_ICALL_ADDR:
2828 case MONO_PATCH_INFO_CLASS_INIT:
2829 case MONO_PATCH_INFO_RGCTX_FETCH:
2830 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2831 case MONO_PATCH_INFO_MONITOR_ENTER:
2832 case MONO_PATCH_INFO_MONITOR_EXIT:
2833 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2843 * Return the symbol identifying the plt entry PLT_OFFSET.
2846 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2850 * The Apple linker reorganizes object files, so it doesn't like branches to local
2851 * labels, since those have no relocations.
2853 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2855 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2862 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2864 static MonoPltEntry*
2865 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2869 if (!is_plt_patch (patch_info))
2872 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2874 // FIXME: This breaks the calculation of final_got_size
2875 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2877 * Allocate a separate PLT slot for each such patch, since some plt
2878 * entries will refer to the method itself, and some will refer to the
2885 MonoJumpInfo *new_ji;
2887 g_assert (!acfg->final_got_size);
2889 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2891 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2892 res->plt_offset = acfg->plt_offset;
2894 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2895 if (acfg->aot_opts.write_symbols)
2896 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2898 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2900 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2902 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2904 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2906 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2907 //mono_print_ji (patch_info); printf ("\n");
2908 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2910 acfg->plt_offset ++;
2919 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2920 * JI could be found if it exists, otherwise allocates a new one.
2923 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2927 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2929 return got_offset - 1;
2931 got_offset = acfg->got_offset;
2932 acfg->got_offset ++;
2934 if (acfg->final_got_size)
2935 g_assert (got_offset < acfg->final_got_size);
2937 acfg->stats.got_slots ++;
2938 acfg->stats.got_slot_types [ji->type] ++;
2940 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2941 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2942 g_ptr_array_add (acfg->got_patches, ji);
2947 /* Add a method to the list of methods which need to be emitted */
2949 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2952 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2953 g_ptr_array_add (acfg->methods, method);
2954 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2955 acfg->nmethods = acfg->methods->len + 1;
2958 if (method->wrapper_type || extra)
2959 g_ptr_array_add (acfg->extra_methods, method);
2963 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2965 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2973 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2977 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2981 index = acfg->method_index;
2982 add_method_with_index (acfg, method, index, extra);
2984 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2986 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2988 acfg->method_index ++;
2994 add_method (MonoAotCompile *acfg, MonoMethod *method)
2996 return add_method_full (acfg, method, FALSE, 0);
3000 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3002 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3003 method = mini_get_shared_method (method);
3005 if (acfg->aot_opts.log_generics)
3006 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3008 add_method_full (acfg, method, TRUE, depth);
3012 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3014 add_extra_method_with_depth (acfg, method, 0);
3018 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3020 MonoAotCompile *acfg = user_data;
3021 MonoJitICallInfo *callinfo = value;
3022 MonoMethod *wrapper;
3028 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3029 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3032 add_method (acfg, wrapper);
3036 get_runtime_invoke_sig (MonoMethodSignature *sig)
3038 MonoMethodBuilder *mb;
3041 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3042 m = mono_mb_create_method (mb, sig, 16);
3043 return mono_marshal_get_runtime_invoke (m, FALSE);
3047 can_marshal_struct (MonoClass *klass)
3049 MonoClassField *field;
3050 gboolean can_marshal = TRUE;
3051 gpointer iter = NULL;
3052 MonoMarshalType *info;
3055 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3058 info = mono_marshal_load_type_info (klass);
3060 /* Only allow a few field types to avoid asserts in the marshalling code */
3061 while ((field = mono_class_get_fields (klass, &iter))) {
3062 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3065 switch (field->type->type) {
3070 case MONO_TYPE_BOOLEAN:
3073 case MONO_TYPE_CHAR:
3081 case MONO_TYPE_STRING:
3083 case MONO_TYPE_VALUETYPE:
3084 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3085 can_marshal = FALSE;
3087 case MONO_TYPE_SZARRAY: {
3088 gboolean has_mspec = FALSE;
3091 for (i = 0; i < info->num_fields; ++i) {
3092 if (info->fields [i].field == field && info->fields [i].mspec)
3097 can_marshal = FALSE;
3101 can_marshal = FALSE;
3107 /* Its hard to compute whenever these can be marshalled or not */
3108 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3115 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3117 /* Create a vtype instantiation */
3118 MonoGenericContext shared_context;
3120 MonoGenericInst *inst;
3121 MonoGenericContainer *container;
3122 MonoClass **constraints;
3125 memset (ctx, 0, sizeof (MonoGenericContext));
3127 if (method->klass->generic_container) {
3128 shared_context = method->klass->generic_container->context;
3129 inst = shared_context.class_inst;
3131 args = g_new0 (MonoType*, inst->type_argc);
3132 for (i = 0; i < inst->type_argc; ++i) {
3133 args [i] = &mono_defaults.int_class->byval_arg;
3135 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3137 if (method->is_generic) {
3138 container = mono_method_get_generic_container (method);
3139 shared_context = container->context;
3140 inst = shared_context.method_inst;
3142 args = g_new0 (MonoType*, inst->type_argc);
3143 for (i = 0; i < container->type_argc; ++i) {
3144 MonoGenericParamInfo *info = &container->type_params [i].info;
3145 gboolean ref_only = FALSE;
3147 if (info && info->constraints) {
3148 constraints = info->constraints;
3150 while (*constraints) {
3151 MonoClass *cklass = *constraints;
3152 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3153 /* Inflaring the method with our vtype would not be valid */
3160 args [i] = &mono_defaults.object_class->byval_arg;
3162 args [i] = &mono_defaults.int_class->byval_arg;
3164 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3168 #define MONO_TYPE_IS_PRIMITIVE(t) ((!(t)->byref && ((((t)->type >= MONO_TYPE_BOOLEAN && (t)->type <= MONO_TYPE_R8) || ((t)->type >= MONO_TYPE_I && (t)->type <= MONO_TYPE_U)))))
3171 add_wrappers (MonoAotCompile *acfg)
3173 MonoMethod *method, *m;
3175 MonoMethodSignature *sig, *csig;
3179 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3180 * so there is only one wrapper of a given type, or inlining their contents into their
3185 * FIXME: This depends on the fact that different wrappers have different
3189 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3191 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3192 gboolean skip = FALSE;
3194 method = mono_get_method (acfg->image, token, NULL);
3196 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3197 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3198 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3201 if (method->is_generic || method->klass->generic_container)
3204 /* Skip methods which can not be handled by get_runtime_invoke () */
3205 sig = mono_method_signature (method);
3208 if ((sig->ret->type == MONO_TYPE_PTR) ||
3209 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3212 for (j = 0; j < sig->param_count; j++) {
3213 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3217 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3218 if (!mono_class_is_contextbound (method->klass)) {
3219 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3220 gboolean has_nullable = FALSE;
3222 for (j = 0; j < sig->param_count; j++) {
3223 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3224 has_nullable = TRUE;
3227 if (info && !has_nullable) {
3228 /* Supported by the dynamic runtime-invoke wrapper */
3236 //printf ("%s\n", mono_method_full_name (method, TRUE));
3237 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3241 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3242 MonoMethodDesc *desc;
3243 MonoMethod *orig_method;
3246 /* Runtime invoke wrappers */
3248 /* void runtime-invoke () [.cctor] */
3249 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3250 csig->ret = &mono_defaults.void_class->byval_arg;
3251 add_method (acfg, get_runtime_invoke_sig (csig));
3253 /* void runtime-invoke () [Finalize] */
3254 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3256 csig->ret = &mono_defaults.void_class->byval_arg;
3257 add_method (acfg, get_runtime_invoke_sig (csig));
3259 /* void runtime-invoke (string) [exception ctor] */
3260 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3262 csig->ret = &mono_defaults.void_class->byval_arg;
3263 csig->params [0] = &mono_defaults.string_class->byval_arg;
3264 add_method (acfg, get_runtime_invoke_sig (csig));
3266 /* void runtime-invoke (string, string) [exception ctor] */
3267 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3269 csig->ret = &mono_defaults.void_class->byval_arg;
3270 csig->params [0] = &mono_defaults.string_class->byval_arg;
3271 csig->params [1] = &mono_defaults.string_class->byval_arg;
3272 add_method (acfg, get_runtime_invoke_sig (csig));
3274 /* string runtime-invoke () [Exception.ToString ()] */
3275 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3277 csig->ret = &mono_defaults.string_class->byval_arg;
3278 add_method (acfg, get_runtime_invoke_sig (csig));
3280 /* void runtime-invoke (string, Exception) [exception ctor] */
3281 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3283 csig->ret = &mono_defaults.void_class->byval_arg;
3284 csig->params [0] = &mono_defaults.string_class->byval_arg;
3285 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3286 add_method (acfg, get_runtime_invoke_sig (csig));
3288 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3289 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3291 csig->ret = &(mono_class_from_name (
3292 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3293 csig->params [0] = &mono_defaults.string_class->byval_arg;
3294 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3295 add_method (acfg, get_runtime_invoke_sig (csig));
3297 /* runtime-invoke used by finalizers */
3298 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3300 /* This is used by mono_runtime_capture_context () */
3301 method = mono_get_context_capture_method ();
3303 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3305 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3306 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3309 /* JIT icall wrappers */
3310 /* FIXME: locking */
3311 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3314 add_method (acfg, mono_marshal_get_stelemref ());
3316 if (MONO_ARCH_HAVE_TLS_GET) {
3317 /* Managed Allocators */
3318 nallocators = mono_gc_get_managed_allocator_types ();
3319 for (i = 0; i < nallocators; ++i) {
3320 m = mono_gc_get_managed_allocator_by_type (i);
3322 add_method (acfg, m);
3325 /* Monitor Enter/Exit */
3326 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3327 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3328 /* This is a v4 method */
3330 method = mono_monitor_get_fast_path (orig_method);
3332 add_method (acfg, method);
3334 mono_method_desc_free (desc);
3336 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3337 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3338 g_assert (orig_method);
3339 mono_method_desc_free (desc);
3340 method = mono_monitor_get_fast_path (orig_method);
3342 add_method (acfg, method);
3345 /* Stelemref wrappers */
3347 MonoMethod **wrappers;
3350 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3351 for (i = 0; i < nwrappers; ++i)
3352 add_method (acfg, wrappers [i]);
3356 /* castclass_with_check wrapper */
3357 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3358 /* isinst_with_check wrapper */
3359 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3361 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3363 MonoMethodDesc *desc;
3366 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3367 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3368 mono_method_desc_free (desc);
3370 m = mono_monitor_get_fast_path (m);
3372 add_method (acfg, m);
3379 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3380 * we use the original method instead at runtime.
3381 * Since full-aot doesn't support remoting, this is not a problem.
3384 /* remoting-invoke wrappers */
3385 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3386 MonoMethodSignature *sig;
3388 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3389 method = mono_get_method (acfg->image, token, NULL);
3391 sig = mono_method_signature (method);
3393 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3394 m = mono_marshal_get_remoting_invoke_with_check (method);
3396 add_method (acfg, m);
3401 /* delegate-invoke wrappers */
3402 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3404 MonoCustomAttrInfo *cattr;
3406 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3407 klass = mono_class_get (acfg->image, token);
3410 mono_loader_clear_error ();
3414 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3417 if (!klass->generic_container) {
3418 method = mono_get_delegate_invoke (klass);
3420 m = mono_marshal_get_delegate_invoke (method, NULL);
3422 add_method (acfg, m);
3424 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3426 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3428 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3430 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3432 cattr = mono_custom_attrs_from_class (klass);
3437 for (j = 0; j < cattr->num_attrs; ++j)
3438 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3440 if (j < cattr->num_attrs)
3441 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3443 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3444 MonoGenericContext ctx;
3445 MonoMethod *inst, *gshared;
3448 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3451 method = mono_get_delegate_invoke (klass);
3452 create_gsharedvt_inst (acfg, method, &ctx);
3454 inst = mono_class_inflate_generic_method (method, &ctx);
3456 m = mono_marshal_get_delegate_invoke (inst, NULL);
3457 g_assert (m->is_inflated);
3459 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3460 add_extra_method (acfg, gshared);
3463 method = mono_get_delegate_begin_invoke (klass);
3464 create_gsharedvt_inst (acfg, method, &ctx);
3466 inst = mono_class_inflate_generic_method (method, &ctx);
3468 m = mono_marshal_get_delegate_begin_invoke (inst);
3469 g_assert (m->is_inflated);
3471 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3472 add_extra_method (acfg, gshared);
3475 method = mono_get_delegate_end_invoke (klass);
3476 create_gsharedvt_inst (acfg, method, &ctx);
3478 inst = mono_class_inflate_generic_method (method, &ctx);
3480 m = mono_marshal_get_delegate_end_invoke (inst);
3481 g_assert (m->is_inflated);
3483 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3484 add_extra_method (acfg, gshared);
3489 /* array access wrappers */
3490 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3493 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3494 klass = mono_class_get (acfg->image, token);
3497 mono_loader_clear_error ();
3501 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3502 MonoMethod *m, *wrapper;
3504 /* Add runtime-invoke wrappers too */
3506 m = mono_class_get_method_from_name (klass, "Get", -1);
3508 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3509 add_extra_method (acfg, wrapper);
3510 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3512 m = mono_class_get_method_from_name (klass, "Set", -1);
3514 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3515 add_extra_method (acfg, wrapper);
3516 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3520 /* Synchronized wrappers */
3521 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3522 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3523 method = mono_get_method (acfg->image, token, NULL);
3525 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3526 if (method->is_generic) {
3528 } else if (method->klass->generic_container) {
3529 MonoGenericContext ctx;
3530 MonoMethod *inst, *gshared, *m;
3533 * Create a generic wrapper for a generic instance, and AOT that.
3535 create_gsharedvt_inst (acfg, method, &ctx);
3536 inst = mono_class_inflate_generic_method (method, &ctx);
3537 m = mono_marshal_get_synchronized_wrapper (inst);
3538 g_assert (m->is_inflated);
3539 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3540 add_method (acfg, gshared);
3542 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3547 /* pinvoke wrappers */
3548 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3550 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3552 method = mono_get_method (acfg->image, token, NULL);
3554 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3555 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3556 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3560 /* native-to-managed wrappers */
3561 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3563 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3564 MonoCustomAttrInfo *cattr;
3567 method = mono_get_method (acfg->image, token, NULL);
3570 * Only generate native-to-managed wrappers for methods which have an
3571 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3572 * name to avoid defining a new assembly to contain it.
3574 cattr = mono_custom_attrs_from_method (method);
3577 for (j = 0; j < cattr->num_attrs; ++j)
3578 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3580 if (j < cattr->num_attrs) {
3581 MonoCustomAttrEntry *e = &cattr->attrs [j];
3582 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3583 const char *p = (const char*)e->data;
3585 int slen, num_named, named_type, data_type;
3589 char *export_name = NULL;
3590 MonoMethod *wrapper;
3592 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3593 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3594 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3595 mono_method_full_name (method, TRUE));
3599 g_assert (sig->param_count == 1);
3600 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3603 * Decode the cattr manually since we can't create objects
3604 * during aot compilation.
3610 /* From load_cattr_value () in reflection.c */
3611 slen = mono_metadata_decode_value (p, &p);
3612 n = g_memdup (p, slen + 1);
3614 t = mono_reflection_type_from_name (n, acfg->image);
3618 klass = mono_class_from_mono_type (t);
3619 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3623 num_named = read16 (p);
3626 g_assert (num_named < 2);
3627 if (num_named == 1) {
3630 MonoType *prop_type;
3632 /* parse ExportSymbol attribute */
3634 named_type = *named;
3639 name_len = mono_metadata_decode_blob_size (named, &named);
3640 name = g_malloc (name_len + 1);
3641 memcpy (name, named, name_len);
3642 name [name_len] = 0;
3645 g_assert (named_type == 0x54);
3646 g_assert (!strcmp (name, "ExportSymbol"));
3648 prop_type = &mono_defaults.string_class->byval_arg;
3650 /* load_cattr_value (), string case */
3651 g_assert (*named != (char)0xff);
3652 slen = mono_metadata_decode_value (named, &named);
3653 export_name = g_malloc (slen + 1);
3654 memcpy (export_name, named, slen);
3655 export_name [slen] = 0;
3659 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3660 add_method (acfg, wrapper);
3662 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3666 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3667 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3668 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3672 /* StructureToPtr/PtrToStructure wrappers */
3673 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3676 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3677 klass = mono_class_get (acfg->image, token);
3680 mono_loader_clear_error ();
3684 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3685 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3686 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3687 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3693 has_type_vars (MonoClass *klass)
3695 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3698 return has_type_vars (klass->element_class);
3699 if (klass->generic_class) {
3700 MonoGenericContext *context = &klass->generic_class->context;
3701 if (context->class_inst) {
3704 for (i = 0; i < context->class_inst->type_argc; ++i)
3705 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3709 if (klass->generic_container)
3715 is_vt_inst (MonoGenericInst *inst)
3719 for (i = 0; i < inst->type_argc; ++i) {
3720 MonoType *t = inst->type_argv [i];
3721 if (t->type == MONO_TYPE_VALUETYPE)
3728 method_has_type_vars (MonoMethod *method)
3730 if (has_type_vars (method->klass))
3733 if (method->is_inflated) {
3734 MonoGenericContext *context = mono_method_get_context (method);
3735 if (context->method_inst) {
3738 for (i = 0; i < context->method_inst->type_argc; ++i)
3739 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3746 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3749 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3751 /* This might lead to a huge code blowup so only do it if neccesary */
3752 if (!acfg->aot_opts.full_aot && !force)
3755 add_generic_class_with_depth (acfg, klass, 0, ref);
3759 check_type_depth (MonoType *t, int depth)
3767 case MONO_TYPE_GENERICINST: {
3768 MonoGenericClass *gklass = t->data.generic_class;
3769 MonoGenericInst *ginst = gklass->context.class_inst;
3772 for (i = 0; i < ginst->type_argc; ++i) {
3773 if (check_type_depth (ginst->type_argv [i], depth + 1))
3787 * add_generic_class:
3789 * Add all methods of a generic class.
3792 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3795 MonoClassField *field;
3797 gboolean use_gsharedvt = FALSE;
3799 if (!acfg->ginst_hash)
3800 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3802 mono_class_init (klass);
3804 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3807 if (has_type_vars (klass))
3810 if (!klass->generic_class && !klass->rank)
3813 if (klass->exception_type)
3816 if (!acfg->ginst_hash)
3817 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3819 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3822 if (check_type_depth (&klass->byval_arg, 0))
3825 if (acfg->aot_opts.log_generics)
3826 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3828 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3831 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3832 * Enable this only for some classes since gsharedvt might not support all methods.
3834 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")))
3835 use_gsharedvt = TRUE;
3838 while ((method = mono_class_get_methods (klass, &iter))) {
3839 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3841 * This is partial sharing, and we can't handle it yet
3846 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt))
3850 if (method->is_generic)
3855 * FIXME: Instances which are referenced by these methods are not added,
3856 * for example Array.Resize<int> for List<int>.Add ().
3858 add_extra_method_with_depth (acfg, method, depth + 1);
3862 while ((field = mono_class_get_fields (klass, &iter))) {
3863 if (field->type->type == MONO_TYPE_GENERICINST)
3864 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3867 if (klass->delegate) {
3868 method = mono_get_delegate_invoke (klass);
3870 method = mono_marshal_get_delegate_invoke (method, NULL);
3872 if (acfg->aot_opts.log_generics)
3873 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3875 add_method (acfg, method);
3878 /* Add superclasses */
3880 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3883 * For ICollection<T>, add instances of the helper methods
3884 * in Array, since a T[] could be cast to ICollection<T>.
3886 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3887 (!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"))) {
3888 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3889 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3893 if (!strcmp (klass->name, "IEnumerator`1"))
3894 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3896 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3898 /* Add the T[]/InternalEnumerator class */
3899 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3903 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3904 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3908 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3909 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3913 while ((method = mono_class_get_methods (array_class, &iter))) {
3914 if (strstr (method->name, name_prefix)) {
3915 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3917 add_extra_method_with_depth (acfg, m, depth);
3921 g_free (name_prefix);
3924 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3925 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3926 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3927 MonoClass *icomparable, *gcomparer;
3928 MonoGenericContext ctx;
3929 MonoType *args [16];
3931 memset (&ctx, 0, sizeof (ctx));
3933 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3934 g_assert (icomparable);
3935 args [0] = &tclass->byval_arg;
3936 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3938 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3939 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3940 g_assert (gcomparer);
3941 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3945 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3946 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3947 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3948 MonoClass *iface, *gcomparer;
3949 MonoGenericContext ctx;
3950 MonoType *args [16];
3952 memset (&ctx, 0, sizeof (ctx));
3954 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3956 args [0] = &tclass->byval_arg;
3957 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3959 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3960 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3961 g_assert (gcomparer);
3962 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3968 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3971 MonoGenericContext ctx;
3972 MonoType *args [16];
3974 if (acfg->aot_opts.no_instances)
3977 memset (&ctx, 0, sizeof (ctx));
3979 for (i = 0; i < ninsts; ++i) {
3980 args [0] = insts [i];
3981 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3982 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3987 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3989 MonoMethodHeader *header;
3990 MonoMethodSignature *sig;
3993 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3995 sig = mono_method_signature (method);
3998 for (j = 0; j < sig->param_count; ++j)
3999 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4000 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4003 header = mono_method_get_header (method);
4006 for (j = 0; j < header->num_locals; ++j)
4007 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4008 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4013 * add_generic_instances:
4015 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4018 add_generic_instances (MonoAotCompile *acfg)
4023 MonoGenericContext *context;
4025 if (acfg->aot_opts.no_instances)
4028 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4029 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4030 method = mono_get_method (acfg->image, token, NULL);
4035 if (method->klass->image != acfg->image)
4038 context = mono_method_get_context (method);
4040 if (context && ((context->class_inst && context->class_inst->is_open)))
4044 * For open methods, create an instantiation which can be passed to the JIT.
4045 * FIXME: Handle class_inst as well.
4047 if (context && context->method_inst && context->method_inst->is_open) {
4048 MonoGenericContext shared_context;
4049 MonoGenericInst *inst;
4050 MonoType **type_argv;
4052 MonoMethod *declaring_method;
4053 gboolean supported = TRUE;
4055 /* Check that the context doesn't contain open constructed types */
4056 if (context->class_inst) {
4057 inst = context->class_inst;
4058 for (i = 0; i < inst->type_argc; ++i) {
4059 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)
4061 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4065 if (context->method_inst) {
4066 inst = context->method_inst;
4067 for (i = 0; i < inst->type_argc; ++i) {
4068 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)
4070 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4078 memset (&shared_context, 0, sizeof (MonoGenericContext));
4080 inst = context->class_inst;
4082 type_argv = g_new0 (MonoType*, inst->type_argc);
4083 for (i = 0; i < inst->type_argc; ++i) {
4084 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)
4085 type_argv [i] = &mono_defaults.object_class->byval_arg;
4087 type_argv [i] = inst->type_argv [i];
4090 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4094 inst = context->method_inst;
4096 type_argv = g_new0 (MonoType*, inst->type_argc);
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)
4099 type_argv [i] = &mono_defaults.object_class->byval_arg;
4101 type_argv [i] = inst->type_argv [i];
4104 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4108 if (method->is_generic || method->klass->generic_container)
4109 declaring_method = method;
4111 declaring_method = mono_method_get_declaring_generic_method (method);
4113 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4117 * If the method is fully sharable, it was already added in place of its
4118 * generic definition.
4120 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4124 * FIXME: Partially shared methods are not shared here, so we end up with
4125 * many identical methods.
4127 add_extra_method (acfg, method);
4130 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4133 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4135 klass = mono_class_get (acfg->image, token);
4136 if (!klass || klass->rank) {
4137 mono_loader_clear_error ();
4141 add_generic_class (acfg, klass, FALSE, "typespec");
4144 /* Add types of args/locals */
4145 for (i = 0; i < acfg->methods->len; ++i) {
4146 method = g_ptr_array_index (acfg->methods, i);
4147 add_types_from_method_header (acfg, method);
4150 if (acfg->image == mono_defaults.corlib) {
4152 MonoType *insts [256];
4155 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4156 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4157 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4158 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4159 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4160 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4161 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4162 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4163 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4164 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4165 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4166 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4168 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4169 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4171 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4172 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4174 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4176 /* Add instances of the array generic interfaces for primitive types */
4177 /* This will add instances of the InternalArray_ helper methods in Array too */
4178 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4180 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4181 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4183 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4184 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4186 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4189 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4190 * used for all instances of GetGenericValueImpl by the AOT runtime.
4193 MonoGenericContext ctx;
4194 MonoType *args [16];
4195 MonoMethod *get_method;
4196 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4198 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4201 memset (&ctx, 0, sizeof (ctx));
4202 args [0] = &mono_defaults.object_class->byval_arg;
4203 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4204 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4208 /* Same for CompareExchange<T>/Exchange<T> */
4210 MonoGenericContext ctx;
4211 MonoType *args [16];
4213 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4214 gpointer iter = NULL;
4216 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4217 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4218 memset (&ctx, 0, sizeof (ctx));
4219 args [0] = &mono_defaults.object_class->byval_arg;
4220 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4221 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4226 /* Same for Volatile.Read/Write<T> */
4228 MonoGenericContext ctx;
4229 MonoType *args [16];
4231 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4232 gpointer iter = NULL;
4234 if (volatile_klass) {
4235 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4236 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4237 memset (&ctx, 0, sizeof (ctx));
4238 args [0] = &mono_defaults.object_class->byval_arg;
4239 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4240 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4249 * is_direct_callable:
4251 * Return whenever the method identified by JI is directly callable without
4252 * going through the PLT.
4255 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4257 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4258 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4260 gboolean direct_callable = TRUE;
4262 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4263 direct_callable = FALSE;
4264 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4265 // FIXME: Maybe call the wrapper directly ?
4266 direct_callable = FALSE;
4268 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4269 /* Disable this so all calls go through load_method (), see the
4270 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4271 * mono_debugger_agent_init ().
4273 direct_callable = FALSE;
4276 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4277 /* sgen does some initialization when the allocator method is created */
4278 direct_callable = FALSE;
4280 if (direct_callable)
4283 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4284 if (acfg->aot_opts.direct_pinvoke)
4286 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4287 if (acfg->aot_opts.direct_icalls)
4296 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4298 MonoImage *image = method->klass->image;
4299 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4300 MonoTableInfo *tables = image->tables;
4301 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4302 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4303 guint32 im_cols [MONO_IMPLMAP_SIZE];
4306 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4310 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4313 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4315 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4318 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4320 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4326 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4328 if (a->native_offset == b->native_offset)
4329 return a->il_offset - b->il_offset;
4331 return a->native_offset - b->native_offset;
4335 * compute_line_numbers:
4337 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4340 static MonoDebugSourceLocation**
4341 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4343 MonoDebugMethodInfo *minfo;
4344 MonoDebugLineNumberEntry *ln_array;
4345 MonoDebugSourceLocation *loc;
4346 int i, prev_line, prev_il_offset;
4347 int *native_to_il_offset = NULL;
4348 MonoDebugSourceLocation **res;
4351 minfo = mono_debug_lookup_method (method);
4354 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4355 if (debug_info->code_size != code_size)
4358 g_assert (code_size);
4360 /* Compute the native->IL offset mapping */
4362 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4363 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4365 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4367 native_to_il_offset = g_new0 (int, code_size + 1);
4369 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4371 MonoDebugLineNumberEntry *lne = &ln_array [i];
4374 for (j = 0; j < lne->native_offset; ++j)
4375 native_to_il_offset [j] = -1;
4378 if (i < debug_info->num_line_numbers - 1) {
4379 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4381 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4382 native_to_il_offset [j] = lne->il_offset;
4384 for (j = lne->native_offset; j < code_size; ++j)
4385 native_to_il_offset [j] = lne->il_offset;
4390 /* Compute the native->line number mapping */
4391 res = g_new0 (MonoDebugSourceLocation*, code_size);
4392 prev_il_offset = -1;
4395 for (i = 0; i < code_size; ++i) {
4396 int il_offset = native_to_il_offset [i];
4398 if (il_offset == -1 || il_offset == prev_il_offset)
4400 prev_il_offset = il_offset;
4401 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4402 if (!(loc && loc->source_file))
4404 if (loc->row == prev_line) {
4405 mono_debug_symfile_free_location (loc);
4408 prev_line = loc->row;
4409 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4411 /* This will cover the prolog too */
4421 get_file_index (MonoAotCompile *acfg, const char *source_file)
4425 // FIXME: Free these
4426 if (!acfg->dwarf_ln_filenames)
4427 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4428 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4430 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4431 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4432 emit_unset_mode (acfg);
4433 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4439 * emit_and_reloc_code:
4441 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4442 * is true, calls are made through the GOT too. This is used for emitting trampolines
4443 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4444 * since trampolines are needed to make PTL work.
4447 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4449 int i, pindex, start_index, method_index;
4451 MonoJumpInfo *patch_info;
4452 MonoMethodHeader *header;
4453 MonoDebugSourceLocation **locs = NULL;
4454 gboolean skip, direct_call, external_call;
4456 const char *direct_call_target = 0;
4457 const char *direct_pinvoke;
4460 header = mono_method_get_header (method);
4462 method_index = get_method_index (acfg, method);
4465 if (acfg->gas_line_numbers && method && debug_info) {
4466 locs = compute_line_numbers (method, code_len, debug_info);
4468 int findex = get_file_index (acfg, "<unknown>");
4469 emit_unset_mode (acfg);
4470 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4474 /* Collect and sort relocations */
4475 patches = g_ptr_array_new ();
4476 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4477 g_ptr_array_add (patches, patch_info);
4478 g_ptr_array_sort (patches, compare_patches);
4481 for (i = 0; i < code_len; i++) {
4483 for (pindex = start_index; pindex < patches->len; ++pindex) {
4484 patch_info = g_ptr_array_index (patches, pindex);
4485 if (patch_info->ip.i >= i)
4489 if (locs && locs [i]) {
4490 MonoDebugSourceLocation *loc = locs [i];
4493 findex = get_file_index (acfg, loc->source_file);
4494 emit_unset_mode (acfg);
4495 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4496 mono_debug_symfile_free_location (loc);
4500 #ifdef MONO_ARCH_AOT_SUPPORTED
4501 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4502 start_index = pindex;
4504 switch (patch_info->type) {
4505 case MONO_PATCH_INFO_NONE:
4507 case MONO_PATCH_INFO_GOT_OFFSET: {
4510 arch_emit_got_offset (acfg, code + i, &code_size);
4513 patch_info->type = MONO_PATCH_INFO_NONE;
4518 * If this patch is a call, try emitting a direct call instead of
4519 * through a PLT entry. This is possible if the called method is in
4520 * the same assembly and requires no initialization.
4522 direct_call = FALSE;
4523 external_call = FALSE;
4524 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4525 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4526 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4527 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4529 direct_call_target = callee_cfg->asm_symbol;
4530 patch_info->type = MONO_PATCH_INFO_NONE;
4531 acfg->stats.direct_calls ++;
4534 acfg->stats.all_calls ++;
4535 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4536 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4537 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4538 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4540 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4541 if (direct_pinvoke) {
4543 g_assert (strlen (direct_pinvoke) < 1000);
4544 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4547 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4548 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4549 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4550 /* Call to a C function implementing a jit icall */
4552 external_call = TRUE;
4553 g_assert (strlen (sym) < 1000);
4554 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4556 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4557 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4558 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4559 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4560 /* Call to a jit icall without a wrapper */
4562 external_call = TRUE;
4563 g_assert (strlen (sym) < 1000);
4564 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4569 patch_info->type = MONO_PATCH_INFO_NONE;
4570 acfg->stats.direct_calls ++;
4573 if (!got_only && !direct_call) {
4574 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4576 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4578 direct_call_target = plt_entry->symbol;
4580 /* Nullify the patch */
4581 patch_info->type = MONO_PATCH_INFO_NONE;
4582 plt_entry->jit_used = TRUE;
4589 arch_emit_direct_call (acfg, direct_call_target, external_call, &call_size);
4594 got_slot = get_got_offset (acfg, patch_info);
4596 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4603 #endif /* MONO_ARCH_AOT_SUPPORTED */
4606 /* Find next patch */
4608 for (pindex = start_index; pindex < patches->len; ++pindex) {
4609 patch_info = g_ptr_array_index (patches, pindex);
4610 if (patch_info->ip.i >= i)
4614 /* Try to emit multiple bytes at once */
4615 if (pindex < patches->len && patch_info->ip.i > i) {
4618 for (limit = i + 1; limit < patch_info->ip.i; ++limit) {
4619 if (locs && locs [limit])
4623 emit_bytes (acfg, code + i, limit - i);
4626 emit_bytes (acfg, code + i, 1);
4637 * Modify SYMBOL so it only includes characters permissible in symbols.
4640 sanitize_symbol (char *symbol)
4642 int i, len = strlen (symbol);
4644 for (i = 0; i < len; ++i)
4645 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
4650 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4652 char *name1, *name2, *cached;
4653 int i, j, len, count;
4656 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4657 if (!prefix || !*prefix)
4661 name1 = mono_method_full_name (method, TRUE);
4662 len = strlen (name1);
4663 name2 = malloc (strlen (prefix) + len + 16);
4664 memcpy (name2, prefix, strlen (prefix));
4665 j = strlen (prefix);
4666 for (i = 0; i < len; ++i) {
4667 if (isalnum (name1 [i])) {
4668 name2 [j ++] = name1 [i];
4669 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4671 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4674 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4683 while (g_hash_table_lookup (cache, name2)) {
4684 sprintf (name2 + j, "_%d", count);
4688 cached = g_strdup (name2);
4689 g_hash_table_insert (cache, cached, cached);
4695 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4700 char *debug_sym = NULL;
4701 char *symbol = NULL;
4702 int func_alignment = AOT_FUNC_ALIGNMENT;
4703 MonoMethodHeader *header;
4706 method = cfg->orig_method;
4707 code = cfg->native_code;
4708 header = cfg->header;
4710 method_index = get_method_index (acfg, method);
4711 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4714 /* Make the labels local */
4715 emit_section_change (acfg, ".text", 0);
4716 emit_alignment (acfg, func_alignment);
4718 if (acfg->global_symbols && acfg->need_no_dead_strip)
4719 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4721 emit_label (acfg, cfg->asm_symbol);
4723 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4725 * Write a C style symbol for every method, this has two uses:
4726 * - it works on platforms where the dwarf debugging info is not
4728 * - it allows the setting of breakpoints of aot-ed methods.
4730 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4732 if (acfg->need_no_dead_strip)
4733 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4734 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4735 emit_label (acfg, debug_sym);
4738 export_name = g_hash_table_lookup (acfg->export_names, method);
4740 /* Emit a global symbol for the method */
4741 emit_global_inner (acfg, export_name, TRUE);
4742 emit_label (acfg, export_name);
4745 if (cfg->verbose_level > 0)
4746 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4748 acfg->stats.code_size += cfg->code_len;
4750 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4752 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
4756 if (acfg->aot_opts.write_symbols) {
4757 emit_symbol_size (acfg, debug_sym, ".");
4761 emit_label (acfg, symbol);
4768 * Encode PATCH_INFO into its disk representation.
4771 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4775 switch (patch_info->type) {
4776 case MONO_PATCH_INFO_NONE:
4778 case MONO_PATCH_INFO_IMAGE:
4779 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4781 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4782 case MONO_PATCH_INFO_JIT_TLS_ID:
4783 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4784 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4786 case MONO_PATCH_INFO_METHOD_REL:
4787 encode_value ((gint)patch_info->data.offset, p, &p);
4789 case MONO_PATCH_INFO_SWITCH: {
4790 gpointer *table = (gpointer *)patch_info->data.table->table;
4793 encode_value (patch_info->data.table->table_size, p, &p);
4794 for (k = 0; k < patch_info->data.table->table_size; k++)
4795 encode_value ((int)(gssize)table [k], p, &p);
4798 case MONO_PATCH_INFO_METHODCONST:
4799 case MONO_PATCH_INFO_METHOD:
4800 case MONO_PATCH_INFO_METHOD_JUMP:
4801 case MONO_PATCH_INFO_ICALL_ADDR:
4802 case MONO_PATCH_INFO_METHOD_RGCTX:
4803 encode_method_ref (acfg, patch_info->data.method, p, &p);
4805 case MONO_PATCH_INFO_INTERNAL_METHOD:
4806 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4807 guint32 len = strlen (patch_info->data.name);
4809 encode_value (len, p, &p);
4811 memcpy (p, patch_info->data.name, len);
4816 case MONO_PATCH_INFO_LDSTR: {
4817 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4818 guint32 token = patch_info->data.token->token;
4819 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4820 encode_value (image_index, p, &p);
4821 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4824 case MONO_PATCH_INFO_RVA:
4825 case MONO_PATCH_INFO_DECLSEC:
4826 case MONO_PATCH_INFO_LDTOKEN:
4827 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4828 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4829 encode_value (patch_info->data.token->token, p, &p);
4830 encode_value (patch_info->data.token->has_context, p, &p);
4831 if (patch_info->data.token->has_context)
4832 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4834 case MONO_PATCH_INFO_EXC_NAME: {
4835 MonoClass *ex_class;
4838 mono_class_from_name (mono_defaults.exception_class->image,
4839 "System", patch_info->data.target);
4840 g_assert (ex_class);
4841 encode_klass_ref (acfg, ex_class, p, &p);
4844 case MONO_PATCH_INFO_R4:
4845 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4847 case MONO_PATCH_INFO_R8:
4848 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4849 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4851 case MONO_PATCH_INFO_VTABLE:
4852 case MONO_PATCH_INFO_CLASS:
4853 case MONO_PATCH_INFO_IID:
4854 case MONO_PATCH_INFO_ADJUSTED_IID:
4855 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4857 case MONO_PATCH_INFO_CLASS_INIT:
4858 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4859 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4861 case MONO_PATCH_INFO_FIELD:
4862 case MONO_PATCH_INFO_SFLDA:
4863 encode_field_info (acfg, patch_info->data.field, p, &p);
4865 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4867 case MONO_PATCH_INFO_RGCTX_FETCH: {
4868 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4873 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4874 * reference the same method, so encode the method only once.
4876 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4878 buf2 = g_malloc (1024);
4881 encode_method_ref (acfg, entry->method, p2, &p2);
4882 g_assert (p2 - buf2 < 1024);
4884 offset = add_to_blob (acfg, buf2, p2 - buf2);
4887 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4892 encode_value (offset, p, &p);
4893 g_assert ((int)entry->info_type < 256);
4894 g_assert (entry->data->type < 256);
4895 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4896 encode_patch (acfg, entry->data, p, &p);
4899 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4900 case MONO_PATCH_INFO_MONITOR_ENTER:
4901 case MONO_PATCH_INFO_MONITOR_EXIT:
4902 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4904 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4905 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4906 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4908 case MONO_PATCH_INFO_SIGNATURE:
4909 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4911 case MONO_PATCH_INFO_TLS_OFFSET:
4912 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
4914 case MONO_PATCH_INFO_GSHAREDVT_CALL:
4915 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
4916 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
4918 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
4919 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
4922 encode_method_ref (acfg, info->method, p, &p);
4923 encode_value (info->entries->len, p, &p);
4924 for (i = 0; i < info->entries->len; ++i) {
4925 MonoRuntimeGenericContextInfoTemplate *template = g_ptr_array_index (info->entries, i);
4927 encode_value (template->info_type, p, &p);
4928 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
4929 case MONO_PATCH_INFO_CLASS:
4930 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
4932 case MONO_PATCH_INFO_FIELD:
4933 encode_field_info (acfg, template->data, p, &p);
4936 g_assert_not_reached ();
4943 g_warning ("unable to handle jump info %d", patch_info->type);
4944 g_assert_not_reached ();
4951 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4954 guint32 pindex, offset;
4955 MonoJumpInfo *patch_info;
4957 encode_value (n_patches, p, &p);
4959 for (pindex = 0; pindex < patches->len; ++pindex) {
4960 patch_info = g_ptr_array_index (patches, pindex);
4962 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4966 offset = get_got_offset (acfg, patch_info);
4967 encode_value (offset, p, &p);
4974 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4978 int pindex, buf_size, n_patches;
4980 MonoJumpInfo *patch_info;
4981 MonoMethodHeader *header;
4982 guint32 method_index;
4984 guint32 first_got_offset;
4986 method = cfg->orig_method;
4987 header = mono_method_get_header (method);
4989 method_index = get_method_index (acfg, method);
4991 /* Sort relocations */
4992 patches = g_ptr_array_new ();
4993 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4994 g_ptr_array_add (patches, patch_info);
4995 g_ptr_array_sort (patches, compare_patches);
4997 first_got_offset = acfg->cfgs [method_index]->got_offset;
4999 /**********************/
5000 /* Encode method info */
5001 /**********************/
5003 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5004 p = buf = g_malloc (buf_size);
5006 if (mono_class_get_cctor (method->klass))
5007 encode_klass_ref (acfg, method->klass, p, &p);
5009 /* Not needed when loading the method */
5010 encode_value (0, p, &p);
5013 if (cfg->opt & MONO_OPT_SHARED) {
5014 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5015 for (l = cfg->ldstr_list; l; l = l->next) {
5016 encode_value ((long)l->data, p, &p);
5020 /* Used only in shared mode */
5021 g_assert (!cfg->ldstr_list);
5024 for (pindex = 0; pindex < patches->len; ++pindex) {
5025 patch_info = g_ptr_array_index (patches, pindex);
5027 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5028 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5029 patch_info->type = MONO_PATCH_INFO_NONE;
5034 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5035 /* Stored in a GOT slot initialized at module load time */
5036 patch_info->type = MONO_PATCH_INFO_NONE;
5040 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5041 /* Stored in a GOT slot initialized at module load time */
5042 patch_info->type = MONO_PATCH_INFO_NONE;
5046 if (is_plt_patch (patch_info)) {
5047 /* Calls are made through the PLT */
5048 patch_info->type = MONO_PATCH_INFO_NONE;
5056 g_assert (cfg->has_got_slots);
5058 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5060 acfg->stats.info_size += p - buf;
5062 g_assert (p - buf < buf_size);
5064 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5069 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5071 guint32 cache_index;
5074 /* Reuse the unwind module to canonize and store unwind info entries */
5075 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5077 /* Use +/- 1 to distinguish 0s from missing entries */
5078 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5086 * It would be easier to use assembler symbols, but the caller needs an
5089 offset = acfg->unwind_info_offset;
5090 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5091 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5094 encode_value (encoded_len, p, &p);
5096 acfg->unwind_info_offset += encoded_len + (p - buf);
5102 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5105 int i, k, buf_size, method_index;
5106 guint32 debug_info_size;
5108 MonoMethodHeader *header;
5109 guint8 *p, *buf, *debug_info;
5110 MonoJitInfo *jinfo = cfg->jit_info;
5112 gboolean use_unwind_ops = FALSE;
5113 MonoSeqPointInfo *seq_points;
5115 method = cfg->orig_method;
5116 code = cfg->native_code;
5117 header = cfg->header;
5119 method_index = get_method_index (acfg, method);
5121 if (!acfg->aot_opts.nodebug) {
5122 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5125 debug_info_size = 0;
5128 seq_points = cfg->seq_point_info;
5130 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
5131 p = buf = g_malloc (buf_size);
5133 #ifdef MONO_ARCH_HAVE_XP_UNWIND
5134 use_unwind_ops = cfg->unwind_ops != NULL;
5137 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);
5139 encode_value (flags, p, &p);
5141 if (use_unwind_ops) {
5142 guint32 encoded_len;
5146 * This is a duplicate of the data in the .debug_frame section, but that
5147 * section cannot be accessed using the dl interface.
5149 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5150 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5153 encode_value (jinfo->used_regs, p, &p);
5156 /*Encode the number of holes before the number of clauses to make decoding easier*/
5157 if (jinfo->has_try_block_holes) {
5158 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5159 encode_value (table->num_holes, p, &p);
5162 /* Exception table */
5163 if (cfg->compile_llvm) {
5165 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5166 * since the information is only available to llc. Instead, we let llc save the data
5167 * into the LSDA, and read it from there at runtime.
5169 /* The assembly might be CIL stripped so emit the data ourselves */
5170 if (header->num_clauses)
5171 encode_value (header->num_clauses, p, &p);
5173 for (k = 0; k < header->num_clauses; ++k) {
5174 MonoExceptionClause *clause;
5176 clause = &header->clauses [k];
5178 encode_value (clause->flags, p, &p);
5179 if (clause->data.catch_class) {
5180 encode_value (1, p, &p);
5181 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5183 encode_value (0, p, &p);
5186 /* Emit a list of nesting clauses */
5187 for (i = 0; i < header->num_clauses; ++i) {
5189 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5191 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5193 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5194 encode_value (i, p, &p);
5196 encode_value (-1, p, &p);
5199 if (jinfo->num_clauses)
5200 encode_value (jinfo->num_clauses, p, &p);
5202 for (k = 0; k < jinfo->num_clauses; ++k) {
5203 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5205 encode_value (ei->flags, p, &p);
5206 encode_value (ei->exvar_offset, p, &p);
5208 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5209 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5211 if (ei->data.catch_class) {
5212 encode_value (1, p, &p);
5213 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
5215 encode_value (0, p, &p);
5219 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5220 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5221 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5225 if (jinfo->has_generic_jit_info) {
5226 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5227 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5231 encode_value (gi->nlocs, p, &p);
5233 for (i = 0; i < gi->nlocs; ++i) {
5234 MonoDwarfLocListEntry *entry = &gi->locations [i];
5236 encode_value (entry->is_reg ? 1 : 0, p, &p);
5237 encode_value (entry->reg, p, &p);
5239 encode_value (entry->offset, p, &p);
5241 g_assert (entry->from == 0);
5243 encode_value (entry->from, p, &p);
5244 encode_value (entry->to, p, &p);
5247 if (!cfg->compile_llvm) {
5248 encode_value (gi->has_this ? 1 : 0, p, &p);
5249 encode_value (gi->this_reg, p, &p);
5250 encode_value (gi->this_offset, p, &p);
5255 * Need to encode jinfo->method too, since it is not equal to 'method'
5256 * when using generic sharing.
5258 encode_method_ref (acfg, jinfo->method, p, &p);
5260 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5261 MonoMethodInflated *inflated;
5262 MonoGenericContext *context;
5263 MonoGenericInst *inst;
5265 g_assert (jinfo->method->is_inflated);
5266 inflated = (MonoMethodInflated*)jinfo->method;
5267 context = &inflated->context;
5269 encode_value (1, p, &p);
5270 if (context->class_inst) {
5271 inst = context->class_inst;
5273 encode_value (inst->type_argc, p, &p);
5274 for (i = 0; i < inst->type_argc; ++i)
5275 encode_value (gsctx->var_is_vt [i], p, &p);
5277 encode_value (0, p, &p);
5279 if (context->method_inst) {
5280 inst = context->method_inst;
5282 encode_value (inst->type_argc, p, &p);
5283 for (i = 0; i < inst->type_argc; ++i)
5284 encode_value (gsctx->mvar_is_vt [i], p, &p);
5286 encode_value (0, p, &p);
5289 encode_value (0, p, &p);
5293 if (jinfo->has_try_block_holes) {
5294 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5295 for (i = 0; i < table->num_holes; ++i) {
5296 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5297 encode_value (hole->clause, p, &p);
5298 encode_value (hole->length, p, &p);
5299 encode_value (hole->offset, p, &p);
5303 if (jinfo->has_arch_eh_info) {
5304 MonoArchEHJitInfo *eh_info;
5306 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5307 encode_value (eh_info->stack_size, p, &p);
5311 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5313 encode_value (seq_points->len, p, &p);
5314 last_il_offset = last_native_offset = 0;
5315 for (i = 0; i < seq_points->len; ++i) {
5316 SeqPoint *sp = &seq_points->seq_points [i];
5317 il_offset = sp->il_offset;
5318 native_offset = sp->native_offset;
5319 encode_value (il_offset - last_il_offset, p, &p);
5320 encode_value (native_offset - last_native_offset, p, &p);
5321 last_il_offset = il_offset;
5322 last_native_offset = native_offset;
5324 encode_value (sp->next_len, p, &p);
5325 for (j = 0; j < sp->next_len; ++j)
5326 encode_value (sp->next [j], p, &p);
5330 g_assert (debug_info_size < buf_size);
5332 encode_value (debug_info_size, p, &p);
5333 if (debug_info_size) {
5334 memcpy (p, debug_info, debug_info_size);
5335 p += debug_info_size;
5336 g_free (debug_info);
5341 encode_value (cfg->gc_map_size, p, &p);
5342 /* The GC map requires 4 bytes of alignment */
5343 while ((gsize)p % 4)
5345 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5346 p += cfg->gc_map_size;
5349 acfg->stats.ex_info_size += p - buf;
5351 g_assert (p - buf < buf_size);
5354 /* The GC Map requires 4 byte alignment */
5355 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5360 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5362 MonoClass *klass = mono_class_get (acfg->image, token);
5364 int i, buf_size, res;
5365 gboolean no_special_static, cant_encode;
5366 gpointer iter = NULL;
5369 mono_loader_clear_error ();
5373 p = buf = g_malloc (buf_size);
5375 /* Mark as unusable */
5376 encode_value (-1, p, &p);
5378 res = add_to_blob (acfg, buf, p - buf);
5384 buf_size = 10240 + (klass->vtable_size * 16);
5385 p = buf = g_malloc (buf_size);
5389 mono_class_init (klass);
5391 mono_class_get_nested_types (klass, &iter);
5392 g_assert (klass->nested_classes_inited);
5394 mono_class_setup_vtable (klass);
5397 * Emit all the information which is required for creating vtables so
5398 * the runtime does not need to create the MonoMethod structures which
5399 * take up a lot of space.
5402 no_special_static = !mono_class_has_special_static_fields (klass);
5404 /* Check whenever we have enough info to encode the vtable */
5405 cant_encode = FALSE;
5406 for (i = 0; i < klass->vtable_size; ++i) {
5407 MonoMethod *cm = klass->vtable [i];
5409 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5413 mono_class_has_finalizer (klass);
5415 if (klass->generic_container || cant_encode) {
5416 encode_value (-1, p, &p);
5418 encode_value (klass->vtable_size, p, &p);
5419 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);
5420 if (klass->has_cctor)
5421 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5422 if (klass->has_finalize)
5423 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5425 encode_value (klass->instance_size, p, &p);
5426 encode_value (mono_class_data_size (klass), p, &p);
5427 encode_value (klass->packing_size, p, &p);
5428 encode_value (klass->min_align, p, &p);
5430 for (i = 0; i < klass->vtable_size; ++i) {
5431 MonoMethod *cm = klass->vtable [i];
5434 encode_method_ref (acfg, cm, p, &p);
5436 encode_value (0, p, &p);
5440 acfg->stats.class_info_size += p - buf;
5442 g_assert (p - buf < buf_size);
5443 res = add_to_blob (acfg, buf, p - buf);
5450 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5452 char *debug_sym = NULL;
5455 case MONO_PATCH_INFO_METHOD:
5456 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5458 case MONO_PATCH_INFO_INTERNAL_METHOD:
5459 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5461 case MONO_PATCH_INFO_CLASS_INIT:
5462 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
5463 sanitize_symbol (debug_sym);
5465 case MONO_PATCH_INFO_RGCTX_FETCH:
5466 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5468 case MONO_PATCH_INFO_ICALL_ADDR: {
5469 char *s = get_debug_sym (ji->data.method, "", cache);
5471 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5475 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5476 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5478 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5479 debug_sym = g_strdup_printf ("plt__generic_class_init");
5489 * Calls made from AOTed code are routed through a table of jumps similar to the
5490 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5491 * control to the AOT runtime through a trampoline.
5494 emit_plt (MonoAotCompile *acfg)
5500 sprintf (symbol, "plt");
5502 emit_section_change (acfg, ".text", 0);
5503 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5504 emit_label (acfg, symbol);
5505 emit_label (acfg, acfg->plt_symbol);
5507 for (i = 0; i < acfg->plt_offset; ++i) {
5508 char *debug_sym = NULL;
5509 MonoPltEntry *plt_entry = NULL;
5514 * The first plt entry is unused.
5518 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5523 * If the target is directly callable, alias the plt symbol to point to
5525 * FIXME: Use this to simplify emit_and_reloc_code ().
5526 * FIXME: Avoid the got slot.
5527 * FIXME: Add support to the binary writer.
5529 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5530 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5533 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5534 /* LLVM calls the PLT entries using bl, so emit a stub */
5535 emit_set_thumb_mode (acfg);
5536 fprintf (acfg->fp, "\n.thumb_func\n");
5537 emit_label (acfg, plt_entry->llvm_symbol);
5538 fprintf (acfg->fp, "bx pc\n");
5539 fprintf (acfg->fp, "nop\n");
5540 emit_set_arm_mode (acfg);
5541 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5543 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5550 debug_sym = plt_entry->debug_sym;
5552 if (acfg->thumb_mixed && !plt_entry->jit_used)
5553 /* Emit only a thumb version */
5556 if (acfg->llvm && !acfg->thumb_mixed)
5557 emit_label (acfg, plt_entry->llvm_symbol);
5560 if (acfg->need_no_dead_strip) {
5561 emit_unset_mode (acfg);
5562 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5564 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5565 emit_label (acfg, debug_sym);
5568 emit_label (acfg, plt_entry->symbol);
5570 arch_emit_plt_entry (acfg, i);
5573 emit_symbol_size (acfg, debug_sym, ".");
5576 if (acfg->thumb_mixed) {
5577 /* Make sure the ARM symbols don't alias the thumb ones */
5578 emit_zero_bytes (acfg, 16);
5581 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5584 for (i = 0; i < acfg->plt_offset; ++i) {
5585 char *debug_sym = NULL;
5586 MonoPltEntry *plt_entry = NULL;
5592 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5595 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5598 /* Skip plt entries not actually called by LLVM code */
5599 if (!plt_entry->llvm_used)
5602 if (acfg->aot_opts.write_symbols) {
5603 if (plt_entry->debug_sym)
5604 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5608 #if defined(TARGET_MACH)
5609 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5610 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5612 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5613 emit_label (acfg, debug_sym);
5615 fprintf (acfg->fp, "\n.thumb_func\n");
5617 emit_label (acfg, plt_entry->llvm_symbol);
5619 arch_emit_llvm_plt_entry (acfg, i);
5622 emit_symbol_size (acfg, debug_sym, ".");
5628 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5630 sprintf (symbol, "plt_end");
5631 emit_label (acfg, symbol);
5635 * emit_trampoline_full:
5637 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5638 * create_jit_info_for_trampoline ().
5640 static G_GNUC_UNUSED void
5641 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5643 char start_symbol [256];
5644 char end_symbol [256];
5646 guint32 buf_size, info_offset;
5647 MonoJumpInfo *patch_info;
5658 code_size = info->code_size;
5660 unwind_ops = info->unwind_ops;
5662 #ifdef __native_client_codegen__
5663 mono_nacl_fix_patches (code, ji);
5668 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5670 emit_section_change (acfg, ".text", 0);
5671 emit_global (acfg, start_symbol, TRUE);
5672 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5673 emit_label (acfg, start_symbol);
5675 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5676 emit_label (acfg, symbol);
5679 * The code should access everything through the GOT, so we pass
5682 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5684 emit_symbol_size (acfg, start_symbol, ".");
5687 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5688 emit_label (acfg, end_symbol);
5693 /* Sort relocations */
5694 patches = g_ptr_array_new ();
5695 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5696 if (patch_info->type != MONO_PATCH_INFO_NONE)
5697 g_ptr_array_add (patches, patch_info);
5698 g_ptr_array_sort (patches, compare_patches);
5700 buf_size = patches->len * 128 + 128;
5701 buf = g_malloc (buf_size);
5704 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5705 g_assert (p - buf < buf_size);
5707 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5709 info_offset = add_to_blob (acfg, buf, p - buf);
5711 emit_section_change (acfg, RODATA_SECT, 0);
5712 emit_global (acfg, symbol, FALSE);
5713 emit_label (acfg, symbol);
5715 emit_int32 (acfg, info_offset);
5719 guint32 encoded_len;
5723 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5725 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5726 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5729 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5730 emit_int32 (acfg, uw_offset);
5733 /* Emit debug info */
5737 sprintf (symbol, "%s", name);
5738 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5741 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5745 static G_GNUC_UNUSED void
5746 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5748 emit_trampoline_full (acfg, got_offset, info, FALSE);
5752 emit_trampolines (MonoAotCompile *acfg)
5755 char end_symbol [256];
5756 int i, tramp_got_offset;
5757 MonoAotTrampoline ntype;
5758 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5762 if (!acfg->aot_opts.full_aot)
5765 g_assert (acfg->image->assembly);
5767 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5768 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5769 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5770 MonoTrampInfo *info;
5773 * Emit the generic trampolines.
5775 * We could save some code by treating the generic trampolines as a wrapper
5776 * method, but that approach has its own complexities, so we choose the simpler
5779 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5780 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5781 #ifdef DISABLE_REMOTING
5782 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5785 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5786 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5789 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5790 emit_trampoline (acfg, acfg->got_offset, info);
5793 mono_arch_get_nullified_class_init_trampoline (&info);
5794 emit_trampoline (acfg, acfg->got_offset, info);
5795 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5796 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5797 emit_trampoline (acfg, acfg->got_offset, info);
5798 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5799 emit_trampoline (acfg, acfg->got_offset, info);
5802 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5803 emit_trampoline (acfg, acfg->got_offset, info);
5805 /* Emit the exception related code pieces */
5806 mono_arch_get_restore_context (&info, TRUE);
5807 emit_trampoline (acfg, acfg->got_offset, info);
5808 mono_arch_get_call_filter (&info, TRUE);
5809 emit_trampoline (acfg, acfg->got_offset, info);
5810 mono_arch_get_throw_exception (&info, TRUE);
5811 emit_trampoline (acfg, acfg->got_offset, info);
5812 mono_arch_get_rethrow_exception (&info, TRUE);
5813 emit_trampoline (acfg, acfg->got_offset, info);
5814 mono_arch_get_throw_corlib_exception (&info, TRUE);
5815 emit_trampoline (acfg, acfg->got_offset, info);
5817 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5818 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5820 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5822 /* Create a separate out trampoline for more information in stack traces */
5823 info->name = g_strdup ("gsharedvt_out_trampoline");
5824 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5828 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5830 GSList *l = mono_arch_get_trampolines (TRUE);
5833 MonoTrampInfo *info = l->data;
5835 emit_trampoline (acfg, acfg->got_offset, info);
5841 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5844 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5845 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5846 emit_trampoline (acfg, acfg->got_offset, info);
5848 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5849 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5850 emit_trampoline (acfg, acfg->got_offset, info);
5853 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
5854 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
5855 emit_trampoline (acfg, acfg->got_offset, info);
5861 /* delegate_invoke_impl trampolines */
5862 l = mono_arch_get_delegate_invoke_impls ();
5864 MonoTrampInfo *info = l->data;
5866 emit_trampoline (acfg, acfg->got_offset, info);
5871 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5873 /* Emit trampolines which are numerous */
5876 * These include the following:
5877 * - specific trampolines
5878 * - static rgctx invoke trampolines
5880 * These trampolines have the same code, they are parameterized by GOT
5882 * They are defined in this file, in the arch_... routines instead of
5883 * in tramp-<ARCH>.c, since it is easier to do it this way.
5887 * When running in aot-only mode, we can't create specific trampolines at
5888 * runtime, so we create a few, and save them in the AOT file.
5889 * Normal trampolines embed their argument as a literal inside the
5890 * trampoline code, we can't do that here, so instead we embed an offset
5891 * which needs to be added to the trampoline address to get the address of
5892 * the GOT slot which contains the argument value.
5893 * The generated trampolines jump to the generic trampolines using another
5894 * GOT slot, which will be setup by the AOT loader to point to the
5895 * generic trampoline code of the given type.
5899 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5903 emit_section_change (acfg, ".text", 0);
5905 tramp_got_offset = acfg->got_offset;
5907 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5909 case MONO_AOT_TRAMP_SPECIFIC:
5910 sprintf (symbol, "specific_trampolines");
5912 case MONO_AOT_TRAMP_STATIC_RGCTX:
5913 sprintf (symbol, "static_rgctx_trampolines");
5915 case MONO_AOT_TRAMP_IMT_THUNK:
5916 sprintf (symbol, "imt_thunks");
5918 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5919 sprintf (symbol, "gsharedvt_arg_trampolines");
5922 g_assert_not_reached ();
5925 sprintf (end_symbol, "%s_e", symbol);
5927 if (acfg->aot_opts.write_symbols)
5928 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5930 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5931 emit_label (acfg, symbol);
5933 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5935 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5939 case MONO_AOT_TRAMP_SPECIFIC:
5940 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5941 tramp_got_offset += 2;
5943 case MONO_AOT_TRAMP_STATIC_RGCTX:
5944 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
5945 tramp_got_offset += 2;
5947 case MONO_AOT_TRAMP_IMT_THUNK:
5948 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5949 tramp_got_offset += 1;
5951 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5952 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
5953 tramp_got_offset += 2;
5956 g_assert_not_reached ();
5958 #ifdef __native_client_codegen__
5959 /* align to avoid 32-byte boundary crossings */
5960 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5963 if (!acfg->trampoline_size [ntype]) {
5964 g_assert (tramp_size);
5965 acfg->trampoline_size [ntype] = tramp_size;
5969 emit_label (acfg, end_symbol);
5972 arch_emit_specific_trampoline_pages (acfg);
5974 /* Reserve some entries at the end of the GOT for our use */
5975 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5978 acfg->got_offset += acfg->num_trampoline_got_entries;
5982 str_begins_with (const char *str1, const char *str2)
5984 int len = strlen (str2);
5985 return strncmp (str1, str2, len) == 0;
5989 mono_aot_readonly_field_override (MonoClassField *field)
5992 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5993 char *p = rdv->name;
5995 len = strlen (field->parent->name_space);
5996 if (strncmp (p, field->parent->name_space, len))
6001 len = strlen (field->parent->name);
6002 if (strncmp (p, field->parent->name, len))
6007 if (strcmp (p, field->name))
6009 switch (rdv->type) {
6011 return &rdv->value.i1;
6013 return &rdv->value.i2;
6015 return &rdv->value.i4;
6024 add_readonly_value (MonoAotOptions *opts, const char *val)
6029 /* the format of val is:
6030 * namespace.typename.fieldname=type/value
6031 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6033 fval = strrchr (val, '/');
6035 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6038 tval = strrchr (val, '=');
6040 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6043 rdv = g_new0 (ReadOnlyValue, 1);
6044 rdv->name = g_malloc0 (tval - val + 1);
6045 memcpy (rdv->name, val, tval - val);
6048 if (strncmp (tval, "i1", 2) == 0) {
6049 rdv->value.i1 = atoi (fval);
6050 rdv->type = MONO_TYPE_I1;
6051 } else if (strncmp (tval, "i2", 2) == 0) {
6052 rdv->value.i2 = atoi (fval);
6053 rdv->type = MONO_TYPE_I2;
6054 } else if (strncmp (tval, "i4", 2) == 0) {
6055 rdv->value.i4 = atoi (fval);
6056 rdv->type = MONO_TYPE_I4;
6058 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6061 rdv->next = readonly_values;
6062 readonly_values = rdv;
6066 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6068 gchar **args, **ptr;
6070 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6071 for (ptr = args; ptr && *ptr; ptr ++) {
6072 const char *arg = *ptr;
6074 if (str_begins_with (arg, "outfile=")) {
6075 opts->outfile = g_strdup (arg + strlen ("outfile="));
6076 } else if (str_begins_with (arg, "save-temps")) {
6077 opts->save_temps = TRUE;
6078 } else if (str_begins_with (arg, "keep-temps")) {
6079 opts->save_temps = TRUE;
6080 } else if (str_begins_with (arg, "write-symbols")) {
6081 opts->write_symbols = TRUE;
6082 } else if (str_begins_with (arg, "no-write-symbols")) {
6083 opts->write_symbols = FALSE;
6084 } else if (str_begins_with (arg, "metadata-only")) {
6085 opts->metadata_only = TRUE;
6086 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6087 opts->bind_to_runtime_version = TRUE;
6088 } else if (str_begins_with (arg, "full")) {
6089 opts->full_aot = TRUE;
6090 } else if (str_begins_with (arg, "threads=")) {
6091 opts->nthreads = atoi (arg + strlen ("threads="));
6092 } else if (str_begins_with (arg, "static")) {
6093 opts->static_link = TRUE;
6094 opts->no_dlsym = TRUE;
6095 } else if (str_begins_with (arg, "asmonly")) {
6096 opts->asm_only = TRUE;
6097 } else if (str_begins_with (arg, "asmwriter")) {
6098 opts->asm_writer = TRUE;
6099 } else if (str_begins_with (arg, "nodebug")) {
6100 opts->nodebug = TRUE;
6101 } else if (str_begins_with (arg, "dwarfdebug")) {
6102 opts->dwarf_debug = TRUE;
6103 } else if (str_begins_with (arg, "nopagetrampolines")) {
6104 opts->use_trampolines_page = FALSE;
6105 } else if (str_begins_with (arg, "ntrampolines=")) {
6106 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6107 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6108 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6109 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6110 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6111 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6112 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6113 } else if (str_begins_with (arg, "autoreg")) {
6114 opts->autoreg = TRUE;
6115 } else if (str_begins_with (arg, "tool-prefix=")) {
6116 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6117 } else if (str_begins_with (arg, "soft-debug")) {
6118 opts->soft_debug = TRUE;
6119 } else if (str_begins_with (arg, "direct-pinvoke")) {
6120 opts->direct_pinvoke = TRUE;
6121 } else if (str_begins_with (arg, "direct-icalls")) {
6122 opts->direct_icalls = TRUE;
6123 #if defined(TARGET_ARM)
6124 } else if (str_begins_with (arg, "iphone-abi")) {
6125 // older full-aot users did depend on this.
6127 } else if (str_begins_with (arg, "no-direct-calls")) {
6128 opts->no_direct_calls = TRUE;
6129 } else if (str_begins_with (arg, "print-skipped")) {
6130 opts->print_skipped_methods = TRUE;
6131 } else if (str_begins_with (arg, "stats")) {
6133 } else if (str_begins_with (arg, "no-instances")) {
6134 opts->no_instances = TRUE;
6135 } else if (str_begins_with (arg, "log-generics")) {
6136 opts->log_generics = TRUE;
6137 } else if (str_begins_with (arg, "mtriple=")) {
6138 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6139 } else if (str_begins_with (arg, "llvm-path=")) {
6140 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6141 } else if (str_begins_with (arg, "readonly-value=")) {
6142 add_readonly_value (opts, arg + strlen ("readonly-value="));
6143 } else if (str_begins_with (arg, "info")) {
6144 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6146 } else if (str_begins_with (arg, "gc-maps")) {
6147 mini_gc_enable_gc_maps_for_aot ();
6148 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6149 printf ("Supported options for --aot:\n");
6150 printf (" outfile=\n");
6151 printf (" save-temps\n");
6152 printf (" keep-temps\n");
6153 printf (" write-symbols\n");
6154 printf (" metadata-only\n");
6155 printf (" bind-to-runtime-version\n");
6157 printf (" threads=\n");
6158 printf (" static\n");
6159 printf (" asmonly\n");
6160 printf (" asmwriter\n");
6161 printf (" nodebug\n");
6162 printf (" dwarfdebug\n");
6163 printf (" ntrampolines=\n");
6164 printf (" nrgctx-trampolines=\n");
6165 printf (" nimt-trampolines=\n");
6166 printf (" ngsharedvt-trampolines=\n");
6167 printf (" autoreg\n");
6168 printf (" tool-prefix=\n");
6169 printf (" readonly-value=\n");
6170 printf (" soft-debug\n");
6171 printf (" gc-maps\n");
6172 printf (" print-skipped\n");
6173 printf (" no-instances\n");
6174 printf (" stats\n");
6176 printf (" help/?\n");
6179 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6184 if (opts->use_trampolines_page) {
6185 opts->ntrampolines = 0;
6186 opts->nrgctx_trampolines = 0;
6187 opts->nimt_trampolines = 0;
6188 opts->ngsharedvt_arg_trampolines = 0;
6194 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6196 MonoMethod *method = (MonoMethod*)key;
6197 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6198 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6199 MonoAotCompile *acfg = user_data;
6201 new_ji->image = ji->image;
6202 new_ji->token = ji->token;
6203 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6207 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6209 if (klass->type_token)
6211 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6214 return can_encode_class (acfg, klass->element_class);
6219 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6221 if (method->wrapper_type) {
6222 switch (method->wrapper_type) {
6223 case MONO_WRAPPER_NONE:
6224 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6225 case MONO_WRAPPER_XDOMAIN_INVOKE:
6226 case MONO_WRAPPER_STFLD:
6227 case MONO_WRAPPER_LDFLD:
6228 case MONO_WRAPPER_LDFLDA:
6229 case MONO_WRAPPER_LDFLD_REMOTE:
6230 case MONO_WRAPPER_STFLD_REMOTE:
6231 case MONO_WRAPPER_STELEMREF:
6232 case MONO_WRAPPER_ISINST:
6233 case MONO_WRAPPER_PROXY_ISINST:
6234 case MONO_WRAPPER_ALLOC:
6235 case MONO_WRAPPER_REMOTING_INVOKE:
6236 case MONO_WRAPPER_UNKNOWN:
6237 case MONO_WRAPPER_WRITE_BARRIER:
6238 case MONO_WRAPPER_DELEGATE_INVOKE:
6239 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6240 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6241 case MONO_WRAPPER_SYNCHRONIZED:
6243 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6244 case MONO_WRAPPER_CASTCLASS: {
6245 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6254 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6258 if (!method->token) {
6259 /* The method is part of a constructed type like Int[,].Set (). */
6260 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6261 if (method->klass->rank)
6271 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6273 switch (patch_info->type) {
6274 case MONO_PATCH_INFO_METHOD:
6275 case MONO_PATCH_INFO_METHODCONST: {
6276 MonoMethod *method = patch_info->data.method;
6278 return can_encode_method (acfg, method);
6280 case MONO_PATCH_INFO_VTABLE:
6281 case MONO_PATCH_INFO_CLASS_INIT:
6282 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6283 case MONO_PATCH_INFO_CLASS:
6284 case MONO_PATCH_INFO_IID:
6285 case MONO_PATCH_INFO_ADJUSTED_IID:
6286 if (!can_encode_class (acfg, patch_info->data.klass)) {
6287 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6291 case MONO_PATCH_INFO_RGCTX_FETCH: {
6292 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6294 if (!can_encode_method (acfg, entry->method))
6296 if (!can_encode_patch (acfg, entry->data))
6310 * AOT compile a given method.
6311 * This function might be called by multiple threads, so it must be thread-safe.
6314 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6317 MonoJumpInfo *patch_info;
6320 MonoMethod *wrapped;
6322 if (acfg->aot_opts.metadata_only)
6325 mono_acfg_lock (acfg);
6326 index = get_method_index (acfg, method);
6327 mono_acfg_unlock (acfg);
6329 /* fixme: maybe we can also precompile wrapper methods */
6330 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6331 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6332 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6333 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6337 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6340 wrapped = mono_marshal_method_from_wrapper (method);
6341 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6342 // FIXME: The wrapper should be generic too, but it is not
6345 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6348 InterlockedIncrement (&acfg->stats.mcount);
6351 if (method->is_generic || method->klass->generic_container) {
6352 InterlockedIncrement (&acfg->stats.genericcount);
6357 //acfg->aot_opts.print_skipped_methods = TRUE;
6360 * Since these methods are the only ones which are compiled with
6361 * AOT support, and they are not used by runtime startup/shutdown code,
6362 * the runtime will not see AOT methods during AOT compilation,so it
6363 * does not need to support them by creating a fake GOT etc.
6365 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
6366 mono_loader_clear_error ();
6368 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6369 if (acfg->aot_opts.print_skipped_methods)
6370 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6371 InterlockedIncrement (&acfg->stats.genericcount);
6374 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6375 if (acfg->aot_opts.print_skipped_methods)
6376 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6377 /* Let the exception happen at runtime */
6381 if (cfg->disable_aot) {
6382 if (acfg->aot_opts.print_skipped_methods)
6383 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6384 InterlockedIncrement (&acfg->stats.ocount);
6385 mono_destroy_compile (cfg);
6388 cfg->method_index = index;
6390 /* Nullify patches which need no aot processing */
6391 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6392 switch (patch_info->type) {
6393 case MONO_PATCH_INFO_LABEL:
6394 case MONO_PATCH_INFO_BB:
6395 patch_info->type = MONO_PATCH_INFO_NONE;
6402 /* Collect method->token associations from the cfg */
6403 mono_acfg_lock (acfg);
6404 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6405 mono_acfg_unlock (acfg);
6408 * Check for absolute addresses.
6411 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6412 switch (patch_info->type) {
6413 case MONO_PATCH_INFO_ABS:
6414 /* unable to handle this */
6423 if (acfg->aot_opts.print_skipped_methods)
6424 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6425 InterlockedIncrement (&acfg->stats.abscount);
6426 mono_destroy_compile (cfg);
6430 /* Lock for the rest of the code */
6431 mono_acfg_lock (acfg);
6434 * Check for methods/klasses we can't encode.
6437 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6438 if (!can_encode_patch (acfg, patch_info))
6443 if (acfg->aot_opts.print_skipped_methods)
6444 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6445 acfg->stats.ocount++;
6446 mono_destroy_compile (cfg);
6447 mono_acfg_unlock (acfg);
6451 /* Adds generic instances referenced by this method */
6453 * The depth is used to avoid infinite loops when generic virtual recursion is
6456 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6457 if (!acfg->aot_opts.no_instances && depth < 32) {
6458 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6459 switch (patch_info->type) {
6460 case MONO_PATCH_INFO_METHOD: {
6461 MonoMethod *m = patch_info->data.method;
6462 if (m->is_inflated) {
6463 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6464 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6465 !method_has_type_vars (m)) {
6466 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6467 if (acfg->aot_opts.full_aot)
6468 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6470 add_extra_method_with_depth (acfg, m, depth + 1);
6471 add_types_from_method_header (acfg, m);
6474 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6476 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6477 add_extra_method_with_depth (acfg, m, depth + 1);
6480 case MONO_PATCH_INFO_VTABLE: {
6481 MonoClass *klass = patch_info->data.klass;
6483 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6484 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6487 case MONO_PATCH_INFO_SFLDA: {
6488 MonoClass *klass = patch_info->data.field->parent;
6490 /* The .cctor needs to run at runtime. */
6491 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6492 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6501 /* Determine whenever the method has GOT slots */
6502 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6503 switch (patch_info->type) {
6504 case MONO_PATCH_INFO_GOT_OFFSET:
6505 case MONO_PATCH_INFO_NONE:
6506 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6508 case MONO_PATCH_INFO_IMAGE:
6509 /* The assembly is stored in GOT slot 0 */
6510 if (patch_info->data.image != acfg->image)
6511 cfg->has_got_slots = TRUE;
6514 if (!is_plt_patch (patch_info))
6515 cfg->has_got_slots = TRUE;
6520 if (!cfg->has_got_slots)
6521 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6524 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6526 /* Make a copy of the patch info which is in the mempool */
6528 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6530 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6531 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6534 patches = new_patch_info;
6536 patches_end->next = new_patch_info;
6537 patches_end = new_patch_info;
6539 cfg->patch_info = patches;
6541 /* Make a copy of the unwind info */
6543 GSList *l, *unwind_ops;
6547 for (l = cfg->unwind_ops; l; l = l->next) {
6548 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6549 memcpy (op, l->data, sizeof (MonoUnwindOp));
6550 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6552 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6554 /* Make a copy of the argument/local info */
6556 MonoInst **args, **locals;
6557 MonoMethodSignature *sig;
6558 MonoMethodHeader *header;
6561 sig = mono_method_signature (method);
6562 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6563 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6564 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6565 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6569 header = mono_method_get_header (method);
6570 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6571 for (i = 0; i < header->num_locals; ++i) {
6572 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6573 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6575 cfg->locals = locals;
6578 /* Free some fields used by cfg to conserve memory */
6579 mono_mempool_destroy (cfg->mempool);
6580 cfg->mempool = NULL;
6581 g_free (cfg->varinfo);
6582 cfg->varinfo = NULL;
6586 mono_regstate_free (cfg->rs);
6590 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6592 while (index >= acfg->cfgs_size) {
6593 MonoCompile **new_cfgs;
6596 new_size = acfg->cfgs_size * 2;
6597 new_cfgs = g_new0 (MonoCompile*, new_size);
6598 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6599 g_free (acfg->cfgs);
6600 acfg->cfgs = new_cfgs;
6601 acfg->cfgs_size = new_size;
6603 acfg->cfgs [index] = cfg;
6605 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6608 if (cfg->orig_method->wrapper_type)
6609 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6612 mono_acfg_unlock (acfg);
6614 InterlockedIncrement (&acfg->stats.ccount);
6618 compile_thread_main (gpointer *user_data)
6620 MonoDomain *domain = user_data [0];
6621 MonoAotCompile *acfg = user_data [1];
6622 GPtrArray *methods = user_data [2];
6625 mono_thread_attach (domain);
6627 for (i = 0; i < methods->len; ++i)
6628 compile_method (acfg, g_ptr_array_index (methods, i));
6632 load_profile_files (MonoAotCompile *acfg)
6636 int file_index, res, method_index, i;
6639 GList *unordered, *l;
6644 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6646 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6651 infile = fopen (tmp, "r");
6654 printf ("Using profile data file '%s'\n", tmp);
6659 res = fscanf (infile, "%32s\n", ver);
6660 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6661 printf ("Profile file has wrong version or invalid.\n");
6668 MonoMethodDesc *desc;
6671 if (fgets (name, 1023, infile) == NULL)
6674 /* Kill the newline */
6675 if (strlen (name) > 0)
6676 name [strlen (name) - 1] = '\0';
6678 desc = mono_method_desc_new (name, TRUE);
6680 method = mono_method_desc_search_in_image (desc, acfg->image);
6682 if (method && mono_method_get_token (method)) {
6683 token = mono_method_get_token (method);
6684 method_index = mono_metadata_token_index (token) - 1;
6687 for (i = 0; i < acfg->method_order->len; ++i) {
6688 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6694 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6696 //printf ("No method found matching '%s'.\n", name);
6702 /* Add missing methods */
6704 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6706 for (i = 0; i < acfg->method_order->len; ++i) {
6707 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6713 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6715 unordered = g_list_reverse (unordered);
6716 for (l = unordered; l; l = l->next)
6717 g_ptr_array_add (acfg->method_order, l->data);
6720 /* Used by the LLVM backend */
6722 mono_aot_get_got_offset (MonoJumpInfo *ji)
6724 return get_got_offset (llvm_acfg, ji);
6728 mono_aot_get_method_name (MonoCompile *cfg)
6730 if (llvm_acfg->aot_opts.static_link)
6731 /* Include the assembly name too to avoid duplicate symbol errors */
6732 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6734 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6738 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6740 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6741 MonoPltEntry *plt_entry;
6744 ji->data.target = data;
6746 if (!can_encode_patch (llvm_acfg, ji))
6749 plt_entry = get_plt_entry (llvm_acfg, ji);
6750 plt_entry->llvm_used = TRUE;
6752 #if defined(TARGET_MACH)
6753 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6755 return g_strdup_printf (plt_entry->llvm_symbol);
6760 mono_aot_get_method_index (MonoMethod *method)
6762 g_assert (llvm_acfg);
6763 return get_method_index (llvm_acfg, method);
6767 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6771 mono_acfg_lock (llvm_acfg);
6772 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6773 mono_acfg_unlock (llvm_acfg);
6783 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6787 emit_llvm_file (MonoAotCompile *acfg)
6789 char *command, *opts, *tempbc;
6791 MonoJumpInfo *patch_info;
6794 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6798 /* Compute the final size of the got */
6799 for (i = 0; i < acfg->nmethods; ++i) {
6800 if (acfg->cfgs [i]) {
6801 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6802 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6803 if (!is_plt_patch (patch_info))
6804 get_got_offset (acfg, patch_info);
6806 get_plt_entry (acfg, patch_info);
6812 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6814 if (acfg->aot_opts.full_aot) {
6818 * Need to add the got entries used by the trampolines.
6819 * This is only a conservative approximation.
6821 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6822 /* For the generic + rgctx trampolines */
6823 acfg->final_got_size += 400;
6824 /* For the specific trampolines */
6825 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6826 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6831 tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
6832 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6836 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6837 * a lot of time, and doesn't seem to save much space.
6838 * The following optimizations cannot be enabled:
6840 * - 'jump-threading' changes our blockaddress references to int constants.
6841 * - 'basiccg' fails because it contains:
6842 * if (CS && !isa<IntrinsicInst>(II)) {
6843 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
6844 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
6845 * The opt list below was produced by taking the output of:
6846 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
6847 * then removing tailcallelim + the global opts, and adding a second gvn.
6849 opts = g_strdup ("-instcombine -simplifycfg");
6850 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");
6852 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
6853 printf ("Executing opt: %s\n", command);
6854 if (system (command) != 0) {
6860 if (!acfg->llc_args)
6861 acfg->llc_args = g_string_new ("");
6863 /* Verbose asm slows down llc greatly */
6864 g_string_append (acfg->llc_args, " -asm-verbose=false");
6866 if (acfg->aot_opts.mtriple)
6867 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
6869 #if defined(TARGET_MACH) && defined(TARGET_ARM)
6870 /* ios requires PIC code now */
6871 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6873 if (llvm_acfg->aot_opts.static_link)
6874 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
6876 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6878 unlink (acfg->tmpfname);
6880 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpfname);
6882 printf ("Executing llc: %s\n", command);
6884 if (system (command) != 0) {
6891 emit_code (MonoAotCompile *acfg)
6893 int oindex, i, prev_index;
6895 char end_symbol [256];
6897 #if defined(TARGET_POWERPC64)
6898 sprintf (symbol, ".Lgot_addr");
6899 emit_section_change (acfg, ".text", 0);
6900 emit_alignment (acfg, 8);
6901 emit_label (acfg, symbol);
6902 emit_pointer (acfg, acfg->got_symbol);
6906 * This global symbol is used to compute the address of each method using the
6907 * code_offsets array. It is also used to compute the memory ranges occupied by
6908 * AOT code, so it must be equal to the address of the first emitted method.
6910 sprintf (symbol, "methods");
6911 emit_section_change (acfg, ".text", 0);
6912 emit_alignment (acfg, 8);
6914 for (i = 0; i < acfg->nmethods; ++i) {
6915 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
6916 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
6920 if (i == acfg->nmethods)
6921 /* No LLVM compiled methods */
6922 emit_label (acfg, symbol);
6924 emit_label (acfg, symbol);
6928 * Emit some padding so the local symbol for the first method doesn't have the
6929 * same address as 'methods'.
6931 #if defined(__default_codegen__)
6932 emit_zero_bytes (acfg, 16);
6933 #elif defined(__native_client_codegen__)
6935 const int kPaddingSize = 16;
6936 guint8 pad_buffer[kPaddingSize];
6937 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
6938 emit_bytes (acfg, pad_buffer, kPaddingSize);
6942 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6946 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6948 cfg = acfg->cfgs [i];
6953 method = cfg->orig_method;
6955 /* Emit unbox trampoline */
6956 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
6957 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
6959 emit_section_change (acfg, ".text", 0);
6960 #ifdef __native_client_codegen__
6961 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6964 if (acfg->thumb_mixed && cfg->compile_llvm) {
6965 emit_set_thumb_mode (acfg);
6966 fprintf (acfg->fp, "\n.thumb_func\n");
6969 emit_label (acfg, symbol);
6971 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
6973 if (acfg->thumb_mixed && cfg->compile_llvm) {
6974 emit_set_arm_mode (acfg);
6978 if (cfg->compile_llvm)
6979 acfg->stats.llvm_count ++;
6981 emit_method_code (acfg, cfg);
6984 sprintf (symbol, "methods_end");
6985 emit_section_change (acfg, ".text", 0);
6986 emit_alignment (acfg, 8);
6987 emit_label (acfg, symbol);
6988 /* To distinguish it from the next symbol */
6989 emit_int32 (acfg, 0);
6992 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6993 * from optimizing them away, since it doesn't see that code_offsets references them.
6994 * JITted methods don't need this since they are referenced using assembler local
6996 * FIXME: This is why write-symbols doesn't work on OSX ?
6998 if (acfg->llvm && acfg->need_no_dead_strip) {
6999 fprintf (acfg->fp, "\n");
7000 for (i = 0; i < acfg->nmethods; ++i) {
7001 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7002 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7007 if (acfg->direct_method_addresses) {
7008 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7011 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7012 * This is PIE code, and the linker can update it if needed.
7014 sprintf (symbol, "method_addresses");
7015 emit_section_change (acfg, ".text", 1);
7016 emit_alignment (acfg, 8);
7017 emit_label (acfg, symbol);
7018 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7019 emit_unset_mode (acfg);
7020 if (acfg->need_no_dead_strip)
7021 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7023 for (i = 0; i < acfg->nmethods; ++i) {
7024 if (acfg->cfgs [i]) {
7025 if (acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm)
7026 fprintf (acfg->fp, "\tblx %s\n", acfg->cfgs [i]->asm_symbol);
7028 fprintf (acfg->fp, "\tbl %s\n", acfg->cfgs [i]->asm_symbol);
7030 fprintf (acfg->fp, "\tbl method_addresses\n");
7034 sprintf (symbol, "method_addresses_end");
7035 emit_label (acfg, symbol);
7038 sprintf (symbol, "code_offsets");
7039 emit_section_change (acfg, RODATA_SECT, 1);
7040 emit_alignment (acfg, 8);
7041 emit_label (acfg, symbol);
7042 emit_int32 (acfg, 0);
7044 sprintf (symbol, "code_offsets");
7045 emit_section_change (acfg, RODATA_SECT, 1);
7046 emit_alignment (acfg, 8);
7047 emit_label (acfg, symbol);
7049 acfg->stats.offsets_size += acfg->nmethods * 4;
7051 sprintf (end_symbol, "methods");
7052 for (i = 0; i < acfg->nmethods; ++i) {
7053 if (acfg->cfgs [i]) {
7054 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
7056 emit_int32 (acfg, 0xffffffff);
7061 sprintf (symbol, "code_offsets");
7062 emit_section_change (acfg, RODATA_SECT, 1);
7063 emit_alignment (acfg, 8);
7064 emit_label (acfg, symbol);
7066 acfg->stats.offsets_size += acfg->nmethods * 4;
7068 sprintf (end_symbol, "methods");
7069 for (i = 0; i < acfg->nmethods; ++i) {
7070 if (acfg->cfgs [i]) {
7071 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
7073 emit_int32 (acfg, 0xffffffff);
7079 /* Emit a sorted table mapping methods to their unbox trampolines */
7080 sprintf (symbol, "unbox_trampolines");
7081 if (acfg->direct_method_addresses)
7082 emit_section_change (acfg, ".text", 0);
7084 emit_section_change (acfg, RODATA_SECT, 0);
7085 emit_alignment (acfg, 8);
7086 emit_label (acfg, symbol);
7088 sprintf (end_symbol, "methods");
7090 for (i = 0; i < acfg->nmethods; ++i) {
7095 cfg = acfg->cfgs [i];
7099 method = cfg->orig_method;
7101 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7102 index = get_method_index (acfg, method);
7103 sprintf (symbol, "ut_%d", index);
7105 emit_int32 (acfg, index);
7106 if (acfg->direct_method_addresses) {
7107 emit_unset_mode (acfg);
7108 if (acfg->thumb_mixed && cfg->compile_llvm)
7109 fprintf (acfg->fp, "\n\tblx %s\n", symbol);
7111 fprintf (acfg->fp, "\n\tbl %s\n", symbol);
7113 emit_symbol_diff (acfg, symbol, end_symbol, 0);
7115 /* Make sure the table is sorted by index */
7116 g_assert (index > prev_index);
7120 sprintf (symbol, "unbox_trampolines_end");
7121 emit_label (acfg, symbol);
7125 emit_info (MonoAotCompile *acfg)
7131 offsets = g_new0 (gint32, acfg->nmethods);
7133 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7134 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7136 if (acfg->cfgs [i]) {
7137 emit_method_info (acfg, acfg->cfgs [i]);
7138 offsets [i] = acfg->cfgs [i]->method_info_offset;
7144 sprintf (symbol, "method_info_offsets");
7145 emit_section_change (acfg, RODATA_SECT, 1);
7146 emit_alignment (acfg, 8);
7147 emit_label (acfg, symbol);
7149 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7154 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7156 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7157 #define mix(a,b,c) { \
7158 a -= c; a ^= rot(c, 4); c += b; \
7159 b -= a; b ^= rot(a, 6); a += c; \
7160 c -= b; c ^= rot(b, 8); b += a; \
7161 a -= c; a ^= rot(c,16); c += b; \
7162 b -= a; b ^= rot(a,19); a += c; \
7163 c -= b; c ^= rot(b, 4); b += a; \
7165 #define final(a,b,c) { \
7166 c ^= b; c -= rot(b,14); \
7167 a ^= c; a -= rot(c,11); \
7168 b ^= a; b -= rot(a,25); \
7169 c ^= b; c -= rot(b,16); \
7170 a ^= c; a -= rot(c,4); \
7171 b ^= a; b -= rot(a,14); \
7172 c ^= b; c -= rot(b,24); \
7176 mono_aot_type_hash (MonoType *t1)
7178 guint hash = t1->type;
7180 hash |= t1->byref << 6; /* do not collide with t1->type values */
7182 case MONO_TYPE_VALUETYPE:
7183 case MONO_TYPE_CLASS:
7184 case MONO_TYPE_SZARRAY:
7185 /* check if the distribution is good enough */
7186 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7188 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7189 case MONO_TYPE_ARRAY:
7190 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7191 case MONO_TYPE_GENERICINST:
7192 return ((hash << 5) - hash) ^ 0;
7199 * mono_aot_method_hash:
7201 * Return a hash code for methods which only depends on metadata.
7204 mono_aot_method_hash (MonoMethod *method)
7206 MonoMethodSignature *sig;
7210 guint32 *hashes_start, *hashes;
7212 MonoGenericInst *ginst = NULL;
7214 /* Similar to the hash in mono_method_get_imt_slot () */
7216 sig = mono_method_signature (method);
7218 if (method->is_inflated)
7219 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7221 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7222 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7223 hashes = hashes_start;
7225 /* Some wrappers are assigned to random classes */
7226 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7227 klass = method->klass;
7229 klass = mono_defaults.object_class;
7231 if (!method->wrapper_type) {
7232 char *full_name = mono_type_full_name (&klass->byval_arg);
7234 hashes [0] = mono_metadata_str_hash (full_name);
7238 hashes [0] = mono_metadata_str_hash (klass->name);
7239 hashes [1] = mono_metadata_str_hash (klass->name_space);
7241 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7242 /* The method name includes a stringified pointer */
7245 hashes [2] = mono_metadata_str_hash (method->name);
7246 hashes [3] = method->wrapper_type;
7247 hashes [4] = mono_aot_type_hash (sig->ret);
7249 for (i = 0; i < sig->param_count; i++) {
7250 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7253 for (i = 0; i < ginst->type_argc; ++i)
7254 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7256 g_assert (hindex == hashes_count);
7258 /* Setup internal state */
7259 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7261 /* Handle most of the hashes */
7262 while (hashes_count > 3) {
7271 /* Handle the last 3 hashes (all the case statements fall through) */
7272 switch (hashes_count) {
7273 case 3 : c += hashes [2];
7274 case 2 : b += hashes [1];
7275 case 1 : a += hashes [0];
7277 case 0: /* nothing left to add */
7281 free (hashes_start);
7290 * mono_aot_get_array_helper_from_wrapper;
7292 * Get the helper method in Array called by an array wrapper method.
7295 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7299 MonoGenericContext ctx;
7300 MonoType *args [16];
7301 char *mname, *iname, *s, *s2, *helper_name = NULL;
7303 prefix = "System.Collections.Generic";
7304 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7305 s2 = strstr (s, "`1.");
7311 //printf ("X: %s %s\n", iname, mname);
7313 if (!strcmp (iname, "IList"))
7314 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7316 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7317 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7319 g_free (helper_name);
7322 if (m->is_generic) {
7323 memset (&ctx, 0, sizeof (ctx));
7324 args [0] = &method->klass->element_class->byval_arg;
7325 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7326 m = mono_class_inflate_generic_method (m, &ctx);
7332 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7334 typedef struct HashEntry {
7335 guint32 key, value, index;
7336 struct HashEntry *next;
7340 * emit_extra_methods:
7342 * Emit methods which are not in the METHOD table, like wrappers.
7345 emit_extra_methods (MonoAotCompile *acfg)
7347 int i, table_size, buf_size;
7350 guint32 *info_offsets;
7353 HashEntry *entry, *new_entry;
7354 int nmethods, max_chain_length;
7357 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7359 /* Emit method info */
7361 for (i = 0; i < acfg->extra_methods->len; ++i) {
7362 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7363 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7369 p = buf = g_malloc (buf_size);
7373 method = cfg->method_to_register;
7375 encode_method_ref (acfg, method, p, &p);
7377 g_assert ((p - buf) < buf_size);
7379 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7384 * Construct a chained hash table for mapping indexes in extra_method_info to
7387 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7388 table = g_ptr_array_sized_new (table_size);
7389 for (i = 0; i < table_size; ++i)
7390 g_ptr_array_add (table, NULL);
7391 chain_lengths = g_new0 (int, table_size);
7392 max_chain_length = 0;
7393 for (i = 0; i < acfg->extra_methods->len; ++i) {
7394 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7395 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7401 key = info_offsets [i];
7402 value = get_method_index (acfg, method);
7404 hash = mono_aot_method_hash (method) % table_size;
7405 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7407 chain_lengths [hash] ++;
7408 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7410 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7411 new_entry->key = key;
7412 new_entry->value = value;
7414 entry = g_ptr_array_index (table, hash);
7415 if (entry == NULL) {
7416 new_entry->index = hash;
7417 g_ptr_array_index (table, hash) = new_entry;
7420 entry = entry->next;
7422 entry->next = new_entry;
7423 new_entry->index = table->len;
7424 g_ptr_array_add (table, new_entry);
7428 //printf ("MAX: %d\n", max_chain_length);
7430 /* Emit the table */
7431 sprintf (symbol, "extra_method_table");
7432 emit_section_change (acfg, RODATA_SECT, 0);
7433 emit_alignment (acfg, 8);
7434 emit_label (acfg, symbol);
7436 emit_int32 (acfg, table_size);
7437 for (i = 0; i < table->len; ++i) {
7438 HashEntry *entry = g_ptr_array_index (table, i);
7440 if (entry == NULL) {
7441 emit_int32 (acfg, 0);
7442 emit_int32 (acfg, 0);
7443 emit_int32 (acfg, 0);
7445 //g_assert (entry->key > 0);
7446 emit_int32 (acfg, entry->key);
7447 emit_int32 (acfg, entry->value);
7449 emit_int32 (acfg, entry->next->index);
7451 emit_int32 (acfg, 0);
7456 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7457 * This is used by mono_aot_find_jit_info ().
7459 sprintf (symbol, "extra_method_info_offsets");
7460 emit_section_change (acfg, RODATA_SECT, 0);
7461 emit_alignment (acfg, 8);
7462 emit_label (acfg, symbol);
7464 emit_int32 (acfg, acfg->extra_methods->len);
7465 for (i = 0; i < acfg->extra_methods->len; ++i) {
7466 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7468 emit_int32 (acfg, get_method_index (acfg, method));
7469 emit_int32 (acfg, info_offsets [i]);
7474 emit_exception_info (MonoAotCompile *acfg)
7480 offsets = g_new0 (gint32, acfg->nmethods);
7481 for (i = 0; i < acfg->nmethods; ++i) {
7482 if (acfg->cfgs [i]) {
7483 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7484 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7490 sprintf (symbol, "ex_info_offsets");
7491 emit_section_change (acfg, RODATA_SECT, 1);
7492 emit_alignment (acfg, 8);
7493 emit_label (acfg, symbol);
7495 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7500 emit_unwind_info (MonoAotCompile *acfg)
7506 * The unwind info contains a lot of duplicates so we emit each unique
7507 * entry once, and only store the offset from the start of the table in the
7511 sprintf (symbol, "unwind_info");
7512 emit_section_change (acfg, RODATA_SECT, 1);
7513 emit_alignment (acfg, 8);
7514 emit_label (acfg, symbol);
7516 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7517 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7518 guint8 *unwind_info;
7519 guint32 unwind_info_len;
7523 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7526 encode_value (unwind_info_len, p, &p);
7527 emit_bytes (acfg, buf, p - buf);
7528 emit_bytes (acfg, unwind_info, unwind_info_len);
7530 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7535 emit_class_info (MonoAotCompile *acfg)
7541 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7542 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7543 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7545 sprintf (symbol, "class_info_offsets");
7546 emit_section_change (acfg, RODATA_SECT, 1);
7547 emit_alignment (acfg, 8);
7548 emit_label (acfg, symbol);
7550 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7554 typedef struct ClassNameTableEntry {
7555 guint32 token, index;
7556 struct ClassNameTableEntry *next;
7557 } ClassNameTableEntry;
7560 emit_class_name_table (MonoAotCompile *acfg)
7563 guint32 token, hash;
7568 ClassNameTableEntry *entry, *new_entry;
7571 * Construct a chained hash table for mapping class names to typedef tokens.
7573 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7574 table = g_ptr_array_sized_new (table_size);
7575 for (i = 0; i < table_size; ++i)
7576 g_ptr_array_add (table, NULL);
7577 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7578 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7579 klass = mono_class_get (acfg->image, token);
7581 mono_loader_clear_error ();
7584 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7585 hash = mono_metadata_str_hash (full_name) % table_size;
7588 /* FIXME: Allocate from the mempool */
7589 new_entry = g_new0 (ClassNameTableEntry, 1);
7590 new_entry->token = token;
7592 entry = g_ptr_array_index (table, hash);
7593 if (entry == NULL) {
7594 new_entry->index = hash;
7595 g_ptr_array_index (table, hash) = new_entry;
7598 entry = entry->next;
7600 entry->next = new_entry;
7601 new_entry->index = table->len;
7602 g_ptr_array_add (table, new_entry);
7606 /* Emit the table */
7607 sprintf (symbol, "class_name_table");
7608 emit_section_change (acfg, RODATA_SECT, 0);
7609 emit_alignment (acfg, 8);
7610 emit_label (acfg, symbol);
7612 /* FIXME: Optimize memory usage */
7613 g_assert (table_size < 65000);
7614 emit_int16 (acfg, table_size);
7615 g_assert (table->len < 65000);
7616 for (i = 0; i < table->len; ++i) {
7617 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7619 if (entry == NULL) {
7620 emit_int16 (acfg, 0);
7621 emit_int16 (acfg, 0);
7623 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7625 emit_int16 (acfg, entry->next->index);
7627 emit_int16 (acfg, 0);
7633 emit_image_table (MonoAotCompile *acfg)
7639 * The image table is small but referenced in a lot of places.
7640 * So we emit it at once, and reference its elements by an index.
7643 sprintf (symbol, "image_table");
7644 emit_section_change (acfg, RODATA_SECT, 1);
7645 emit_alignment (acfg, 8);
7646 emit_label (acfg, symbol);
7648 emit_int32 (acfg, acfg->image_table->len);
7649 for (i = 0; i < acfg->image_table->len; i++) {
7650 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7651 MonoAssemblyName *aname = &image->assembly->aname;
7653 /* FIXME: Support multi-module assemblies */
7654 g_assert (image->assembly->image == image);
7656 emit_string (acfg, image->assembly_name);
7657 emit_string (acfg, image->guid);
7658 emit_string (acfg, aname->culture ? aname->culture : "");
7659 emit_string (acfg, (const char*)aname->public_key_token);
7661 emit_alignment (acfg, 8);
7662 emit_int32 (acfg, aname->flags);
7663 emit_int32 (acfg, aname->major);
7664 emit_int32 (acfg, aname->minor);
7665 emit_int32 (acfg, aname->build);
7666 emit_int32 (acfg, aname->revision);
7671 emit_got_info (MonoAotCompile *acfg)
7674 int i, first_plt_got_patch, buf_size;
7676 guint32 *got_info_offsets;
7678 /* Add the patches needed by the PLT to the GOT */
7679 acfg->plt_got_offset_base = acfg->got_offset;
7680 first_plt_got_patch = acfg->got_patches->len;
7681 for (i = 1; i < acfg->plt_offset; ++i) {
7682 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7684 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7686 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7689 acfg->got_offset += acfg->plt_offset;
7693 * - optimize offsets table.
7694 * - reduce number of exported symbols.
7695 * - emit info for a klass only once.
7696 * - determine when a method uses a GOT slot which is guaranteed to be already
7698 * - clean up and document the code.
7699 * - use String.Empty in class libs.
7702 /* Encode info required to decode shared GOT entries */
7703 buf_size = acfg->got_patches->len * 128;
7704 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7705 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7706 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7708 if (acfg->plt_offset)
7709 acfg->plt_got_info_offsets [0] = 0;
7710 for (i = 0; i < acfg->got_patches->len; ++i) {
7711 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7716 encode_value (ji->type, p, &p);
7718 encode_patch (acfg, ji, p, &p);
7719 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7720 g_assert (p - buf <= buf_size);
7721 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7723 if (i >= first_plt_got_patch)
7724 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7725 acfg->stats.got_info_size += p - buf;
7728 /* Emit got_info_offsets table */
7729 sprintf (symbol, "got_info_offsets");
7730 emit_section_change (acfg, RODATA_SECT, 1);
7731 emit_alignment (acfg, 8);
7732 emit_label (acfg, symbol);
7734 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7735 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7739 emit_got (MonoAotCompile *acfg)
7744 /* Don't make GOT global so accesses to it don't need relocations */
7745 sprintf (symbol, "%s", acfg->got_symbol);
7746 emit_section_change (acfg, ".bss", 0);
7747 emit_alignment (acfg, 8);
7748 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7749 emit_label (acfg, symbol);
7750 if (acfg->got_offset > 0)
7751 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7753 sprintf (symbol, "got_end");
7754 emit_label (acfg, symbol);
7758 typedef struct GlobalsTableEntry {
7759 guint32 value, index;
7760 struct GlobalsTableEntry *next;
7761 } GlobalsTableEntry;
7764 emit_globals (MonoAotCompile *acfg)
7770 GlobalsTableEntry *entry, *new_entry;
7772 if (!acfg->aot_opts.static_link)
7776 * When static linking, we emit a table containing our globals.
7780 * Construct a chained hash table for mapping global names to their index in
7781 * the globals table.
7783 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7784 table = g_ptr_array_sized_new (table_size);
7785 for (i = 0; i < table_size; ++i)
7786 g_ptr_array_add (table, NULL);
7787 for (i = 0; i < acfg->globals->len; ++i) {
7788 char *name = g_ptr_array_index (acfg->globals, i);
7790 hash = mono_metadata_str_hash (name) % table_size;
7792 /* FIXME: Allocate from the mempool */
7793 new_entry = g_new0 (GlobalsTableEntry, 1);
7794 new_entry->value = i;
7796 entry = g_ptr_array_index (table, hash);
7797 if (entry == NULL) {
7798 new_entry->index = hash;
7799 g_ptr_array_index (table, hash) = new_entry;
7802 entry = entry->next;
7804 entry->next = new_entry;
7805 new_entry->index = table->len;
7806 g_ptr_array_add (table, new_entry);
7810 /* Emit the table */
7811 sprintf (symbol, ".Lglobals_hash");
7812 emit_section_change (acfg, RODATA_SECT, 0);
7813 emit_alignment (acfg, 8);
7814 emit_label (acfg, symbol);
7816 /* FIXME: Optimize memory usage */
7817 g_assert (table_size < 65000);
7818 emit_int16 (acfg, table_size);
7819 for (i = 0; i < table->len; ++i) {
7820 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7822 if (entry == NULL) {
7823 emit_int16 (acfg, 0);
7824 emit_int16 (acfg, 0);
7826 emit_int16 (acfg, entry->value + 1);
7828 emit_int16 (acfg, entry->next->index);
7830 emit_int16 (acfg, 0);
7834 /* Emit the names */
7835 for (i = 0; i < acfg->globals->len; ++i) {
7836 char *name = g_ptr_array_index (acfg->globals, i);
7838 sprintf (symbol, "name_%d", i);
7839 emit_section_change (acfg, RODATA_SECT, 1);
7841 emit_alignment (acfg, 4);
7843 emit_label (acfg, symbol);
7844 emit_string (acfg, name);
7847 /* Emit the globals table */
7848 sprintf (symbol, "globals");
7849 emit_section_change (acfg, ".data", 0);
7850 /* This is not a global, since it is accessed by the init function */
7851 emit_alignment (acfg, 8);
7852 emit_label (acfg, symbol);
7854 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
7855 emit_pointer (acfg, symbol);
7857 for (i = 0; i < acfg->globals->len; ++i) {
7858 char *name = g_ptr_array_index (acfg->globals, i);
7860 sprintf (symbol, "name_%d", i);
7861 emit_pointer (acfg, symbol);
7863 sprintf (symbol, "%s", name);
7864 emit_pointer (acfg, symbol);
7866 /* Null terminate the table */
7867 emit_int32 (acfg, 0);
7868 emit_int32 (acfg, 0);
7872 emit_autoreg (MonoAotCompile *acfg)
7877 * Emit a function into the .ctor section which will be called by the ELF
7878 * loader to register this module with the runtime.
7880 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
7883 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
7885 arch_emit_autoreg (acfg, symbol);
7891 emit_mem_end (MonoAotCompile *acfg)
7895 sprintf (symbol, "mem_end");
7896 emit_section_change (acfg, ".text", 1);
7897 emit_alignment (acfg, 8);
7898 emit_label (acfg, symbol);
7902 * Emit a structure containing all the information not stored elsewhere.
7905 emit_file_info (MonoAotCompile *acfg)
7910 const char *gc_name;
7913 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
7915 if (acfg->aot_opts.bind_to_runtime_version) {
7916 build_info = mono_get_runtime_build_info ();
7917 emit_string_symbol (acfg, "runtime_version", build_info);
7918 g_free (build_info);
7920 emit_string_symbol (acfg, "runtime_version", "");
7923 /* Emit a string holding the assembly name */
7924 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
7927 * The managed allocators are GC specific, so can't use an AOT image created by one GC
7930 gc_name = mono_gc_get_gc_name ();
7931 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
7933 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
7934 emit_section_change (acfg, ".data", 0);
7935 emit_alignment (acfg, 8);
7936 emit_label (acfg, symbol);
7937 if (!acfg->aot_opts.static_link)
7938 emit_global (acfg, symbol, FALSE);
7940 /* The data emitted here must match MonoAotFileInfo. */
7942 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
7943 emit_int32 (acfg, 0);
7946 * We emit pointers to our data structures instead of emitting global symbols which
7947 * point to them, to reduce the number of globals, and because using globals leads to
7948 * various problems (i.e. arm/thumb).
7950 emit_pointer (acfg, acfg->got_symbol);
7951 emit_pointer (acfg, "methods");
7954 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
7956 emit_pointer (acfg, "mono_eh_frame");
7958 emit_pointer (acfg, NULL);
7960 emit_pointer (acfg, "blob");
7961 emit_pointer (acfg, "class_name_table");
7962 emit_pointer (acfg, "class_info_offsets");
7963 emit_pointer (acfg, "method_info_offsets");
7964 emit_pointer (acfg, "ex_info_offsets");
7965 emit_pointer (acfg, "code_offsets");
7966 if (acfg->direct_method_addresses)
7967 emit_pointer (acfg, "method_addresses");
7969 emit_pointer (acfg, NULL);
7970 emit_pointer (acfg, "extra_method_info_offsets");
7971 emit_pointer (acfg, "extra_method_table");
7972 emit_pointer (acfg, "got_info_offsets");
7973 emit_pointer (acfg, "methods_end");
7974 emit_pointer (acfg, "unwind_info");
7975 emit_pointer (acfg, "mem_end");
7976 emit_pointer (acfg, "image_table");
7977 emit_pointer (acfg, "plt");
7978 emit_pointer (acfg, "plt_end");
7979 emit_pointer (acfg, "assembly_guid");
7980 emit_pointer (acfg, "runtime_version");
7981 if (acfg->num_trampoline_got_entries) {
7982 emit_pointer (acfg, "specific_trampolines");
7983 emit_pointer (acfg, "static_rgctx_trampolines");
7984 emit_pointer (acfg, "imt_thunks");
7985 emit_pointer (acfg, "gsharedvt_arg_trampolines");
7987 emit_pointer (acfg, NULL);
7988 emit_pointer (acfg, NULL);
7989 emit_pointer (acfg, NULL);
7990 emit_pointer (acfg, NULL);
7992 if (acfg->thumb_mixed) {
7993 emit_pointer (acfg, "thumb_end");
7995 emit_pointer (acfg, NULL);
7997 if (acfg->aot_opts.static_link) {
7998 emit_pointer (acfg, "globals");
8000 emit_pointer (acfg, NULL);
8002 emit_pointer (acfg, "assembly_name");
8003 emit_pointer (acfg, "unbox_trampolines");
8004 emit_pointer (acfg, "unbox_trampolines_end");
8006 emit_int32 (acfg, acfg->plt_got_offset_base);
8007 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8008 emit_int32 (acfg, acfg->plt_offset);
8009 emit_int32 (acfg, acfg->nmethods);
8010 emit_int32 (acfg, acfg->flags);
8011 emit_int32 (acfg, acfg->opts);
8012 emit_int32 (acfg, acfg->simd_opts);
8013 emit_int32 (acfg, gc_name_offset);
8015 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8016 emit_int32 (acfg, acfg->num_trampolines [i]);
8017 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8018 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8019 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8020 emit_int32 (acfg, acfg->trampoline_size [i]);
8021 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8023 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8028 memset (&t, 0, sizeof (MonoType));
8029 t.type = MONO_TYPE_R8;
8030 mono_type_size (&t, &align);
8031 emit_int32 (acfg, align);
8033 memset (&t, 0, sizeof (MonoType));
8034 t.type = MONO_TYPE_I8;
8035 mono_type_size (&t, &align);
8037 emit_int32 (acfg, align);
8040 emit_int32 (acfg, __alignof__ (double));
8041 emit_int32 (acfg, __alignof__ (gint64));
8043 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8045 if (acfg->aot_opts.static_link) {
8049 * Emit a global symbol which can be passed by an embedding app to
8050 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8053 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8055 /* Get rid of characters which cannot occur in symbols */
8057 for (p = symbol; *p; ++p) {
8058 if (!(isalnum (*p) || *p == '_'))
8061 acfg->static_linking_symbol = g_strdup (symbol);
8062 emit_global_inner (acfg, symbol, FALSE);
8063 emit_alignment (acfg, sizeof (gpointer));
8064 emit_label (acfg, symbol);
8065 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8070 emit_blob (MonoAotCompile *acfg)
8074 sprintf (symbol, "blob");
8075 emit_section_change (acfg, RODATA_SECT, 1);
8076 emit_alignment (acfg, 8);
8077 emit_label (acfg, symbol);
8079 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8083 emit_dwarf_info (MonoAotCompile *acfg)
8085 #ifdef EMIT_DWARF_INFO
8089 /* DIEs for methods */
8090 for (i = 0; i < acfg->nmethods; ++i) {
8091 MonoCompile *cfg = acfg->cfgs [i];
8096 // FIXME: LLVM doesn't define .Lme_...
8097 if (cfg->compile_llvm)
8100 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8102 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->method, mono_domain_get ()));
8108 collect_methods (MonoAotCompile *acfg)
8111 MonoImage *image = acfg->image;
8113 /* Collect methods */
8114 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8116 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8118 method = mono_get_method (acfg->image, token, NULL);
8121 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8125 /* Load all methods eagerly to skip the slower lazy loading code */
8126 mono_class_setup_methods (method->klass);
8128 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8129 /* Compile the wrapper instead */
8130 /* We do this here instead of add_wrappers () because it is easy to do it here */
8131 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8135 /* FIXME: Some mscorlib methods don't have debug info */
8137 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8138 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8139 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8140 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8141 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8142 if (!mono_debug_lookup_method (method)) {
8143 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8150 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8151 add_method_with_index (acfg, method, i, FALSE);
8152 acfg->method_index ++;
8155 /* gsharedvt methods */
8156 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8158 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8160 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8163 method = mono_get_method (acfg->image, token, NULL);
8167 if (strcmp (method->name, "gshared2"))
8171 if (!strstr (method->klass->image->name, "mini"))
8174 if (method->is_generic || method->klass->generic_container) {
8175 MonoMethod *gshared;
8177 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8178 add_extra_method (acfg, gshared);
8182 add_generic_instances (acfg);
8184 if (acfg->aot_opts.full_aot)
8185 add_wrappers (acfg);
8189 compile_methods (MonoAotCompile *acfg)
8193 if (acfg->aot_opts.nthreads > 0) {
8198 gpointer *user_data;
8199 MonoMethod **methods;
8201 methods_len = acfg->methods->len;
8203 len = acfg->methods->len / acfg->aot_opts.nthreads;
8206 * Partition the list of methods into fragments, and hand it to threads to
8209 threads = g_ptr_array_new ();
8210 /* Make a copy since acfg->methods is modified by compile_method () */
8211 methods = g_new0 (MonoMethod*, methods_len);
8212 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8213 for (i = 0; i < methods_len; ++i)
8214 methods [i] = g_ptr_array_index (acfg->methods, i);
8216 while (i < methods_len) {
8217 frag = g_ptr_array_new ();
8218 for (j = 0; j < len; ++j) {
8219 if (i < methods_len) {
8220 g_ptr_array_add (frag, methods [i]);
8225 user_data = g_new0 (gpointer, 3);
8226 user_data [0] = mono_domain_get ();
8227 user_data [1] = acfg;
8228 user_data [2] = frag;
8230 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
8231 g_ptr_array_add (threads, handle);
8235 for (i = 0; i < threads->len; ++i) {
8236 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8242 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8243 for (i = methods_len; i < acfg->methods->len; ++i) {
8244 /* This can new methods to acfg->methods */
8245 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8250 compile_asm (MonoAotCompile *acfg)
8252 char *command, *objfile;
8253 char *outfile_name, *tmp_outfile_name;
8254 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8256 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8257 #define AS_OPTIONS "--64"
8258 #elif defined(TARGET_POWERPC64)
8259 #define AS_OPTIONS "-a64 -mppc64"
8260 #define LD_OPTIONS "-m elf64ppc"
8261 #elif defined(sparc) && SIZEOF_VOID_P == 8
8262 #define AS_OPTIONS "-xarch=v9"
8263 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8264 #define AS_OPTIONS "-arch i386 -W"
8266 #define AS_OPTIONS ""
8269 #ifdef __native_client_codegen__
8270 #if defined(TARGET_AMD64)
8271 #define AS_NAME "nacl64-as"
8273 #define AS_NAME "nacl-as"
8276 #define AS_NAME "as"
8280 #define LD_OPTIONS ""
8283 #define EH_LD_OPTIONS ""
8285 if (acfg->aot_opts.asm_only) {
8286 printf ("Output file: '%s'.\n", acfg->tmpfname);
8287 if (acfg->aot_opts.static_link)
8288 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8292 if (acfg->aot_opts.static_link) {
8293 if (acfg->aot_opts.outfile)
8294 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8296 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8298 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8300 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);
8301 printf ("Executing the native assembler: %s\n", command);
8302 if (system (command) != 0) {
8310 if (acfg->aot_opts.static_link) {
8311 printf ("Output file: '%s'.\n", objfile);
8312 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8317 if (acfg->aot_opts.outfile)
8318 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8320 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8322 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8325 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8326 #elif defined(__ppc__) && defined(TARGET_MACH)
8327 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8328 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8329 command = g_strdup_printf ("gcc --shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8330 #elif defined(HOST_WIN32)
8331 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8332 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8333 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8335 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8337 printf ("Executing the native linker: %s\n", command);
8338 if (system (command) != 0) {
8339 g_free (tmp_outfile_name);
8340 g_free (outfile_name);
8348 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8349 printf ("Stripping the binary: %s\n", com);
8353 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8355 * gas generates 'mapping symbols' each time code and data is mixed, which
8356 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8358 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8359 printf ("Stripping the binary: %s\n", command);
8360 if (system (command) != 0) {
8361 g_free (tmp_outfile_name);
8362 g_free (outfile_name);
8369 rename (tmp_outfile_name, outfile_name);
8371 #if defined(TARGET_MACH)
8372 command = g_strdup_printf ("dsymutil %s", outfile_name);
8373 printf ("Generating debug symbols: %s\n", command);
8374 if (system (command) != 0) {
8379 if (!acfg->aot_opts.save_temps)
8382 g_free (tmp_outfile_name);
8383 g_free (outfile_name);
8386 if (acfg->aot_opts.save_temps)
8387 printf ("Retained input file.\n");
8389 unlink (acfg->tmpfname);
8394 static MonoAotCompile*
8395 acfg_create (MonoAssembly *ass, guint32 opts)
8397 MonoImage *image = ass->image;
8398 MonoAotCompile *acfg;
8401 acfg = g_new0 (MonoAotCompile, 1);
8402 acfg->methods = g_ptr_array_new ();
8403 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8404 acfg->method_depth = g_hash_table_new (NULL, NULL);
8405 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8406 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8407 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8408 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8409 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8410 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8411 acfg->got_patches = g_ptr_array_new ();
8412 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8413 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8414 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8415 acfg->image_hash = g_hash_table_new (NULL, NULL);
8416 acfg->image_table = g_ptr_array_new ();
8417 acfg->globals = g_ptr_array_new ();
8418 acfg->image = image;
8420 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8421 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8422 acfg->mempool = mono_mempool_new ();
8423 acfg->extra_methods = g_ptr_array_new ();
8424 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8425 acfg->unwind_ops = g_ptr_array_new ();
8426 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8427 acfg->method_order = g_ptr_array_new ();
8428 acfg->export_names = g_hash_table_new (NULL, NULL);
8429 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8430 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8431 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8432 InitializeCriticalSection (&acfg->mutex);
8438 acfg_free (MonoAotCompile *acfg)
8442 img_writer_destroy (acfg->w);
8443 for (i = 0; i < acfg->nmethods; ++i)
8445 g_free (acfg->cfgs [i]);
8446 g_free (acfg->cfgs);
8447 g_free (acfg->static_linking_symbol);
8448 g_free (acfg->got_symbol);
8449 g_free (acfg->plt_symbol);
8450 g_ptr_array_free (acfg->methods, TRUE);
8451 g_ptr_array_free (acfg->got_patches, TRUE);
8452 g_ptr_array_free (acfg->image_table, TRUE);
8453 g_ptr_array_free (acfg->globals, TRUE);
8454 g_ptr_array_free (acfg->unwind_ops, TRUE);
8455 g_hash_table_destroy (acfg->method_indexes);
8456 g_hash_table_destroy (acfg->method_depth);
8457 g_hash_table_destroy (acfg->plt_offset_to_entry);
8458 g_hash_table_destroy (acfg->patch_to_plt_entry);
8459 g_hash_table_destroy (acfg->patch_to_got_offset);
8460 g_hash_table_destroy (acfg->method_to_cfg);
8461 g_hash_table_destroy (acfg->token_info_hash);
8462 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8463 g_hash_table_destroy (acfg->image_hash);
8464 g_hash_table_destroy (acfg->unwind_info_offsets);
8465 g_hash_table_destroy (acfg->method_label_hash);
8466 g_hash_table_destroy (acfg->export_names);
8467 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8468 g_hash_table_destroy (acfg->klass_blob_hash);
8469 g_hash_table_destroy (acfg->method_blob_hash);
8470 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8471 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8472 g_free (acfg->patch_to_got_offset_by_type);
8473 mono_mempool_destroy (acfg->mempool);
8478 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8480 MonoImage *image = ass->image;
8482 MonoAotCompile *acfg;
8483 char *outfile_name, *tmp_outfile_name, *p;
8484 char llvm_stats_msg [256];
8488 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || (!defined(MONO_EXTENSIONS) && !defined(MONOTOUCH))
8489 if (opts & MONO_OPT_GSHAREDVT) {
8490 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8495 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8497 acfg = acfg_create (ass, opts);
8499 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8500 acfg->aot_opts.write_symbols = TRUE;
8501 acfg->aot_opts.ntrampolines = 1024;
8502 acfg->aot_opts.nrgctx_trampolines = 1024;
8503 acfg->aot_opts.nimt_trampolines = 128;
8504 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8505 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8506 acfg->aot_opts.llvm_path = g_strdup ("");
8508 acfg->aot_opts.use_trampolines_page = TRUE;
8511 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8513 if (acfg->aot_opts.static_link)
8514 acfg->aot_opts.autoreg = TRUE;
8516 //acfg->aot_opts.print_skipped_methods = TRUE;
8518 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8519 if (acfg->aot_opts.full_aot) {
8520 printf ("--aot=full is not supported on this platform.\n");
8525 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8526 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8530 if (acfg->aot_opts.static_link)
8531 acfg->aot_opts.asm_writer = TRUE;
8533 if (acfg->aot_opts.soft_debug) {
8534 MonoDebugOptions *opt = mini_get_debug_options ();
8536 opt->mdb_optimizations = TRUE;
8537 opt->gen_seq_points = TRUE;
8539 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8540 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8543 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8546 if (mono_use_llvm) {
8548 acfg->aot_opts.asm_writer = TRUE;
8549 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8551 if (acfg->aot_opts.soft_debug) {
8552 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8557 if (acfg->aot_opts.full_aot)
8558 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8560 load_profile_files (acfg);
8562 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8563 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8564 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8566 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8567 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8568 if (acfg->opts & MONO_OPT_GSHAREDVT)
8569 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8572 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8576 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8577 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8578 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8580 /* Get rid of characters which cannot occur in symbols */
8581 for (p = acfg->got_symbol_base; *p; ++p) {
8582 if (!(isalnum (*p) || *p == '_'))
8585 for (p = acfg->plt_symbol; *p; ++p) {
8586 if (!(isalnum (*p) || *p == '_'))
8589 for (p = acfg->assembly_name_sym; *p; ++p) {
8590 if (!(isalnum (*p) || *p == '_'))
8594 acfg->method_index = 1;
8598 if (acfg->aot_opts.full_aot)
8599 mono_set_partial_sharing_supported (TRUE);
8602 collect_methods (acfg);
8604 acfg->cfgs_size = acfg->methods->len + 32;
8605 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8607 /* PLT offset 0 is reserved for the PLT trampoline */
8608 acfg->plt_offset = 1;
8613 mono_llvm_create_aot_module (acfg->got_symbol_base);
8617 /* GOT offset 0 is reserved for the address of the current assembly */
8621 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8622 ji->type = MONO_PATCH_INFO_IMAGE;
8623 ji->data.image = acfg->image;
8625 get_got_offset (acfg, ji);
8627 /* Slot 1 is reserved for the mscorlib got addr */
8628 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8629 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8630 get_got_offset (acfg, ji);
8632 /* This is very common */
8633 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8634 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8635 get_got_offset (acfg, ji);
8637 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8638 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8639 get_got_offset (acfg, ji);
8644 compile_methods (acfg);
8648 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8654 if (acfg->aot_opts.asm_only) {
8655 if (acfg->aot_opts.outfile)
8656 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8658 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8660 acfg->tmpfname = g_strdup ("temp.s");
8663 emit_llvm_file (acfg);
8667 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8668 if (acfg->aot_opts.outfile)
8669 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8671 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8674 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8675 * it might be in another file system so the rename () won't work.
8677 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8679 acfg->fp = fopen (tmp_outfile_name, "w");
8681 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8685 acfg->w = img_writer_create (acfg->fp, TRUE);
8686 acfg->use_bin_writer = TRUE;
8689 /* Append to the .s file created by llvm */
8690 /* FIXME: Use multiple files instead */
8691 acfg->fp = fopen (acfg->tmpfname, "a+");
8693 if (acfg->aot_opts.asm_only) {
8694 if (acfg->aot_opts.outfile)
8695 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8697 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8698 acfg->fp = fopen (acfg->tmpfname, "w+");
8700 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8701 acfg->fp = fdopen (i, "w+");
8703 if (acfg->fp == 0) {
8704 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8708 acfg->w = img_writer_create (acfg->fp, FALSE);
8710 tmp_outfile_name = NULL;
8711 outfile_name = NULL;
8714 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8716 /* Compute symbols for methods */
8717 for (i = 0; i < acfg->nmethods; ++i) {
8718 if (acfg->cfgs [i]) {
8719 MonoCompile *cfg = acfg->cfgs [i];
8720 int method_index = get_method_index (acfg, cfg->orig_method);
8722 if (COMPILE_LLVM (cfg))
8723 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8724 else if (acfg->global_symbols)
8725 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8727 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8731 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
8733 * CLANG supports GAS .file/.loc directives, so emit line number information this way
8735 acfg->gas_line_numbers = TRUE;
8738 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8739 if (acfg->aot_opts.dwarf_debug && mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8740 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8743 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
8746 img_writer_emit_start (acfg->w);
8749 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
8751 if (acfg->thumb_mixed) {
8754 * This global symbol marks the end of THUMB code, and the beginning of ARM
8755 * code generated by our JIT.
8757 sprintf (symbol, "thumb_end");
8758 emit_section_change (acfg, ".text", 0);
8759 emit_alignment (acfg, 8);
8760 emit_label (acfg, symbol);
8761 emit_zero_bytes (acfg, 16);
8763 fprintf (acfg->fp, ".arm\n");
8770 emit_extra_methods (acfg);
8772 emit_trampolines (acfg);
8774 emit_class_name_table (acfg);
8776 emit_got_info (acfg);
8778 emit_exception_info (acfg);
8780 emit_unwind_info (acfg);
8782 emit_class_info (acfg);
8786 emit_image_table (acfg);
8790 emit_file_info (acfg);
8794 emit_globals (acfg);
8796 emit_autoreg (acfg);
8799 emit_dwarf_info (acfg);
8800 mono_dwarf_writer_close (acfg->dwarf);
8803 emit_mem_end (acfg);
8805 if (acfg->need_pt_gnu_stack) {
8806 /* This is required so the .so doesn't have an executable stack */
8807 /* The bin writer already emits this */
8808 if (!acfg->use_bin_writer)
8809 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
8814 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
8817 g_assert (acfg->got_offset <= acfg->final_got_size);
8820 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
8822 strcpy (llvm_stats_msg, "");
8823 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);
8824 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
8825 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
8827 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
8828 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
8829 if (acfg->stats.genericcount)
8830 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
8831 if (acfg->stats.abscount)
8832 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
8833 if (acfg->stats.lmfcount)
8834 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
8835 if (acfg->stats.ocount)
8836 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
8839 res = img_writer_emit_writeout (acfg->w);
8844 if (acfg->use_bin_writer) {
8845 int err = rename (tmp_outfile_name, outfile_name);
8848 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
8852 res = compile_asm (acfg);
8859 acfg->stats.link_time = TV_ELAPSED (atv, btv);
8861 if (acfg->aot_opts.stats) {
8864 printf ("GOT slot distribution:\n");
8865 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
8866 if (acfg->stats.got_slot_types [i])
8867 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
8870 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);
8882 mono_aot_readonly_field_override (MonoClassField *field)
8888 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)