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 log_instances;
132 gboolean direct_pinvoke;
133 gboolean direct_icalls;
134 gboolean no_direct_calls;
135 gboolean use_trampolines_page;
136 gboolean no_instances;
140 int nrgctx_trampolines;
141 int nimt_trampolines;
142 int ngsharedvt_arg_trampolines;
143 int nrgctx_fetch_trampolines;
144 gboolean print_skipped_methods;
150 char *instances_logfile_path;
153 typedef struct MonoAotStats {
154 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
155 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
156 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
157 int got_slots, offsets_size;
158 int got_slot_types [MONO_PATCH_INFO_NONE];
159 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
160 int jit_time, gen_time, link_time;
163 typedef struct MonoAotCompile {
166 GHashTable *method_indexes;
167 GHashTable *method_depth;
170 GHashTable **patch_to_plt_entry;
171 GHashTable *plt_offset_to_entry;
172 GHashTable *patch_to_got_offset;
173 GHashTable **patch_to_got_offset_by_type;
174 GPtrArray *got_patches;
175 GHashTable *image_hash;
176 GHashTable *method_to_cfg;
177 GHashTable *token_info_hash;
178 GHashTable *method_to_pinvoke_import;
179 GPtrArray *extra_methods;
180 GPtrArray *image_table;
182 GPtrArray *method_order;
183 GHashTable *export_names;
184 /* Maps MonoClass* -> blob offset */
185 GHashTable *klass_blob_hash;
186 /* Maps MonoMethod* -> blob offset */
187 GHashTable *method_blob_hash;
188 guint32 *plt_got_info_offsets;
189 guint32 got_offset, plt_offset, plt_got_offset_base;
190 guint32 final_got_size;
191 /* Number of GOT entries reserved for trampolines */
192 guint32 num_trampoline_got_entries;
193 guint32 tramp_page_size;
195 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
196 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
197 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
198 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
200 MonoAotOptions aot_opts;
204 MonoMemPool *mempool;
207 char *static_linking_symbol;
208 CRITICAL_SECTION mutex;
209 gboolean use_bin_writer;
210 gboolean gas_line_numbers;
212 MonoDwarfWriter *dwarf;
217 GHashTable *unwind_info_offsets;
218 GPtrArray *unwind_ops;
219 guint32 unwind_info_offset;
220 char *got_symbol_base;
223 char *methods_symbol;
224 GHashTable *method_label_hash;
225 const char *temp_prefix;
226 const char *user_symbol_prefix;
227 const char *llvm_label_prefix;
228 const char *inst_directive;
229 guint32 label_generator;
231 MonoAotFileFlags flags;
232 MonoDynamicStream blob;
233 MonoClass **typespec_classes;
236 char *assembly_name_sym;
237 GHashTable *plt_entry_debug_sym_cache;
238 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
239 GHashTable *ginst_hash;
240 GHashTable *dwarf_ln_filenames;
241 gboolean global_symbols;
242 gboolean direct_method_addresses;
243 int objc_selector_index, objc_selector_index_2;
244 GPtrArray *objc_selectors;
245 GHashTable *objc_selector_to_index;
246 FILE *instances_logfile;
251 char *symbol, *llvm_symbol, *debug_sym;
253 gboolean jit_used, llvm_used;
256 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
257 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
259 /* This points to the current acfg in LLVM mode */
260 static MonoAotCompile *llvm_acfg;
262 #ifdef HAVE_ARRAY_ELEM_INIT
263 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
264 #define MSGSTRFIELD1(line) str##line
265 static const struct msgstr_t {
266 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
267 #include "patch-info.h"
270 #define PATCH_INFO(a,b) b,
271 #include "patch-info.h"
274 static const gint16 opidx [] = {
275 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
276 #include "patch-info.h"
280 static G_GNUC_UNUSED const char*
281 get_patch_name (int info)
283 return (const char*)&opstr + opidx [info];
287 #define PATCH_INFO(a,b) b,
288 static const char* const
289 patch_types [MONO_PATCH_INFO_NUM + 1] = {
290 #include "patch-info.h"
294 static G_GNUC_UNUSED const char*
295 get_patch_name (int info)
297 return patch_types [info];
303 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
305 /* Wrappers around the image writer functions */
308 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
310 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
314 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
316 img_writer_emit_push_section (acfg->w, section_name, subsection);
320 emit_pop_section (MonoAotCompile *acfg)
322 img_writer_emit_pop_section (acfg->w);
326 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
328 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
332 emit_label (MonoAotCompile *acfg, const char *name)
334 img_writer_emit_label (acfg->w, name);
338 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
340 img_writer_emit_bytes (acfg->w, buf, size);
344 emit_string (MonoAotCompile *acfg, const char *value)
346 img_writer_emit_string (acfg->w, value);
350 emit_line (MonoAotCompile *acfg)
352 img_writer_emit_line (acfg->w);
356 emit_alignment (MonoAotCompile *acfg, int size)
358 img_writer_emit_alignment (acfg->w, size);
362 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
364 img_writer_emit_pointer_unaligned (acfg->w, target);
368 emit_pointer (MonoAotCompile *acfg, const char *target)
370 img_writer_emit_pointer (acfg->w, target);
374 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
376 if (prefix [0] != '\0') {
377 char *s = g_strdup_printf ("%s%s", prefix, target);
378 img_writer_emit_pointer (acfg->w, s);
381 img_writer_emit_pointer (acfg->w, target);
386 emit_int16 (MonoAotCompile *acfg, int value)
388 img_writer_emit_int16 (acfg->w, value);
392 emit_int32 (MonoAotCompile *acfg, int value)
394 img_writer_emit_int32 (acfg->w, value);
398 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
400 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
404 emit_zero_bytes (MonoAotCompile *acfg, int num)
406 img_writer_emit_zero_bytes (acfg->w, num);
410 emit_byte (MonoAotCompile *acfg, guint8 val)
412 img_writer_emit_byte (acfg->w, val);
415 #ifdef __native_client_codegen__
417 emit_nacl_call_alignment (MonoAotCompile *acfg)
419 img_writer_emit_nacl_call_alignment (acfg->w);
423 static G_GNUC_UNUSED void
424 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
426 img_writer_emit_global (acfg->w, name, func);
430 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
432 if (acfg->aot_opts.no_dlsym) {
433 g_ptr_array_add (acfg->globals, g_strdup (name));
434 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
436 img_writer_emit_global (acfg->w, name, func);
441 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
443 img_writer_emit_symbol_size (acfg->w, name, end_label);
447 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
449 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
451 /* On apple, all symbols need to be aligned to avoid warnings from ld */
452 emit_alignment (acfg, 4);
454 img_writer_emit_label (acfg->w, name);
455 img_writer_emit_string (acfg->w, value);
458 static G_GNUC_UNUSED void
459 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
462 guint8 b = value & 0x7f;
464 if (value != 0) /* more bytes to come */
470 static G_GNUC_UNUSED void
471 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
474 gboolean negative = (value < 0);
481 /* the following is unnecessary if the
482 * implementation of >>= uses an arithmetic rather
483 * than logical shift for a signed left operand
487 value |= - ((gint64)1 <<(size - 7));
488 /* sign bit of byte is second high order bit (0x40) */
489 if ((value == 0 && !(byte & 0x40)) ||
490 (value == -1 && (byte & 0x40)))
494 emit_byte (acfg, byte);
498 static G_GNUC_UNUSED void
499 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
504 guint8 b = value & 0x7f;
506 if (value != 0) /* more bytes to come */
514 static G_GNUC_UNUSED void
515 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
518 gboolean negative = (value < 0);
526 /* the following is unnecessary if the
527 * implementation of >>= uses an arithmetic rather
528 * than logical shift for a signed left operand
532 value |= - (1 <<(size - 7));
533 /* sign bit of byte is second high order bit (0x40) */
534 if ((value == 0 && !(byte & 0x40)) ||
535 (value == -1 && (byte & 0x40)))
546 emit_unset_mode (MonoAotCompile *acfg)
548 img_writer_emit_unset_mode (acfg->w);
551 static G_GNUC_UNUSED void
552 emit_set_thumb_mode (MonoAotCompile *acfg)
554 emit_unset_mode (acfg);
555 fprintf (acfg->fp, ".code 16\n");
558 static G_GNUC_UNUSED void
559 emit_set_arm_mode (MonoAotCompile *acfg)
561 emit_unset_mode (acfg);
562 fprintf (acfg->fp, ".code 32\n");
566 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
571 g_assert (size % 4 == 0);
572 emit_unset_mode (acfg);
573 for (i = 0; i < size; i += 4)
574 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
576 emit_bytes (acfg, buf, size);
580 /* ARCHITECTURE SPECIFIC CODE */
582 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
583 #define EMIT_DWARF_INFO 1
586 #if defined(TARGET_ARM)
587 #define AOT_FUNC_ALIGNMENT 4
589 #define AOT_FUNC_ALIGNMENT 16
591 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
592 #undef AOT_FUNC_ALIGNMENT
593 #define AOT_FUNC_ALIGNMENT 32
596 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
597 #define PPC_LD_OP "ld"
598 #define PPC_LDX_OP "ldx"
600 #define PPC_LD_OP "lwz"
601 #define PPC_LDX_OP "lwzx"
605 #define AOT_TARGET_STR "AMD64"
610 #define AOT_TARGET_STR "ARM (MACH)"
612 #define AOT_TARGET_STR "ARM (!MACH)"
618 #define AOT_TARGET_STR "ARM64 (MACH)"
620 #define AOT_TARGET_STR "ARM64 (!MACH)"
624 #ifdef TARGET_POWERPC64
625 #ifdef __mono_ilp32__
626 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
628 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
631 #ifdef TARGET_POWERPC
632 #ifdef __mono_ilp32__
633 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
635 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
642 #define AOT_TARGET_STR "X86 (WIN32)"
643 #elif defined(__native_client_codegen__)
644 #define AOT_TARGET_STR "X86 (native client codegen)"
646 #define AOT_TARGET_STR "X86 (!native client codegen)"
650 #ifndef AOT_TARGET_STR
651 #define AOT_TARGET_STR ""
655 arch_init (MonoAotCompile *acfg)
657 acfg->llc_args = g_string_new ("");
658 acfg->as_args = g_string_new ("");
661 * The prefix LLVM likes to put in front of symbol names on darwin.
662 * The mach-os specs require this for globals, but LLVM puts them in front of all
663 * symbols. We need to handle this, since we need to refer to LLVM generated
666 acfg->llvm_label_prefix = "";
667 acfg->user_symbol_prefix = "";
669 #if defined(TARGET_AMD64)
670 g_string_append (acfg->llc_args, " -march=x86-64");
674 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
675 g_string_append (acfg->llc_args, "-mattr=+v6");
678 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
679 g_string_append (acfg->as_args, " -mfpu=vfp3");
681 g_string_append (acfg->llc_args, " -soft-float");
684 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
685 acfg->thumb_mixed = TRUE;
687 if (acfg->aot_opts.mtriple)
688 mono_arch_set_target (acfg->aot_opts.mtriple);
692 acfg->inst_directive = ".inst";
693 if (acfg->aot_opts.mtriple)
694 mono_arch_set_target (acfg->aot_opts.mtriple);
698 acfg->user_symbol_prefix = "_";
699 acfg->llvm_label_prefix = "_";
700 acfg->inst_directive = ".word";
701 acfg->need_no_dead_strip = TRUE;
702 acfg->aot_opts.gnu_asm = TRUE;
705 #if defined(__linux__) && !defined(TARGET_ARM)
706 acfg->need_pt_gnu_stack = TRUE;
710 acfg->direct_method_addresses = TRUE;
711 acfg->global_symbols = TRUE;
717 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
721 #ifdef MONO_ARCH_AOT_SUPPORTED
723 * arch_emit_direct_call:
725 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
729 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
731 #if defined(TARGET_X86) || defined(TARGET_AMD64)
732 /* Need to make sure this is exactly 5 bytes long */
733 if (external && !acfg->use_bin_writer) {
734 emit_unset_mode (acfg);
735 fprintf (acfg->fp, "call %s\n", target);
737 emit_byte (acfg, '\xe8');
738 emit_symbol_diff (acfg, target, ".", -4);
741 #elif defined(TARGET_ARM)
742 if (acfg->use_bin_writer) {
749 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
750 emit_bytes (acfg, buf, 4);
752 emit_unset_mode (acfg);
754 fprintf (acfg->fp, "blx %s\n", target);
756 fprintf (acfg->fp, "bl %s\n", target);
759 #elif defined(TARGET_ARM64)
760 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
761 #elif defined(TARGET_POWERPC)
762 if (acfg->use_bin_writer) {
763 g_assert_not_reached ();
765 emit_unset_mode (acfg);
766 fprintf (acfg->fp, "bl %s\n", target);
770 g_assert_not_reached ();
777 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
779 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
780 * in in the 2. slot of every GOT, and require every method to place the GOT
781 * address in r30, even when it doesn't access the GOT otherwise. This way,
782 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
787 * PPC64 uses function descriptors which greatly complicate all code, since
788 * these are used very inconsistently in the runtime. Some functions like
789 * mono_compile_method () return ftn descriptors, while others like the
790 * trampoline creation functions do not.
791 * We assume that all GOT slots contain function descriptors, and create
792 * descriptors in aot-runtime.c when needed.
793 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
794 * from function descriptors, we could do the same, but it would require
795 * rewriting all the ppc/aot code to handle function descriptors properly.
796 * So instead, we use the same approach as on PPC32.
797 * This is a horrible mess, but fixing it would probably lead to an even bigger
803 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
806 #ifdef MONO_ARCH_AOT_SUPPORTED
808 * arch_emit_got_offset:
810 * The memory pointed to by CODE should hold native code for computing the GOT
811 * address. Emit this code while patching it with the offset between code and
812 * the GOT. CODE_SIZE is set to the number of bytes emitted.
815 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
817 #if defined(TARGET_POWERPC64)
818 g_assert (!acfg->use_bin_writer);
819 emit_unset_mode (acfg);
821 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
822 * unsupported relocations. So we store the got address into the .Lgot_addr
823 * symbol which is in the text segment, compute its address, and load it.
825 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
826 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
827 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
828 fprintf (acfg->fp, "add 30, 30, 0\n");
829 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
830 acfg->label_generator ++;
832 #elif defined(TARGET_POWERPC)
833 g_assert (!acfg->use_bin_writer);
834 emit_unset_mode (acfg);
835 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
836 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
837 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
838 acfg->label_generator ++;
841 guint32 offset = mono_arch_get_patch_offset (code);
842 emit_bytes (acfg, code, offset);
843 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
845 *code_size = offset + 4;
850 * arch_emit_got_access:
852 * The memory pointed to by CODE should hold native code for loading a GOT
853 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
854 * CODE_SIZE is set to the number of bytes emitted.
857 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
859 /* Emit beginning of instruction */
860 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
862 /* Emit the offset */
864 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
865 *code_size = mono_arch_get_patch_offset (code) + 4;
866 #elif defined(TARGET_X86)
867 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
868 *code_size = mono_arch_get_patch_offset (code) + 4;
869 #elif defined(TARGET_ARM)
870 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
871 *code_size = mono_arch_get_patch_offset (code) + 4;
872 #elif defined(TARGET_ARM64)
873 arm64_emit_got_access (acfg, code, got_slot, code_size);
874 #elif defined(TARGET_POWERPC)
880 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
881 g_assert (code - buf == 8);
882 emit_bytes (acfg, buf, code - buf);
883 *code_size = code - buf;
886 g_assert_not_reached ();
892 #ifdef MONO_ARCH_AOT_SUPPORTED
894 * arch_emit_objc_selector_ref:
896 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
899 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
901 #if defined(TARGET_ARM)
904 int lindex = acfg->objc_selector_index_2 ++;
907 emit_bytes (acfg, code, 8);
909 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
910 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
912 emit_label (acfg, symbol1);
913 img_writer_emit_unset_mode (acfg->w);
914 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
917 #elif defined(TARGET_ARM64)
918 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
920 g_assert_not_reached ();
926 * arch_emit_plt_entry:
928 * Emit code for the PLT entry with index INDEX.
931 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
933 #if defined(TARGET_X86)
934 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
935 #if defined(__default_codegen__)
936 /* jmp *<offset>(%ebx) */
937 emit_byte (acfg, 0xff);
938 emit_byte (acfg, 0xa3);
939 emit_int32 (acfg, offset);
940 /* Used by mono_aot_get_plt_info_offset */
941 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
942 #elif defined(__native_client_codegen__)
943 const guint8 kSizeOfNaClJmp = 11;
944 guint8 bytes[kSizeOfNaClJmp];
945 guint8 *pbytes = &bytes[0];
947 x86_jump_membase32 (pbytes, X86_EBX, offset);
948 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
949 /* four bytes of data, used by mono_arch_patch_plt_entry */
950 /* For Native Client, make this work with data embedded in push. */
951 emit_byte (acfg, 0x68); /* hide data in a push */
952 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
953 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
954 #endif /*__native_client_codegen__*/
955 #elif defined(TARGET_AMD64)
956 #if defined(__default_codegen__)
958 * We can't emit jumps because they are 32 bits only so they can't be patched.
959 * So we make indirect calls through GOT entries which are patched by the AOT
960 * loader to point to .Lpd entries.
962 /* jmpq *<offset>(%rip) */
963 emit_byte (acfg, '\xff');
964 emit_byte (acfg, '\x25');
965 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
966 /* Used by mono_aot_get_plt_info_offset */
967 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
968 acfg->stats.plt_size += 10;
969 #elif defined(__native_client_codegen__)
971 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
972 guint8 *code = buf_aligned;
974 /* mov <OFFSET>(%rip), %r11d */
975 emit_byte (acfg, '\x45');
976 emit_byte (acfg, '\x8b');
977 emit_byte (acfg, '\x1d');
978 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
980 amd64_jump_reg (code, AMD64_R11);
981 /* This should be constant for the plt patch */
982 g_assert ((size_t)(code-buf_aligned) == 10);
983 emit_bytes (acfg, buf_aligned, code - buf_aligned);
985 /* Hide data in a push imm32 so it passes validation */
986 emit_byte (acfg, 0x68); /* push */
987 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
988 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
989 #endif /*__native_client_codegen__*/
990 #elif defined(TARGET_ARM)
995 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
996 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
997 emit_bytes (acfg, buf, code - buf);
998 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
999 /* Used by mono_aot_get_plt_info_offset */
1000 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1001 #elif defined(TARGET_ARM64)
1002 arm64_emit_plt_entry (acfg, index);
1003 #elif defined(TARGET_POWERPC)
1004 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1006 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1007 g_assert (!acfg->use_bin_writer);
1008 emit_unset_mode (acfg);
1009 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1010 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1011 fprintf (acfg->fp, "add 11, 11, 30\n");
1012 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1013 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1014 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1015 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1017 fprintf (acfg->fp, "mtctr 11\n");
1018 fprintf (acfg->fp, "bctr\n");
1019 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1021 g_assert_not_reached ();
1026 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
1028 #if defined(TARGET_ARM)
1030 /* LLVM calls the PLT entries using bl, so emit a stub */
1031 /* FIXME: Too much overhead on every call */
1032 fprintf (acfg->fp, ".thumb_func\n");
1033 fprintf (acfg->fp, "bx pc\n");
1034 fprintf (acfg->fp, "nop\n");
1035 fprintf (acfg->fp, ".arm\n");
1037 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1038 /* The caller already transitioned to thumb */
1039 /* The code below should be 12 bytes long */
1040 /* clang has trouble encoding these instructions, so emit the binary */
1042 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1043 /* thumb can't encode ld pc, [pc, ip] */
1044 fprintf (acfg->fp, "add ip, pc, ip\n");
1045 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1046 fprintf (acfg->fp, "bx ip\n");
1048 emit_set_thumb_mode (acfg);
1049 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1050 fprintf (acfg->fp, ".2byte 0x44fc\n");
1051 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1052 fprintf (acfg->fp, ".2byte 0x4760\n");
1053 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1054 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1055 emit_unset_mode (acfg);
1056 emit_set_arm_mode (acfg);
1058 g_assert_not_reached ();
1063 * arch_emit_specific_trampoline_pages:
1065 * Emits a page full of trampolines: each trampoline uses its own address to
1066 * lookup both the generic trampoline code and the data argument.
1067 * This page can be remapped in process multiple times so we can get an
1068 * unlimited number of trampolines.
1069 * Specifically this implementation uses the following trick: two memory pages
1070 * are allocated, with the first containing the data and the second containing the trampolines.
1071 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1072 * implementation does all the lifting.
1073 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1074 * on the arm 32 bit system.
1077 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1079 #if defined(TARGET_ARM)
1082 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1084 #define COMMON_TRAMP_SIZE 16
1085 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1086 int imm8, rot_amount;
1089 if (!acfg->aot_opts.use_trampolines_page)
1092 acfg->tramp_page_size = mono_pagesize ();
1094 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1095 emit_alignment (acfg, mono_pagesize ());
1096 emit_global (acfg, symbol, TRUE);
1097 emit_label (acfg, symbol);
1099 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1101 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1102 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1103 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1104 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1106 g_assert (code - buf == COMMON_TRAMP_SIZE);
1109 emit_bytes (acfg, buf, code - buf);
1111 for (i = 0; i < count; ++i) {
1113 ARM_PUSH (code, 0x5fff);
1115 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1116 g_assert (code - buf == 8);
1117 emit_bytes (acfg, buf, code - buf);
1120 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1121 * the instruction pointer address, so the generic trampoline at the start of the page
1122 * subtracts 4096 to get to the data page and loads the values
1123 * We again fit the generic trampiline in 16 bytes.
1125 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1126 emit_global (acfg, symbol, TRUE);
1127 emit_label (acfg, symbol);
1129 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1130 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1131 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1132 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1134 g_assert (code - buf == COMMON_TRAMP_SIZE);
1137 emit_bytes (acfg, buf, code - buf);
1139 for (i = 0; i < count; ++i) {
1141 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1143 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1144 g_assert (code - buf == 8);
1145 emit_bytes (acfg, buf, code - buf);
1149 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1151 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1152 emit_global (acfg, symbol, TRUE);
1153 emit_label (acfg, symbol);
1155 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1156 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1157 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1158 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1159 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1160 g_assert (code - buf == COMMON_TRAMP_SIZE);
1162 emit_bytes (acfg, buf, code - buf);
1164 for (i = 0; i < count; ++i) {
1166 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1168 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1169 g_assert (code - buf == 8);
1170 emit_bytes (acfg, buf, code - buf);
1173 /* now the imt trampolines: each specific trampolines puts in the ip register
1174 * the instruction pointer address, so the generic trampoline at the start of the page
1175 * subtracts 4096 to get to the data page and loads the values
1176 * We again fit the generic trampiline in 16 bytes.
1178 #define IMT_TRAMP_SIZE 72
1179 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1180 emit_global (acfg, symbol, TRUE);
1181 emit_label (acfg, symbol);
1183 /* Need at least two free registers, plus a slot for storing the pc */
1184 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1186 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1187 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1188 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1190 /* The IMT method is in v5, r0 has the imt array address */
1193 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1194 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1195 imt_found_check = code;
1196 ARM_B_COND (code, ARMCOND_EQ, 0);
1198 /* End-of-loop check */
1199 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1200 loop_end_check = code;
1201 ARM_B_COND (code, ARMCOND_EQ, 0);
1204 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1205 loop_branch_back = code;
1207 arm_patch (loop_branch_back, loop_start);
1210 arm_patch (imt_found_check, code);
1211 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1212 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1213 /* Save it to the third stack slot */
1214 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1215 /* Restore the registers and branch */
1216 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1219 arm_patch (loop_end_check, code);
1220 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1221 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1222 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1226 g_assert (code - buf == IMT_TRAMP_SIZE);
1227 emit_bytes (acfg, buf, code - buf);
1229 for (i = 0; i < count; ++i) {
1231 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1233 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1234 g_assert (code - buf == 8);
1235 emit_bytes (acfg, buf, code - buf);
1237 #elif defined(TARGET_ARM64)
1238 arm64_emit_specific_trampoline_pages (acfg);
1243 * arch_emit_specific_trampoline:
1245 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1246 * two GOT slots which contain the generic trampoline address and the trampoline
1247 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1250 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1253 * The trampolines created here are variations of the specific
1254 * trampolines created in mono_arch_create_specific_trampoline (). The
1256 * - the generic trampoline address is taken from a got slot.
1257 * - the offset of the got slot where the trampoline argument is stored
1258 * is embedded in the instruction stream, and the generic trampoline
1259 * can load the argument by loading the offset, adding it to the
1260 * address of the trampoline to get the address of the got slot, and
1261 * loading the argument from there.
1262 * - all the trampolines should be of the same length.
1264 #if defined(TARGET_AMD64)
1265 #if defined(__default_codegen__)
1266 /* This should be exactly 16 bytes long */
1268 /* call *<offset>(%rip) */
1269 emit_byte (acfg, '\x41');
1270 emit_byte (acfg, '\xff');
1271 emit_byte (acfg, '\x15');
1272 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1273 /* This should be relative to the start of the trampoline */
1274 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1275 emit_zero_bytes (acfg, 5);
1276 #elif defined(__native_client_codegen__)
1278 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1279 guint8 *code = buf_aligned;
1284 /* Emit this call in 'code' so we can find out how long it is. */
1285 amd64_call_reg (code, AMD64_R11);
1286 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1287 call_len = code - call_start;
1289 /* The tramp_size is twice the NaCl alignment because it starts with */
1290 /* a call which needs to be aligned to the end of the boundary. */
1291 *tramp_size = kNaClAlignment*2;
1293 /* Emit nops to align call site below which is 7 bytes plus */
1294 /* the length of the call sequence emitted above. */
1295 /* Note: this requires the specific trampoline starts on a */
1296 /* kNaclAlignedment aligned address, which it does because */
1297 /* it's its own function that is aligned. */
1298 guint8 nop_buf[256];
1299 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1300 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1301 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1303 /* The trampoline is stored at the offset'th pointer, the -4 is */
1304 /* present because RIP relative addressing starts at the end of */
1305 /* the current instruction, while the label "." is relative to */
1306 /* the beginning of the current asm location, which in this case */
1307 /* is not the mov instruction, but the offset itself, due to the */
1308 /* way the bytes and ints are emitted here. */
1309 got_offset = (offset * sizeof(gpointer)) - 4;
1311 /* mov <OFFSET>(%rip), %r11d */
1312 emit_byte (acfg, '\x45');
1313 emit_byte (acfg, '\x8b');
1314 emit_byte (acfg, '\x1d');
1315 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1318 emit_bytes (acfg, call_start, call_len);
1320 /* The arg is stored at the offset+1 pointer, relative to beginning */
1321 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1322 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1324 /* We can't emit this data directly, hide in a "push imm32" */
1325 emit_byte (acfg, '\x68'); /* push */
1326 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1327 emit_alignment (acfg, kNaClAlignment);
1328 #endif /*__native_client_codegen__*/
1329 #elif defined(TARGET_ARM)
1333 /* This should be exactly 20 bytes long */
1336 ARM_PUSH (code, 0x5fff);
1337 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1338 /* Load the value from the GOT */
1339 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1341 ARM_BLX_REG (code, ARMREG_R1);
1343 g_assert (code - buf == 16);
1346 emit_bytes (acfg, buf, code - buf);
1348 * Only one offset is needed, since the second one would be equal to the
1351 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1352 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1353 #elif defined(TARGET_ARM64)
1354 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1355 #elif defined(TARGET_POWERPC)
1362 g_assert (!acfg->use_bin_writer);
1365 * PPC has no ip relative addressing, so we need to compute the address
1366 * of the mscorlib got. That is slow and complex, so instead, we store it
1367 * in the second got slot of every aot image. The caller already computed
1368 * the address of its got and placed it into r30.
1370 emit_unset_mode (acfg);
1371 /* Load mscorlib got address */
1372 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1373 /* Load generic trampoline address */
1374 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1375 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1376 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1377 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1378 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1380 fprintf (acfg->fp, "mtctr 11\n");
1381 /* Load trampoline argument */
1382 /* On ppc, we pass it normally to the generic trampoline */
1383 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1384 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1385 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1386 /* Branch to generic trampoline */
1387 fprintf (acfg->fp, "bctr\n");
1389 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1390 *tramp_size = 10 * 4;
1392 *tramp_size = 9 * 4;
1394 #elif defined(TARGET_X86)
1398 /* Similar to the PPC code above */
1400 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1402 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1403 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1404 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1408 /* Load mscorlib got address */
1409 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1410 /* Push trampoline argument */
1411 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1412 /* Load generic trampoline address */
1413 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1414 /* Branch to generic trampoline */
1415 x86_jump_reg (code, X86_ECX);
1417 #ifdef __native_client_codegen__
1419 /* emit nops to next 32 byte alignment */
1420 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1421 while (code < (buf + a)) x86_nop(code);
1424 emit_bytes (acfg, buf, code - buf);
1426 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1427 g_assert (code - buf == *tramp_size);
1429 g_assert_not_reached ();
1434 * arch_emit_unbox_trampoline:
1436 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1437 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1440 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1442 #if defined(TARGET_AMD64)
1447 this_reg = mono_arch_get_this_arg_reg (NULL);
1449 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1451 emit_bytes (acfg, buf, code - buf);
1453 emit_byte (acfg, '\xe9');
1454 emit_symbol_diff (acfg, call_target, ".", -4);
1455 #elif defined(TARGET_X86)
1462 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1464 emit_bytes (acfg, buf, code - buf);
1467 emit_byte (acfg, '\xe9');
1468 emit_symbol_diff (acfg, call_target, ".", -4);
1469 #elif defined(TARGET_ARM)
1473 if (acfg->thumb_mixed && cfg->compile_llvm) {
1474 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1475 fprintf (acfg->fp, "b %s\n", call_target);
1476 fprintf (acfg->fp, ".arm\n");
1477 fprintf (acfg->fp, ".align 2\n");
1483 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1485 emit_bytes (acfg, buf, code - buf);
1486 /* jump to method */
1487 if (acfg->use_bin_writer) {
1494 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1495 emit_bytes (acfg, buf, 4);
1497 if (acfg->thumb_mixed && cfg->compile_llvm)
1498 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1500 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1502 #elif defined(TARGET_ARM64)
1503 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1504 #elif defined(TARGET_POWERPC)
1507 g_assert (!acfg->use_bin_writer);
1509 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1510 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1512 g_assert_not_reached ();
1517 * arch_emit_static_rgctx_trampoline:
1519 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1520 * two GOT slots which contain the rgctx argument, and the method to jump to.
1521 * TRAMP_SIZE is set to the size of the emitted trampoline.
1522 * These kinds of trampolines cannot be enumerated statically, since there could
1523 * be one trampoline per method instantiation, so we emit the same code for all
1524 * trampolines, and parameterize them using two GOT slots.
1527 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1529 #if defined(TARGET_AMD64)
1530 #if defined(__default_codegen__)
1531 /* This should be exactly 13 bytes long */
1534 /* mov <OFFSET>(%rip), %r10 */
1535 emit_byte (acfg, '\x4d');
1536 emit_byte (acfg, '\x8b');
1537 emit_byte (acfg, '\x15');
1538 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1540 /* jmp *<offset>(%rip) */
1541 emit_byte (acfg, '\xff');
1542 emit_byte (acfg, '\x25');
1543 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1544 #elif defined(__native_client_codegen__)
1546 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1547 guint8 *code = buf_aligned;
1549 /* mov <OFFSET>(%rip), %r10d */
1550 emit_byte (acfg, '\x45');
1551 emit_byte (acfg, '\x8b');
1552 emit_byte (acfg, '\x15');
1553 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1555 /* mov <OFFSET>(%rip), %r11d */
1556 emit_byte (acfg, '\x45');
1557 emit_byte (acfg, '\x8b');
1558 emit_byte (acfg, '\x1d');
1559 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1562 amd64_jump_reg (code, AMD64_R11);
1563 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1565 emit_alignment (acfg, kNaClAlignment);
1566 *tramp_size = kNaClAlignment;
1567 #endif /*__native_client_codegen__*/
1569 #elif defined(TARGET_ARM)
1573 /* This should be exactly 24 bytes long */
1576 /* Load rgctx value */
1577 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1578 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1579 /* Load branch addr + branch */
1580 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1581 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1583 g_assert (code - buf == 16);
1586 emit_bytes (acfg, buf, code - buf);
1587 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1588 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1589 #elif defined(TARGET_ARM64)
1590 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1591 #elif defined(TARGET_POWERPC)
1598 g_assert (!acfg->use_bin_writer);
1601 * PPC has no ip relative addressing, so we need to compute the address
1602 * of the mscorlib got. That is slow and complex, so instead, we store it
1603 * in the second got slot of every aot image. The caller already computed
1604 * the address of its got and placed it into r30.
1606 emit_unset_mode (acfg);
1607 /* Load mscorlib got address */
1608 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1610 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1611 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1612 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1613 /* Load target address */
1614 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1615 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1616 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1617 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1618 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1619 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1621 fprintf (acfg->fp, "mtctr 11\n");
1622 /* Branch to the target address */
1623 fprintf (acfg->fp, "bctr\n");
1625 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1626 *tramp_size = 11 * 4;
1628 *tramp_size = 9 * 4;
1631 #elif defined(TARGET_X86)
1635 /* Similar to the PPC code above */
1637 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1640 /* Load mscorlib got address */
1641 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1643 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1644 /* Branch to the target address */
1645 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1647 #ifdef __native_client_codegen__
1649 /* emit nops to next 32 byte alignment */
1650 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1651 while (code < (buf + a)) x86_nop(code);
1655 emit_bytes (acfg, buf, code - buf);
1657 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1658 g_assert (code - buf == *tramp_size);
1660 g_assert_not_reached ();
1665 * arch_emit_imt_thunk:
1667 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1668 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1669 * key is the IMT key, and ptr holds the address of a memory location holding
1670 * the address to branch to if the IMT arg matches the key. The array is
1671 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1673 * TRAMP_SIZE is set to the size of the emitted trampoline.
1676 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1678 #if defined(TARGET_AMD64)
1680 #if defined(__native_client_codegen__)
1683 guint8 *labels [16];
1685 guint8 *mov_buf_ptr = mov_buf;
1687 const int kSizeOfMove = 7;
1688 #if defined(__default_codegen__)
1689 code = buf = g_malloc (256);
1690 #elif defined(__native_client_codegen__)
1691 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1692 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1693 /* The RIP relative move below is emitted first */
1698 /* FIXME: Optimize this, i.e. use binary search etc. */
1699 /* Maybe move the body into a separate function (slower, but much smaller) */
1701 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1704 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1706 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1709 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1711 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1714 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1715 amd64_jump_code (code, labels [0]);
1718 mono_amd64_patch (labels [2], code);
1719 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1720 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1723 mono_amd64_patch (labels [1], code);
1724 /* Load fail tramp */
1725 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1726 /* Check if there is a fail tramp */
1727 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1729 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1730 /* Jump to fail tramp */
1731 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1734 mono_amd64_patch (labels [3], code);
1735 x86_breakpoint (code);
1737 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1738 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1739 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1740 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1741 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1742 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1744 emit_bytes (acfg, buf, code - buf);
1746 *tramp_size = code - buf + kSizeOfMove;
1747 #if defined(__native_client_codegen__)
1748 /* The tramp will be padded to the next kNaClAlignment bundle. */
1749 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1752 #if defined(__default_codegen__)
1754 #elif defined(__native_client_codegen__)
1758 #elif defined(TARGET_X86)
1760 #ifdef __native_client_codegen__
1763 guint8 *labels [16];
1765 #if defined(__default_codegen__)
1766 code = buf = g_malloc (256);
1767 #elif defined(__native_client_codegen__)
1768 buf_alloc = g_malloc (256 + kNaClAlignment);
1769 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1772 /* Allocate a temporary stack slot */
1773 x86_push_reg (code, X86_EAX);
1775 x86_push_reg (code, X86_EAX);
1777 /* Load mscorlib got address */
1778 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1780 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1783 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1785 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1788 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1790 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1793 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1794 x86_jump_code (code, labels [0]);
1797 mono_x86_patch (labels [2], code);
1798 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1799 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1800 /* Save the target address to the temporary stack location */
1801 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1803 x86_pop_reg (code, X86_EAX);
1804 /* Jump to the target address */
1808 mono_x86_patch (labels [1], code);
1809 /* Load fail tramp */
1810 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1811 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1813 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1814 /* Jump to fail tramp */
1815 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1816 x86_pop_reg (code, X86_EAX);
1820 mono_x86_patch (labels [3], code);
1821 x86_breakpoint (code);
1823 #ifdef __native_client_codegen__
1825 /* emit nops to next 32 byte alignment */
1826 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1827 while (code < (buf + a)) x86_nop(code);
1830 emit_bytes (acfg, buf, code - buf);
1832 *tramp_size = code - buf;
1834 #if defined(__default_codegen__)
1836 #elif defined(__native_client_codegen__)
1840 #elif defined(TARGET_ARM)
1842 guint8 *code, *code2, *labels [16];
1846 /* The IMT method is in v5 */
1848 /* Need at least two free registers, plus a slot for storing the pc */
1849 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1851 /* Load the parameter from the GOT */
1852 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1853 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1856 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1857 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1859 ARM_B_COND (code, ARMCOND_EQ, 0);
1861 /* End-of-loop check */
1862 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1864 ARM_B_COND (code, ARMCOND_EQ, 0);
1867 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1870 arm_patch (labels [4], labels [1]);
1873 arm_patch (labels [2], code);
1874 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1875 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1876 /* Save it to the third stack slot */
1877 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1878 /* Restore the registers and branch */
1879 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1882 arm_patch (labels [3], code);
1883 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1884 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1885 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1889 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1891 emit_bytes (acfg, buf, code - buf);
1892 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1894 *tramp_size = code - buf + 4;
1895 #elif defined(TARGET_ARM64)
1896 arm64_emit_imt_thunk (acfg, offset, tramp_size);
1897 #elif defined(TARGET_POWERPC)
1899 guint8 *code, *labels [16];
1903 /* Load the mscorlib got address */
1904 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1905 /* Load the parameter from the GOT */
1906 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1907 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1909 /* Load and check key */
1911 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1912 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1914 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1916 /* End-of-loop check */
1917 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1919 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1922 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1925 mono_ppc_patch (labels [4], labels [1]);
1928 mono_ppc_patch (labels [2], code);
1929 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1930 /* r11 now contains the value of the vtable slot */
1931 /* this is not a function descriptor on ppc64 */
1932 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1933 ppc_mtctr (code, ppc_r11);
1934 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1937 mono_ppc_patch (labels [3], code);
1941 *tramp_size = code - buf;
1943 emit_bytes (acfg, buf, code - buf);
1945 g_assert_not_reached ();
1950 * arch_emit_gsharedvt_arg_trampoline:
1952 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1953 * two GOT slots which contain the argument, and the code to jump to.
1954 * TRAMP_SIZE is set to the size of the emitted trampoline.
1955 * These kinds of trampolines cannot be enumerated statically, since there could
1956 * be one trampoline per method instantiation, so we emit the same code for all
1957 * trampolines, and parameterize them using two GOT slots.
1960 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1962 #if defined(TARGET_X86)
1966 /* Similar to the PPC code above */
1968 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1971 /* Load mscorlib got address */
1972 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1974 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1975 /* Branch to the target address */
1976 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1978 #ifdef __native_client_codegen__
1980 /* emit nops to next 32 byte alignment */
1981 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1982 while (code < (buf + a)) x86_nop(code);
1986 emit_bytes (acfg, buf, code - buf);
1988 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1989 g_assert (code - buf == *tramp_size);
1990 #elif defined(TARGET_ARM)
1994 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1995 /* Similar to arch_emit_specific_trampoline () */
1998 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1999 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2000 /* Load the arg value from the GOT */
2001 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2002 /* Load the addr from the GOT */
2003 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2005 ARM_BX (code, ARMREG_R1);
2007 g_assert (code - buf == 20);
2010 emit_bytes (acfg, buf, code - buf);
2011 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2012 #elif defined(TARGET_ARM64)
2013 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2015 g_assert_not_reached ();
2020 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2022 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2023 /* Based on code generated by gcc */
2024 emit_unset_mode (acfg);
2027 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2028 ".section .ctors,\"aw\",@progbits\n"
2032 ".section .opd,\"aw\"\n"
2035 ".long .%s,.TOC.@tocbase32\n"
2038 ".type .%s,@function\n"
2040 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2042 ".section .ctors,\"aw\",@progbits\n"
2046 ".section .opd,\"aw\"\n"
2049 ".long .%1$s,.TOC.@tocbase32\n"
2050 ".size %1$s,.-%1$s\n"
2052 ".type .%1$s,@function\n"
2054 ".%1$s:\n", symbol);
2065 "lis 3, .Lglobals@h\n"
2066 "ori 3, 3, .Lglobals@l\n"
2067 "bl .mono_aot_register_module\n"
2075 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2077 ".size .%s,.-.%s\n", symbol, symbol);
2080 ".size .%1$s,.-.%1$s\n", symbol);
2086 /* END OF ARCH SPECIFIC CODE */
2089 mono_get_field_token (MonoClassField *field)
2091 MonoClass *klass = field->parent;
2094 for (i = 0; i < klass->field.count; ++i) {
2095 if (field == &klass->fields [i])
2096 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2099 g_assert_not_reached ();
2104 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2108 //printf ("ENCODE: %d 0x%x.\n", value, value);
2111 * Same encoding as the one used in the metadata, extended to handle values
2112 * greater than 0x1fffffff.
2114 if ((value >= 0) && (value <= 127))
2116 else if ((value >= 0) && (value <= 16383)) {
2117 p [0] = 0x80 | (value >> 8);
2118 p [1] = value & 0xff;
2120 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2121 p [0] = (value >> 24) | 0xc0;
2122 p [1] = (value >> 16) & 0xff;
2123 p [2] = (value >> 8) & 0xff;
2124 p [3] = value & 0xff;
2129 p [1] = (value >> 24) & 0xff;
2130 p [2] = (value >> 16) & 0xff;
2131 p [3] = (value >> 8) & 0xff;
2132 p [4] = value & 0xff;
2140 stream_init (MonoDynamicStream *sh)
2143 sh->alloc_size = 4096;
2144 sh->data = g_malloc (4096);
2146 /* So offsets are > 0 */
2152 make_room_in_stream (MonoDynamicStream *stream, int size)
2154 if (size <= stream->alloc_size)
2157 while (stream->alloc_size <= size) {
2158 if (stream->alloc_size < 4096)
2159 stream->alloc_size = 4096;
2161 stream->alloc_size *= 2;
2164 stream->data = g_realloc (stream->data, stream->alloc_size);
2168 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2172 make_room_in_stream (stream, stream->index + len);
2173 memcpy (stream->data + stream->index, data, len);
2174 idx = stream->index;
2175 stream->index += len;
2182 * Add data to the binary blob inside the aot image. Returns the offset inside the
2183 * blob where the data was stored.
2186 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2188 if (acfg->blob.alloc_size == 0)
2189 stream_init (&acfg->blob);
2191 return add_stream_data (&acfg->blob, (char*)data, data_len);
2195 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2200 if (acfg->blob.alloc_size == 0)
2201 stream_init (&acfg->blob);
2203 count = acfg->blob.index % align;
2205 /* we assume the stream data will be aligned */
2207 add_stream_data (&acfg->blob, buf, 4 - count);
2209 return add_stream_data (&acfg->blob, (char*)data, data_len);
2213 * emit_offset_table:
2215 * Emit a table of increasing offsets in a compact form using differential encoding.
2216 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2217 * group size, the more compact the table becomes, but the slower it becomes to compute
2218 * a given entry. Returns the size of the table.
2221 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2223 gint32 current_offset;
2224 int i, buf_size, ngroups, index_entry_size;
2226 guint32 *index_offsets;
2228 ngroups = (noffsets + (group_size - 1)) / group_size;
2230 index_offsets = g_new0 (guint32, ngroups);
2232 buf_size = noffsets * 4;
2233 p = buf = g_malloc0 (buf_size);
2236 for (i = 0; i < noffsets; ++i) {
2237 //printf ("D: %d -> %d\n", i, offsets [i]);
2238 if ((i % group_size) == 0) {
2239 index_offsets [i / group_size] = p - buf;
2240 /* Emit the full value for these entries */
2241 encode_value (offsets [i], p, &p);
2243 /* The offsets are allowed to be non-increasing */
2244 //g_assert (offsets [i] >= current_offset);
2245 encode_value (offsets [i] - current_offset, p, &p);
2247 current_offset = offsets [i];
2250 if (ngroups && index_offsets [ngroups - 1] < 65000)
2251 index_entry_size = 2;
2253 index_entry_size = 4;
2255 /* Emit the header */
2256 emit_int32 (acfg, noffsets);
2257 emit_int32 (acfg, group_size);
2258 emit_int32 (acfg, ngroups);
2259 emit_int32 (acfg, index_entry_size);
2261 /* Emit the index */
2262 for (i = 0; i < ngroups; ++i) {
2263 if (index_entry_size == 2)
2264 emit_int16 (acfg, index_offsets [i]);
2266 emit_int32 (acfg, index_offsets [i]);
2270 emit_bytes (acfg, buf, p - buf);
2272 return (int)(p - buf) + (ngroups * 4);
2276 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2280 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2284 index = g_hash_table_size (cfg->image_hash);
2285 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2286 g_ptr_array_add (cfg->image_table, image);
2292 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2295 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2297 /* FIXME: Search referenced images as well */
2298 if (!acfg->typespec_classes) {
2299 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2300 for (i = 0; i < len; ++i) {
2301 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2304 for (i = 0; i < len; ++i) {
2305 if (acfg->typespec_classes [i] == klass)
2310 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2316 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2319 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2322 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2325 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2328 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2333 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2337 if (klass->generic_class) {
2339 g_assert (klass->type_token);
2341 /* Find a typespec for a class if possible */
2342 token = find_typespec_for_class (acfg, klass);
2344 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2345 encode_value (token, p, &p);
2347 MonoClass *gclass = klass->generic_class->container_class;
2348 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2349 static int count = 0;
2352 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2353 encode_klass_ref (acfg, gclass, p, &p);
2354 encode_ginst (acfg, inst, p, &p);
2358 } else if (klass->type_token) {
2359 int iindex = get_image_index (acfg, klass->image);
2361 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2363 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2364 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2366 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2367 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2368 encode_value (get_image_index (acfg, klass->image), p, &p);
2370 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2371 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2372 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2374 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2375 encode_value (klass->byval_arg.type, p, &p);
2376 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2378 encode_value (container ? 1 : 0, p, &p);
2380 encode_value (container->is_method, p, &p);
2381 g_assert (par->serial == 0);
2382 if (container->is_method)
2383 encode_method_ref (acfg, container->owner.method, p, &p);
2385 encode_klass_ref (acfg, container->owner.klass, p, &p);
2387 encode_value (par->serial, p, &p);
2389 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2390 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2391 encode_type (acfg, &klass->byval_arg, p, &p);
2394 g_assert (klass->rank > 0);
2395 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2396 encode_value (klass->rank, p, &p);
2397 encode_klass_ref (acfg, klass->element_class, p, &p);
2405 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2406 * standard metadata encoding.
2409 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2411 gboolean shared = FALSE;
2414 * The encoding of generic instances is large so emit them only once.
2416 if (klass->generic_class) {
2418 g_assert (klass->type_token);
2420 /* Find a typespec for a class if possible */
2421 token = find_typespec_for_class (acfg, klass);
2424 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2429 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2433 buf2 = g_malloc (1024);
2436 encode_klass_ref_inner (acfg, klass, p, &p);
2437 g_assert (p - buf2 < 1024);
2439 offset = add_to_blob (acfg, buf2, p - buf2);
2442 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2448 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2449 encode_value (offset, p, &p);
2454 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2458 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2460 guint32 token = mono_get_field_token (field);
2463 encode_klass_ref (cfg, field->parent, p, &p);
2464 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2465 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2470 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2475 encode_value (inst->type_argc, p, &p);
2476 for (i = 0; i < inst->type_argc; ++i)
2477 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2482 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2485 MonoGenericInst *inst;
2487 inst = context->class_inst;
2489 g_assert (inst->type_argc);
2490 encode_ginst (acfg, inst, p, &p);
2492 encode_value (0, p, &p);
2494 inst = context->method_inst;
2496 g_assert (inst->type_argc);
2497 encode_ginst (acfg, inst, p, &p);
2499 encode_value (0, p, &p);
2505 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2509 g_assert (t->num_mods == 0);
2510 /* t->attrs can be ignored */
2511 //g_assert (t->attrs == 0);
2514 *p = MONO_TYPE_PINNED;
2518 *p = MONO_TYPE_BYREF;
2526 case MONO_TYPE_VOID:
2527 case MONO_TYPE_BOOLEAN:
2528 case MONO_TYPE_CHAR:
2541 case MONO_TYPE_STRING:
2542 case MONO_TYPE_OBJECT:
2543 case MONO_TYPE_TYPEDBYREF:
2545 case MONO_TYPE_VALUETYPE:
2546 case MONO_TYPE_CLASS:
2547 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2549 case MONO_TYPE_SZARRAY:
2550 encode_klass_ref (acfg, t->data.klass, p, &p);
2553 encode_type (acfg, t->data.type, p, &p);
2555 case MONO_TYPE_GENERICINST: {
2556 MonoClass *gclass = t->data.generic_class->container_class;
2557 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2559 encode_klass_ref (acfg, gclass, p, &p);
2560 encode_ginst (acfg, inst, p, &p);
2563 case MONO_TYPE_ARRAY: {
2564 MonoArrayType *array = t->data.array;
2567 encode_klass_ref (acfg, array->eklass, p, &p);
2568 encode_value (array->rank, p, &p);
2569 encode_value (array->numsizes, p, &p);
2570 for (i = 0; i < array->numsizes; ++i)
2571 encode_value (array->sizes [i], p, &p);
2572 encode_value (array->numlobounds, p, &p);
2573 for (i = 0; i < array->numlobounds; ++i)
2574 encode_value (array->lobounds [i], p, &p);
2578 case MONO_TYPE_MVAR:
2579 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2582 g_assert_not_reached ();
2589 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2595 /* Similar to the metadata encoding */
2596 if (sig->generic_param_count)
2600 if (sig->explicit_this)
2602 flags |= (sig->call_convention & 0x0F);
2606 if (sig->generic_param_count)
2607 encode_value (sig->generic_param_count, p, &p);
2608 encode_value (sig->param_count, p, &p);
2610 encode_type (acfg, sig->ret, p, &p);
2611 for (i = 0; i < sig->param_count; ++i) {
2612 if (sig->sentinelpos == i) {
2613 *p = MONO_TYPE_SENTINEL;
2616 encode_type (acfg, sig->params [i], p, &p);
2622 #define MAX_IMAGE_INDEX 250
2625 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2627 guint32 image_index = get_image_index (acfg, method->klass->image);
2628 guint32 token = method->token;
2629 MonoJumpInfoToken *ji;
2633 * The encoding for most methods is as follows:
2634 * - image index encoded as a leb128
2635 * - token index encoded as a leb128
2636 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2637 * types of method encodings.
2640 /* Mark methods which can't use aot trampolines because they need the further
2641 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2643 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2644 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2645 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2647 if (method->wrapper_type) {
2648 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2650 encode_value (method->wrapper_type, p, &p);
2652 switch (method->wrapper_type) {
2653 case MONO_WRAPPER_REMOTING_INVOKE:
2654 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2655 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2658 m = mono_marshal_method_from_wrapper (method);
2660 encode_method_ref (acfg, m, p, &p);
2663 case MONO_WRAPPER_PROXY_ISINST:
2664 case MONO_WRAPPER_LDFLD:
2665 case MONO_WRAPPER_LDFLDA:
2666 case MONO_WRAPPER_STFLD:
2667 case MONO_WRAPPER_ISINST: {
2668 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2669 encode_klass_ref (acfg, proxy_class, p, &p);
2672 case MONO_WRAPPER_LDFLD_REMOTE:
2673 case MONO_WRAPPER_STFLD_REMOTE:
2675 case MONO_WRAPPER_ALLOC: {
2676 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2678 /* The GC name is saved once in MonoAotFileInfo */
2679 g_assert (info->alloc_type != -1);
2680 encode_value (info->alloc_type, p, &p);
2683 case MONO_WRAPPER_WRITE_BARRIER:
2685 case MONO_WRAPPER_STELEMREF: {
2686 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2689 encode_value (info->subtype, p, &p);
2690 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2691 encode_value (info->d.virtual_stelemref.kind, p, &p);
2694 case MONO_WRAPPER_UNKNOWN: {
2695 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2698 encode_value (info->subtype, p, &p);
2699 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2700 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2701 encode_klass_ref (acfg, method->klass, p, &p);
2702 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2703 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2704 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2705 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2708 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2709 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2712 encode_value (info->subtype, p, &p);
2713 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2714 strcpy ((char*)p, method->name);
2715 p += strlen (method->name) + 1;
2716 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2717 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2719 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2720 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2724 case MONO_WRAPPER_SYNCHRONIZED: {
2727 m = mono_marshal_method_from_wrapper (method);
2729 g_assert (m != method);
2730 encode_method_ref (acfg, m, p, &p);
2733 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2734 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2737 encode_value (info->subtype, p, &p);
2739 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2740 encode_value (info->d.element_addr.rank, p, &p);
2741 encode_value (info->d.element_addr.elem_size, p, &p);
2742 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2743 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2745 g_assert_not_reached ();
2749 case MONO_WRAPPER_CASTCLASS: {
2750 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2753 encode_value (info->subtype, p, &p);
2756 case MONO_WRAPPER_RUNTIME_INVOKE: {
2757 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2760 encode_value (info->subtype, p, &p);
2761 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2762 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2763 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2764 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2767 case MONO_WRAPPER_DELEGATE_INVOKE:
2768 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2769 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2770 if (method->is_inflated) {
2771 /* These wrappers are identified by their class */
2772 encode_value (1, p, &p);
2773 encode_klass_ref (acfg, method->klass, p, &p);
2775 MonoMethodSignature *sig = mono_method_signature (method);
2776 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2778 encode_value (0, p, &p);
2779 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2780 encode_value (info ? info->subtype : 0, p, &p);
2781 encode_signature (acfg, sig, p, &p);
2785 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2786 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2789 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2790 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2794 g_assert_not_reached ();
2796 } else if (mono_method_signature (method)->is_inflated) {
2798 * This is a generic method, find the original token which referenced it and
2800 * Obtain the token from information recorded by the JIT.
2802 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2804 image_index = get_image_index (acfg, ji->image);
2805 g_assert (image_index < MAX_IMAGE_INDEX);
2808 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2809 encode_value (image_index, p, &p);
2810 encode_value (token, p, &p);
2812 MonoMethod *declaring;
2813 MonoGenericContext *context = mono_method_get_context (method);
2815 g_assert (method->is_inflated);
2816 declaring = ((MonoMethodInflated*)method)->declaring;
2819 * This might be a non-generic method of a generic instance, which
2820 * doesn't have a token since the reference is generated by the JIT
2821 * like Nullable:Box/Unbox, or by generic sharing.
2823 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2824 /* Encode the klass */
2825 encode_klass_ref (acfg, method->klass, p, &p);
2826 /* Encode the method */
2827 image_index = get_image_index (acfg, method->klass->image);
2828 g_assert (image_index < MAX_IMAGE_INDEX);
2829 g_assert (declaring->token);
2830 token = declaring->token;
2831 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2832 encode_value (image_index, p, &p);
2833 encode_value (token, p, &p);
2834 encode_generic_context (acfg, context, p, &p);
2836 } else if (token == 0) {
2837 /* This might be a method of a constructed type like int[,].Set */
2838 /* Obtain the token from information recorded by the JIT */
2839 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2841 image_index = get_image_index (acfg, ji->image);
2842 g_assert (image_index < MAX_IMAGE_INDEX);
2845 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2846 encode_value (image_index, p, &p);
2847 encode_value (token, p, &p);
2850 g_assert (method->klass->rank);
2852 /* Encode directly */
2853 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2854 encode_klass_ref (acfg, method->klass, p, &p);
2855 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2856 encode_value (0, p, &p);
2857 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2858 encode_value (1, p, &p);
2859 else if (!strcmp (method->name, "Get"))
2860 encode_value (2, p, &p);
2861 else if (!strcmp (method->name, "Address"))
2862 encode_value (3, p, &p);
2863 else if (!strcmp (method->name, "Set"))
2864 encode_value (4, p, &p);
2866 g_assert_not_reached ();
2869 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2871 if (image_index >= MONO_AOT_METHODREF_MIN) {
2872 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2873 encode_value (image_index, p, &p);
2874 encode_value (mono_metadata_token_index (token), p, &p);
2876 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2883 compare_patches (gconstpointer a, gconstpointer b)
2887 i = (*(MonoJumpInfo**)a)->ip.i;
2888 j = (*(MonoJumpInfo**)b)->ip.i;
2899 static G_GNUC_UNUSED char*
2900 patch_to_string (MonoJumpInfo *patch_info)
2904 str = g_string_new ("");
2906 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2908 switch (patch_info->type) {
2909 case MONO_PATCH_INFO_VTABLE:
2910 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2915 g_string_append_printf (str, ")");
2916 return g_string_free (str, FALSE);
2922 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2925 static inline gboolean
2926 is_plt_patch (MonoJumpInfo *patch_info)
2928 switch (patch_info->type) {
2929 case MONO_PATCH_INFO_METHOD:
2930 case MONO_PATCH_INFO_INTERNAL_METHOD:
2931 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2932 case MONO_PATCH_INFO_ICALL_ADDR:
2933 case MONO_PATCH_INFO_CLASS_INIT:
2934 case MONO_PATCH_INFO_RGCTX_FETCH:
2935 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2936 case MONO_PATCH_INFO_MONITOR_ENTER:
2937 case MONO_PATCH_INFO_MONITOR_EXIT:
2938 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2948 * Return the symbol identifying the plt entry PLT_OFFSET.
2951 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2955 * The Apple linker reorganizes object files, so it doesn't like branches to local
2956 * labels, since those have no relocations.
2958 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2960 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2967 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2969 static MonoPltEntry*
2970 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2974 if (!is_plt_patch (patch_info))
2977 if (!acfg->patch_to_plt_entry [patch_info->type])
2978 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
2979 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
2981 // FIXME: This breaks the calculation of final_got_size
2982 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2984 * Allocate a separate PLT slot for each such patch, since some plt
2985 * entries will refer to the method itself, and some will refer to the
2992 MonoJumpInfo *new_ji;
2994 g_assert (!acfg->final_got_size);
2996 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2998 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2999 res->plt_offset = acfg->plt_offset;
3001 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3002 if (acfg->aot_opts.write_symbols)
3003 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3005 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3007 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3009 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3011 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3013 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3014 //mono_print_ji (patch_info); printf ("\n");
3015 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3017 acfg->plt_offset ++;
3026 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3027 * JI could be found if it exists, otherwise allocates a new one.
3030 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
3034 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
3036 return got_offset - 1;
3038 got_offset = acfg->got_offset;
3039 acfg->got_offset ++;
3041 if (acfg->final_got_size)
3042 g_assert (got_offset < acfg->final_got_size);
3044 acfg->stats.got_slots ++;
3045 acfg->stats.got_slot_types [ji->type] ++;
3047 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3048 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3049 g_ptr_array_add (acfg->got_patches, ji);
3054 /* Add a method to the list of methods which need to be emitted */
3056 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3059 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3060 g_ptr_array_add (acfg->methods, method);
3061 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3062 acfg->nmethods = acfg->methods->len + 1;
3065 if (method->wrapper_type || extra)
3066 g_ptr_array_add (acfg->extra_methods, method);
3070 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3072 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3080 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3084 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3088 index = acfg->method_index;
3089 add_method_with_index (acfg, method, index, extra);
3091 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3093 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3095 acfg->method_index ++;
3101 add_method (MonoAotCompile *acfg, MonoMethod *method)
3103 return add_method_full (acfg, method, FALSE, 0);
3107 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3109 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3110 method = mini_get_shared_method (method);
3112 if (acfg->aot_opts.log_generics)
3113 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3115 add_method_full (acfg, method, TRUE, depth);
3119 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3121 add_extra_method_with_depth (acfg, method, 0);
3125 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3127 MonoAotCompile *acfg = user_data;
3128 MonoJitICallInfo *callinfo = value;
3129 MonoMethod *wrapper;
3135 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3136 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3139 add_method (acfg, wrapper);
3143 get_runtime_invoke_sig (MonoMethodSignature *sig)
3145 MonoMethodBuilder *mb;
3148 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3149 m = mono_mb_create_method (mb, sig, 16);
3150 return mono_marshal_get_runtime_invoke (m, FALSE);
3154 can_marshal_struct (MonoClass *klass)
3156 MonoClassField *field;
3157 gboolean can_marshal = TRUE;
3158 gpointer iter = NULL;
3159 MonoMarshalType *info;
3162 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3165 info = mono_marshal_load_type_info (klass);
3167 /* Only allow a few field types to avoid asserts in the marshalling code */
3168 while ((field = mono_class_get_fields (klass, &iter))) {
3169 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3172 switch (field->type->type) {
3177 case MONO_TYPE_BOOLEAN:
3180 case MONO_TYPE_CHAR:
3188 case MONO_TYPE_STRING:
3190 case MONO_TYPE_VALUETYPE:
3191 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3192 can_marshal = FALSE;
3194 case MONO_TYPE_SZARRAY: {
3195 gboolean has_mspec = FALSE;
3198 for (i = 0; i < info->num_fields; ++i) {
3199 if (info->fields [i].field == field && info->fields [i].mspec)
3204 can_marshal = FALSE;
3208 can_marshal = FALSE;
3214 /* Its hard to compute whenever these can be marshalled or not */
3215 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3222 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3224 /* Create a vtype instantiation */
3225 MonoGenericContext shared_context;
3227 MonoGenericInst *inst;
3228 MonoGenericContainer *container;
3229 MonoClass **constraints;
3232 memset (ctx, 0, sizeof (MonoGenericContext));
3234 if (method->klass->generic_container) {
3235 shared_context = method->klass->generic_container->context;
3236 inst = shared_context.class_inst;
3238 args = g_new0 (MonoType*, inst->type_argc);
3239 for (i = 0; i < inst->type_argc; ++i) {
3240 args [i] = &mono_defaults.int_class->byval_arg;
3242 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3244 if (method->is_generic) {
3245 container = mono_method_get_generic_container (method);
3246 shared_context = container->context;
3247 inst = shared_context.method_inst;
3249 args = g_new0 (MonoType*, inst->type_argc);
3250 for (i = 0; i < container->type_argc; ++i) {
3251 MonoGenericParamInfo *info = &container->type_params [i].info;
3252 gboolean ref_only = FALSE;
3254 if (info && info->constraints) {
3255 constraints = info->constraints;
3257 while (*constraints) {
3258 MonoClass *cklass = *constraints;
3259 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3260 /* Inflaring the method with our vtype would not be valid */
3267 args [i] = &mono_defaults.object_class->byval_arg;
3269 args [i] = &mono_defaults.int_class->byval_arg;
3271 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3276 add_wrappers (MonoAotCompile *acfg)
3278 MonoMethod *method, *m;
3280 MonoMethodSignature *sig, *csig;
3284 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3285 * so there is only one wrapper of a given type, or inlining their contents into their
3288 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3290 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3291 gboolean skip = FALSE;
3293 method = mono_get_method (acfg->image, token, NULL);
3295 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3296 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3297 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3300 /* Skip methods which can not be handled by get_runtime_invoke () */
3301 sig = mono_method_signature (method);
3304 if ((sig->ret->type == MONO_TYPE_PTR) ||
3305 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3307 if (mono_class_is_open_constructed_type (sig->ret))
3310 for (j = 0; j < sig->param_count; j++) {
3311 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3313 if (mono_class_is_open_constructed_type (sig->params [j]))
3317 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3318 if (!mono_class_is_contextbound (method->klass)) {
3319 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3320 gboolean has_nullable = FALSE;
3322 for (j = 0; j < sig->param_count; j++) {
3323 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3324 has_nullable = TRUE;
3327 if (info && !has_nullable) {
3328 /* Supported by the dynamic runtime-invoke wrapper */
3336 //printf ("%s\n", mono_method_full_name (method, TRUE));
3337 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3341 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3342 MonoMethodDesc *desc;
3343 MonoMethod *orig_method;
3346 /* Runtime invoke wrappers */
3348 /* void runtime-invoke () [.cctor] */
3349 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3350 csig->ret = &mono_defaults.void_class->byval_arg;
3351 add_method (acfg, get_runtime_invoke_sig (csig));
3353 /* void runtime-invoke () [Finalize] */
3354 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3356 csig->ret = &mono_defaults.void_class->byval_arg;
3357 add_method (acfg, get_runtime_invoke_sig (csig));
3359 /* void runtime-invoke (string) [exception ctor] */
3360 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3362 csig->ret = &mono_defaults.void_class->byval_arg;
3363 csig->params [0] = &mono_defaults.string_class->byval_arg;
3364 add_method (acfg, get_runtime_invoke_sig (csig));
3366 /* void runtime-invoke (string, string) [exception ctor] */
3367 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3369 csig->ret = &mono_defaults.void_class->byval_arg;
3370 csig->params [0] = &mono_defaults.string_class->byval_arg;
3371 csig->params [1] = &mono_defaults.string_class->byval_arg;
3372 add_method (acfg, get_runtime_invoke_sig (csig));
3374 /* string runtime-invoke () [Exception.ToString ()] */
3375 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3377 csig->ret = &mono_defaults.string_class->byval_arg;
3378 add_method (acfg, get_runtime_invoke_sig (csig));
3380 /* void runtime-invoke (string, Exception) [exception ctor] */
3381 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3383 csig->ret = &mono_defaults.void_class->byval_arg;
3384 csig->params [0] = &mono_defaults.string_class->byval_arg;
3385 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3386 add_method (acfg, get_runtime_invoke_sig (csig));
3388 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3389 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3391 csig->ret = &(mono_class_from_name (
3392 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3393 csig->params [0] = &mono_defaults.string_class->byval_arg;
3394 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3395 add_method (acfg, get_runtime_invoke_sig (csig));
3397 /* runtime-invoke used by finalizers */
3398 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3400 /* This is used by mono_runtime_capture_context () */
3401 method = mono_get_context_capture_method ();
3403 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3405 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3406 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3410 add_method (acfg, mono_marshal_get_stelemref ());
3412 if (MONO_ARCH_HAVE_TLS_GET) {
3413 /* Managed Allocators */
3414 nallocators = mono_gc_get_managed_allocator_types ();
3415 for (i = 0; i < nallocators; ++i) {
3416 m = mono_gc_get_managed_allocator_by_type (i);
3418 add_method (acfg, m);
3421 /* Monitor Enter/Exit */
3422 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3423 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3424 /* This is a v4 method */
3426 method = mono_monitor_get_fast_path (orig_method);
3428 add_method (acfg, method);
3430 mono_method_desc_free (desc);
3432 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3433 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3434 g_assert (orig_method);
3435 mono_method_desc_free (desc);
3436 method = mono_monitor_get_fast_path (orig_method);
3438 add_method (acfg, method);
3441 /* Stelemref wrappers */
3443 MonoMethod **wrappers;
3446 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3447 for (i = 0; i < nwrappers; ++i)
3448 add_method (acfg, wrappers [i]);
3452 /* castclass_with_check wrapper */
3453 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3454 /* isinst_with_check wrapper */
3455 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3457 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3459 MonoMethodDesc *desc;
3462 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3463 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3464 mono_method_desc_free (desc);
3466 m = mono_monitor_get_fast_path (m);
3468 add_method (acfg, m);
3473 /* JIT icall wrappers */
3474 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3475 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3479 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3480 * we use the original method instead at runtime.
3481 * Since full-aot doesn't support remoting, this is not a problem.
3484 /* remoting-invoke wrappers */
3485 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3486 MonoMethodSignature *sig;
3488 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3489 method = mono_get_method (acfg->image, token, NULL);
3491 sig = mono_method_signature (method);
3493 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3494 m = mono_marshal_get_remoting_invoke_with_check (method);
3496 add_method (acfg, m);
3501 /* delegate-invoke wrappers */
3502 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3504 MonoCustomAttrInfo *cattr;
3506 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3507 klass = mono_class_get (acfg->image, token);
3510 mono_loader_clear_error ();
3514 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3517 if (!klass->generic_container) {
3518 method = mono_get_delegate_invoke (klass);
3520 m = mono_marshal_get_delegate_invoke (method, NULL);
3522 add_method (acfg, m);
3524 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3526 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3528 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3530 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3532 cattr = mono_custom_attrs_from_class (klass);
3537 for (j = 0; j < cattr->num_attrs; ++j)
3538 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3540 if (j < cattr->num_attrs)
3541 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3543 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3544 MonoGenericContext ctx;
3545 MonoMethod *inst, *gshared;
3548 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3551 method = mono_get_delegate_invoke (klass);
3552 create_gsharedvt_inst (acfg, method, &ctx);
3554 inst = mono_class_inflate_generic_method (method, &ctx);
3556 m = mono_marshal_get_delegate_invoke (inst, NULL);
3557 g_assert (m->is_inflated);
3559 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3560 add_extra_method (acfg, gshared);
3563 method = mono_get_delegate_begin_invoke (klass);
3564 create_gsharedvt_inst (acfg, method, &ctx);
3566 inst = mono_class_inflate_generic_method (method, &ctx);
3568 m = mono_marshal_get_delegate_begin_invoke (inst);
3569 g_assert (m->is_inflated);
3571 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3572 add_extra_method (acfg, gshared);
3575 method = mono_get_delegate_end_invoke (klass);
3576 create_gsharedvt_inst (acfg, method, &ctx);
3578 inst = mono_class_inflate_generic_method (method, &ctx);
3580 m = mono_marshal_get_delegate_end_invoke (inst);
3581 g_assert (m->is_inflated);
3583 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3584 add_extra_method (acfg, gshared);
3589 /* array access wrappers */
3590 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3593 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3594 klass = mono_class_get (acfg->image, token);
3597 mono_loader_clear_error ();
3601 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3602 MonoMethod *m, *wrapper;
3604 /* Add runtime-invoke wrappers too */
3606 m = mono_class_get_method_from_name (klass, "Get", -1);
3608 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3609 add_extra_method (acfg, wrapper);
3610 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3612 m = mono_class_get_method_from_name (klass, "Set", -1);
3614 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3615 add_extra_method (acfg, wrapper);
3616 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3620 /* Synchronized wrappers */
3621 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3622 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3623 method = mono_get_method (acfg->image, token, NULL);
3625 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3626 if (method->is_generic) {
3628 } else if (method->klass->generic_container) {
3629 MonoGenericContext ctx;
3630 MonoMethod *inst, *gshared, *m;
3633 * Create a generic wrapper for a generic instance, and AOT that.
3635 create_gsharedvt_inst (acfg, method, &ctx);
3636 inst = mono_class_inflate_generic_method (method, &ctx);
3637 m = mono_marshal_get_synchronized_wrapper (inst);
3638 g_assert (m->is_inflated);
3639 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3640 add_method (acfg, gshared);
3642 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3647 /* pinvoke wrappers */
3648 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3650 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3652 method = mono_get_method (acfg->image, token, NULL);
3654 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3655 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3656 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3660 /* native-to-managed wrappers */
3661 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3663 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3664 MonoCustomAttrInfo *cattr;
3667 method = mono_get_method (acfg->image, token, NULL);
3670 * Only generate native-to-managed wrappers for methods which have an
3671 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3672 * name to avoid defining a new assembly to contain it.
3674 cattr = mono_custom_attrs_from_method (method);
3677 for (j = 0; j < cattr->num_attrs; ++j)
3678 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3680 if (j < cattr->num_attrs) {
3681 MonoCustomAttrEntry *e = &cattr->attrs [j];
3682 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3683 const char *p = (const char*)e->data;
3685 int slen, num_named, named_type, data_type;
3689 char *export_name = NULL;
3690 MonoMethod *wrapper;
3692 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3693 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3694 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3695 mono_method_full_name (method, TRUE));
3699 g_assert (sig->param_count == 1);
3700 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3703 * Decode the cattr manually since we can't create objects
3704 * during aot compilation.
3710 /* From load_cattr_value () in reflection.c */
3711 slen = mono_metadata_decode_value (p, &p);
3712 n = g_memdup (p, slen + 1);
3714 t = mono_reflection_type_from_name (n, acfg->image);
3718 klass = mono_class_from_mono_type (t);
3719 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3723 num_named = read16 (p);
3726 g_assert (num_named < 2);
3727 if (num_named == 1) {
3730 MonoType *prop_type;
3732 /* parse ExportSymbol attribute */
3734 named_type = *named;
3739 name_len = mono_metadata_decode_blob_size (named, &named);
3740 name = g_malloc (name_len + 1);
3741 memcpy (name, named, name_len);
3742 name [name_len] = 0;
3745 g_assert (named_type == 0x54);
3746 g_assert (!strcmp (name, "ExportSymbol"));
3748 prop_type = &mono_defaults.string_class->byval_arg;
3750 /* load_cattr_value (), string case */
3751 g_assert (*named != (char)0xff);
3752 slen = mono_metadata_decode_value (named, &named);
3753 export_name = g_malloc (slen + 1);
3754 memcpy (export_name, named, slen);
3755 export_name [slen] = 0;
3759 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3760 add_method (acfg, wrapper);
3762 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3766 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3767 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3768 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3772 /* StructureToPtr/PtrToStructure wrappers */
3773 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3776 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3777 klass = mono_class_get (acfg->image, token);
3780 mono_loader_clear_error ();
3784 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3785 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3786 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3787 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3793 has_type_vars (MonoClass *klass)
3795 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3798 return has_type_vars (klass->element_class);
3799 if (klass->generic_class) {
3800 MonoGenericContext *context = &klass->generic_class->context;
3801 if (context->class_inst) {
3804 for (i = 0; i < context->class_inst->type_argc; ++i)
3805 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3809 if (klass->generic_container)
3815 is_vt_inst (MonoGenericInst *inst)
3819 for (i = 0; i < inst->type_argc; ++i) {
3820 MonoType *t = inst->type_argv [i];
3821 if (t->type == MONO_TYPE_VALUETYPE)
3828 method_has_type_vars (MonoMethod *method)
3830 if (has_type_vars (method->klass))
3833 if (method->is_inflated) {
3834 MonoGenericContext *context = mono_method_get_context (method);
3835 if (context->method_inst) {
3838 for (i = 0; i < context->method_inst->type_argc; ++i)
3839 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3846 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3849 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3851 /* This might lead to a huge code blowup so only do it if neccesary */
3852 if (!acfg->aot_opts.full_aot && !force)
3855 add_generic_class_with_depth (acfg, klass, 0, ref);
3859 check_type_depth (MonoType *t, int depth)
3867 case MONO_TYPE_GENERICINST: {
3868 MonoGenericClass *gklass = t->data.generic_class;
3869 MonoGenericInst *ginst = gklass->context.class_inst;
3872 for (i = 0; i < ginst->type_argc; ++i) {
3873 if (check_type_depth (ginst->type_argv [i], depth + 1))
3887 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3890 * add_generic_class:
3892 * Add all methods of a generic class.
3895 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3898 MonoClassField *field;
3900 gboolean use_gsharedvt = FALSE;
3902 if (!acfg->ginst_hash)
3903 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3905 mono_class_init (klass);
3907 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3910 if (has_type_vars (klass))
3913 if (!klass->generic_class && !klass->rank)
3916 if (klass->exception_type)
3919 if (!acfg->ginst_hash)
3920 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3922 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3925 if (check_type_depth (&klass->byval_arg, 0))
3928 if (acfg->aot_opts.log_generics)
3929 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3931 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3934 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3935 * Enable this only for some classes since gsharedvt might not support all methods.
3937 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) &&
3938 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
3939 use_gsharedvt = TRUE;
3942 while ((method = mono_class_get_methods (klass, &iter))) {
3943 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3945 * This is partial sharing, and we can't handle it yet
3950 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
3952 add_types_from_method_header (acfg, method);
3956 if (method->is_generic)
3961 * FIXME: Instances which are referenced by these methods are not added,
3962 * for example Array.Resize<int> for List<int>.Add ().
3964 add_extra_method_with_depth (acfg, method, depth + 1);
3968 while ((field = mono_class_get_fields (klass, &iter))) {
3969 if (field->type->type == MONO_TYPE_GENERICINST)
3970 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3973 if (klass->delegate) {
3974 method = mono_get_delegate_invoke (klass);
3976 method = mono_marshal_get_delegate_invoke (method, NULL);
3978 if (acfg->aot_opts.log_generics)
3979 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3981 add_method (acfg, method);
3984 /* Add superclasses */
3986 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3989 * For ICollection<T>, add instances of the helper methods
3990 * in Array, since a T[] could be cast to ICollection<T>.
3992 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3993 (!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"))) {
3994 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3995 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3999 if (!strcmp (klass->name, "IEnumerator`1"))
4000 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4002 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4004 /* Add the T[]/InternalEnumerator class */
4005 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4009 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4010 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4014 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4015 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4019 while ((method = mono_class_get_methods (array_class, &iter))) {
4020 if (strstr (method->name, name_prefix)) {
4021 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4023 add_extra_method_with_depth (acfg, m, depth);
4027 g_free (name_prefix);
4030 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4031 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4032 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4033 MonoClass *icomparable, *gcomparer;
4034 MonoGenericContext ctx;
4035 MonoType *args [16];
4037 memset (&ctx, 0, sizeof (ctx));
4039 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4040 g_assert (icomparable);
4041 args [0] = &tclass->byval_arg;
4042 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4044 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4045 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4046 g_assert (gcomparer);
4047 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4051 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4052 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4053 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4054 MonoClass *iface, *gcomparer;
4055 MonoGenericContext ctx;
4056 MonoType *args [16];
4058 memset (&ctx, 0, sizeof (ctx));
4060 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4062 args [0] = &tclass->byval_arg;
4063 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4065 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4066 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4067 g_assert (gcomparer);
4068 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4074 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4077 MonoGenericContext ctx;
4078 MonoType *args [16];
4080 if (acfg->aot_opts.no_instances)
4083 memset (&ctx, 0, sizeof (ctx));
4085 for (i = 0; i < ninsts; ++i) {
4086 args [0] = insts [i];
4087 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4088 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4093 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4095 MonoMethodHeader *header;
4096 MonoMethodSignature *sig;
4099 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4101 sig = mono_method_signature (method);
4104 for (j = 0; j < sig->param_count; ++j)
4105 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4106 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4109 header = mono_method_get_header (method);
4112 for (j = 0; j < header->num_locals; ++j)
4113 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4114 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4116 mono_loader_clear_error ();
4121 * add_generic_instances:
4123 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4126 add_generic_instances (MonoAotCompile *acfg)
4131 MonoGenericContext *context;
4133 if (acfg->aot_opts.no_instances)
4136 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4137 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4138 method = mono_get_method (acfg->image, token, NULL);
4143 if (method->klass->image != acfg->image)
4146 context = mono_method_get_context (method);
4148 if (context && ((context->class_inst && context->class_inst->is_open)))
4152 * For open methods, create an instantiation which can be passed to the JIT.
4153 * FIXME: Handle class_inst as well.
4155 if (context && context->method_inst && context->method_inst->is_open) {
4156 MonoGenericContext shared_context;
4157 MonoGenericInst *inst;
4158 MonoType **type_argv;
4160 MonoMethod *declaring_method;
4161 gboolean supported = TRUE;
4163 /* Check that the context doesn't contain open constructed types */
4164 if (context->class_inst) {
4165 inst = context->class_inst;
4166 for (i = 0; i < inst->type_argc; ++i) {
4167 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)
4169 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4173 if (context->method_inst) {
4174 inst = context->method_inst;
4175 for (i = 0; i < inst->type_argc; ++i) {
4176 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)
4178 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4186 memset (&shared_context, 0, sizeof (MonoGenericContext));
4188 inst = context->class_inst;
4190 type_argv = g_new0 (MonoType*, inst->type_argc);
4191 for (i = 0; i < inst->type_argc; ++i) {
4192 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)
4193 type_argv [i] = &mono_defaults.object_class->byval_arg;
4195 type_argv [i] = inst->type_argv [i];
4198 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4202 inst = context->method_inst;
4204 type_argv = g_new0 (MonoType*, inst->type_argc);
4205 for (i = 0; i < inst->type_argc; ++i) {
4206 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)
4207 type_argv [i] = &mono_defaults.object_class->byval_arg;
4209 type_argv [i] = inst->type_argv [i];
4212 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4216 if (method->is_generic || method->klass->generic_container)
4217 declaring_method = method;
4219 declaring_method = mono_method_get_declaring_generic_method (method);
4221 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4225 * If the method is fully sharable, it was already added in place of its
4226 * generic definition.
4228 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4232 * FIXME: Partially shared methods are not shared here, so we end up with
4233 * many identical methods.
4235 add_extra_method (acfg, method);
4238 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4241 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4243 klass = mono_class_get (acfg->image, token);
4244 if (!klass || klass->rank) {
4245 mono_loader_clear_error ();
4249 add_generic_class (acfg, klass, FALSE, "typespec");
4252 /* Add types of args/locals */
4253 for (i = 0; i < acfg->methods->len; ++i) {
4254 method = g_ptr_array_index (acfg->methods, i);
4255 add_types_from_method_header (acfg, method);
4258 if (acfg->image == mono_defaults.corlib) {
4260 MonoType *insts [256];
4263 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4264 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4265 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4266 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4267 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4268 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4269 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4270 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4271 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4272 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4273 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4274 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4276 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4277 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4279 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4280 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4282 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4284 /* Add instances of the array generic interfaces for primitive types */
4285 /* This will add instances of the InternalArray_ helper methods in Array too */
4286 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4288 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4289 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4291 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4292 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4294 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4297 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4298 * used for all instances of GetGenericValueImpl by the AOT runtime.
4301 MonoGenericContext ctx;
4302 MonoType *args [16];
4303 MonoMethod *get_method;
4304 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4306 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4309 memset (&ctx, 0, sizeof (ctx));
4310 args [0] = &mono_defaults.object_class->byval_arg;
4311 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4312 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4316 /* Same for CompareExchange<T>/Exchange<T> */
4318 MonoGenericContext ctx;
4319 MonoType *args [16];
4321 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4322 gpointer iter = NULL;
4324 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4325 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4326 memset (&ctx, 0, sizeof (ctx));
4327 args [0] = &mono_defaults.object_class->byval_arg;
4328 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4329 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4334 /* Same for Volatile.Read/Write<T> */
4336 MonoGenericContext ctx;
4337 MonoType *args [16];
4339 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4340 gpointer iter = NULL;
4342 if (volatile_klass) {
4343 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4344 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4345 memset (&ctx, 0, sizeof (ctx));
4346 args [0] = &mono_defaults.object_class->byval_arg;
4347 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4348 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4357 * is_direct_callable:
4359 * Return whenever the method identified by JI is directly callable without
4360 * going through the PLT.
4363 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4365 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4366 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4368 gboolean direct_callable = TRUE;
4370 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4371 direct_callable = FALSE;
4372 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4373 // FIXME: Maybe call the wrapper directly ?
4374 direct_callable = FALSE;
4376 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4377 /* Disable this so all calls go through load_method (), see the
4378 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4379 * mono_debugger_agent_init ().
4381 direct_callable = FALSE;
4384 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4385 /* sgen does some initialization when the allocator method is created */
4386 direct_callable = FALSE;
4388 if (direct_callable)
4391 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4392 if (acfg->aot_opts.direct_pinvoke)
4394 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4395 if (acfg->aot_opts.direct_icalls)
4403 #ifdef MONO_ARCH_AOT_SUPPORTED
4405 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4407 MonoImage *image = method->klass->image;
4408 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4409 MonoTableInfo *tables = image->tables;
4410 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4411 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4412 guint32 im_cols [MONO_IMPLMAP_SIZE];
4415 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4419 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4422 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4424 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4427 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4429 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4436 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4438 if (a->native_offset == b->native_offset)
4439 return a->il_offset - b->il_offset;
4441 return a->native_offset - b->native_offset;
4445 * compute_line_numbers:
4447 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4450 static MonoDebugSourceLocation**
4451 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4453 MonoDebugMethodInfo *minfo;
4454 MonoDebugLineNumberEntry *ln_array;
4455 MonoDebugSourceLocation *loc;
4456 int i, prev_line, prev_il_offset;
4457 int *native_to_il_offset = NULL;
4458 MonoDebugSourceLocation **res;
4461 minfo = mono_debug_lookup_method (method);
4464 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4465 if (debug_info->code_size != code_size)
4468 g_assert (code_size);
4470 /* Compute the native->IL offset mapping */
4472 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4473 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4475 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4477 native_to_il_offset = g_new0 (int, code_size + 1);
4479 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4481 MonoDebugLineNumberEntry *lne = &ln_array [i];
4484 for (j = 0; j < lne->native_offset; ++j)
4485 native_to_il_offset [j] = -1;
4488 if (i < debug_info->num_line_numbers - 1) {
4489 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4491 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4492 native_to_il_offset [j] = lne->il_offset;
4494 for (j = lne->native_offset; j < code_size; ++j)
4495 native_to_il_offset [j] = lne->il_offset;
4500 /* Compute the native->line number mapping */
4501 res = g_new0 (MonoDebugSourceLocation*, code_size);
4502 prev_il_offset = -1;
4505 for (i = 0; i < code_size; ++i) {
4506 int il_offset = native_to_il_offset [i];
4508 if (il_offset == -1 || il_offset == prev_il_offset)
4510 prev_il_offset = il_offset;
4511 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4512 if (!(loc && loc->source_file))
4514 if (loc->row == prev_line) {
4515 mono_debug_symfile_free_location (loc);
4518 prev_line = loc->row;
4519 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4521 /* This will cover the prolog too */
4531 get_file_index (MonoAotCompile *acfg, const char *source_file)
4535 // FIXME: Free these
4536 if (!acfg->dwarf_ln_filenames)
4537 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4538 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4540 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4541 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4542 emit_unset_mode (acfg);
4543 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4555 * emit_and_reloc_code:
4557 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4558 * is true, calls are made through the GOT too. This is used for emitting trampolines
4559 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4560 * since trampolines are needed to make PTL work.
4563 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4565 int i, pindex, start_index, method_index;
4567 MonoJumpInfo *patch_info;
4568 MonoMethodHeader *header;
4569 MonoDebugSourceLocation **locs = NULL;
4571 #ifdef MONO_ARCH_AOT_SUPPORTED
4572 gboolean direct_call, external_call;
4574 const char *direct_call_target = 0;
4575 const char *direct_pinvoke;
4579 header = mono_method_get_header (method);
4581 method_index = get_method_index (acfg, method);
4584 if (acfg->gas_line_numbers && method && debug_info) {
4585 locs = compute_line_numbers (method, code_len, debug_info);
4587 int findex = get_file_index (acfg, "<unknown>");
4588 emit_unset_mode (acfg);
4589 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4593 /* Collect and sort relocations */
4594 patches = g_ptr_array_new ();
4595 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4596 g_ptr_array_add (patches, patch_info);
4597 g_ptr_array_sort (patches, compare_patches);
4600 for (i = 0; i < code_len; i += INST_LEN) {
4602 for (pindex = start_index; pindex < patches->len; ++pindex) {
4603 patch_info = g_ptr_array_index (patches, pindex);
4604 if (patch_info->ip.i >= i)
4608 if (locs && locs [i]) {
4609 MonoDebugSourceLocation *loc = locs [i];
4612 findex = get_file_index (acfg, loc->source_file);
4613 emit_unset_mode (acfg);
4614 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4615 mono_debug_symfile_free_location (loc);
4619 #ifdef MONO_ARCH_AOT_SUPPORTED
4620 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4621 start_index = pindex;
4623 switch (patch_info->type) {
4624 case MONO_PATCH_INFO_NONE:
4626 case MONO_PATCH_INFO_GOT_OFFSET: {
4629 arch_emit_got_offset (acfg, code + i, &code_size);
4630 i += code_size - INST_LEN;
4632 patch_info->type = MONO_PATCH_INFO_NONE;
4635 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4636 int code_size, index;
4637 char *selector = (void*)patch_info->data.target;
4639 if (!acfg->objc_selector_to_index)
4640 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4641 if (!acfg->objc_selectors)
4642 acfg->objc_selectors = g_ptr_array_new ();
4643 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4647 index = acfg->objc_selector_index;
4648 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4649 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4650 acfg->objc_selector_index ++;
4653 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4654 i += code_size - INST_LEN;
4656 patch_info->type = MONO_PATCH_INFO_NONE;
4661 * If this patch is a call, try emitting a direct call instead of
4662 * through a PLT entry. This is possible if the called method is in
4663 * the same assembly and requires no initialization.
4665 direct_call = FALSE;
4666 external_call = FALSE;
4667 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4668 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4669 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4670 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4672 direct_call_target = callee_cfg->asm_symbol;
4673 patch_info->type = MONO_PATCH_INFO_NONE;
4674 acfg->stats.direct_calls ++;
4677 acfg->stats.all_calls ++;
4678 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4679 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4680 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4681 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4683 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4684 if (direct_pinvoke) {
4686 g_assert (strlen (direct_pinvoke) < 1000);
4687 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4690 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4691 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4692 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4693 /* Call to a C function implementing a jit icall */
4695 external_call = TRUE;
4696 g_assert (strlen (sym) < 1000);
4697 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4699 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4700 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4701 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4702 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4703 /* Call to a jit icall without a wrapper */
4705 external_call = TRUE;
4706 g_assert (strlen (sym) < 1000);
4707 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4712 patch_info->type = MONO_PATCH_INFO_NONE;
4713 acfg->stats.direct_calls ++;
4716 if (!got_only && !direct_call) {
4717 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4719 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4721 direct_call_target = plt_entry->symbol;
4723 /* Nullify the patch */
4724 patch_info->type = MONO_PATCH_INFO_NONE;
4725 plt_entry->jit_used = TRUE;
4732 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4733 i += call_size - INST_LEN;
4737 got_slot = get_got_offset (acfg, patch_info);
4739 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4740 i += code_size - INST_LEN;
4746 #endif /* MONO_ARCH_AOT_SUPPORTED */
4749 /* Find next patch */
4751 for (pindex = start_index; pindex < patches->len; ++pindex) {
4752 patch_info = g_ptr_array_index (patches, pindex);
4753 if (patch_info->ip.i >= i)
4757 /* Try to emit multiple bytes at once */
4758 if (pindex < patches->len && patch_info->ip.i > i) {
4761 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4762 if (locs && locs [limit])
4766 emit_code_bytes (acfg, code + i, limit - i);
4767 i = limit - INST_LEN;
4769 emit_code_bytes (acfg, code + i, INST_LEN);
4780 * Return a modified version of S which only includes characters permissible in symbols.
4783 sanitize_symbol (MonoAotCompile *acfg, char *s)
4785 gboolean process = FALSE;
4794 for (i = 0; i < len; ++i)
4795 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4800 gs = g_string_sized_new (len);
4801 for (i = 0; i < len; ++i) {
4803 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4804 g_string_append_c (gs, c);
4805 } else if (c > 0x7f) {
4806 /* multi-byte utf8 */
4807 g_string_append_printf (gs, "_0x%x", c);
4810 while (c >> 6 == 0x2) {
4811 g_string_append_printf (gs, "%x", c);
4815 g_string_append_printf (gs, "_");
4818 g_string_append_c (gs, '_');
4822 res = mono_mempool_strdup (acfg->mempool, gs->str);
4823 g_string_free (gs, TRUE);
4828 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4830 char *name1, *name2, *cached;
4831 int i, j, len, count;
4834 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4835 if (!prefix || !*prefix)
4839 name1 = mono_method_full_name (method, TRUE);
4840 len = strlen (name1);
4841 name2 = malloc (strlen (prefix) + len + 16);
4842 memcpy (name2, prefix, strlen (prefix));
4843 j = strlen (prefix);
4844 for (i = 0; i < len; ++i) {
4845 if (isalnum (name1 [i])) {
4846 name2 [j ++] = name1 [i];
4847 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4849 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4852 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4861 while (g_hash_table_lookup (cache, name2)) {
4862 sprintf (name2 + j, "_%d", count);
4866 cached = g_strdup (name2);
4867 g_hash_table_insert (cache, cached, cached);
4873 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4878 char *debug_sym = NULL;
4879 char *symbol = NULL;
4880 int func_alignment = AOT_FUNC_ALIGNMENT;
4881 MonoMethodHeader *header;
4884 method = cfg->orig_method;
4885 code = cfg->native_code;
4886 header = cfg->header;
4888 method_index = get_method_index (acfg, method);
4889 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4892 /* Make the labels local */
4893 emit_section_change (acfg, ".text", 0);
4894 emit_alignment (acfg, func_alignment);
4896 if (acfg->global_symbols && acfg->need_no_dead_strip)
4897 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4899 emit_label (acfg, cfg->asm_symbol);
4901 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4903 * Write a C style symbol for every method, this has two uses:
4904 * - it works on platforms where the dwarf debugging info is not
4906 * - it allows the setting of breakpoints of aot-ed methods.
4908 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4910 if (acfg->need_no_dead_strip)
4911 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4912 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4913 emit_label (acfg, debug_sym);
4916 export_name = g_hash_table_lookup (acfg->export_names, method);
4918 /* Emit a global symbol for the method */
4919 emit_global_inner (acfg, export_name, TRUE);
4920 emit_label (acfg, export_name);
4923 if (cfg->verbose_level > 0)
4924 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4926 acfg->stats.code_size += cfg->code_len;
4928 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4930 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
4934 if (acfg->aot_opts.write_symbols) {
4935 emit_symbol_size (acfg, debug_sym, ".");
4939 emit_label (acfg, symbol);
4946 * Encode PATCH_INFO into its disk representation.
4949 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4953 switch (patch_info->type) {
4954 case MONO_PATCH_INFO_NONE:
4956 case MONO_PATCH_INFO_IMAGE:
4957 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4959 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4960 case MONO_PATCH_INFO_JIT_TLS_ID:
4961 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4962 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4964 case MONO_PATCH_INFO_METHOD_REL:
4965 encode_value ((gint)patch_info->data.offset, p, &p);
4967 case MONO_PATCH_INFO_SWITCH: {
4968 gpointer *table = (gpointer *)patch_info->data.table->table;
4971 encode_value (patch_info->data.table->table_size, p, &p);
4972 for (k = 0; k < patch_info->data.table->table_size; k++)
4973 encode_value ((int)(gssize)table [k], p, &p);
4976 case MONO_PATCH_INFO_METHODCONST:
4977 case MONO_PATCH_INFO_METHOD:
4978 case MONO_PATCH_INFO_METHOD_JUMP:
4979 case MONO_PATCH_INFO_ICALL_ADDR:
4980 case MONO_PATCH_INFO_METHOD_RGCTX:
4981 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
4982 encode_method_ref (acfg, patch_info->data.method, p, &p);
4984 case MONO_PATCH_INFO_INTERNAL_METHOD:
4985 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4986 guint32 len = strlen (patch_info->data.name);
4988 encode_value (len, p, &p);
4990 memcpy (p, patch_info->data.name, len);
4995 case MONO_PATCH_INFO_LDSTR: {
4996 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4997 guint32 token = patch_info->data.token->token;
4998 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4999 encode_value (image_index, p, &p);
5000 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5003 case MONO_PATCH_INFO_RVA:
5004 case MONO_PATCH_INFO_DECLSEC:
5005 case MONO_PATCH_INFO_LDTOKEN:
5006 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5007 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5008 encode_value (patch_info->data.token->token, p, &p);
5009 encode_value (patch_info->data.token->has_context, p, &p);
5010 if (patch_info->data.token->has_context)
5011 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5013 case MONO_PATCH_INFO_EXC_NAME: {
5014 MonoClass *ex_class;
5017 mono_class_from_name (mono_defaults.exception_class->image,
5018 "System", patch_info->data.target);
5019 g_assert (ex_class);
5020 encode_klass_ref (acfg, ex_class, p, &p);
5023 case MONO_PATCH_INFO_R4:
5024 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5026 case MONO_PATCH_INFO_R8:
5027 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5028 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5030 case MONO_PATCH_INFO_VTABLE:
5031 case MONO_PATCH_INFO_CLASS:
5032 case MONO_PATCH_INFO_IID:
5033 case MONO_PATCH_INFO_ADJUSTED_IID:
5034 case MONO_PATCH_INFO_CLASS_INIT:
5035 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5037 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5038 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5039 if (patch_info->data.del_tramp->method) {
5040 encode_value (1, p, &p);
5041 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5043 encode_value (0, p, &p);
5046 case MONO_PATCH_INFO_FIELD:
5047 case MONO_PATCH_INFO_SFLDA:
5048 encode_field_info (acfg, patch_info->data.field, p, &p);
5050 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5052 case MONO_PATCH_INFO_RGCTX_FETCH: {
5053 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5058 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5059 * reference the same method, so encode the method only once.
5061 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5063 buf2 = g_malloc (1024);
5066 encode_method_ref (acfg, entry->method, p2, &p2);
5067 g_assert (p2 - buf2 < 1024);
5069 offset = add_to_blob (acfg, buf2, p2 - buf2);
5072 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5077 encode_value (offset, p, &p);
5078 g_assert ((int)entry->info_type < 256);
5079 g_assert (entry->data->type < 256);
5080 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5081 encode_patch (acfg, entry->data, p, &p);
5084 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5085 case MONO_PATCH_INFO_MONITOR_ENTER:
5086 case MONO_PATCH_INFO_MONITOR_EXIT:
5087 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5089 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5090 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5091 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5093 case MONO_PATCH_INFO_SIGNATURE:
5094 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5096 case MONO_PATCH_INFO_TLS_OFFSET:
5097 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5099 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5100 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5101 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5103 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5104 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5107 encode_method_ref (acfg, info->method, p, &p);
5108 encode_value (info->num_entries, p, &p);
5109 for (i = 0; i < info->num_entries; ++i) {
5110 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5112 encode_value (template->info_type, p, &p);
5113 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5114 case MONO_PATCH_INFO_CLASS:
5115 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5117 case MONO_PATCH_INFO_FIELD:
5118 encode_field_info (acfg, template->data, p, &p);
5121 g_assert_not_reached ();
5128 g_warning ("unable to handle jump info %d", patch_info->type);
5129 g_assert_not_reached ();
5136 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5139 guint32 pindex, offset;
5140 MonoJumpInfo *patch_info;
5142 encode_value (n_patches, p, &p);
5144 for (pindex = 0; pindex < patches->len; ++pindex) {
5145 patch_info = g_ptr_array_index (patches, pindex);
5147 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5151 offset = get_got_offset (acfg, patch_info);
5152 encode_value (offset, p, &p);
5159 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5163 int pindex, buf_size, n_patches;
5165 MonoJumpInfo *patch_info;
5166 MonoMethodHeader *header;
5167 guint32 method_index;
5169 guint32 first_got_offset;
5171 method = cfg->orig_method;
5172 header = mono_method_get_header (method);
5174 method_index = get_method_index (acfg, method);
5176 /* Sort relocations */
5177 patches = g_ptr_array_new ();
5178 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5179 g_ptr_array_add (patches, patch_info);
5180 g_ptr_array_sort (patches, compare_patches);
5182 first_got_offset = acfg->cfgs [method_index]->got_offset;
5184 /**********************/
5185 /* Encode method info */
5186 /**********************/
5188 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5189 p = buf = g_malloc (buf_size);
5191 if (mono_class_get_cctor (method->klass))
5192 encode_klass_ref (acfg, method->klass, p, &p);
5194 /* Not needed when loading the method */
5195 encode_value (0, p, &p);
5198 if (cfg->opt & MONO_OPT_SHARED) {
5199 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5200 for (l = cfg->ldstr_list; l; l = l->next) {
5201 encode_value ((long)l->data, p, &p);
5205 /* Used only in shared mode */
5206 g_assert (!cfg->ldstr_list);
5209 for (pindex = 0; pindex < patches->len; ++pindex) {
5210 patch_info = g_ptr_array_index (patches, pindex);
5212 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5213 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5214 patch_info->type = MONO_PATCH_INFO_NONE;
5219 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5220 /* Stored in a GOT slot initialized at module load time */
5221 patch_info->type = MONO_PATCH_INFO_NONE;
5225 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5226 /* Stored in a GOT slot initialized at module load time */
5227 patch_info->type = MONO_PATCH_INFO_NONE;
5231 if (is_plt_patch (patch_info)) {
5232 /* Calls are made through the PLT */
5233 patch_info->type = MONO_PATCH_INFO_NONE;
5241 g_assert (cfg->has_got_slots);
5243 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5245 acfg->stats.info_size += p - buf;
5247 g_assert (p - buf < buf_size);
5249 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5254 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5256 guint32 cache_index;
5259 /* Reuse the unwind module to canonize and store unwind info entries */
5260 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5262 /* Use +/- 1 to distinguish 0s from missing entries */
5263 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5271 * It would be easier to use assembler symbols, but the caller needs an
5274 offset = acfg->unwind_info_offset;
5275 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5276 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5279 encode_value (encoded_len, p, &p);
5281 acfg->unwind_info_offset += encoded_len + (p - buf);
5287 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5290 int i, k, buf_size, method_index;
5291 guint32 debug_info_size;
5293 MonoMethodHeader *header;
5294 guint8 *p, *buf, *debug_info;
5295 MonoJitInfo *jinfo = cfg->jit_info;
5297 gboolean use_unwind_ops = FALSE;
5298 MonoSeqPointInfo *seq_points;
5300 method = cfg->orig_method;
5301 code = cfg->native_code;
5302 header = cfg->header;
5304 method_index = get_method_index (acfg, method);
5306 if (!acfg->aot_opts.nodebug) {
5307 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5310 debug_info_size = 0;
5313 seq_points = cfg->seq_point_info;
5315 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 128) : 0) + cfg->gc_map_size;
5316 p = buf = g_malloc (buf_size);
5318 use_unwind_ops = cfg->unwind_ops != NULL;
5320 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);
5322 encode_value (flags, p, &p);
5324 if (use_unwind_ops) {
5325 guint32 encoded_len;
5329 * This is a duplicate of the data in the .debug_frame section, but that
5330 * section cannot be accessed using the dl interface.
5332 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5333 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5336 encode_value (jinfo->used_regs, p, &p);
5339 /*Encode the number of holes before the number of clauses to make decoding easier*/
5340 if (jinfo->has_try_block_holes) {
5341 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5342 encode_value (table->num_holes, p, &p);
5345 /* Exception table */
5346 if (cfg->compile_llvm) {
5348 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5349 * since the information is only available to llc. Instead, we let llc save the data
5350 * into the LSDA, and read it from there at runtime.
5352 /* The assembly might be CIL stripped so emit the data ourselves */
5353 if (header->num_clauses)
5354 encode_value (header->num_clauses, p, &p);
5356 for (k = 0; k < header->num_clauses; ++k) {
5357 MonoExceptionClause *clause;
5359 clause = &header->clauses [k];
5361 encode_value (clause->flags, p, &p);
5362 if (clause->data.catch_class) {
5363 encode_value (1, p, &p);
5364 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5366 encode_value (0, p, &p);
5369 /* Emit a list of nesting clauses */
5370 for (i = 0; i < header->num_clauses; ++i) {
5372 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5374 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5376 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5377 encode_value (i, p, &p);
5379 encode_value (-1, p, &p);
5382 if (jinfo->num_clauses)
5383 encode_value (jinfo->num_clauses, p, &p);
5385 for (k = 0; k < jinfo->num_clauses; ++k) {
5386 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5388 encode_value (ei->flags, p, &p);
5389 encode_value (ei->exvar_offset, p, &p);
5391 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5392 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5394 if (ei->data.catch_class) {
5398 buf2 = g_malloc (4096);
5400 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5402 g_assert (len < 4096);
5403 encode_value (len, p, &p);
5404 memcpy (p, buf2, len);
5408 encode_value (0, p, &p);
5412 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5413 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5414 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5418 if (jinfo->has_try_block_holes) {
5419 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5420 for (i = 0; i < table->num_holes; ++i) {
5421 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5422 encode_value (hole->clause, p, &p);
5423 encode_value (hole->length, p, &p);
5424 encode_value (hole->offset, p, &p);
5428 if (jinfo->has_arch_eh_info) {
5429 MonoArchEHJitInfo *eh_info;
5431 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5432 encode_value (eh_info->stack_size, p, &p);
5435 if (jinfo->has_generic_jit_info) {
5436 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5437 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5443 encode_value (gi->nlocs, p, &p);
5445 for (i = 0; i < gi->nlocs; ++i) {
5446 MonoDwarfLocListEntry *entry = &gi->locations [i];
5448 encode_value (entry->is_reg ? 1 : 0, p, &p);
5449 encode_value (entry->reg, p, &p);
5451 encode_value (entry->offset, p, &p);
5453 g_assert (entry->from == 0);
5455 encode_value (entry->from, p, &p);
5456 encode_value (entry->to, p, &p);
5459 if (!cfg->compile_llvm) {
5460 encode_value (gi->has_this ? 1 : 0, p, &p);
5461 encode_value (gi->this_reg, p, &p);
5462 encode_value (gi->this_offset, p, &p);
5467 * Need to encode jinfo->method too, since it is not equal to 'method'
5468 * when using generic sharing.
5470 buf2 = g_malloc (4096);
5472 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5474 g_assert (len < 4096);
5475 encode_value (len, p, &p);
5476 memcpy (p, buf2, len);
5480 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5481 MonoMethodInflated *inflated;
5482 MonoGenericContext *context;
5483 MonoGenericInst *inst;
5485 g_assert (jinfo->d.method->is_inflated);
5486 inflated = (MonoMethodInflated*)jinfo->d.method;
5487 context = &inflated->context;
5489 encode_value (1, p, &p);
5490 if (context->class_inst) {
5491 inst = context->class_inst;
5493 encode_value (inst->type_argc, p, &p);
5494 for (i = 0; i < inst->type_argc; ++i)
5495 encode_value (gsctx->var_is_vt [i], p, &p);
5497 encode_value (0, p, &p);
5499 if (context->method_inst) {
5500 inst = context->method_inst;
5502 encode_value (inst->type_argc, p, &p);
5503 for (i = 0; i < inst->type_argc; ++i)
5504 encode_value (gsctx->mvar_is_vt [i], p, &p);
5506 encode_value (0, p, &p);
5509 encode_value (0, p, &p);
5514 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5516 encode_value (seq_points->len, p, &p);
5517 last_il_offset = last_native_offset = 0;
5518 for (i = 0; i < seq_points->len; ++i) {
5519 SeqPoint *sp = &seq_points->seq_points [i];
5520 il_offset = sp->il_offset;
5521 native_offset = sp->native_offset;
5522 encode_value (il_offset - last_il_offset, p, &p);
5523 encode_value (native_offset - last_native_offset, p, &p);
5524 last_il_offset = il_offset;
5525 last_native_offset = native_offset;
5527 encode_value (sp->flags, p, &p);
5528 encode_value (sp->next_len, p, &p);
5529 for (j = 0; j < sp->next_len; ++j)
5530 encode_value (sp->next [j], p, &p);
5534 g_assert (debug_info_size < buf_size);
5536 encode_value (debug_info_size, p, &p);
5537 if (debug_info_size) {
5538 memcpy (p, debug_info, debug_info_size);
5539 p += debug_info_size;
5540 g_free (debug_info);
5545 encode_value (cfg->gc_map_size, p, &p);
5546 /* The GC map requires 4 bytes of alignment */
5547 while ((gsize)p % 4)
5549 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5550 p += cfg->gc_map_size;
5553 acfg->stats.ex_info_size += p - buf;
5555 g_assert (p - buf < buf_size);
5558 /* The GC Map requires 4 byte alignment */
5559 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5564 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5566 MonoClass *klass = mono_class_get (acfg->image, token);
5568 int i, buf_size, res;
5569 gboolean no_special_static, cant_encode;
5570 gpointer iter = NULL;
5573 mono_loader_clear_error ();
5577 p = buf = g_malloc (buf_size);
5579 /* Mark as unusable */
5580 encode_value (-1, p, &p);
5582 res = add_to_blob (acfg, buf, p - buf);
5588 buf_size = 10240 + (klass->vtable_size * 16);
5589 p = buf = g_malloc (buf_size);
5593 mono_class_init (klass);
5595 mono_class_get_nested_types (klass, &iter);
5596 g_assert (klass->nested_classes_inited);
5598 mono_class_setup_vtable (klass);
5601 * Emit all the information which is required for creating vtables so
5602 * the runtime does not need to create the MonoMethod structures which
5603 * take up a lot of space.
5606 no_special_static = !mono_class_has_special_static_fields (klass);
5608 /* Check whenever we have enough info to encode the vtable */
5609 cant_encode = FALSE;
5610 for (i = 0; i < klass->vtable_size; ++i) {
5611 MonoMethod *cm = klass->vtable [i];
5613 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5617 mono_class_has_finalizer (klass);
5619 if (klass->generic_container || cant_encode) {
5620 encode_value (-1, p, &p);
5622 encode_value (klass->vtable_size, p, &p);
5623 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);
5624 if (klass->has_cctor)
5625 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5626 if (klass->has_finalize)
5627 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5629 encode_value (klass->instance_size, p, &p);
5630 encode_value (mono_class_data_size (klass), p, &p);
5631 encode_value (klass->packing_size, p, &p);
5632 encode_value (klass->min_align, p, &p);
5634 for (i = 0; i < klass->vtable_size; ++i) {
5635 MonoMethod *cm = klass->vtable [i];
5638 encode_method_ref (acfg, cm, p, &p);
5640 encode_value (0, p, &p);
5644 acfg->stats.class_info_size += p - buf;
5646 g_assert (p - buf < buf_size);
5647 res = add_to_blob (acfg, buf, p - buf);
5654 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5656 char *debug_sym = NULL;
5660 case MONO_PATCH_INFO_METHOD:
5661 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5663 case MONO_PATCH_INFO_INTERNAL_METHOD:
5664 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5666 case MONO_PATCH_INFO_CLASS_INIT:
5667 s = mono_type_get_name (&ji->data.klass->byval_arg);
5668 debug_sym = g_strdup_printf ("plt__class_init_%s", s);
5671 case MONO_PATCH_INFO_RGCTX_FETCH:
5672 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5674 case MONO_PATCH_INFO_ICALL_ADDR: {
5675 char *s = get_debug_sym (ji->data.method, "", cache);
5677 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5681 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5682 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5684 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5685 debug_sym = g_strdup_printf ("plt__generic_class_init");
5691 return sanitize_symbol (acfg, debug_sym);
5695 * Calls made from AOTed code are routed through a table of jumps similar to the
5696 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5697 * control to the AOT runtime through a trampoline.
5700 emit_plt (MonoAotCompile *acfg)
5706 sprintf (symbol, "plt");
5708 emit_section_change (acfg, ".text", 0);
5709 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5710 emit_label (acfg, symbol);
5711 emit_label (acfg, acfg->plt_symbol);
5713 for (i = 0; i < acfg->plt_offset; ++i) {
5714 char *debug_sym = NULL;
5715 MonoPltEntry *plt_entry = NULL;
5720 * The first plt entry is unused.
5724 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5729 * If the target is directly callable, alias the plt symbol to point to
5731 * FIXME: Use this to simplify emit_and_reloc_code ().
5732 * FIXME: Avoid the got slot.
5733 * FIXME: Add support to the binary writer.
5735 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5736 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5739 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5740 /* LLVM calls the PLT entries using bl, so emit a stub */
5741 emit_set_thumb_mode (acfg);
5742 fprintf (acfg->fp, "\n.thumb_func\n");
5743 emit_label (acfg, plt_entry->llvm_symbol);
5744 fprintf (acfg->fp, "bx pc\n");
5745 fprintf (acfg->fp, "nop\n");
5746 emit_set_arm_mode (acfg);
5747 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5749 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5756 debug_sym = plt_entry->debug_sym;
5758 if (acfg->thumb_mixed && !plt_entry->jit_used)
5759 /* Emit only a thumb version */
5762 if (acfg->llvm && !acfg->thumb_mixed)
5763 emit_label (acfg, plt_entry->llvm_symbol);
5766 if (acfg->need_no_dead_strip) {
5767 emit_unset_mode (acfg);
5768 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5770 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5771 emit_label (acfg, debug_sym);
5774 emit_label (acfg, plt_entry->symbol);
5776 arch_emit_plt_entry (acfg, i);
5779 emit_symbol_size (acfg, debug_sym, ".");
5782 if (acfg->thumb_mixed) {
5783 /* Make sure the ARM symbols don't alias the thumb ones */
5784 emit_zero_bytes (acfg, 16);
5787 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5790 for (i = 0; i < acfg->plt_offset; ++i) {
5791 char *debug_sym = NULL;
5792 MonoPltEntry *plt_entry = NULL;
5798 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5801 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5804 /* Skip plt entries not actually called by LLVM code */
5805 if (!plt_entry->llvm_used)
5808 if (acfg->aot_opts.write_symbols) {
5809 if (plt_entry->debug_sym)
5810 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5814 #if defined(TARGET_MACH)
5815 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5816 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5818 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5819 emit_label (acfg, debug_sym);
5821 fprintf (acfg->fp, "\n.thumb_func\n");
5823 emit_label (acfg, plt_entry->llvm_symbol);
5825 arch_emit_llvm_plt_entry (acfg, i);
5828 emit_symbol_size (acfg, debug_sym, ".");
5834 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5836 sprintf (symbol, "plt_end");
5837 emit_label (acfg, symbol);
5841 * emit_trampoline_full:
5843 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5844 * create_jit_info_for_trampoline ().
5846 static G_GNUC_UNUSED void
5847 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5849 char start_symbol [256];
5850 char end_symbol [256];
5852 guint32 buf_size, info_offset;
5853 MonoJumpInfo *patch_info;
5866 code_size = info->code_size;
5868 unwind_ops = info->unwind_ops;
5870 #ifdef __native_client_codegen__
5871 mono_nacl_fix_patches (code, ji);
5876 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5878 emit_section_change (acfg, ".text", 0);
5879 emit_global (acfg, start_symbol, TRUE);
5880 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5881 emit_label (acfg, start_symbol);
5883 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5884 emit_label (acfg, symbol);
5887 * The code should access everything through the GOT, so we pass
5890 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5892 emit_symbol_size (acfg, start_symbol, ".");
5895 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5896 emit_label (acfg, end_symbol);
5901 /* Sort relocations */
5902 patches = g_ptr_array_new ();
5903 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5904 if (patch_info->type != MONO_PATCH_INFO_NONE)
5905 g_ptr_array_add (patches, patch_info);
5906 g_ptr_array_sort (patches, compare_patches);
5908 buf_size = patches->len * 128 + 128;
5909 buf = g_malloc (buf_size);
5912 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5913 g_assert (p - buf < buf_size);
5915 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5917 info_offset = add_to_blob (acfg, buf, p - buf);
5919 emit_section_change (acfg, RODATA_SECT, 0);
5920 emit_global (acfg, symbol, FALSE);
5921 emit_label (acfg, symbol);
5923 emit_int32 (acfg, info_offset);
5927 guint32 encoded_len;
5931 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5933 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5934 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5937 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5938 emit_int32 (acfg, uw_offset);
5941 /* Emit debug info */
5945 sprintf (symbol, "%s", name);
5946 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5949 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5953 static G_GNUC_UNUSED void
5954 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5956 emit_trampoline_full (acfg, got_offset, info, FALSE);
5960 emit_trampolines (MonoAotCompile *acfg)
5963 char end_symbol [256];
5964 int i, tramp_got_offset;
5965 MonoAotTrampoline ntype;
5966 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5970 if (!acfg->aot_opts.full_aot)
5973 g_assert (acfg->image->assembly);
5975 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5976 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5977 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5978 MonoTrampInfo *info;
5981 * Emit the generic trampolines.
5983 * We could save some code by treating the generic trampolines as a wrapper
5984 * method, but that approach has its own complexities, so we choose the simpler
5987 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5988 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5989 #ifdef DISABLE_REMOTING
5990 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5993 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5994 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5997 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5998 emit_trampoline (acfg, acfg->got_offset, info);
6001 mono_arch_get_nullified_class_init_trampoline (&info);
6002 emit_trampoline (acfg, acfg->got_offset, info);
6003 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6004 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
6005 emit_trampoline (acfg, acfg->got_offset, info);
6006 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6007 emit_trampoline (acfg, acfg->got_offset, info);
6010 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6011 emit_trampoline (acfg, acfg->got_offset, info);
6013 /* Emit the exception related code pieces */
6014 mono_arch_get_restore_context (&info, TRUE);
6015 emit_trampoline (acfg, acfg->got_offset, info);
6016 mono_arch_get_call_filter (&info, TRUE);
6017 emit_trampoline (acfg, acfg->got_offset, info);
6018 mono_arch_get_throw_exception (&info, TRUE);
6019 emit_trampoline (acfg, acfg->got_offset, info);
6020 mono_arch_get_rethrow_exception (&info, TRUE);
6021 emit_trampoline (acfg, acfg->got_offset, info);
6022 mono_arch_get_throw_corlib_exception (&info, TRUE);
6023 emit_trampoline (acfg, acfg->got_offset, info);
6025 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6026 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6028 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6030 /* Create a separate out trampoline for more information in stack traces */
6031 info->name = g_strdup ("gsharedvt_out_trampoline");
6032 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6036 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6038 GSList *l = mono_arch_get_trampolines (TRUE);
6041 MonoTrampInfo *info = l->data;
6043 emit_trampoline (acfg, acfg->got_offset, info);
6049 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6052 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6053 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6054 emit_trampoline (acfg, acfg->got_offset, info);
6056 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6057 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6058 emit_trampoline (acfg, acfg->got_offset, info);
6061 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6062 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6063 emit_trampoline (acfg, acfg->got_offset, info);
6069 /* delegate_invoke_impl trampolines */
6070 l = mono_arch_get_delegate_invoke_impls ();
6072 MonoTrampInfo *info = l->data;
6074 emit_trampoline (acfg, acfg->got_offset, info);
6079 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6081 /* Emit trampolines which are numerous */
6084 * These include the following:
6085 * - specific trampolines
6086 * - static rgctx invoke trampolines
6088 * These trampolines have the same code, they are parameterized by GOT
6090 * They are defined in this file, in the arch_... routines instead of
6091 * in tramp-<ARCH>.c, since it is easier to do it this way.
6095 * When running in aot-only mode, we can't create specific trampolines at
6096 * runtime, so we create a few, and save them in the AOT file.
6097 * Normal trampolines embed their argument as a literal inside the
6098 * trampoline code, we can't do that here, so instead we embed an offset
6099 * which needs to be added to the trampoline address to get the address of
6100 * the GOT slot which contains the argument value.
6101 * The generated trampolines jump to the generic trampolines using another
6102 * GOT slot, which will be setup by the AOT loader to point to the
6103 * generic trampoline code of the given type.
6107 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6111 emit_section_change (acfg, ".text", 0);
6113 tramp_got_offset = acfg->got_offset;
6115 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6117 case MONO_AOT_TRAMP_SPECIFIC:
6118 sprintf (symbol, "specific_trampolines");
6120 case MONO_AOT_TRAMP_STATIC_RGCTX:
6121 sprintf (symbol, "static_rgctx_trampolines");
6123 case MONO_AOT_TRAMP_IMT_THUNK:
6124 sprintf (symbol, "imt_thunks");
6126 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6127 sprintf (symbol, "gsharedvt_arg_trampolines");
6130 g_assert_not_reached ();
6133 sprintf (end_symbol, "%s_e", symbol);
6135 if (acfg->aot_opts.write_symbols)
6136 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6138 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6139 emit_label (acfg, symbol);
6141 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6143 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6147 case MONO_AOT_TRAMP_SPECIFIC:
6148 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6149 tramp_got_offset += 2;
6151 case MONO_AOT_TRAMP_STATIC_RGCTX:
6152 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6153 tramp_got_offset += 2;
6155 case MONO_AOT_TRAMP_IMT_THUNK:
6156 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6157 tramp_got_offset += 1;
6159 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6160 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6161 tramp_got_offset += 2;
6164 g_assert_not_reached ();
6166 #ifdef __native_client_codegen__
6167 /* align to avoid 32-byte boundary crossings */
6168 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6171 if (!acfg->trampoline_size [ntype]) {
6172 g_assert (tramp_size);
6173 acfg->trampoline_size [ntype] = tramp_size;
6177 emit_label (acfg, end_symbol);
6178 emit_int32 (acfg, 0);
6181 arch_emit_specific_trampoline_pages (acfg);
6183 /* Reserve some entries at the end of the GOT for our use */
6184 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6187 acfg->got_offset += acfg->num_trampoline_got_entries;
6191 str_begins_with (const char *str1, const char *str2)
6193 int len = strlen (str2);
6194 return strncmp (str1, str2, len) == 0;
6198 mono_aot_readonly_field_override (MonoClassField *field)
6201 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6202 char *p = rdv->name;
6204 len = strlen (field->parent->name_space);
6205 if (strncmp (p, field->parent->name_space, len))
6210 len = strlen (field->parent->name);
6211 if (strncmp (p, field->parent->name, len))
6216 if (strcmp (p, field->name))
6218 switch (rdv->type) {
6220 return &rdv->value.i1;
6222 return &rdv->value.i2;
6224 return &rdv->value.i4;
6233 add_readonly_value (MonoAotOptions *opts, const char *val)
6238 /* the format of val is:
6239 * namespace.typename.fieldname=type/value
6240 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6242 fval = strrchr (val, '/');
6244 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6247 tval = strrchr (val, '=');
6249 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6252 rdv = g_new0 (ReadOnlyValue, 1);
6253 rdv->name = g_malloc0 (tval - val + 1);
6254 memcpy (rdv->name, val, tval - val);
6257 if (strncmp (tval, "i1", 2) == 0) {
6258 rdv->value.i1 = atoi (fval);
6259 rdv->type = MONO_TYPE_I1;
6260 } else if (strncmp (tval, "i2", 2) == 0) {
6261 rdv->value.i2 = atoi (fval);
6262 rdv->type = MONO_TYPE_I2;
6263 } else if (strncmp (tval, "i4", 2) == 0) {
6264 rdv->value.i4 = atoi (fval);
6265 rdv->type = MONO_TYPE_I4;
6267 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6270 rdv->next = readonly_values;
6271 readonly_values = rdv;
6275 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6277 gchar **args, **ptr;
6279 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6280 for (ptr = args; ptr && *ptr; ptr ++) {
6281 const char *arg = *ptr;
6283 if (str_begins_with (arg, "outfile=")) {
6284 opts->outfile = g_strdup (arg + strlen ("outfile="));
6285 } else if (str_begins_with (arg, "save-temps")) {
6286 opts->save_temps = TRUE;
6287 } else if (str_begins_with (arg, "keep-temps")) {
6288 opts->save_temps = TRUE;
6289 } else if (str_begins_with (arg, "write-symbols")) {
6290 opts->write_symbols = TRUE;
6291 } else if (str_begins_with (arg, "no-write-symbols")) {
6292 opts->write_symbols = FALSE;
6293 } else if (str_begins_with (arg, "metadata-only")) {
6294 opts->metadata_only = TRUE;
6295 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6296 opts->bind_to_runtime_version = TRUE;
6297 } else if (str_begins_with (arg, "full")) {
6298 opts->full_aot = TRUE;
6299 } else if (str_begins_with (arg, "threads=")) {
6300 opts->nthreads = atoi (arg + strlen ("threads="));
6301 } else if (str_begins_with (arg, "static")) {
6302 opts->static_link = TRUE;
6303 opts->no_dlsym = TRUE;
6304 } else if (str_begins_with (arg, "asmonly")) {
6305 opts->asm_only = TRUE;
6306 } else if (str_begins_with (arg, "asmwriter")) {
6307 opts->asm_writer = TRUE;
6308 } else if (str_begins_with (arg, "nodebug")) {
6309 opts->nodebug = TRUE;
6310 } else if (str_begins_with (arg, "dwarfdebug")) {
6311 opts->dwarf_debug = TRUE;
6312 } else if (str_begins_with (arg, "nopagetrampolines")) {
6313 opts->use_trampolines_page = FALSE;
6314 } else if (str_begins_with (arg, "ntrampolines=")) {
6315 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6316 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6317 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6318 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6319 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6320 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6321 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6322 } else if (str_begins_with (arg, "autoreg")) {
6323 opts->autoreg = TRUE;
6324 } else if (str_begins_with (arg, "tool-prefix=")) {
6325 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6326 } else if (str_begins_with (arg, "soft-debug")) {
6327 opts->soft_debug = TRUE;
6328 } else if (str_begins_with (arg, "direct-pinvoke")) {
6329 opts->direct_pinvoke = TRUE;
6330 } else if (str_begins_with (arg, "direct-icalls")) {
6331 opts->direct_icalls = TRUE;
6332 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6333 } else if (str_begins_with (arg, "iphone-abi")) {
6334 // older full-aot users did depend on this.
6336 } else if (str_begins_with (arg, "no-direct-calls")) {
6337 opts->no_direct_calls = TRUE;
6338 } else if (str_begins_with (arg, "print-skipped")) {
6339 opts->print_skipped_methods = TRUE;
6340 } else if (str_begins_with (arg, "stats")) {
6342 } else if (str_begins_with (arg, "no-instances")) {
6343 opts->no_instances = TRUE;
6344 } else if (str_begins_with (arg, "log-generics")) {
6345 opts->log_generics = TRUE;
6346 } else if (str_begins_with (arg, "log-instances=")) {
6347 opts->log_instances = TRUE;
6348 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6349 } else if (str_begins_with (arg, "log-instances")) {
6350 opts->log_instances = TRUE;
6351 } else if (str_begins_with (arg, "mtriple=")) {
6352 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6353 } else if (str_begins_with (arg, "llvm-path=")) {
6354 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6355 } else if (str_begins_with (arg, "readonly-value=")) {
6356 add_readonly_value (opts, arg + strlen ("readonly-value="));
6357 } else if (str_begins_with (arg, "info")) {
6358 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6360 } else if (str_begins_with (arg, "gc-maps")) {
6361 mini_gc_enable_gc_maps_for_aot ();
6362 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6363 printf ("Supported options for --aot:\n");
6364 printf (" outfile=\n");
6365 printf (" save-temps\n");
6366 printf (" keep-temps\n");
6367 printf (" write-symbols\n");
6368 printf (" metadata-only\n");
6369 printf (" bind-to-runtime-version\n");
6371 printf (" threads=\n");
6372 printf (" static\n");
6373 printf (" asmonly\n");
6374 printf (" asmwriter\n");
6375 printf (" nodebug\n");
6376 printf (" dwarfdebug\n");
6377 printf (" ntrampolines=\n");
6378 printf (" nrgctx-trampolines=\n");
6379 printf (" nimt-trampolines=\n");
6380 printf (" ngsharedvt-trampolines=\n");
6381 printf (" autoreg\n");
6382 printf (" tool-prefix=\n");
6383 printf (" readonly-value=\n");
6384 printf (" soft-debug\n");
6385 printf (" gc-maps\n");
6386 printf (" print-skipped\n");
6387 printf (" no-instances\n");
6388 printf (" stats\n");
6390 printf (" help/?\n");
6393 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6398 if (opts->use_trampolines_page) {
6399 opts->ntrampolines = 0;
6400 opts->nrgctx_trampolines = 0;
6401 opts->nimt_trampolines = 0;
6402 opts->ngsharedvt_arg_trampolines = 0;
6408 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6410 MonoMethod *method = (MonoMethod*)key;
6411 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6412 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6413 MonoAotCompile *acfg = user_data;
6415 new_ji->image = ji->image;
6416 new_ji->token = ji->token;
6417 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6421 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6423 if (klass->type_token)
6425 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6428 return can_encode_class (acfg, klass->element_class);
6433 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6435 if (method->wrapper_type) {
6436 switch (method->wrapper_type) {
6437 case MONO_WRAPPER_NONE:
6438 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6439 case MONO_WRAPPER_XDOMAIN_INVOKE:
6440 case MONO_WRAPPER_STFLD:
6441 case MONO_WRAPPER_LDFLD:
6442 case MONO_WRAPPER_LDFLDA:
6443 case MONO_WRAPPER_LDFLD_REMOTE:
6444 case MONO_WRAPPER_STFLD_REMOTE:
6445 case MONO_WRAPPER_STELEMREF:
6446 case MONO_WRAPPER_ISINST:
6447 case MONO_WRAPPER_PROXY_ISINST:
6448 case MONO_WRAPPER_ALLOC:
6449 case MONO_WRAPPER_REMOTING_INVOKE:
6450 case MONO_WRAPPER_UNKNOWN:
6451 case MONO_WRAPPER_WRITE_BARRIER:
6452 case MONO_WRAPPER_DELEGATE_INVOKE:
6453 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6454 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6455 case MONO_WRAPPER_SYNCHRONIZED:
6457 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6458 case MONO_WRAPPER_CASTCLASS: {
6459 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6468 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6472 if (!method->token) {
6473 /* The method is part of a constructed type like Int[,].Set (). */
6474 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6475 if (method->klass->rank)
6485 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6487 switch (patch_info->type) {
6488 case MONO_PATCH_INFO_METHOD:
6489 case MONO_PATCH_INFO_METHODCONST:
6490 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6491 MonoMethod *method = patch_info->data.method;
6493 return can_encode_method (acfg, method);
6495 case MONO_PATCH_INFO_VTABLE:
6496 case MONO_PATCH_INFO_CLASS_INIT:
6497 case MONO_PATCH_INFO_CLASS:
6498 case MONO_PATCH_INFO_IID:
6499 case MONO_PATCH_INFO_ADJUSTED_IID:
6500 if (!can_encode_class (acfg, patch_info->data.klass)) {
6501 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6505 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6506 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6507 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6512 case MONO_PATCH_INFO_RGCTX_FETCH: {
6513 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6515 if (!can_encode_method (acfg, entry->method))
6517 if (!can_encode_patch (acfg, entry->data))
6531 * AOT compile a given method.
6532 * This function might be called by multiple threads, so it must be thread-safe.
6535 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6538 MonoJumpInfo *patch_info;
6541 MonoMethod *wrapped;
6543 if (acfg->aot_opts.metadata_only)
6546 mono_acfg_lock (acfg);
6547 index = get_method_index (acfg, method);
6548 mono_acfg_unlock (acfg);
6550 /* fixme: maybe we can also precompile wrapper methods */
6551 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6552 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6553 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6554 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6558 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6561 wrapped = mono_marshal_method_from_wrapper (method);
6562 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6563 // FIXME: The wrapper should be generic too, but it is not
6566 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6569 InterlockedIncrement (&acfg->stats.mcount);
6572 if (method->is_generic || method->klass->generic_container) {
6573 InterlockedIncrement (&acfg->stats.genericcount);
6578 //acfg->aot_opts.print_skipped_methods = TRUE;
6581 * Since these methods are the only ones which are compiled with
6582 * AOT support, and they are not used by runtime startup/shutdown code,
6583 * the runtime will not see AOT methods during AOT compilation,so it
6584 * does not need to support them by creating a fake GOT etc.
6586 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), acfg->aot_opts.full_aot ? (JIT_FLAG_AOT|JIT_FLAG_FULL_AOT) : (JIT_FLAG_AOT), 0);
6587 mono_loader_clear_error ();
6589 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6590 if (acfg->aot_opts.print_skipped_methods)
6591 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6592 InterlockedIncrement (&acfg->stats.genericcount);
6595 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6596 if (acfg->aot_opts.print_skipped_methods)
6597 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6598 /* Let the exception happen at runtime */
6602 if (cfg->disable_aot) {
6603 if (acfg->aot_opts.print_skipped_methods)
6604 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6605 InterlockedIncrement (&acfg->stats.ocount);
6606 mono_destroy_compile (cfg);
6609 cfg->method_index = index;
6611 /* Nullify patches which need no aot processing */
6612 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6613 switch (patch_info->type) {
6614 case MONO_PATCH_INFO_LABEL:
6615 case MONO_PATCH_INFO_BB:
6616 patch_info->type = MONO_PATCH_INFO_NONE;
6623 /* Collect method->token associations from the cfg */
6624 mono_acfg_lock (acfg);
6625 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6626 mono_acfg_unlock (acfg);
6629 * Check for absolute addresses.
6632 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6633 switch (patch_info->type) {
6634 case MONO_PATCH_INFO_ABS:
6635 /* unable to handle this */
6644 if (acfg->aot_opts.print_skipped_methods)
6645 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6646 InterlockedIncrement (&acfg->stats.abscount);
6647 mono_destroy_compile (cfg);
6651 /* Lock for the rest of the code */
6652 mono_acfg_lock (acfg);
6655 * Check for methods/klasses we can't encode.
6658 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6659 if (!can_encode_patch (acfg, patch_info))
6664 if (acfg->aot_opts.print_skipped_methods)
6665 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6666 acfg->stats.ocount++;
6667 mono_destroy_compile (cfg);
6668 mono_acfg_unlock (acfg);
6672 if (method->is_inflated && acfg->aot_opts.log_instances) {
6673 if (acfg->instances_logfile)
6674 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6676 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6679 /* Adds generic instances referenced by this method */
6681 * The depth is used to avoid infinite loops when generic virtual recursion is
6684 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6685 if (!acfg->aot_opts.no_instances && depth < 32) {
6686 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6687 switch (patch_info->type) {
6688 case MONO_PATCH_INFO_METHOD: {
6689 MonoMethod *m = patch_info->data.method;
6690 if (m->is_inflated) {
6691 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6692 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6693 !method_has_type_vars (m)) {
6694 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6695 if (acfg->aot_opts.full_aot)
6696 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6698 add_extra_method_with_depth (acfg, m, depth + 1);
6699 add_types_from_method_header (acfg, m);
6702 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6704 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6705 add_extra_method_with_depth (acfg, m, depth + 1);
6708 case MONO_PATCH_INFO_VTABLE: {
6709 MonoClass *klass = patch_info->data.klass;
6711 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6712 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6715 case MONO_PATCH_INFO_SFLDA: {
6716 MonoClass *klass = patch_info->data.field->parent;
6718 /* The .cctor needs to run at runtime. */
6719 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6720 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6729 /* Determine whenever the method has GOT slots */
6730 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6731 switch (patch_info->type) {
6732 case MONO_PATCH_INFO_GOT_OFFSET:
6733 case MONO_PATCH_INFO_NONE:
6734 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6736 case MONO_PATCH_INFO_IMAGE:
6737 /* The assembly is stored in GOT slot 0 */
6738 if (patch_info->data.image != acfg->image)
6739 cfg->has_got_slots = TRUE;
6742 if (!is_plt_patch (patch_info))
6743 cfg->has_got_slots = TRUE;
6748 if (!cfg->has_got_slots)
6749 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6752 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6754 /* Make a copy of the patch info which is in the mempool */
6756 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6758 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6759 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6762 patches = new_patch_info;
6764 patches_end->next = new_patch_info;
6765 patches_end = new_patch_info;
6767 cfg->patch_info = patches;
6769 /* Make a copy of the unwind info */
6771 GSList *l, *unwind_ops;
6775 for (l = cfg->unwind_ops; l; l = l->next) {
6776 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6777 memcpy (op, l->data, sizeof (MonoUnwindOp));
6778 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6780 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6782 /* Make a copy of the argument/local info */
6784 MonoInst **args, **locals;
6785 MonoMethodSignature *sig;
6786 MonoMethodHeader *header;
6789 sig = mono_method_signature (method);
6790 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6791 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6792 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6793 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6797 header = mono_method_get_header (method);
6798 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6799 for (i = 0; i < header->num_locals; ++i) {
6800 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6801 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6803 cfg->locals = locals;
6806 /* Free some fields used by cfg to conserve memory */
6807 mono_mempool_destroy (cfg->mempool);
6808 cfg->mempool = NULL;
6809 g_free (cfg->varinfo);
6810 cfg->varinfo = NULL;
6814 mono_regstate_free (cfg->rs);
6818 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6820 while (index >= acfg->cfgs_size) {
6821 MonoCompile **new_cfgs;
6824 new_size = acfg->cfgs_size * 2;
6825 new_cfgs = g_new0 (MonoCompile*, new_size);
6826 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6827 g_free (acfg->cfgs);
6828 acfg->cfgs = new_cfgs;
6829 acfg->cfgs_size = new_size;
6831 acfg->cfgs [index] = cfg;
6833 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6836 if (cfg->orig_method->wrapper_type)
6837 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6840 mono_acfg_unlock (acfg);
6842 InterlockedIncrement (&acfg->stats.ccount);
6846 compile_thread_main (gpointer *user_data)
6848 MonoDomain *domain = user_data [0];
6849 MonoAotCompile *acfg = user_data [1];
6850 GPtrArray *methods = user_data [2];
6853 mono_thread_attach (domain);
6855 for (i = 0; i < methods->len; ++i)
6856 compile_method (acfg, g_ptr_array_index (methods, i));
6860 load_profile_files (MonoAotCompile *acfg)
6864 int file_index, res, method_index, i;
6867 GList *unordered, *l;
6872 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6874 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6879 infile = fopen (tmp, "r");
6882 printf ("Using profile data file '%s'\n", tmp);
6887 res = fscanf (infile, "%32s\n", ver);
6888 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6889 printf ("Profile file has wrong version or invalid.\n");
6896 MonoMethodDesc *desc;
6899 if (fgets (name, 1023, infile) == NULL)
6902 /* Kill the newline */
6903 if (strlen (name) > 0)
6904 name [strlen (name) - 1] = '\0';
6906 desc = mono_method_desc_new (name, TRUE);
6908 method = mono_method_desc_search_in_image (desc, acfg->image);
6910 if (method && mono_method_get_token (method)) {
6911 token = mono_method_get_token (method);
6912 method_index = mono_metadata_token_index (token) - 1;
6915 for (i = 0; i < acfg->method_order->len; ++i) {
6916 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6922 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6924 //printf ("No method found matching '%s'.\n", name);
6930 /* Add missing methods */
6932 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6934 for (i = 0; i < acfg->method_order->len; ++i) {
6935 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6941 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6943 unordered = g_list_reverse (unordered);
6944 for (l = unordered; l; l = l->next)
6945 g_ptr_array_add (acfg->method_order, l->data);
6948 /* Used by the LLVM backend */
6950 mono_aot_get_got_offset (MonoJumpInfo *ji)
6952 return get_got_offset (llvm_acfg, ji);
6956 mono_aot_get_method_name (MonoCompile *cfg)
6958 if (llvm_acfg->aot_opts.static_link)
6959 /* Include the assembly name too to avoid duplicate symbol errors */
6960 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6962 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6966 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6968 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6969 MonoPltEntry *plt_entry;
6972 ji->data.target = data;
6974 if (!can_encode_patch (llvm_acfg, ji))
6977 plt_entry = get_plt_entry (llvm_acfg, ji);
6978 plt_entry->llvm_used = TRUE;
6980 #if defined(TARGET_MACH)
6981 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6983 return g_strdup_printf (plt_entry->llvm_symbol);
6988 mono_aot_get_method_index (MonoMethod *method)
6990 g_assert (llvm_acfg);
6991 return get_method_index (llvm_acfg, method);
6995 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6999 mono_acfg_lock (llvm_acfg);
7000 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7001 mono_acfg_unlock (llvm_acfg);
7011 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7015 emit_llvm_file (MonoAotCompile *acfg)
7017 char *command, *opts, *tempbc;
7019 MonoJumpInfo *patch_info;
7022 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
7026 /* Compute the final size of the got */
7027 for (i = 0; i < acfg->nmethods; ++i) {
7028 if (acfg->cfgs [i]) {
7029 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
7030 if (patch_info->type != MONO_PATCH_INFO_NONE) {
7031 if (!is_plt_patch (patch_info))
7032 get_got_offset (acfg, patch_info);
7034 get_plt_entry (acfg, patch_info);
7040 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
7042 if (acfg->aot_opts.full_aot) {
7046 * Need to add the got entries used by the trampolines.
7047 * This is only a conservative approximation.
7049 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
7050 /* For the generic + rgctx trampolines */
7051 acfg->final_got_size += 400;
7052 /* For the specific trampolines */
7053 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
7054 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
7059 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7060 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
7064 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7065 * a lot of time, and doesn't seem to save much space.
7066 * The following optimizations cannot be enabled:
7068 * - 'jump-threading' changes our blockaddress references to int constants.
7069 * - 'basiccg' fails because it contains:
7070 * if (CS && !isa<IntrinsicInst>(II)) {
7071 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7072 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7073 * The opt list below was produced by taking the output of:
7074 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7075 * then removing tailcallelim + the global opts.
7076 * strip-dead-prototypes deletes unused intrinsics definitions.
7078 opts = g_strdup ("-instcombine -simplifycfg");
7079 //opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -domtree -verify");
7080 /* The dse pass is disabled because of #13734 and #17616 */
7082 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7083 * // If we have no DataLayout information around, then the size of the store
7084 * // is inferrable from the pointee type. If they are the same type, then
7085 * // we know that the store is safe.
7086 * if (AA.getDataLayout() == 0 &&
7087 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7088 * return OverwriteComplete;
7089 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7091 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -adce -simplifycfg -instcombine -strip-dead-prototypes -domtree -verify");
7093 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7094 printf ("Executing opt: %s\n", command);
7095 if (system (command) != 0) {
7101 if (!acfg->llc_args)
7102 acfg->llc_args = g_string_new ("");
7104 /* Verbose asm slows down llc greatly */
7105 g_string_append (acfg->llc_args, " -asm-verbose=false");
7107 if (acfg->aot_opts.mtriple)
7108 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7110 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7111 /* ios requires PIC code now */
7112 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7114 if (llvm_acfg->aot_opts.static_link)
7115 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7117 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7119 unlink (acfg->tmpfname);
7121 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpbasename);
7123 printf ("Executing llc: %s\n", command);
7125 if (system (command) != 0) {
7132 emit_code (MonoAotCompile *acfg)
7134 int oindex, i, prev_index;
7137 #if defined(TARGET_POWERPC64)
7138 sprintf (symbol, ".Lgot_addr");
7139 emit_section_change (acfg, ".text", 0);
7140 emit_alignment (acfg, 8);
7141 emit_label (acfg, symbol);
7142 emit_pointer (acfg, acfg->got_symbol);
7146 * This global symbol is used to compute the address of each method using the
7147 * code_offsets array. It is also used to compute the memory ranges occupied by
7148 * AOT code, so it must be equal to the address of the first emitted method.
7150 emit_section_change (acfg, ".text", 0);
7151 emit_alignment (acfg, 8);
7153 for (i = 0; i < acfg->nmethods; ++i) {
7154 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7155 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7160 if (!acfg->methods_symbol) {
7161 sprintf (symbol, "methods");
7162 emit_label (acfg, symbol);
7163 acfg->methods_symbol = g_strdup (symbol);
7167 * Emit some padding so the local symbol for the first method doesn't have the
7168 * same address as 'methods'.
7170 #if defined(__default_codegen__)
7171 emit_zero_bytes (acfg, 16);
7172 #elif defined(__native_client_codegen__)
7174 const int kPaddingSize = 16;
7175 guint8 pad_buffer[kPaddingSize];
7176 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7177 emit_bytes (acfg, pad_buffer, kPaddingSize);
7181 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7185 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7187 cfg = acfg->cfgs [i];
7192 method = cfg->orig_method;
7194 /* Emit unbox trampoline */
7195 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7196 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7198 emit_section_change (acfg, ".text", 0);
7199 #ifdef __native_client_codegen__
7200 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7203 if (acfg->thumb_mixed && cfg->compile_llvm) {
7204 emit_set_thumb_mode (acfg);
7205 fprintf (acfg->fp, "\n.thumb_func\n");
7208 emit_label (acfg, symbol);
7210 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7212 if (acfg->thumb_mixed && cfg->compile_llvm) {
7213 emit_set_arm_mode (acfg);
7217 if (cfg->compile_llvm)
7218 acfg->stats.llvm_count ++;
7220 emit_method_code (acfg, cfg);
7223 sprintf (symbol, "methods_end");
7224 emit_section_change (acfg, ".text", 0);
7225 emit_alignment (acfg, 8);
7226 emit_label (acfg, symbol);
7227 /* To distinguish it from the next symbol */
7228 emit_int32 (acfg, 0);
7231 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7232 * from optimizing them away, since it doesn't see that code_offsets references them.
7233 * JITted methods don't need this since they are referenced using assembler local
7235 * FIXME: This is why write-symbols doesn't work on OSX ?
7237 if (acfg->llvm && acfg->need_no_dead_strip) {
7238 fprintf (acfg->fp, "\n");
7239 for (i = 0; i < acfg->nmethods; ++i) {
7240 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7241 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7245 if (acfg->direct_method_addresses) {
7246 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7249 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7250 * This is PIE code, and the linker can update it if needed.
7252 sprintf (symbol, "method_addresses");
7253 emit_section_change (acfg, ".text", 1);
7254 emit_alignment (acfg, 8);
7255 emit_label (acfg, symbol);
7256 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7257 emit_unset_mode (acfg);
7258 if (acfg->need_no_dead_strip)
7259 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7261 for (i = 0; i < acfg->nmethods; ++i) {
7264 #ifdef MONO_ARCH_AOT_SUPPORTED
7266 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7268 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7272 sprintf (symbol, "method_addresses_end");
7273 emit_label (acfg, symbol);
7276 sprintf (symbol, "code_offsets");
7277 emit_section_change (acfg, RODATA_SECT, 1);
7278 emit_alignment (acfg, 8);
7279 emit_label (acfg, symbol);
7280 emit_int32 (acfg, 0);
7282 sprintf (symbol, "code_offsets");
7283 emit_section_change (acfg, RODATA_SECT, 1);
7284 emit_alignment (acfg, 8);
7285 emit_label (acfg, symbol);
7287 acfg->stats.offsets_size += acfg->nmethods * 4;
7289 for (i = 0; i < acfg->nmethods; ++i) {
7290 if (acfg->cfgs [i]) {
7291 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7293 emit_int32 (acfg, 0xffffffff);
7299 /* Emit a sorted table mapping methods to their unbox trampolines */
7300 sprintf (symbol, "unbox_trampolines");
7301 if (acfg->direct_method_addresses)
7302 emit_section_change (acfg, ".text", 0);
7304 emit_section_change (acfg, RODATA_SECT, 0);
7305 emit_alignment (acfg, 8);
7306 emit_label (acfg, symbol);
7309 for (i = 0; i < acfg->nmethods; ++i) {
7314 cfg = acfg->cfgs [i];
7318 method = cfg->orig_method;
7320 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7323 index = get_method_index (acfg, method);
7324 sprintf (symbol, "ut_%d", index);
7326 emit_int32 (acfg, index);
7327 if (acfg->direct_method_addresses) {
7328 #ifdef MONO_ARCH_AOT_SUPPORTED
7329 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7332 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7334 /* Make sure the table is sorted by index */
7335 g_assert (index > prev_index);
7339 sprintf (symbol, "unbox_trampolines_end");
7340 emit_label (acfg, symbol);
7341 emit_int32 (acfg, 0);
7345 emit_info (MonoAotCompile *acfg)
7351 offsets = g_new0 (gint32, acfg->nmethods);
7353 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7354 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7356 if (acfg->cfgs [i]) {
7357 emit_method_info (acfg, acfg->cfgs [i]);
7358 offsets [i] = acfg->cfgs [i]->method_info_offset;
7364 sprintf (symbol, "method_info_offsets");
7365 emit_section_change (acfg, RODATA_SECT, 1);
7366 emit_alignment (acfg, 8);
7367 emit_label (acfg, symbol);
7369 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7374 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7376 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7377 #define mix(a,b,c) { \
7378 a -= c; a ^= rot(c, 4); c += b; \
7379 b -= a; b ^= rot(a, 6); a += c; \
7380 c -= b; c ^= rot(b, 8); b += a; \
7381 a -= c; a ^= rot(c,16); c += b; \
7382 b -= a; b ^= rot(a,19); a += c; \
7383 c -= b; c ^= rot(b, 4); b += a; \
7385 #define final(a,b,c) { \
7386 c ^= b; c -= rot(b,14); \
7387 a ^= c; a -= rot(c,11); \
7388 b ^= a; b -= rot(a,25); \
7389 c ^= b; c -= rot(b,16); \
7390 a ^= c; a -= rot(c,4); \
7391 b ^= a; b -= rot(a,14); \
7392 c ^= b; c -= rot(b,24); \
7396 mono_aot_type_hash (MonoType *t1)
7398 guint hash = t1->type;
7400 hash |= t1->byref << 6; /* do not collide with t1->type values */
7402 case MONO_TYPE_VALUETYPE:
7403 case MONO_TYPE_CLASS:
7404 case MONO_TYPE_SZARRAY:
7405 /* check if the distribution is good enough */
7406 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7408 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7409 case MONO_TYPE_ARRAY:
7410 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7411 case MONO_TYPE_GENERICINST:
7412 return ((hash << 5) - hash) ^ 0;
7419 * mono_aot_method_hash:
7421 * Return a hash code for methods which only depends on metadata.
7424 mono_aot_method_hash (MonoMethod *method)
7426 MonoMethodSignature *sig;
7430 guint32 *hashes_start, *hashes;
7432 MonoGenericInst *ginst = NULL;
7434 /* Similar to the hash in mono_method_get_imt_slot () */
7436 sig = mono_method_signature (method);
7438 if (method->is_inflated)
7439 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7441 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7442 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7443 hashes = hashes_start;
7445 /* Some wrappers are assigned to random classes */
7446 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7447 klass = method->klass;
7449 klass = mono_defaults.object_class;
7451 if (!method->wrapper_type) {
7452 char *full_name = mono_type_full_name (&klass->byval_arg);
7454 hashes [0] = mono_metadata_str_hash (full_name);
7458 hashes [0] = mono_metadata_str_hash (klass->name);
7459 hashes [1] = mono_metadata_str_hash (klass->name_space);
7461 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7462 /* The method name includes a stringified pointer */
7465 hashes [2] = mono_metadata_str_hash (method->name);
7466 hashes [3] = method->wrapper_type;
7467 hashes [4] = mono_aot_type_hash (sig->ret);
7469 for (i = 0; i < sig->param_count; i++) {
7470 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7473 for (i = 0; i < ginst->type_argc; ++i)
7474 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7476 g_assert (hindex == hashes_count);
7478 /* Setup internal state */
7479 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7481 /* Handle most of the hashes */
7482 while (hashes_count > 3) {
7491 /* Handle the last 3 hashes (all the case statements fall through) */
7492 switch (hashes_count) {
7493 case 3 : c += hashes [2];
7494 case 2 : b += hashes [1];
7495 case 1 : a += hashes [0];
7497 case 0: /* nothing left to add */
7501 free (hashes_start);
7510 * mono_aot_get_array_helper_from_wrapper;
7512 * Get the helper method in Array called by an array wrapper method.
7515 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7519 MonoGenericContext ctx;
7520 MonoType *args [16];
7521 char *mname, *iname, *s, *s2, *helper_name = NULL;
7523 prefix = "System.Collections.Generic";
7524 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7525 s2 = strstr (s, "`1.");
7531 //printf ("X: %s %s\n", iname, mname);
7533 if (!strcmp (iname, "IList"))
7534 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7536 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7537 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7539 g_free (helper_name);
7542 if (m->is_generic) {
7543 memset (&ctx, 0, sizeof (ctx));
7544 args [0] = &method->klass->element_class->byval_arg;
7545 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7546 m = mono_class_inflate_generic_method (m, &ctx);
7552 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7554 typedef struct HashEntry {
7555 guint32 key, value, index;
7556 struct HashEntry *next;
7560 * emit_extra_methods:
7562 * Emit methods which are not in the METHOD table, like wrappers.
7565 emit_extra_methods (MonoAotCompile *acfg)
7567 int i, table_size, buf_size;
7570 guint32 *info_offsets;
7573 HashEntry *entry, *new_entry;
7574 int nmethods, max_chain_length;
7577 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7579 /* Emit method info */
7581 for (i = 0; i < acfg->extra_methods->len; ++i) {
7582 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7583 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7589 p = buf = g_malloc (buf_size);
7593 method = cfg->method_to_register;
7595 encode_method_ref (acfg, method, p, &p);
7597 g_assert ((p - buf) < buf_size);
7599 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7604 * Construct a chained hash table for mapping indexes in extra_method_info to
7607 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7608 table = g_ptr_array_sized_new (table_size);
7609 for (i = 0; i < table_size; ++i)
7610 g_ptr_array_add (table, NULL);
7611 chain_lengths = g_new0 (int, table_size);
7612 max_chain_length = 0;
7613 for (i = 0; i < acfg->extra_methods->len; ++i) {
7614 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7615 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7621 key = info_offsets [i];
7622 value = get_method_index (acfg, method);
7624 hash = mono_aot_method_hash (method) % table_size;
7625 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7627 chain_lengths [hash] ++;
7628 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7630 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7631 new_entry->key = key;
7632 new_entry->value = value;
7634 entry = g_ptr_array_index (table, hash);
7635 if (entry == NULL) {
7636 new_entry->index = hash;
7637 g_ptr_array_index (table, hash) = new_entry;
7640 entry = entry->next;
7642 entry->next = new_entry;
7643 new_entry->index = table->len;
7644 g_ptr_array_add (table, new_entry);
7648 //printf ("MAX: %d\n", max_chain_length);
7650 /* Emit the table */
7651 sprintf (symbol, "extra_method_table");
7652 emit_section_change (acfg, RODATA_SECT, 0);
7653 emit_alignment (acfg, 8);
7654 emit_label (acfg, symbol);
7656 emit_int32 (acfg, table_size);
7657 for (i = 0; i < table->len; ++i) {
7658 HashEntry *entry = g_ptr_array_index (table, i);
7660 if (entry == NULL) {
7661 emit_int32 (acfg, 0);
7662 emit_int32 (acfg, 0);
7663 emit_int32 (acfg, 0);
7665 //g_assert (entry->key > 0);
7666 emit_int32 (acfg, entry->key);
7667 emit_int32 (acfg, entry->value);
7669 emit_int32 (acfg, entry->next->index);
7671 emit_int32 (acfg, 0);
7676 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7677 * This is used by mono_aot_find_jit_info ().
7679 sprintf (symbol, "extra_method_info_offsets");
7680 emit_section_change (acfg, RODATA_SECT, 0);
7681 emit_alignment (acfg, 8);
7682 emit_label (acfg, symbol);
7684 emit_int32 (acfg, acfg->extra_methods->len);
7685 for (i = 0; i < acfg->extra_methods->len; ++i) {
7686 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7688 emit_int32 (acfg, get_method_index (acfg, method));
7689 emit_int32 (acfg, info_offsets [i]);
7694 emit_exception_info (MonoAotCompile *acfg)
7700 offsets = g_new0 (gint32, acfg->nmethods);
7701 for (i = 0; i < acfg->nmethods; ++i) {
7702 if (acfg->cfgs [i]) {
7703 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7704 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7710 sprintf (symbol, "ex_info_offsets");
7711 emit_section_change (acfg, RODATA_SECT, 1);
7712 emit_alignment (acfg, 8);
7713 emit_label (acfg, symbol);
7715 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7720 emit_unwind_info (MonoAotCompile *acfg)
7726 * The unwind info contains a lot of duplicates so we emit each unique
7727 * entry once, and only store the offset from the start of the table in the
7731 sprintf (symbol, "unwind_info");
7732 emit_section_change (acfg, RODATA_SECT, 1);
7733 emit_alignment (acfg, 8);
7734 emit_label (acfg, symbol);
7736 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7737 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7738 guint8 *unwind_info;
7739 guint32 unwind_info_len;
7743 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7746 encode_value (unwind_info_len, p, &p);
7747 emit_bytes (acfg, buf, p - buf);
7748 emit_bytes (acfg, unwind_info, unwind_info_len);
7750 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7755 emit_class_info (MonoAotCompile *acfg)
7761 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7762 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7763 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7765 sprintf (symbol, "class_info_offsets");
7766 emit_section_change (acfg, RODATA_SECT, 1);
7767 emit_alignment (acfg, 8);
7768 emit_label (acfg, symbol);
7770 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7774 typedef struct ClassNameTableEntry {
7775 guint32 token, index;
7776 struct ClassNameTableEntry *next;
7777 } ClassNameTableEntry;
7780 emit_class_name_table (MonoAotCompile *acfg)
7783 guint32 token, hash;
7788 ClassNameTableEntry *entry, *new_entry;
7791 * Construct a chained hash table for mapping class names to typedef tokens.
7793 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7794 table = g_ptr_array_sized_new (table_size);
7795 for (i = 0; i < table_size; ++i)
7796 g_ptr_array_add (table, NULL);
7797 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7798 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7799 klass = mono_class_get (acfg->image, token);
7801 mono_loader_clear_error ();
7804 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7805 hash = mono_metadata_str_hash (full_name) % table_size;
7808 /* FIXME: Allocate from the mempool */
7809 new_entry = g_new0 (ClassNameTableEntry, 1);
7810 new_entry->token = token;
7812 entry = g_ptr_array_index (table, hash);
7813 if (entry == NULL) {
7814 new_entry->index = hash;
7815 g_ptr_array_index (table, hash) = new_entry;
7818 entry = entry->next;
7820 entry->next = new_entry;
7821 new_entry->index = table->len;
7822 g_ptr_array_add (table, new_entry);
7826 /* Emit the table */
7827 sprintf (symbol, "class_name_table");
7828 emit_section_change (acfg, RODATA_SECT, 0);
7829 emit_alignment (acfg, 8);
7830 emit_label (acfg, symbol);
7832 /* FIXME: Optimize memory usage */
7833 g_assert (table_size < 65000);
7834 emit_int16 (acfg, table_size);
7835 g_assert (table->len < 65000);
7836 for (i = 0; i < table->len; ++i) {
7837 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7839 if (entry == NULL) {
7840 emit_int16 (acfg, 0);
7841 emit_int16 (acfg, 0);
7843 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7845 emit_int16 (acfg, entry->next->index);
7847 emit_int16 (acfg, 0);
7853 emit_image_table (MonoAotCompile *acfg)
7859 * The image table is small but referenced in a lot of places.
7860 * So we emit it at once, and reference its elements by an index.
7863 sprintf (symbol, "image_table");
7864 emit_section_change (acfg, RODATA_SECT, 1);
7865 emit_alignment (acfg, 8);
7866 emit_label (acfg, symbol);
7868 emit_int32 (acfg, acfg->image_table->len);
7869 for (i = 0; i < acfg->image_table->len; i++) {
7870 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7871 MonoAssemblyName *aname = &image->assembly->aname;
7873 /* FIXME: Support multi-module assemblies */
7874 g_assert (image->assembly->image == image);
7876 emit_string (acfg, image->assembly_name);
7877 emit_string (acfg, image->guid);
7878 emit_string (acfg, aname->culture ? aname->culture : "");
7879 emit_string (acfg, (const char*)aname->public_key_token);
7881 emit_alignment (acfg, 8);
7882 emit_int32 (acfg, aname->flags);
7883 emit_int32 (acfg, aname->major);
7884 emit_int32 (acfg, aname->minor);
7885 emit_int32 (acfg, aname->build);
7886 emit_int32 (acfg, aname->revision);
7891 emit_got_info (MonoAotCompile *acfg)
7894 int i, first_plt_got_patch, buf_size;
7896 guint32 *got_info_offsets;
7898 /* Add the patches needed by the PLT to the GOT */
7899 acfg->plt_got_offset_base = acfg->got_offset;
7900 first_plt_got_patch = acfg->got_patches->len;
7901 for (i = 1; i < acfg->plt_offset; ++i) {
7902 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7904 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7906 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7909 acfg->got_offset += acfg->plt_offset;
7913 * - optimize offsets table.
7914 * - reduce number of exported symbols.
7915 * - emit info for a klass only once.
7916 * - determine when a method uses a GOT slot which is guaranteed to be already
7918 * - clean up and document the code.
7919 * - use String.Empty in class libs.
7922 /* Encode info required to decode shared GOT entries */
7923 buf_size = acfg->got_patches->len * 128;
7924 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7925 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7926 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7928 if (acfg->plt_offset)
7929 acfg->plt_got_info_offsets [0] = 0;
7930 for (i = 0; i < acfg->got_patches->len; ++i) {
7931 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7936 encode_value (ji->type, p, &p);
7938 encode_patch (acfg, ji, p, &p);
7939 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7940 g_assert (p - buf <= buf_size);
7941 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7943 if (i >= first_plt_got_patch)
7944 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7945 acfg->stats.got_info_size += p - buf;
7948 /* Emit got_info_offsets table */
7949 sprintf (symbol, "got_info_offsets");
7950 emit_section_change (acfg, RODATA_SECT, 1);
7951 emit_alignment (acfg, 8);
7952 emit_label (acfg, symbol);
7954 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7955 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7959 emit_got (MonoAotCompile *acfg)
7964 /* Don't make GOT global so accesses to it don't need relocations */
7965 sprintf (symbol, "%s", acfg->got_symbol);
7966 emit_section_change (acfg, ".bss", 0);
7967 emit_alignment (acfg, 8);
7968 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7969 emit_label (acfg, symbol);
7970 if (acfg->got_offset > 0)
7971 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7973 sprintf (symbol, "got_end");
7974 emit_label (acfg, symbol);
7978 typedef struct GlobalsTableEntry {
7979 guint32 value, index;
7980 struct GlobalsTableEntry *next;
7981 } GlobalsTableEntry;
7984 emit_globals (MonoAotCompile *acfg)
7990 GlobalsTableEntry *entry, *new_entry;
7992 if (!acfg->aot_opts.static_link)
7996 * When static linking, we emit a table containing our globals.
8000 * Construct a chained hash table for mapping global names to their index in
8001 * the globals table.
8003 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8004 table = g_ptr_array_sized_new (table_size);
8005 for (i = 0; i < table_size; ++i)
8006 g_ptr_array_add (table, NULL);
8007 for (i = 0; i < acfg->globals->len; ++i) {
8008 char *name = g_ptr_array_index (acfg->globals, i);
8010 hash = mono_metadata_str_hash (name) % table_size;
8012 /* FIXME: Allocate from the mempool */
8013 new_entry = g_new0 (GlobalsTableEntry, 1);
8014 new_entry->value = i;
8016 entry = g_ptr_array_index (table, hash);
8017 if (entry == NULL) {
8018 new_entry->index = hash;
8019 g_ptr_array_index (table, hash) = new_entry;
8022 entry = entry->next;
8024 entry->next = new_entry;
8025 new_entry->index = table->len;
8026 g_ptr_array_add (table, new_entry);
8030 /* Emit the table */
8031 sprintf (symbol, ".Lglobals_hash");
8032 emit_section_change (acfg, RODATA_SECT, 0);
8033 emit_alignment (acfg, 8);
8034 emit_label (acfg, symbol);
8036 /* FIXME: Optimize memory usage */
8037 g_assert (table_size < 65000);
8038 emit_int16 (acfg, table_size);
8039 for (i = 0; i < table->len; ++i) {
8040 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8042 if (entry == NULL) {
8043 emit_int16 (acfg, 0);
8044 emit_int16 (acfg, 0);
8046 emit_int16 (acfg, entry->value + 1);
8048 emit_int16 (acfg, entry->next->index);
8050 emit_int16 (acfg, 0);
8054 /* Emit the names */
8055 for (i = 0; i < acfg->globals->len; ++i) {
8056 char *name = g_ptr_array_index (acfg->globals, i);
8058 sprintf (symbol, "name_%d", i);
8059 emit_section_change (acfg, RODATA_SECT, 1);
8061 emit_alignment (acfg, 4);
8063 emit_label (acfg, symbol);
8064 emit_string (acfg, name);
8067 /* Emit the globals table */
8068 sprintf (symbol, "globals");
8069 emit_section_change (acfg, ".data", 0);
8070 /* This is not a global, since it is accessed by the init function */
8071 emit_alignment (acfg, 8);
8072 emit_label (acfg, symbol);
8074 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8075 emit_pointer (acfg, symbol);
8077 for (i = 0; i < acfg->globals->len; ++i) {
8078 char *name = g_ptr_array_index (acfg->globals, i);
8080 sprintf (symbol, "name_%d", i);
8081 emit_pointer (acfg, symbol);
8083 sprintf (symbol, "%s", name);
8084 emit_pointer (acfg, symbol);
8086 /* Null terminate the table */
8087 emit_int32 (acfg, 0);
8088 emit_int32 (acfg, 0);
8092 emit_autoreg (MonoAotCompile *acfg)
8097 * Emit a function into the .ctor section which will be called by the ELF
8098 * loader to register this module with the runtime.
8100 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8103 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8105 arch_emit_autoreg (acfg, symbol);
8111 emit_mem_end (MonoAotCompile *acfg)
8115 sprintf (symbol, "mem_end");
8116 emit_section_change (acfg, ".text", 1);
8117 emit_alignment (acfg, 8);
8118 emit_label (acfg, symbol);
8122 * Emit a structure containing all the information not stored elsewhere.
8125 emit_file_info (MonoAotCompile *acfg)
8130 const char *gc_name;
8133 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8135 if (acfg->aot_opts.bind_to_runtime_version) {
8136 build_info = mono_get_runtime_build_info ();
8137 emit_string_symbol (acfg, "runtime_version", build_info);
8138 g_free (build_info);
8140 emit_string_symbol (acfg, "runtime_version", "");
8143 /* Emit a string holding the assembly name */
8144 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8147 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8150 gc_name = mono_gc_get_gc_name ();
8151 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8153 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8154 emit_section_change (acfg, ".data", 0);
8155 emit_alignment (acfg, 8);
8156 emit_label (acfg, symbol);
8157 if (!acfg->aot_opts.static_link)
8158 emit_global (acfg, symbol, FALSE);
8160 /* The data emitted here must match MonoAotFileInfo. */
8162 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8163 emit_int32 (acfg, 0);
8166 * We emit pointers to our data structures instead of emitting global symbols which
8167 * point to them, to reduce the number of globals, and because using globals leads to
8168 * various problems (i.e. arm/thumb).
8170 emit_pointer (acfg, acfg->got_symbol);
8171 emit_pointer (acfg, acfg->methods_symbol);
8174 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8176 emit_pointer (acfg, "mono_eh_frame");
8178 emit_pointer (acfg, NULL);
8180 emit_pointer (acfg, "blob");
8181 emit_pointer (acfg, "class_name_table");
8182 emit_pointer (acfg, "class_info_offsets");
8183 emit_pointer (acfg, "method_info_offsets");
8184 emit_pointer (acfg, "ex_info_offsets");
8185 emit_pointer (acfg, "code_offsets");
8186 if (acfg->direct_method_addresses)
8187 emit_pointer (acfg, "method_addresses");
8189 emit_pointer (acfg, NULL);
8190 emit_pointer (acfg, "extra_method_info_offsets");
8191 emit_pointer (acfg, "extra_method_table");
8192 emit_pointer (acfg, "got_info_offsets");
8193 emit_pointer (acfg, "methods_end");
8194 emit_pointer (acfg, "unwind_info");
8195 emit_pointer (acfg, "mem_end");
8196 emit_pointer (acfg, "image_table");
8197 emit_pointer (acfg, "plt");
8198 emit_pointer (acfg, "plt_end");
8199 emit_pointer (acfg, "assembly_guid");
8200 emit_pointer (acfg, "runtime_version");
8201 if (acfg->num_trampoline_got_entries) {
8202 emit_pointer (acfg, "specific_trampolines");
8203 emit_pointer (acfg, "static_rgctx_trampolines");
8204 emit_pointer (acfg, "imt_thunks");
8205 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8207 emit_pointer (acfg, NULL);
8208 emit_pointer (acfg, NULL);
8209 emit_pointer (acfg, NULL);
8210 emit_pointer (acfg, NULL);
8212 if (acfg->thumb_mixed) {
8213 emit_pointer (acfg, "thumb_end");
8215 emit_pointer (acfg, NULL);
8217 if (acfg->aot_opts.static_link) {
8218 emit_pointer (acfg, "globals");
8220 emit_pointer (acfg, NULL);
8222 emit_pointer (acfg, "assembly_name");
8223 emit_pointer (acfg, "unbox_trampolines");
8224 emit_pointer (acfg, "unbox_trampolines_end");
8226 emit_int32 (acfg, acfg->plt_got_offset_base);
8227 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8228 emit_int32 (acfg, acfg->plt_offset);
8229 emit_int32 (acfg, acfg->nmethods);
8230 emit_int32 (acfg, acfg->flags);
8231 emit_int32 (acfg, acfg->opts);
8232 emit_int32 (acfg, acfg->simd_opts);
8233 emit_int32 (acfg, gc_name_offset);
8235 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8236 emit_int32 (acfg, acfg->num_trampolines [i]);
8237 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8238 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8239 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8240 emit_int32 (acfg, acfg->trampoline_size [i]);
8241 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8243 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8248 memset (&t, 0, sizeof (MonoType));
8249 t.type = MONO_TYPE_R8;
8250 mono_type_size (&t, &align);
8251 emit_int32 (acfg, align);
8253 memset (&t, 0, sizeof (MonoType));
8254 t.type = MONO_TYPE_I8;
8255 mono_type_size (&t, &align);
8257 emit_int32 (acfg, align);
8260 emit_int32 (acfg, __alignof__ (double));
8261 emit_int32 (acfg, __alignof__ (gint64));
8263 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8264 emit_int32 (acfg, acfg->tramp_page_size);
8265 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8266 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8268 if (acfg->aot_opts.static_link) {
8272 * Emit a global symbol which can be passed by an embedding app to
8273 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8276 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8278 /* Get rid of characters which cannot occur in symbols */
8280 for (p = symbol; *p; ++p) {
8281 if (!(isalnum (*p) || *p == '_'))
8284 acfg->static_linking_symbol = g_strdup (symbol);
8285 emit_global_inner (acfg, symbol, FALSE);
8286 emit_alignment (acfg, sizeof (gpointer));
8287 emit_label (acfg, symbol);
8288 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8293 emit_blob (MonoAotCompile *acfg)
8297 sprintf (symbol, "blob");
8298 emit_section_change (acfg, RODATA_SECT, 1);
8299 emit_alignment (acfg, 8);
8300 emit_label (acfg, symbol);
8302 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8306 emit_objc_selectors (MonoAotCompile *acfg)
8310 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8315 * cat > foo.m << EOF
8318 * return @selector(print:);
8323 img_writer_emit_unset_mode (acfg->w);
8324 g_assert (acfg->fp);
8325 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8326 fprintf (acfg->fp, ".align 3\n");
8327 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8328 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8329 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8331 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8332 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8333 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8334 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8337 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8338 fprintf (acfg->fp, ".align 3\n");
8339 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8340 fprintf (acfg->fp, ".long 0\n");
8341 fprintf (acfg->fp, ".long 16\n");
8345 emit_dwarf_info (MonoAotCompile *acfg)
8347 #ifdef EMIT_DWARF_INFO
8351 /* DIEs for methods */
8352 for (i = 0; i < acfg->nmethods; ++i) {
8353 MonoCompile *cfg = acfg->cfgs [i];
8358 // FIXME: LLVM doesn't define .Lme_...
8359 if (cfg->compile_llvm)
8362 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8364 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
8370 collect_methods (MonoAotCompile *acfg)
8373 MonoImage *image = acfg->image;
8375 /* Collect methods */
8376 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8378 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8380 method = mono_get_method (acfg->image, token, NULL);
8383 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8384 printf ("Run with MONO_LOG_LEVEL=debug for more information.\n");
8388 /* Load all methods eagerly to skip the slower lazy loading code */
8389 mono_class_setup_methods (method->klass);
8391 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8392 /* Compile the wrapper instead */
8393 /* We do this here instead of add_wrappers () because it is easy to do it here */
8394 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8398 /* FIXME: Some mscorlib methods don't have debug info */
8400 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8401 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8402 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8403 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8404 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8405 if (!mono_debug_lookup_method (method)) {
8406 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8413 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8414 add_method_with_index (acfg, method, i, FALSE);
8415 acfg->method_index ++;
8418 /* gsharedvt methods */
8419 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8421 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8423 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8426 method = mono_get_method (acfg->image, token, NULL);
8430 if (strcmp (method->name, "gshared2"))
8434 if (!strstr (method->klass->image->name, "mini"))
8437 if (method->is_generic || method->klass->generic_container) {
8438 MonoMethod *gshared;
8440 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8441 add_extra_method (acfg, gshared);
8445 add_generic_instances (acfg);
8447 if (acfg->aot_opts.full_aot)
8448 add_wrappers (acfg);
8452 compile_methods (MonoAotCompile *acfg)
8456 if (acfg->aot_opts.nthreads > 0) {
8461 gpointer *user_data;
8462 MonoMethod **methods;
8464 methods_len = acfg->methods->len;
8466 len = acfg->methods->len / acfg->aot_opts.nthreads;
8469 * Partition the list of methods into fragments, and hand it to threads to
8472 threads = g_ptr_array_new ();
8473 /* Make a copy since acfg->methods is modified by compile_method () */
8474 methods = g_new0 (MonoMethod*, methods_len);
8475 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8476 for (i = 0; i < methods_len; ++i)
8477 methods [i] = g_ptr_array_index (acfg->methods, i);
8479 while (i < methods_len) {
8480 frag = g_ptr_array_new ();
8481 for (j = 0; j < len; ++j) {
8482 if (i < methods_len) {
8483 g_ptr_array_add (frag, methods [i]);
8488 user_data = g_new0 (gpointer, 3);
8489 user_data [0] = mono_domain_get ();
8490 user_data [1] = acfg;
8491 user_data [2] = frag;
8493 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8494 g_ptr_array_add (threads, handle);
8498 for (i = 0; i < threads->len; ++i) {
8499 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8505 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8506 for (i = methods_len; i < acfg->methods->len; ++i) {
8507 /* This can new methods to acfg->methods */
8508 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8513 compile_asm (MonoAotCompile *acfg)
8515 char *command, *objfile;
8516 char *outfile_name, *tmp_outfile_name;
8517 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8519 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8520 #define AS_OPTIONS "--64"
8521 #elif defined(TARGET_POWERPC64)
8522 #define AS_OPTIONS "-a64 -mppc64"
8523 #define LD_OPTIONS "-m elf64ppc"
8524 #elif defined(sparc) && SIZEOF_VOID_P == 8
8525 #define AS_OPTIONS "-xarch=v9"
8526 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8527 #define AS_OPTIONS "-arch i386"
8529 #define AS_OPTIONS ""
8532 #ifdef __native_client_codegen__
8533 #if defined(TARGET_AMD64)
8534 #define AS_NAME "nacl64-as"
8536 #define AS_NAME "nacl-as"
8538 #elif defined(TARGET_OSX)
8539 #define AS_NAME "clang -c -x assembler"
8541 #define AS_NAME "as"
8545 #define LD_OPTIONS ""
8549 #define LD_NAME "ld -shared -G"
8550 #elif defined(__ppc__) && defined(TARGET_MACH)
8551 #define LD_NAME "gcc -dynamiclib"
8552 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8553 #define LD_NAME "clang --shared"
8554 #elif defined(HOST_WIN32)
8555 #define LD_NAME "gcc -shared --dll"
8556 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8557 #define LD_NAME "clang -m32 -dynamiclib"
8560 if (acfg->aot_opts.asm_only) {
8561 printf ("Output file: '%s'.\n", acfg->tmpfname);
8562 if (acfg->aot_opts.static_link)
8563 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8567 if (acfg->aot_opts.static_link) {
8568 if (acfg->aot_opts.outfile)
8569 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8571 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8573 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8575 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);
8576 printf ("Executing the native assembler: %s\n", command);
8577 if (system (command) != 0) {
8585 if (acfg->aot_opts.static_link) {
8586 printf ("Output file: '%s'.\n", objfile);
8587 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8592 if (acfg->aot_opts.outfile)
8593 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8595 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8597 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8600 command = g_strdup_printf ("%s -o %s %s.o", LD_NAME, tmp_outfile_name, acfg->tmpfname);
8602 command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8604 printf ("Executing the native linker: %s\n", command);
8605 if (system (command) != 0) {
8606 g_free (tmp_outfile_name);
8607 g_free (outfile_name);
8615 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8616 printf ("Stripping the binary: %s\n", com);
8620 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8622 * gas generates 'mapping symbols' each time code and data is mixed, which
8623 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8625 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8626 printf ("Stripping the binary: %s\n", command);
8627 if (system (command) != 0) {
8628 g_free (tmp_outfile_name);
8629 g_free (outfile_name);
8636 rename (tmp_outfile_name, outfile_name);
8638 #if defined(TARGET_MACH)
8639 command = g_strdup_printf ("dsymutil %s", outfile_name);
8640 printf ("Executing dsymutil: %s\n", command);
8641 if (system (command) != 0) {
8646 if (!acfg->aot_opts.save_temps)
8649 g_free (tmp_outfile_name);
8650 g_free (outfile_name);
8653 if (acfg->aot_opts.save_temps)
8654 printf ("Retained input file.\n");
8656 unlink (acfg->tmpfname);
8661 static MonoAotCompile*
8662 acfg_create (MonoAssembly *ass, guint32 opts)
8664 MonoImage *image = ass->image;
8665 MonoAotCompile *acfg;
8668 acfg = g_new0 (MonoAotCompile, 1);
8669 acfg->methods = g_ptr_array_new ();
8670 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8671 acfg->method_depth = g_hash_table_new (NULL, NULL);
8672 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8673 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8674 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8675 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8676 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8677 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8678 acfg->got_patches = g_ptr_array_new ();
8679 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8680 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8681 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8682 acfg->image_hash = g_hash_table_new (NULL, NULL);
8683 acfg->image_table = g_ptr_array_new ();
8684 acfg->globals = g_ptr_array_new ();
8685 acfg->image = image;
8687 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8688 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8689 acfg->mempool = mono_mempool_new ();
8690 acfg->extra_methods = g_ptr_array_new ();
8691 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8692 acfg->unwind_ops = g_ptr_array_new ();
8693 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8694 acfg->method_order = g_ptr_array_new ();
8695 acfg->export_names = g_hash_table_new (NULL, NULL);
8696 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8697 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8698 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8699 InitializeCriticalSection (&acfg->mutex);
8705 acfg_free (MonoAotCompile *acfg)
8709 img_writer_destroy (acfg->w);
8710 for (i = 0; i < acfg->nmethods; ++i)
8712 g_free (acfg->cfgs [i]);
8713 g_free (acfg->cfgs);
8714 g_free (acfg->static_linking_symbol);
8715 g_free (acfg->got_symbol);
8716 g_free (acfg->plt_symbol);
8717 g_ptr_array_free (acfg->methods, TRUE);
8718 g_ptr_array_free (acfg->got_patches, TRUE);
8719 g_ptr_array_free (acfg->image_table, TRUE);
8720 g_ptr_array_free (acfg->globals, TRUE);
8721 g_ptr_array_free (acfg->unwind_ops, TRUE);
8722 g_hash_table_destroy (acfg->method_indexes);
8723 g_hash_table_destroy (acfg->method_depth);
8724 g_hash_table_destroy (acfg->plt_offset_to_entry);
8725 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8726 if (acfg->patch_to_plt_entry [i])
8727 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8729 g_free (acfg->patch_to_plt_entry);
8730 g_hash_table_destroy (acfg->patch_to_got_offset);
8731 g_hash_table_destroy (acfg->method_to_cfg);
8732 g_hash_table_destroy (acfg->token_info_hash);
8733 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8734 g_hash_table_destroy (acfg->image_hash);
8735 g_hash_table_destroy (acfg->unwind_info_offsets);
8736 g_hash_table_destroy (acfg->method_label_hash);
8737 g_hash_table_destroy (acfg->export_names);
8738 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8739 g_hash_table_destroy (acfg->klass_blob_hash);
8740 g_hash_table_destroy (acfg->method_blob_hash);
8741 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8742 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8743 g_free (acfg->patch_to_got_offset_by_type);
8744 mono_mempool_destroy (acfg->mempool);
8749 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8751 MonoImage *image = ass->image;
8752 int i, res, all_sizes;
8753 MonoAotCompile *acfg;
8754 char *outfile_name, *tmp_outfile_name, *p;
8755 char llvm_stats_msg [256];
8759 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8760 if (opts & MONO_OPT_GSHAREDVT) {
8761 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8766 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8768 acfg = acfg_create (ass, opts);
8770 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8771 acfg->aot_opts.write_symbols = TRUE;
8772 acfg->aot_opts.ntrampolines = 1024;
8773 acfg->aot_opts.nrgctx_trampolines = 1024;
8774 acfg->aot_opts.nimt_trampolines = 128;
8775 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8776 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8777 acfg->aot_opts.llvm_path = g_strdup ("");
8779 acfg->aot_opts.use_trampolines_page = TRUE;
8782 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8784 if (acfg->aot_opts.static_link)
8785 acfg->aot_opts.autoreg = TRUE;
8787 //acfg->aot_opts.print_skipped_methods = TRUE;
8789 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8790 if (acfg->aot_opts.full_aot) {
8791 printf ("--aot=full is not supported on this platform.\n");
8796 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8797 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8801 if (acfg->aot_opts.static_link)
8802 acfg->aot_opts.asm_writer = TRUE;
8804 if (acfg->aot_opts.soft_debug) {
8805 MonoDebugOptions *opt = mini_get_debug_options ();
8807 opt->mdb_optimizations = TRUE;
8808 opt->gen_seq_points = TRUE;
8810 if (!mono_debug_enabled ()) {
8811 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8814 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8817 if (mono_use_llvm) {
8819 acfg->aot_opts.asm_writer = TRUE;
8820 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8822 if (acfg->aot_opts.soft_debug) {
8823 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8828 if (acfg->aot_opts.full_aot)
8829 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8831 if (acfg->aot_opts.instances_logfile_path) {
8832 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
8833 if (!acfg->instances_logfile) {
8834 fprintf (stderr, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
8839 load_profile_files (acfg);
8841 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8842 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8843 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8845 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8846 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8847 if (acfg->opts & MONO_OPT_GSHAREDVT)
8848 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8851 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8855 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8856 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8857 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8859 /* Get rid of characters which cannot occur in symbols */
8860 for (p = acfg->got_symbol_base; *p; ++p) {
8861 if (!(isalnum (*p) || *p == '_'))
8864 for (p = acfg->plt_symbol; *p; ++p) {
8865 if (!(isalnum (*p) || *p == '_'))
8868 for (p = acfg->assembly_name_sym; *p; ++p) {
8869 if (!(isalnum (*p) || *p == '_'))
8873 acfg->method_index = 1;
8877 if (acfg->aot_opts.full_aot)
8878 mono_set_partial_sharing_supported (TRUE);
8881 collect_methods (acfg);
8883 acfg->cfgs_size = acfg->methods->len + 32;
8884 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8886 /* PLT offset 0 is reserved for the PLT trampoline */
8887 acfg->plt_offset = 1;
8892 mono_llvm_create_aot_module (acfg->got_symbol_base);
8896 /* GOT offset 0 is reserved for the address of the current assembly */
8900 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8901 ji->type = MONO_PATCH_INFO_IMAGE;
8902 ji->data.image = acfg->image;
8904 get_got_offset (acfg, ji);
8906 /* Slot 1 is reserved for the mscorlib got addr */
8907 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8908 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8909 get_got_offset (acfg, ji);
8911 /* This is very common */
8912 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8913 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8914 get_got_offset (acfg, ji);
8916 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8917 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8918 get_got_offset (acfg, ji);
8923 compile_methods (acfg);
8927 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8933 if (acfg->aot_opts.asm_only) {
8934 if (acfg->aot_opts.outfile) {
8935 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8936 acfg->tmpbasename = g_strdup (acfg->tmpfname);
8938 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
8939 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8942 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
8943 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8946 emit_llvm_file (acfg);
8950 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8951 if (acfg->aot_opts.outfile)
8952 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8954 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8957 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8958 * it might be in another file system so the rename () won't work.
8960 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8962 acfg->fp = fopen (tmp_outfile_name, "w");
8964 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8968 acfg->w = img_writer_create (acfg->fp, TRUE);
8969 acfg->use_bin_writer = TRUE;
8972 /* Append to the .s file created by llvm */
8973 /* FIXME: Use multiple files instead */
8974 acfg->fp = fopen (acfg->tmpfname, "a+");
8976 if (acfg->aot_opts.asm_only) {
8977 if (acfg->aot_opts.outfile)
8978 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8980 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8981 acfg->fp = fopen (acfg->tmpfname, "w+");
8983 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8984 acfg->fp = fdopen (i, "w+");
8987 if (acfg->fp == 0) {
8988 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8991 acfg->w = img_writer_create (acfg->fp, FALSE);
8993 tmp_outfile_name = NULL;
8994 outfile_name = NULL;
8997 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8999 /* Compute symbols for methods */
9000 for (i = 0; i < acfg->nmethods; ++i) {
9001 if (acfg->cfgs [i]) {
9002 MonoCompile *cfg = acfg->cfgs [i];
9003 int method_index = get_method_index (acfg, cfg->orig_method);
9005 if (COMPILE_LLVM (cfg))
9006 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9007 else if (acfg->global_symbols)
9008 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
9010 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9014 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9016 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9017 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9020 //acfg->gas_line_numbers = TRUE;
9023 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9024 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9025 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
9028 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9031 img_writer_emit_start (acfg->w);
9034 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9036 if (acfg->thumb_mixed) {
9039 * This global symbol marks the end of THUMB code, and the beginning of ARM
9040 * code generated by our JIT.
9042 sprintf (symbol, "thumb_end");
9043 emit_section_change (acfg, ".text", 0);
9044 emit_alignment (acfg, 8);
9045 emit_label (acfg, symbol);
9046 emit_zero_bytes (acfg, 16);
9048 fprintf (acfg->fp, ".arm\n");
9055 emit_extra_methods (acfg);
9057 emit_trampolines (acfg);
9059 emit_class_name_table (acfg);
9061 emit_got_info (acfg);
9063 emit_exception_info (acfg);
9065 emit_unwind_info (acfg);
9067 emit_class_info (acfg);
9071 emit_image_table (acfg);
9075 emit_file_info (acfg);
9079 emit_objc_selectors (acfg);
9081 emit_globals (acfg);
9083 emit_autoreg (acfg);
9086 emit_dwarf_info (acfg);
9087 mono_dwarf_writer_close (acfg->dwarf);
9090 emit_mem_end (acfg);
9092 if (acfg->need_pt_gnu_stack) {
9093 /* This is required so the .so doesn't have an executable stack */
9094 /* The bin writer already emits this */
9095 if (!acfg->use_bin_writer)
9096 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9101 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9104 g_assert (acfg->got_offset <= acfg->final_got_size);
9107 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9109 strcpy (llvm_stats_msg, "");
9111 all_sizes = acfg->stats.code_size + acfg->stats.info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
9113 printf ("Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d\n",
9114 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9115 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9116 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9117 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9118 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9119 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9120 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9121 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9122 (int)(acfg->got_offset * sizeof (gpointer)));
9123 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9124 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9126 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9127 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9128 if (acfg->stats.genericcount)
9129 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9130 if (acfg->stats.abscount)
9131 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9132 if (acfg->stats.lmfcount)
9133 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9134 if (acfg->stats.ocount)
9135 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9138 res = img_writer_emit_writeout (acfg->w);
9143 if (acfg->use_bin_writer) {
9144 int err = rename (tmp_outfile_name, outfile_name);
9147 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9151 res = compile_asm (acfg);
9158 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9160 if (acfg->aot_opts.stats) {
9163 printf ("GOT slot distribution:\n");
9164 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9165 if (acfg->stats.got_slot_types [i])
9166 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9169 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);
9181 mono_aot_readonly_field_override (MonoClassField *field)
9187 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)