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"
75 #define RODATA_SECT ".text"
78 #define TV_DECLARE(name) gint64 name
79 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
80 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
83 #define SHARED_EXT ".dll"
84 #elif defined(__ppc__) && defined(TARGET_MACH)
85 #define SHARED_EXT ".dylib"
86 #elif defined(TARGET_MACH) && defined(TARGET_X86) && !defined(__native_client_codegen__)
87 #define SHARED_EXT ".dylib"
88 #elif defined(TARGET_MACH) && defined(TARGET_AMD64) && !defined(__native_client_codegen__)
89 #define SHARED_EXT ".dylib"
91 #define SHARED_EXT ".so"
94 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
95 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
96 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
98 /* predefined values for static readonly fields without needed to run the .cctor */
99 typedef struct _ReadOnlyValue ReadOnlyValue;
100 struct _ReadOnlyValue {
103 int type; /* to be used later for typechecking to prevent user errors */
112 static ReadOnlyValue *readonly_values = NULL;
114 typedef struct MonoAotOptions {
117 gboolean write_symbols;
118 gboolean metadata_only;
119 gboolean bind_to_runtime_version;
122 gboolean static_link;
126 gboolean dwarf_debug;
128 gboolean log_generics;
129 gboolean direct_pinvoke;
130 gboolean direct_icalls;
131 gboolean no_direct_calls;
132 gboolean use_trampolines_page;
133 gboolean no_instances;
137 int nrgctx_trampolines;
138 int nimt_trampolines;
139 int ngsharedvt_arg_trampolines;
140 int nrgctx_fetch_trampolines;
141 gboolean print_skipped_methods;
149 typedef struct MonoAotStats {
150 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
151 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
152 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
153 int got_slots, offsets_size;
154 int got_slot_types [MONO_PATCH_INFO_NONE];
155 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
156 int jit_time, gen_time, link_time;
159 typedef struct MonoAotCompile {
162 GHashTable *method_indexes;
163 GHashTable *method_depth;
166 GHashTable *patch_to_plt_entry;
167 GHashTable *plt_offset_to_entry;
168 GHashTable *patch_to_got_offset;
169 GHashTable **patch_to_got_offset_by_type;
170 GPtrArray *got_patches;
171 GHashTable *image_hash;
172 GHashTable *method_to_cfg;
173 GHashTable *token_info_hash;
174 GHashTable *method_to_pinvoke_import;
175 GPtrArray *extra_methods;
176 GPtrArray *image_table;
178 GPtrArray *method_order;
179 GHashTable *export_names;
180 /* Maps MonoClass* -> blob offset */
181 GHashTable *klass_blob_hash;
182 /* Maps MonoMethod* -> blob offset */
183 GHashTable *method_blob_hash;
184 guint32 *plt_got_info_offsets;
185 guint32 got_offset, plt_offset, plt_got_offset_base;
186 guint32 final_got_size;
187 /* Number of GOT entries reserved for trampolines */
188 guint32 num_trampoline_got_entries;
190 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
191 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
192 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
194 MonoAotOptions aot_opts;
198 MonoMemPool *mempool;
201 char *static_linking_symbol;
202 CRITICAL_SECTION mutex;
203 gboolean use_bin_writer;
204 gboolean gas_line_numbers;
206 MonoDwarfWriter *dwarf;
210 GHashTable *unwind_info_offsets;
211 GPtrArray *unwind_ops;
212 guint32 unwind_info_offset;
213 char *got_symbol_base;
216 GHashTable *method_label_hash;
217 const char *temp_prefix;
218 const char *user_symbol_prefix;
219 const char *llvm_label_prefix;
220 guint32 label_generator;
222 MonoAotFileFlags flags;
223 MonoDynamicStream blob;
224 MonoClass **typespec_classes;
227 char *assembly_name_sym;
228 GHashTable *plt_entry_debug_sym_cache;
229 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
230 GHashTable *ginst_hash;
231 GHashTable *dwarf_ln_filenames;
232 gboolean global_symbols;
233 gboolean direct_method_addresses;
238 char *symbol, *llvm_symbol, *debug_sym;
240 gboolean jit_used, llvm_used;
243 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
244 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
246 /* This points to the current acfg in LLVM mode */
247 static MonoAotCompile *llvm_acfg;
249 #ifdef HAVE_ARRAY_ELEM_INIT
250 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
251 #define MSGSTRFIELD1(line) str##line
252 static const struct msgstr_t {
253 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
254 #include "patch-info.h"
257 #define PATCH_INFO(a,b) b,
258 #include "patch-info.h"
261 static const gint16 opidx [] = {
262 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
263 #include "patch-info.h"
267 static G_GNUC_UNUSED const char*
268 get_patch_name (int info)
270 return (const char*)&opstr + opidx [info];
274 #define PATCH_INFO(a,b) b,
275 static const char* const
276 patch_types [MONO_PATCH_INFO_NUM + 1] = {
277 #include "patch-info.h"
281 static G_GNUC_UNUSED const char*
282 get_patch_name (int info)
284 return patch_types [info];
290 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
292 /* Wrappers around the image writer functions */
295 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
297 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
301 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
303 img_writer_emit_push_section (acfg->w, section_name, subsection);
307 emit_pop_section (MonoAotCompile *acfg)
309 img_writer_emit_pop_section (acfg->w);
313 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
315 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
319 emit_label (MonoAotCompile *acfg, const char *name)
321 img_writer_emit_label (acfg->w, name);
325 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
327 img_writer_emit_bytes (acfg->w, buf, size);
331 emit_string (MonoAotCompile *acfg, const char *value)
333 img_writer_emit_string (acfg->w, value);
337 emit_line (MonoAotCompile *acfg)
339 img_writer_emit_line (acfg->w);
343 emit_alignment (MonoAotCompile *acfg, int size)
345 img_writer_emit_alignment (acfg->w, size);
349 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
351 img_writer_emit_pointer_unaligned (acfg->w, target);
355 emit_pointer (MonoAotCompile *acfg, const char *target)
357 img_writer_emit_pointer (acfg->w, target);
361 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
363 if (prefix [0] != '\0') {
364 char *s = g_strdup_printf ("%s%s", prefix, target);
365 img_writer_emit_pointer (acfg->w, s);
368 img_writer_emit_pointer (acfg->w, target);
373 emit_int16 (MonoAotCompile *acfg, int value)
375 img_writer_emit_int16 (acfg->w, value);
379 emit_int32 (MonoAotCompile *acfg, int value)
381 img_writer_emit_int32 (acfg->w, value);
385 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
387 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
391 emit_zero_bytes (MonoAotCompile *acfg, int num)
393 img_writer_emit_zero_bytes (acfg->w, num);
397 emit_byte (MonoAotCompile *acfg, guint8 val)
399 img_writer_emit_byte (acfg->w, val);
402 #ifdef __native_client_codegen__
404 emit_nacl_call_alignment (MonoAotCompile *acfg)
406 img_writer_emit_nacl_call_alignment (acfg->w);
410 static G_GNUC_UNUSED void
411 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
413 img_writer_emit_global (acfg->w, name, func);
417 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
419 if (acfg->aot_opts.no_dlsym) {
420 g_ptr_array_add (acfg->globals, g_strdup (name));
421 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
423 img_writer_emit_global (acfg->w, name, func);
428 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
430 img_writer_emit_symbol_size (acfg->w, name, end_label);
434 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
436 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
438 /* On apple, all symbols need to be aligned to avoid warnings from ld */
439 emit_alignment (acfg, 4);
441 img_writer_emit_label (acfg->w, name);
442 img_writer_emit_string (acfg->w, value);
445 static G_GNUC_UNUSED void
446 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
449 guint8 b = value & 0x7f;
451 if (value != 0) /* more bytes to come */
457 static G_GNUC_UNUSED void
458 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
461 gboolean negative = (value < 0);
468 /* the following is unnecessary if the
469 * implementation of >>= uses an arithmetic rather
470 * than logical shift for a signed left operand
474 value |= - ((gint64)1 <<(size - 7));
475 /* sign bit of byte is second high order bit (0x40) */
476 if ((value == 0 && !(byte & 0x40)) ||
477 (value == -1 && (byte & 0x40)))
481 emit_byte (acfg, byte);
485 static G_GNUC_UNUSED void
486 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
491 guint8 b = value & 0x7f;
493 if (value != 0) /* more bytes to come */
501 static G_GNUC_UNUSED void
502 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
505 gboolean negative = (value < 0);
513 /* the following is unnecessary if the
514 * implementation of >>= uses an arithmetic rather
515 * than logical shift for a signed left operand
519 value |= - (1 <<(size - 7));
520 /* sign bit of byte is second high order bit (0x40) */
521 if ((value == 0 && !(byte & 0x40)) ||
522 (value == -1 && (byte & 0x40)))
532 /* ARCHITECTURE SPECIFIC CODE */
534 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
535 #define EMIT_DWARF_INFO 1
538 #if defined(TARGET_ARM)
539 #define AOT_FUNC_ALIGNMENT 4
541 #define AOT_FUNC_ALIGNMENT 16
543 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
544 #undef AOT_FUNC_ALIGNMENT
545 #define AOT_FUNC_ALIGNMENT 32
548 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
549 #define PPC_LD_OP "ld"
550 #define PPC_LDX_OP "ldx"
552 #define PPC_LD_OP "lwz"
553 #define PPC_LDX_OP "lwzx"
557 #define AOT_TARGET_STR "AMD64"
562 #define AOT_TARGET_STR "ARM (MACH)"
564 #define AOT_TARGET_STR "ARM (!MACH)"
568 #ifdef TARGET_POWERPC64
569 #ifdef __mono_ilp32__
570 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
572 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
575 #ifdef TARGET_POWERPC
576 #ifdef __mono_ilp32__
577 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
579 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
586 #define AOT_TARGET_STR "X86 (WIN32)"
587 #elif defined(__native_client_codegen__)
588 #define AOT_TARGET_STR "X86 (native client codegen)"
590 #define AOT_TARGET_STR "X86 (!native client codegen)"
594 #ifndef AOT_TARGET_STR
595 #define AOT_TARGET_STR ""
599 arch_init (MonoAotCompile *acfg)
601 acfg->llc_args = g_string_new ("");
602 acfg->as_args = g_string_new ("");
605 * The prefix LLVM likes to put in front of symbol names on darwin.
606 * The mach-os specs require this for globals, but LLVM puts them in front of all
607 * symbols. We need to handle this, since we need to refer to LLVM generated
610 acfg->llvm_label_prefix = "";
611 acfg->user_symbol_prefix = "";
613 #if defined(TARGET_AMD64) && defined(TARGET_MACH)
614 /* osx contains an old as which doesn't support avx opcodes */
615 g_string_append (acfg->llc_args, "-mattr=-avx");
619 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
620 g_string_append (acfg->llc_args, "-mattr=+v6");
623 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
624 g_string_append (acfg->as_args, " -mfpu=vfp3");
626 g_string_append (acfg->llc_args, " -soft-float");
629 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
630 acfg->thumb_mixed = TRUE;
632 if (acfg->aot_opts.mtriple)
633 mono_arch_set_target (acfg->aot_opts.mtriple);
637 acfg->user_symbol_prefix = "_";
638 acfg->llvm_label_prefix = "_";
639 acfg->need_no_dead_strip = TRUE;
640 acfg->aot_opts.gnu_asm = TRUE;
643 #if defined(__linux__) && !defined(TARGET_ARM)
644 acfg->need_pt_gnu_stack = TRUE;
648 acfg->direct_method_addresses = TRUE;
649 acfg->global_symbols = TRUE;
654 * arch_emit_direct_call:
656 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
660 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, int *call_size)
662 #if defined(TARGET_X86) || defined(TARGET_AMD64)
663 /* Need to make sure this is exactly 5 bytes long */
664 if (external && !acfg->use_bin_writer) {
665 img_writer_emit_unset_mode (acfg->w);
666 fprintf (acfg->fp, "call %s\n", target);
668 emit_byte (acfg, '\xe8');
669 emit_symbol_diff (acfg, target, ".", -4);
672 #elif defined(TARGET_ARM)
673 if (acfg->use_bin_writer) {
680 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
681 emit_bytes (acfg, buf, 4);
683 img_writer_emit_unset_mode (acfg->w);
684 fprintf (acfg->fp, "bl %s\n", target);
687 #elif defined(TARGET_POWERPC)
688 if (acfg->use_bin_writer) {
689 g_assert_not_reached ();
691 img_writer_emit_unset_mode (acfg->w);
692 fprintf (acfg->fp, "bl %s\n", target);
696 g_assert_not_reached ();
702 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
704 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
705 * in in the 2. slot of every GOT, and require every method to place the GOT
706 * address in r30, even when it doesn't access the GOT otherwise. This way,
707 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
712 * PPC64 uses function descriptors which greatly complicate all code, since
713 * these are used very inconsistently in the runtime. Some functions like
714 * mono_compile_method () return ftn descriptors, while others like the
715 * trampoline creation functions do not.
716 * We assume that all GOT slots contain function descriptors, and create
717 * descriptors in aot-runtime.c when needed.
718 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
719 * from function descriptors, we could do the same, but it would require
720 * rewriting all the ppc/aot code to handle function descriptors properly.
721 * So instead, we use the same approach as on PPC32.
722 * This is a horrible mess, but fixing it would probably lead to an even bigger
728 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
731 #ifdef MONO_ARCH_AOT_SUPPORTED
733 * arch_emit_got_offset:
735 * The memory pointed to by CODE should hold native code for computing the GOT
736 * address. Emit this code while patching it with the offset between code and
737 * the GOT. CODE_SIZE is set to the number of bytes emitted.
740 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
742 #if defined(TARGET_POWERPC64)
743 g_assert (!acfg->use_bin_writer);
744 img_writer_emit_unset_mode (acfg->w);
746 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
747 * unsupported relocations. So we store the got address into the .Lgot_addr
748 * symbol which is in the text segment, compute its address, and load it.
750 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
751 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
752 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
753 fprintf (acfg->fp, "add 30, 30, 0\n");
754 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
755 acfg->label_generator ++;
757 #elif defined(TARGET_POWERPC)
758 g_assert (!acfg->use_bin_writer);
759 img_writer_emit_unset_mode (acfg->w);
760 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
761 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
762 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
763 acfg->label_generator ++;
766 guint32 offset = mono_arch_get_patch_offset (code);
767 emit_bytes (acfg, code, offset);
768 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
770 *code_size = offset + 4;
775 * arch_emit_got_access:
777 * The memory pointed to by CODE should hold native code for loading a GOT
778 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
779 * CODE_SIZE is set to the number of bytes emitted.
782 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
784 /* Emit beginning of instruction */
785 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
787 /* Emit the offset */
789 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
790 *code_size = mono_arch_get_patch_offset (code) + 4;
791 #elif defined(TARGET_X86)
792 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
793 *code_size = mono_arch_get_patch_offset (code) + 4;
794 #elif defined(TARGET_ARM)
795 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
796 *code_size = mono_arch_get_patch_offset (code) + 4;
797 #elif defined(TARGET_POWERPC)
803 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
804 g_assert (code - buf == 8);
805 emit_bytes (acfg, buf, code - buf);
806 *code_size = code - buf;
809 g_assert_not_reached ();
816 * arch_emit_plt_entry:
818 * Emit code for the PLT entry with index INDEX.
821 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
823 #if defined(TARGET_X86)
824 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
825 #if defined(__default_codegen__)
826 /* jmp *<offset>(%ebx) */
827 emit_byte (acfg, 0xff);
828 emit_byte (acfg, 0xa3);
829 emit_int32 (acfg, offset);
830 /* Used by mono_aot_get_plt_info_offset */
831 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
832 #elif defined(__native_client_codegen__)
833 const guint8 kSizeOfNaClJmp = 11;
834 guint8 bytes[kSizeOfNaClJmp];
835 guint8 *pbytes = &bytes[0];
837 x86_jump_membase32 (pbytes, X86_EBX, offset);
838 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
839 /* four bytes of data, used by mono_arch_patch_plt_entry */
840 /* For Native Client, make this work with data embedded in push. */
841 emit_byte (acfg, 0x68); /* hide data in a push */
842 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
843 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
844 #endif /*__native_client_codegen__*/
845 #elif defined(TARGET_AMD64)
846 #if defined(__default_codegen__)
848 * We can't emit jumps because they are 32 bits only so they can't be patched.
849 * So we make indirect calls through GOT entries which are patched by the AOT
850 * loader to point to .Lpd entries.
852 /* jmpq *<offset>(%rip) */
853 emit_byte (acfg, '\xff');
854 emit_byte (acfg, '\x25');
855 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
856 /* Used by mono_aot_get_plt_info_offset */
857 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
858 #elif defined(__native_client_codegen__)
860 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
861 guint8 *code = buf_aligned;
863 /* mov <OFFSET>(%rip), %r11d */
864 emit_byte (acfg, '\x45');
865 emit_byte (acfg, '\x8b');
866 emit_byte (acfg, '\x1d');
867 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
869 amd64_jump_reg (code, AMD64_R11);
870 /* This should be constant for the plt patch */
871 g_assert ((size_t)(code-buf_aligned) == 10);
872 emit_bytes (acfg, buf_aligned, code - buf_aligned);
874 /* Hide data in a push imm32 so it passes validation */
875 emit_byte (acfg, 0x68); /* push */
876 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
877 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
878 #endif /*__native_client_codegen__*/
879 #elif defined(TARGET_ARM)
884 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
885 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
886 emit_bytes (acfg, buf, code - buf);
887 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
888 /* Used by mono_aot_get_plt_info_offset */
889 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
890 #elif defined(TARGET_POWERPC)
891 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
893 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
894 g_assert (!acfg->use_bin_writer);
895 img_writer_emit_unset_mode (acfg->w);
896 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
897 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
898 fprintf (acfg->fp, "add 11, 11, 30\n");
899 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
900 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
901 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
902 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
904 fprintf (acfg->fp, "mtctr 11\n");
905 fprintf (acfg->fp, "bctr\n");
906 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
908 g_assert_not_reached ();
913 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
915 #if defined(TARGET_ARM)
917 /* LLVM calls the PLT entries using bl, so emit a stub */
918 /* FIXME: Too much overhead on every call */
919 fprintf (acfg->fp, ".thumb_func\n");
920 fprintf (acfg->fp, "bx pc\n");
921 fprintf (acfg->fp, "nop\n");
922 fprintf (acfg->fp, ".arm\n");
924 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
925 /* The caller already transitioned to thumb */
926 /* The code below should be 12 bytes long */
927 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
928 /* thumb can't encode ld pc, [pc, ip] */
929 fprintf (acfg->fp, "add ip, pc, ip\n");
930 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
931 fprintf (acfg->fp, "bx ip\n");
932 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
933 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
935 g_assert_not_reached ();
940 * arch_emit_specific_trampoline_pages:
942 * Emits a page full of trampolines: each trampoline uses its own address to
943 * lookup both the generic trampoline code and the data argument.
944 * This page can be remapped in process multiple times so we can get an
945 * unlimited number of trampolines.
946 * Specifically this implementation uses the following trick: two memory pages
947 * are allocated, with the first containing the data and the second containing the trampolines.
948 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
949 * implementation does all the lifting.
950 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
951 * on the arm 32 bit system.
954 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
956 #if defined(TARGET_ARM)
959 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
961 #define COMMON_TRAMP_SIZE 16
962 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
963 int imm8, rot_amount;
966 if (!acfg->aot_opts.use_trampolines_page)
969 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
970 emit_alignment (acfg, mono_pagesize ());
971 emit_global (acfg, symbol, TRUE);
972 emit_label (acfg, symbol);
974 /* emit the generic code first, the trampoline address + 8 is in the lr register */
976 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
977 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
978 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
979 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
981 g_assert (code - buf == COMMON_TRAMP_SIZE);
984 emit_bytes (acfg, buf, code - buf);
986 for (i = 0; i < count; ++i) {
988 ARM_PUSH (code, 0x5fff);
990 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
991 g_assert (code - buf == 8);
992 emit_bytes (acfg, buf, code - buf);
995 /* now the rgctx trampolines: each specific trampolines puts in the ip register
996 * the instruction pointer address, so the generic trampoline at the start of the page
997 * subtracts 4096 to get to the data page and loads the values
998 * We again fit the generic trampiline in 16 bytes.
1000 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1001 emit_global (acfg, symbol, TRUE);
1002 emit_label (acfg, symbol);
1004 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1005 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1006 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1007 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1009 g_assert (code - buf == COMMON_TRAMP_SIZE);
1012 emit_bytes (acfg, buf, code - buf);
1014 for (i = 0; i < count; ++i) {
1016 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1018 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1019 g_assert (code - buf == 8);
1020 emit_bytes (acfg, buf, code - buf);
1024 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1026 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1027 emit_global (acfg, symbol, TRUE);
1028 emit_label (acfg, symbol);
1030 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1031 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1032 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1033 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1034 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1035 g_assert (code - buf == COMMON_TRAMP_SIZE);
1037 emit_bytes (acfg, buf, code - buf);
1039 for (i = 0; i < count; ++i) {
1041 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1043 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1044 g_assert (code - buf == 8);
1045 emit_bytes (acfg, buf, code - buf);
1048 /* now the imt trampolines: each specific trampolines puts in the ip register
1049 * the instruction pointer address, so the generic trampoline at the start of the page
1050 * subtracts 4096 to get to the data page and loads the values
1051 * We again fit the generic trampiline in 16 bytes.
1053 #define IMT_TRAMP_SIZE 72
1054 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1055 emit_global (acfg, symbol, TRUE);
1056 emit_label (acfg, symbol);
1058 /* Need at least two free registers, plus a slot for storing the pc */
1059 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1061 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1062 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1063 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1065 /* The IMT method is in v5, r0 has the imt array address */
1068 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1069 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1070 imt_found_check = code;
1071 ARM_B_COND (code, ARMCOND_EQ, 0);
1073 /* End-of-loop check */
1074 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1075 loop_end_check = code;
1076 ARM_B_COND (code, ARMCOND_EQ, 0);
1079 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1080 loop_branch_back = code;
1082 arm_patch (loop_branch_back, loop_start);
1085 arm_patch (imt_found_check, code);
1086 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1087 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1088 /* Save it to the third stack slot */
1089 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1090 /* Restore the registers and branch */
1091 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1094 arm_patch (loop_end_check, code);
1095 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1096 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1097 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1101 g_assert (code - buf == IMT_TRAMP_SIZE);
1102 emit_bytes (acfg, buf, code - buf);
1104 for (i = 0; i < count; ++i) {
1106 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1108 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1109 g_assert (code - buf == 8);
1110 emit_bytes (acfg, buf, code - buf);
1116 * arch_emit_specific_trampoline:
1118 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1119 * two GOT slots which contain the generic trampoline address and the trampoline
1120 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1123 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1126 * The trampolines created here are variations of the specific
1127 * trampolines created in mono_arch_create_specific_trampoline (). The
1129 * - the generic trampoline address is taken from a got slot.
1130 * - the offset of the got slot where the trampoline argument is stored
1131 * is embedded in the instruction stream, and the generic trampoline
1132 * can load the argument by loading the offset, adding it to the
1133 * address of the trampoline to get the address of the got slot, and
1134 * loading the argument from there.
1135 * - all the trampolines should be of the same length.
1137 #if defined(TARGET_AMD64)
1138 #if defined(__default_codegen__)
1139 /* This should be exactly 16 bytes long */
1141 /* call *<offset>(%rip) */
1142 emit_byte (acfg, '\x41');
1143 emit_byte (acfg, '\xff');
1144 emit_byte (acfg, '\x15');
1145 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1146 /* This should be relative to the start of the trampoline */
1147 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1148 emit_zero_bytes (acfg, 5);
1149 #elif defined(__native_client_codegen__)
1151 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1152 guint8 *code = buf_aligned;
1157 /* Emit this call in 'code' so we can find out how long it is. */
1158 amd64_call_reg (code, AMD64_R11);
1159 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1160 call_len = code - call_start;
1162 /* The tramp_size is twice the NaCl alignment because it starts with */
1163 /* a call which needs to be aligned to the end of the boundary. */
1164 *tramp_size = kNaClAlignment*2;
1166 /* Emit nops to align call site below which is 7 bytes plus */
1167 /* the length of the call sequence emitted above. */
1168 /* Note: this requires the specific trampoline starts on a */
1169 /* kNaclAlignedment aligned address, which it does because */
1170 /* it's its own function that is aligned. */
1171 guint8 nop_buf[256];
1172 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1173 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1174 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1176 /* The trampoline is stored at the offset'th pointer, the -4 is */
1177 /* present because RIP relative addressing starts at the end of */
1178 /* the current instruction, while the label "." is relative to */
1179 /* the beginning of the current asm location, which in this case */
1180 /* is not the mov instruction, but the offset itself, due to the */
1181 /* way the bytes and ints are emitted here. */
1182 got_offset = (offset * sizeof(gpointer)) - 4;
1184 /* mov <OFFSET>(%rip), %r11d */
1185 emit_byte (acfg, '\x45');
1186 emit_byte (acfg, '\x8b');
1187 emit_byte (acfg, '\x1d');
1188 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1191 emit_bytes (acfg, call_start, call_len);
1193 /* The arg is stored at the offset+1 pointer, relative to beginning */
1194 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1195 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1197 /* We can't emit this data directly, hide in a "push imm32" */
1198 emit_byte (acfg, '\x68'); /* push */
1199 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1200 emit_alignment (acfg, kNaClAlignment);
1201 #endif /*__native_client_codegen__*/
1202 #elif defined(TARGET_ARM)
1206 /* This should be exactly 20 bytes long */
1209 ARM_PUSH (code, 0x5fff);
1210 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1211 /* Load the value from the GOT */
1212 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1214 ARM_BLX_REG (code, ARMREG_R1);
1216 g_assert (code - buf == 16);
1219 emit_bytes (acfg, buf, code - buf);
1221 * Only one offset is needed, since the second one would be equal to the
1224 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1225 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1226 #elif defined(TARGET_POWERPC)
1233 g_assert (!acfg->use_bin_writer);
1236 * PPC has no ip relative addressing, so we need to compute the address
1237 * of the mscorlib got. That is slow and complex, so instead, we store it
1238 * in the second got slot of every aot image. The caller already computed
1239 * the address of its got and placed it into r30.
1241 img_writer_emit_unset_mode (acfg->w);
1242 /* Load mscorlib got address */
1243 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1244 /* Load generic trampoline address */
1245 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1246 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1247 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1248 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1249 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1251 fprintf (acfg->fp, "mtctr 11\n");
1252 /* Load trampoline argument */
1253 /* On ppc, we pass it normally to the generic trampoline */
1254 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1255 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1256 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1257 /* Branch to generic trampoline */
1258 fprintf (acfg->fp, "bctr\n");
1260 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1261 *tramp_size = 10 * 4;
1263 *tramp_size = 9 * 4;
1265 #elif defined(TARGET_X86)
1269 /* Similar to the PPC code above */
1271 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1273 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1274 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1275 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1279 /* Load mscorlib got address */
1280 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1281 /* Push trampoline argument */
1282 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1283 /* Load generic trampoline address */
1284 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1285 /* Branch to generic trampoline */
1286 x86_jump_reg (code, X86_ECX);
1288 #ifdef __native_client_codegen__
1290 /* emit nops to next 32 byte alignment */
1291 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1292 while (code < (buf + a)) x86_nop(code);
1295 emit_bytes (acfg, buf, code - buf);
1297 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1298 g_assert (code - buf == *tramp_size);
1300 g_assert_not_reached ();
1305 * arch_emit_unbox_trampoline:
1307 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1308 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1311 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1313 #if defined(TARGET_AMD64)
1318 this_reg = mono_arch_get_this_arg_reg (NULL);
1320 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1322 emit_bytes (acfg, buf, code - buf);
1324 emit_byte (acfg, '\xe9');
1325 emit_symbol_diff (acfg, call_target, ".", -4);
1326 #elif defined(TARGET_X86)
1333 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1335 emit_bytes (acfg, buf, code - buf);
1338 emit_byte (acfg, '\xe9');
1339 emit_symbol_diff (acfg, call_target, ".", -4);
1340 #elif defined(TARGET_ARM)
1344 if (acfg->thumb_mixed && cfg->compile_llvm) {
1345 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1346 fprintf (acfg->fp, "b %s\n", call_target);
1347 fprintf (acfg->fp, ".arm\n");
1348 fprintf (acfg->fp, ".align 2\n");
1354 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1356 emit_bytes (acfg, buf, code - buf);
1357 /* jump to method */
1358 if (acfg->use_bin_writer) {
1365 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1366 emit_bytes (acfg, buf, 4);
1368 if (acfg->thumb_mixed && cfg->compile_llvm)
1369 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1371 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1373 #elif defined(TARGET_POWERPC)
1376 g_assert (!acfg->use_bin_writer);
1378 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1379 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1381 g_assert_not_reached ();
1386 * arch_emit_static_rgctx_trampoline:
1388 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1389 * two GOT slots which contain the rgctx argument, and the method to jump to.
1390 * TRAMP_SIZE is set to the size of the emitted trampoline.
1391 * These kinds of trampolines cannot be enumerated statically, since there could
1392 * be one trampoline per method instantiation, so we emit the same code for all
1393 * trampolines, and parameterize them using two GOT slots.
1396 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1398 #if defined(TARGET_AMD64)
1399 #if defined(__default_codegen__)
1400 /* This should be exactly 13 bytes long */
1403 /* mov <OFFSET>(%rip), %r10 */
1404 emit_byte (acfg, '\x4d');
1405 emit_byte (acfg, '\x8b');
1406 emit_byte (acfg, '\x15');
1407 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1409 /* jmp *<offset>(%rip) */
1410 emit_byte (acfg, '\xff');
1411 emit_byte (acfg, '\x25');
1412 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1413 #elif defined(__native_client_codegen__)
1415 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1416 guint8 *code = buf_aligned;
1418 /* mov <OFFSET>(%rip), %r10d */
1419 emit_byte (acfg, '\x45');
1420 emit_byte (acfg, '\x8b');
1421 emit_byte (acfg, '\x15');
1422 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1424 /* mov <OFFSET>(%rip), %r11d */
1425 emit_byte (acfg, '\x45');
1426 emit_byte (acfg, '\x8b');
1427 emit_byte (acfg, '\x1d');
1428 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1431 amd64_jump_reg (code, AMD64_R11);
1432 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1434 emit_alignment (acfg, kNaClAlignment);
1435 *tramp_size = kNaClAlignment;
1436 #endif /*__native_client_codegen__*/
1438 #elif defined(TARGET_ARM)
1442 /* This should be exactly 24 bytes long */
1445 /* Load rgctx value */
1446 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1447 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1448 /* Load branch addr + branch */
1449 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1450 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1452 g_assert (code - buf == 16);
1455 emit_bytes (acfg, buf, code - buf);
1456 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1457 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1458 #elif defined(TARGET_POWERPC)
1465 g_assert (!acfg->use_bin_writer);
1468 * PPC has no ip relative addressing, so we need to compute the address
1469 * of the mscorlib got. That is slow and complex, so instead, we store it
1470 * in the second got slot of every aot image. The caller already computed
1471 * the address of its got and placed it into r30.
1473 img_writer_emit_unset_mode (acfg->w);
1474 /* Load mscorlib got address */
1475 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1477 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1478 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1479 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1480 /* Load target address */
1481 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1482 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1483 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1484 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1485 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1486 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1488 fprintf (acfg->fp, "mtctr 11\n");
1489 /* Branch to the target address */
1490 fprintf (acfg->fp, "bctr\n");
1492 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1493 *tramp_size = 11 * 4;
1495 *tramp_size = 9 * 4;
1498 #elif defined(TARGET_X86)
1502 /* Similar to the PPC code above */
1504 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1507 /* Load mscorlib got address */
1508 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1510 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1511 /* Branch to the target address */
1512 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1514 #ifdef __native_client_codegen__
1516 /* emit nops to next 32 byte alignment */
1517 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1518 while (code < (buf + a)) x86_nop(code);
1522 emit_bytes (acfg, buf, code - buf);
1524 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1525 g_assert (code - buf == *tramp_size);
1527 g_assert_not_reached ();
1532 * arch_emit_imt_thunk:
1534 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1535 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1536 * key is the IMT key, and ptr holds the address of a memory location holding
1537 * the address to branch to if the IMT arg matches the key. The array is
1538 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1540 * TRAMP_SIZE is set to the size of the emitted trampoline.
1543 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1545 #if defined(TARGET_AMD64)
1547 #if defined(__native_client_codegen__)
1550 guint8 *labels [16];
1552 guint8 *mov_buf_ptr = mov_buf;
1554 const int kSizeOfMove = 7;
1555 #if defined(__default_codegen__)
1556 code = buf = g_malloc (256);
1557 #elif defined(__native_client_codegen__)
1558 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1559 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1560 /* The RIP relative move below is emitted first */
1565 /* FIXME: Optimize this, i.e. use binary search etc. */
1566 /* Maybe move the body into a separate function (slower, but much smaller) */
1568 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1571 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1573 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1576 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1578 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1581 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1582 amd64_jump_code (code, labels [0]);
1585 mono_amd64_patch (labels [2], code);
1586 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1587 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1590 mono_amd64_patch (labels [1], code);
1591 /* Load fail tramp */
1592 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1593 /* Check if there is a fail tramp */
1594 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1596 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1597 /* Jump to fail tramp */
1598 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1601 mono_amd64_patch (labels [3], code);
1602 x86_breakpoint (code);
1604 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1605 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1606 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1607 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1608 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1609 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1611 emit_bytes (acfg, buf, code - buf);
1613 *tramp_size = code - buf + kSizeOfMove;
1614 #if defined(__native_client_codegen__)
1615 /* The tramp will be padded to the next kNaClAlignment bundle. */
1616 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1619 #if defined(__default_codegen__)
1621 #elif defined(__native_client_codegen__)
1625 #elif defined(TARGET_X86)
1627 #ifdef __native_client_codegen__
1630 guint8 *labels [16];
1632 #if defined(__default_codegen__)
1633 code = buf = g_malloc (256);
1634 #elif defined(__native_client_codegen__)
1635 buf_alloc = g_malloc (256 + kNaClAlignment);
1636 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1639 /* Allocate a temporary stack slot */
1640 x86_push_reg (code, X86_EAX);
1642 x86_push_reg (code, X86_EAX);
1644 /* Load mscorlib got address */
1645 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1647 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1650 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1652 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1655 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1657 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1660 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1661 x86_jump_code (code, labels [0]);
1664 mono_x86_patch (labels [2], code);
1665 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1666 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1667 /* Save the target address to the temporary stack location */
1668 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1670 x86_pop_reg (code, X86_EAX);
1671 /* Jump to the target address */
1675 mono_x86_patch (labels [1], code);
1676 /* Load fail tramp */
1677 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1678 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1680 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1681 /* Jump to fail tramp */
1682 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1683 x86_pop_reg (code, X86_EAX);
1687 mono_x86_patch (labels [3], code);
1688 x86_breakpoint (code);
1690 #ifdef __native_client_codegen__
1692 /* emit nops to next 32 byte alignment */
1693 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1694 while (code < (buf + a)) x86_nop(code);
1697 emit_bytes (acfg, buf, code - buf);
1699 *tramp_size = code - buf;
1701 #if defined(__default_codegen__)
1703 #elif defined(__native_client_codegen__)
1707 #elif defined(TARGET_ARM)
1709 guint8 *code, *code2, *labels [16];
1713 /* The IMT method is in v5 */
1715 /* Need at least two free registers, plus a slot for storing the pc */
1716 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1718 /* Load the parameter from the GOT */
1719 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1720 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1723 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1724 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1726 ARM_B_COND (code, ARMCOND_EQ, 0);
1728 /* End-of-loop check */
1729 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1731 ARM_B_COND (code, ARMCOND_EQ, 0);
1734 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1737 arm_patch (labels [4], labels [1]);
1740 arm_patch (labels [2], code);
1741 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1742 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1743 /* Save it to the third stack slot */
1744 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1745 /* Restore the registers and branch */
1746 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1749 arm_patch (labels [3], code);
1750 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1751 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1752 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1756 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1758 emit_bytes (acfg, buf, code - buf);
1759 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1761 *tramp_size = code - buf + 4;
1762 #elif defined(TARGET_POWERPC)
1764 guint8 *code, *labels [16];
1768 /* Load the mscorlib got address */
1769 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1770 /* Load the parameter from the GOT */
1771 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1772 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1774 /* Load and check key */
1776 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1777 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1779 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1781 /* End-of-loop check */
1782 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1784 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1787 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1790 mono_ppc_patch (labels [4], labels [1]);
1793 mono_ppc_patch (labels [2], code);
1794 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1795 /* r11 now contains the value of the vtable slot */
1796 /* this is not a function descriptor on ppc64 */
1797 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1798 ppc_mtctr (code, ppc_r11);
1799 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1802 mono_ppc_patch (labels [3], code);
1806 *tramp_size = code - buf;
1808 emit_bytes (acfg, buf, code - buf);
1810 g_assert_not_reached ();
1815 * arch_emit_gsharedvt_arg_trampoline:
1817 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1818 * two GOT slots which contain the argument, and the code to jump to.
1819 * TRAMP_SIZE is set to the size of the emitted trampoline.
1820 * These kinds of trampolines cannot be enumerated statically, since there could
1821 * be one trampoline per method instantiation, so we emit the same code for all
1822 * trampolines, and parameterize them using two GOT slots.
1825 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1827 #if defined(TARGET_X86)
1831 /* Similar to the PPC code above */
1833 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1836 /* Load mscorlib got address */
1837 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1839 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1840 /* Branch to the target address */
1841 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1843 #ifdef __native_client_codegen__
1845 /* emit nops to next 32 byte alignment */
1846 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1847 while (code < (buf + a)) x86_nop(code);
1851 emit_bytes (acfg, buf, code - buf);
1853 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1854 g_assert (code - buf == *tramp_size);
1855 #elif defined(TARGET_ARM)
1859 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1860 /* Similar to arch_emit_specific_trampoline () */
1863 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1864 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1865 /* Load the arg value from the GOT */
1866 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1867 /* Load the addr from the GOT */
1868 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1870 ARM_BX (code, ARMREG_R1);
1872 g_assert (code - buf == 20);
1875 emit_bytes (acfg, buf, code - buf);
1876 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1878 g_assert_not_reached ();
1883 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1885 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1886 /* Based on code generated by gcc */
1887 img_writer_emit_unset_mode (acfg->w);
1890 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1891 ".section .ctors,\"aw\",@progbits\n"
1895 ".section .opd,\"aw\"\n"
1898 ".long .%s,.TOC.@tocbase32\n"
1901 ".type .%s,@function\n"
1903 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1905 ".section .ctors,\"aw\",@progbits\n"
1909 ".section .opd,\"aw\"\n"
1912 ".long .%1$s,.TOC.@tocbase32\n"
1913 ".size %1$s,.-%1$s\n"
1915 ".type .%1$s,@function\n"
1917 ".%1$s:\n", symbol);
1928 "lis 3, .Lglobals@h\n"
1929 "ori 3, 3, .Lglobals@l\n"
1930 "bl .mono_aot_register_module\n"
1938 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1940 ".size .%s,.-.%s\n", symbol, symbol);
1943 ".size .%1$s,.-.%1$s\n", symbol);
1949 /* END OF ARCH SPECIFIC CODE */
1952 mono_get_field_token (MonoClassField *field)
1954 MonoClass *klass = field->parent;
1957 for (i = 0; i < klass->field.count; ++i) {
1958 if (field == &klass->fields [i])
1959 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1962 g_assert_not_reached ();
1967 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1971 //printf ("ENCODE: %d 0x%x.\n", value, value);
1974 * Same encoding as the one used in the metadata, extended to handle values
1975 * greater than 0x1fffffff.
1977 if ((value >= 0) && (value <= 127))
1979 else if ((value >= 0) && (value <= 16383)) {
1980 p [0] = 0x80 | (value >> 8);
1981 p [1] = value & 0xff;
1983 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1984 p [0] = (value >> 24) | 0xc0;
1985 p [1] = (value >> 16) & 0xff;
1986 p [2] = (value >> 8) & 0xff;
1987 p [3] = value & 0xff;
1992 p [1] = (value >> 24) & 0xff;
1993 p [2] = (value >> 16) & 0xff;
1994 p [3] = (value >> 8) & 0xff;
1995 p [4] = value & 0xff;
2003 stream_init (MonoDynamicStream *sh)
2006 sh->alloc_size = 4096;
2007 sh->data = g_malloc (4096);
2009 /* So offsets are > 0 */
2015 make_room_in_stream (MonoDynamicStream *stream, int size)
2017 if (size <= stream->alloc_size)
2020 while (stream->alloc_size <= size) {
2021 if (stream->alloc_size < 4096)
2022 stream->alloc_size = 4096;
2024 stream->alloc_size *= 2;
2027 stream->data = g_realloc (stream->data, stream->alloc_size);
2031 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2035 make_room_in_stream (stream, stream->index + len);
2036 memcpy (stream->data + stream->index, data, len);
2037 idx = stream->index;
2038 stream->index += len;
2045 * Add data to the binary blob inside the aot image. Returns the offset inside the
2046 * blob where the data was stored.
2049 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2051 if (acfg->blob.alloc_size == 0)
2052 stream_init (&acfg->blob);
2054 return add_stream_data (&acfg->blob, (char*)data, data_len);
2058 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2063 if (acfg->blob.alloc_size == 0)
2064 stream_init (&acfg->blob);
2066 count = acfg->blob.index % align;
2068 /* we assume the stream data will be aligned */
2070 add_stream_data (&acfg->blob, buf, 4 - count);
2072 return add_stream_data (&acfg->blob, (char*)data, data_len);
2076 * emit_offset_table:
2078 * Emit a table of increasing offsets in a compact form using differential encoding.
2079 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2080 * group size, the more compact the table becomes, but the slower it becomes to compute
2081 * a given entry. Returns the size of the table.
2084 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2086 gint32 current_offset;
2087 int i, buf_size, ngroups, index_entry_size;
2089 guint32 *index_offsets;
2091 ngroups = (noffsets + (group_size - 1)) / group_size;
2093 index_offsets = g_new0 (guint32, ngroups);
2095 buf_size = noffsets * 4;
2096 p = buf = g_malloc0 (buf_size);
2099 for (i = 0; i < noffsets; ++i) {
2100 //printf ("D: %d -> %d\n", i, offsets [i]);
2101 if ((i % group_size) == 0) {
2102 index_offsets [i / group_size] = p - buf;
2103 /* Emit the full value for these entries */
2104 encode_value (offsets [i], p, &p);
2106 /* The offsets are allowed to be non-increasing */
2107 //g_assert (offsets [i] >= current_offset);
2108 encode_value (offsets [i] - current_offset, p, &p);
2110 current_offset = offsets [i];
2113 if (ngroups && index_offsets [ngroups - 1] < 65000)
2114 index_entry_size = 2;
2116 index_entry_size = 4;
2118 /* Emit the header */
2119 emit_int32 (acfg, noffsets);
2120 emit_int32 (acfg, group_size);
2121 emit_int32 (acfg, ngroups);
2122 emit_int32 (acfg, index_entry_size);
2124 /* Emit the index */
2125 for (i = 0; i < ngroups; ++i) {
2126 if (index_entry_size == 2)
2127 emit_int16 (acfg, index_offsets [i]);
2129 emit_int32 (acfg, index_offsets [i]);
2133 emit_bytes (acfg, buf, p - buf);
2135 return (int)(p - buf) + (ngroups * 4);
2139 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2143 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2147 index = g_hash_table_size (cfg->image_hash);
2148 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2149 g_ptr_array_add (cfg->image_table, image);
2155 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2158 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2160 /* FIXME: Search referenced images as well */
2161 if (!acfg->typespec_classes) {
2162 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2163 for (i = 0; i < len; ++i) {
2164 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2167 for (i = 0; i < len; ++i) {
2168 if (acfg->typespec_classes [i] == klass)
2173 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2179 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2182 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2185 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2188 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2191 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2196 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2200 if (klass->generic_class) {
2202 g_assert (klass->type_token);
2204 /* Find a typespec for a class if possible */
2205 token = find_typespec_for_class (acfg, klass);
2207 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2208 encode_value (token, p, &p);
2210 MonoClass *gclass = klass->generic_class->container_class;
2211 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2212 static int count = 0;
2215 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2216 encode_klass_ref (acfg, gclass, p, &p);
2217 encode_ginst (acfg, inst, p, &p);
2221 } else if (klass->type_token) {
2222 int iindex = get_image_index (acfg, klass->image);
2224 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2226 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2227 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2229 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2230 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2231 encode_value (get_image_index (acfg, klass->image), p, &p);
2233 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2234 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2235 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2237 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2238 encode_value (klass->byval_arg.type, p, &p);
2239 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2241 encode_value (container ? 1 : 0, p, &p);
2243 encode_value (container->is_method, p, &p);
2244 g_assert (par->serial == 0);
2245 if (container->is_method)
2246 encode_method_ref (acfg, container->owner.method, p, &p);
2248 encode_klass_ref (acfg, container->owner.klass, p, &p);
2250 encode_value (par->serial, p, &p);
2252 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2253 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2254 encode_type (acfg, &klass->byval_arg, p, &p);
2257 g_assert (klass->rank > 0);
2258 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2259 encode_value (klass->rank, p, &p);
2260 encode_klass_ref (acfg, klass->element_class, p, &p);
2268 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2269 * standard metadata encoding.
2272 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2274 gboolean shared = FALSE;
2277 * The encoding of generic instances is large so emit them only once.
2279 if (klass->generic_class) {
2281 g_assert (klass->type_token);
2283 /* Find a typespec for a class if possible */
2284 token = find_typespec_for_class (acfg, klass);
2287 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2292 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2296 buf2 = g_malloc (1024);
2299 encode_klass_ref_inner (acfg, klass, p, &p);
2300 g_assert (p - buf2 < 1024);
2302 offset = add_to_blob (acfg, buf2, p - buf2);
2305 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2311 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2312 encode_value (offset, p, &p);
2317 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2321 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2323 guint32 token = mono_get_field_token (field);
2326 encode_klass_ref (cfg, field->parent, p, &p);
2327 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2328 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2333 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2338 encode_value (inst->type_argc, p, &p);
2339 for (i = 0; i < inst->type_argc; ++i)
2340 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2345 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2348 MonoGenericInst *inst;
2350 inst = context->class_inst;
2352 g_assert (inst->type_argc);
2353 encode_ginst (acfg, inst, p, &p);
2355 encode_value (0, p, &p);
2357 inst = context->method_inst;
2359 g_assert (inst->type_argc);
2360 encode_ginst (acfg, inst, p, &p);
2362 encode_value (0, p, &p);
2368 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2372 g_assert (t->num_mods == 0);
2373 /* t->attrs can be ignored */
2374 //g_assert (t->attrs == 0);
2377 *p = MONO_TYPE_PINNED;
2381 *p = MONO_TYPE_BYREF;
2389 case MONO_TYPE_VOID:
2390 case MONO_TYPE_BOOLEAN:
2391 case MONO_TYPE_CHAR:
2404 case MONO_TYPE_STRING:
2405 case MONO_TYPE_OBJECT:
2406 case MONO_TYPE_TYPEDBYREF:
2408 case MONO_TYPE_VALUETYPE:
2409 case MONO_TYPE_CLASS:
2410 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2412 case MONO_TYPE_SZARRAY:
2413 encode_klass_ref (acfg, t->data.klass, p, &p);
2416 encode_type (acfg, t->data.type, p, &p);
2418 case MONO_TYPE_GENERICINST: {
2419 MonoClass *gclass = t->data.generic_class->container_class;
2420 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2422 encode_klass_ref (acfg, gclass, p, &p);
2423 encode_ginst (acfg, inst, p, &p);
2426 case MONO_TYPE_ARRAY: {
2427 MonoArrayType *array = t->data.array;
2430 encode_klass_ref (acfg, array->eklass, p, &p);
2431 encode_value (array->rank, p, &p);
2432 encode_value (array->numsizes, p, &p);
2433 for (i = 0; i < array->numsizes; ++i)
2434 encode_value (array->sizes [i], p, &p);
2435 encode_value (array->numlobounds, p, &p);
2436 for (i = 0; i < array->numlobounds; ++i)
2437 encode_value (array->lobounds [i], p, &p);
2441 case MONO_TYPE_MVAR:
2442 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2445 g_assert_not_reached ();
2452 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2458 /* Similar to the metadata encoding */
2459 if (sig->generic_param_count)
2463 if (sig->explicit_this)
2465 flags |= (sig->call_convention & 0x0F);
2469 if (sig->generic_param_count)
2470 encode_value (sig->generic_param_count, p, &p);
2471 encode_value (sig->param_count, p, &p);
2473 encode_type (acfg, sig->ret, p, &p);
2474 for (i = 0; i < sig->param_count; ++i) {
2475 if (sig->sentinelpos == i) {
2476 *p = MONO_TYPE_SENTINEL;
2479 encode_type (acfg, sig->params [i], p, &p);
2485 #define MAX_IMAGE_INDEX 250
2488 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2490 guint32 image_index = get_image_index (acfg, method->klass->image);
2491 guint32 token = method->token;
2492 MonoJumpInfoToken *ji;
2496 * The encoding for most methods is as follows:
2497 * - image index encoded as a leb128
2498 * - token index encoded as a leb128
2499 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2500 * types of method encodings.
2503 /* Mark methods which can't use aot trampolines because they need the further
2504 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2506 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2507 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2508 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2510 if (method->wrapper_type) {
2511 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2513 encode_value (method->wrapper_type, p, &p);
2515 switch (method->wrapper_type) {
2516 case MONO_WRAPPER_REMOTING_INVOKE:
2517 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2518 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2521 m = mono_marshal_method_from_wrapper (method);
2523 encode_method_ref (acfg, m, p, &p);
2526 case MONO_WRAPPER_PROXY_ISINST:
2527 case MONO_WRAPPER_LDFLD:
2528 case MONO_WRAPPER_LDFLDA:
2529 case MONO_WRAPPER_STFLD:
2530 case MONO_WRAPPER_ISINST: {
2531 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2532 encode_klass_ref (acfg, proxy_class, p, &p);
2535 case MONO_WRAPPER_LDFLD_REMOTE:
2536 case MONO_WRAPPER_STFLD_REMOTE:
2538 case MONO_WRAPPER_ALLOC: {
2539 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2541 /* The GC name is saved once in MonoAotFileInfo */
2542 g_assert (info->alloc_type != -1);
2543 encode_value (info->alloc_type, p, &p);
2546 case MONO_WRAPPER_WRITE_BARRIER:
2548 case MONO_WRAPPER_STELEMREF: {
2549 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2552 encode_value (info->subtype, p, &p);
2553 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2554 encode_value (info->d.virtual_stelemref.kind, p, &p);
2557 case MONO_WRAPPER_UNKNOWN: {
2558 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2561 encode_value (info->subtype, p, &p);
2562 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2563 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2564 encode_klass_ref (acfg, method->klass, p, &p);
2565 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2566 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2569 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2570 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2573 encode_value (info->subtype, p, &p);
2574 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2575 strcpy ((char*)p, method->name);
2576 p += strlen (method->name) + 1;
2577 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2578 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2580 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2581 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2585 case MONO_WRAPPER_SYNCHRONIZED: {
2588 m = mono_marshal_method_from_wrapper (method);
2590 g_assert (m != method);
2591 encode_method_ref (acfg, m, p, &p);
2594 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2595 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2598 encode_value (info->subtype, p, &p);
2600 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2601 encode_value (info->d.element_addr.rank, p, &p);
2602 encode_value (info->d.element_addr.elem_size, p, &p);
2603 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2604 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2606 g_assert_not_reached ();
2610 case MONO_WRAPPER_CASTCLASS: {
2611 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2614 encode_value (info->subtype, p, &p);
2617 case MONO_WRAPPER_RUNTIME_INVOKE: {
2618 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2621 encode_value (info->subtype, p, &p);
2622 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2623 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2624 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2625 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2628 case MONO_WRAPPER_DELEGATE_INVOKE:
2629 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2630 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2631 if (method->is_inflated) {
2632 /* These wrappers are identified by their class */
2633 encode_value (1, p, &p);
2634 encode_klass_ref (acfg, method->klass, p, &p);
2636 MonoMethodSignature *sig = mono_method_signature (method);
2638 encode_value (0, p, &p);
2639 encode_signature (acfg, sig, p, &p);
2643 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2644 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2647 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2648 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2652 g_assert_not_reached ();
2654 } else if (mono_method_signature (method)->is_inflated) {
2656 * This is a generic method, find the original token which referenced it and
2658 * Obtain the token from information recorded by the JIT.
2660 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2662 image_index = get_image_index (acfg, ji->image);
2663 g_assert (image_index < MAX_IMAGE_INDEX);
2666 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2667 encode_value (image_index, p, &p);
2668 encode_value (token, p, &p);
2670 MonoMethod *declaring;
2671 MonoGenericContext *context = mono_method_get_context (method);
2673 g_assert (method->is_inflated);
2674 declaring = ((MonoMethodInflated*)method)->declaring;
2677 * This might be a non-generic method of a generic instance, which
2678 * doesn't have a token since the reference is generated by the JIT
2679 * like Nullable:Box/Unbox, or by generic sharing.
2681 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2682 /* Encode the klass */
2683 encode_klass_ref (acfg, method->klass, p, &p);
2684 /* Encode the method */
2685 image_index = get_image_index (acfg, method->klass->image);
2686 g_assert (image_index < MAX_IMAGE_INDEX);
2687 g_assert (declaring->token);
2688 token = declaring->token;
2689 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2690 encode_value (image_index, p, &p);
2691 encode_value (token, p, &p);
2692 encode_generic_context (acfg, context, p, &p);
2694 } else if (token == 0) {
2695 /* This might be a method of a constructed type like int[,].Set */
2696 /* Obtain the token from information recorded by the JIT */
2697 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2699 image_index = get_image_index (acfg, ji->image);
2700 g_assert (image_index < MAX_IMAGE_INDEX);
2703 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2704 encode_value (image_index, p, &p);
2705 encode_value (token, p, &p);
2708 g_assert (method->klass->rank);
2710 /* Encode directly */
2711 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2712 encode_klass_ref (acfg, method->klass, p, &p);
2713 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2714 encode_value (0, p, &p);
2715 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2716 encode_value (1, p, &p);
2717 else if (!strcmp (method->name, "Get"))
2718 encode_value (2, p, &p);
2719 else if (!strcmp (method->name, "Address"))
2720 encode_value (3, p, &p);
2721 else if (!strcmp (method->name, "Set"))
2722 encode_value (4, p, &p);
2724 g_assert_not_reached ();
2727 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2729 if (image_index >= MONO_AOT_METHODREF_MIN) {
2730 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2731 encode_value (image_index, p, &p);
2732 encode_value (mono_metadata_token_index (token), p, &p);
2734 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2741 compare_patches (gconstpointer a, gconstpointer b)
2745 i = (*(MonoJumpInfo**)a)->ip.i;
2746 j = (*(MonoJumpInfo**)b)->ip.i;
2757 static G_GNUC_UNUSED char*
2758 patch_to_string (MonoJumpInfo *patch_info)
2762 str = g_string_new ("");
2764 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2766 switch (patch_info->type) {
2767 case MONO_PATCH_INFO_VTABLE:
2768 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2773 g_string_append_printf (str, ")");
2774 return g_string_free (str, FALSE);
2780 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2783 static inline gboolean
2784 is_plt_patch (MonoJumpInfo *patch_info)
2786 switch (patch_info->type) {
2787 case MONO_PATCH_INFO_METHOD:
2788 case MONO_PATCH_INFO_INTERNAL_METHOD:
2789 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2790 case MONO_PATCH_INFO_ICALL_ADDR:
2791 case MONO_PATCH_INFO_CLASS_INIT:
2792 case MONO_PATCH_INFO_RGCTX_FETCH:
2793 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2794 case MONO_PATCH_INFO_MONITOR_ENTER:
2795 case MONO_PATCH_INFO_MONITOR_EXIT:
2796 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2806 * Return the symbol identifying the plt entry PLT_OFFSET.
2809 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2813 * The Apple linker reorganizes object files, so it doesn't like branches to local
2814 * labels, since those have no relocations.
2816 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2818 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2825 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2827 static MonoPltEntry*
2828 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2832 if (!is_plt_patch (patch_info))
2835 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2837 // FIXME: This breaks the calculation of final_got_size
2838 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2840 * Allocate a separate PLT slot for each such patch, since some plt
2841 * entries will refer to the method itself, and some will refer to the
2848 MonoJumpInfo *new_ji;
2850 g_assert (!acfg->final_got_size);
2852 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2854 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2855 res->plt_offset = acfg->plt_offset;
2857 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2858 if (acfg->aot_opts.write_symbols)
2859 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2861 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2863 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2865 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2867 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2869 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2870 //mono_print_ji (patch_info); printf ("\n");
2871 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2873 acfg->plt_offset ++;
2882 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2883 * JI could be found if it exists, otherwise allocates a new one.
2886 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2890 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2892 return got_offset - 1;
2894 got_offset = acfg->got_offset;
2895 acfg->got_offset ++;
2897 if (acfg->final_got_size)
2898 g_assert (got_offset < acfg->final_got_size);
2900 acfg->stats.got_slots ++;
2901 acfg->stats.got_slot_types [ji->type] ++;
2903 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2904 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2905 g_ptr_array_add (acfg->got_patches, ji);
2910 /* Add a method to the list of methods which need to be emitted */
2912 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2915 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2916 g_ptr_array_add (acfg->methods, method);
2917 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2918 acfg->nmethods = acfg->methods->len + 1;
2921 if (method->wrapper_type || extra)
2922 g_ptr_array_add (acfg->extra_methods, method);
2926 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2928 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2936 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2940 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2944 index = acfg->method_index;
2945 add_method_with_index (acfg, method, index, extra);
2947 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2949 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2951 acfg->method_index ++;
2957 add_method (MonoAotCompile *acfg, MonoMethod *method)
2959 return add_method_full (acfg, method, FALSE, 0);
2963 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2965 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
2966 method = mini_get_shared_method (method);
2968 if (acfg->aot_opts.log_generics)
2969 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2971 add_method_full (acfg, method, TRUE, depth);
2975 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2977 add_extra_method_with_depth (acfg, method, 0);
2981 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2983 MonoAotCompile *acfg = user_data;
2984 MonoJitICallInfo *callinfo = value;
2985 MonoMethod *wrapper;
2991 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2992 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2995 add_method (acfg, wrapper);
2999 get_runtime_invoke_sig (MonoMethodSignature *sig)
3001 MonoMethodBuilder *mb;
3004 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3005 m = mono_mb_create_method (mb, sig, 16);
3006 return mono_marshal_get_runtime_invoke (m, FALSE);
3010 can_marshal_struct (MonoClass *klass)
3012 MonoClassField *field;
3013 gboolean can_marshal = TRUE;
3014 gpointer iter = NULL;
3015 MonoMarshalType *info;
3018 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3021 info = mono_marshal_load_type_info (klass);
3023 /* Only allow a few field types to avoid asserts in the marshalling code */
3024 while ((field = mono_class_get_fields (klass, &iter))) {
3025 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3028 switch (field->type->type) {
3033 case MONO_TYPE_BOOLEAN:
3036 case MONO_TYPE_CHAR:
3044 case MONO_TYPE_STRING:
3046 case MONO_TYPE_VALUETYPE:
3047 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3048 can_marshal = FALSE;
3050 case MONO_TYPE_SZARRAY: {
3051 gboolean has_mspec = FALSE;
3054 for (i = 0; i < info->num_fields; ++i) {
3055 if (info->fields [i].field == field && info->fields [i].mspec)
3060 can_marshal = FALSE;
3064 can_marshal = FALSE;
3070 /* Its hard to compute whenever these can be marshalled or not */
3071 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3078 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3080 /* Create a vtype instantiation */
3081 MonoGenericContext shared_context;
3083 MonoGenericInst *inst;
3084 MonoGenericContainer *container;
3085 MonoClass **constraints;
3088 memset (ctx, 0, sizeof (MonoGenericContext));
3090 if (method->klass->generic_container) {
3091 shared_context = method->klass->generic_container->context;
3092 inst = shared_context.class_inst;
3094 args = g_new0 (MonoType*, inst->type_argc);
3095 for (i = 0; i < inst->type_argc; ++i) {
3096 args [i] = &mono_defaults.int_class->byval_arg;
3098 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3100 if (method->is_generic) {
3101 container = mono_method_get_generic_container (method);
3102 shared_context = container->context;
3103 inst = shared_context.method_inst;
3105 args = g_new0 (MonoType*, inst->type_argc);
3106 for (i = 0; i < container->type_argc; ++i) {
3107 MonoGenericParamInfo *info = &container->type_params [i].info;
3108 gboolean ref_only = FALSE;
3110 if (info && info->constraints) {
3111 constraints = info->constraints;
3113 while (*constraints) {
3114 MonoClass *cklass = *constraints;
3115 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3116 /* Inflaring the method with our vtype would not be valid */
3123 args [i] = &mono_defaults.object_class->byval_arg;
3125 args [i] = &mono_defaults.int_class->byval_arg;
3127 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3132 add_wrappers (MonoAotCompile *acfg)
3134 MonoMethod *method, *m;
3136 MonoMethodSignature *sig, *csig;
3140 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3141 * so there is only one wrapper of a given type, or inlining their contents into their
3146 * FIXME: This depends on the fact that different wrappers have different
3150 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3152 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3153 gboolean skip = FALSE;
3155 method = mono_get_method (acfg->image, token, NULL);
3157 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3158 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3159 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3162 if (method->is_generic || method->klass->generic_container)
3165 /* Skip methods which can not be handled by get_runtime_invoke () */
3166 sig = mono_method_signature (method);
3169 if ((sig->ret->type == MONO_TYPE_PTR) ||
3170 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3173 for (j = 0; j < sig->param_count; j++) {
3174 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3178 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3179 if (!mono_class_is_contextbound (method->klass)) {
3180 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3181 gboolean has_nullable = FALSE;
3183 for (j = 0; j < sig->param_count; j++) {
3184 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3185 has_nullable = TRUE;
3188 if (info && !has_nullable) {
3189 /* Supported by the dynamic runtime-invoke wrapper */
3197 //printf ("%s\n", mono_method_full_name (method, TRUE));
3198 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3202 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3203 MonoMethodDesc *desc;
3204 MonoMethod *orig_method;
3207 /* Runtime invoke wrappers */
3209 /* void runtime-invoke () [.cctor] */
3210 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3211 csig->ret = &mono_defaults.void_class->byval_arg;
3212 add_method (acfg, get_runtime_invoke_sig (csig));
3214 /* void runtime-invoke () [Finalize] */
3215 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3217 csig->ret = &mono_defaults.void_class->byval_arg;
3218 add_method (acfg, get_runtime_invoke_sig (csig));
3220 /* void runtime-invoke (string) [exception ctor] */
3221 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3223 csig->ret = &mono_defaults.void_class->byval_arg;
3224 csig->params [0] = &mono_defaults.string_class->byval_arg;
3225 add_method (acfg, get_runtime_invoke_sig (csig));
3227 /* void runtime-invoke (string, string) [exception ctor] */
3228 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3230 csig->ret = &mono_defaults.void_class->byval_arg;
3231 csig->params [0] = &mono_defaults.string_class->byval_arg;
3232 csig->params [1] = &mono_defaults.string_class->byval_arg;
3233 add_method (acfg, get_runtime_invoke_sig (csig));
3235 /* string runtime-invoke () [Exception.ToString ()] */
3236 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3238 csig->ret = &mono_defaults.string_class->byval_arg;
3239 add_method (acfg, get_runtime_invoke_sig (csig));
3241 /* void runtime-invoke (string, Exception) [exception ctor] */
3242 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3244 csig->ret = &mono_defaults.void_class->byval_arg;
3245 csig->params [0] = &mono_defaults.string_class->byval_arg;
3246 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3247 add_method (acfg, get_runtime_invoke_sig (csig));
3249 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3250 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3252 csig->ret = &(mono_class_from_name (
3253 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3254 csig->params [0] = &mono_defaults.string_class->byval_arg;
3255 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3256 add_method (acfg, get_runtime_invoke_sig (csig));
3258 /* runtime-invoke used by finalizers */
3259 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3261 /* This is used by mono_runtime_capture_context () */
3262 method = mono_get_context_capture_method ();
3264 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3266 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3267 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3270 /* JIT icall wrappers */
3271 /* FIXME: locking */
3272 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3275 add_method (acfg, mono_marshal_get_stelemref ());
3277 if (MONO_ARCH_HAVE_TLS_GET) {
3278 /* Managed Allocators */
3279 nallocators = mono_gc_get_managed_allocator_types ();
3280 for (i = 0; i < nallocators; ++i) {
3281 m = mono_gc_get_managed_allocator_by_type (i);
3283 add_method (acfg, m);
3286 /* Monitor Enter/Exit */
3287 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3288 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3289 /* This is a v4 method */
3291 method = mono_monitor_get_fast_path (orig_method);
3293 add_method (acfg, method);
3295 mono_method_desc_free (desc);
3297 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3298 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3299 g_assert (orig_method);
3300 mono_method_desc_free (desc);
3301 method = mono_monitor_get_fast_path (orig_method);
3303 add_method (acfg, method);
3306 /* Stelemref wrappers */
3308 MonoMethod **wrappers;
3311 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3312 for (i = 0; i < nwrappers; ++i)
3313 add_method (acfg, wrappers [i]);
3317 /* castclass_with_check wrapper */
3318 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3319 /* isinst_with_check wrapper */
3320 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3322 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3324 MonoMethodDesc *desc;
3327 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3328 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3329 mono_method_desc_free (desc);
3331 m = mono_monitor_get_fast_path (m);
3333 add_method (acfg, m);
3340 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3341 * we use the original method instead at runtime.
3342 * Since full-aot doesn't support remoting, this is not a problem.
3345 /* remoting-invoke wrappers */
3346 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3347 MonoMethodSignature *sig;
3349 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3350 method = mono_get_method (acfg->image, token, NULL);
3352 sig = mono_method_signature (method);
3354 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3355 m = mono_marshal_get_remoting_invoke_with_check (method);
3357 add_method (acfg, m);
3362 /* delegate-invoke wrappers */
3363 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3365 MonoCustomAttrInfo *cattr;
3367 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3368 klass = mono_class_get (acfg->image, token);
3371 mono_loader_clear_error ();
3375 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3378 if (!klass->generic_container) {
3379 method = mono_get_delegate_invoke (klass);
3381 m = mono_marshal_get_delegate_invoke (method, NULL);
3383 add_method (acfg, m);
3385 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3387 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3389 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3391 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3393 cattr = mono_custom_attrs_from_class (klass);
3398 for (j = 0; j < cattr->num_attrs; ++j)
3399 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3401 if (j < cattr->num_attrs)
3402 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3404 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3405 MonoGenericContext ctx;
3406 MonoMethod *inst, *gshared;
3409 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3412 method = mono_get_delegate_invoke (klass);
3413 create_gsharedvt_inst (acfg, method, &ctx);
3415 inst = mono_class_inflate_generic_method (method, &ctx);
3417 m = mono_marshal_get_delegate_invoke (inst, NULL);
3418 g_assert (m->is_inflated);
3420 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3421 add_extra_method (acfg, gshared);
3424 method = mono_get_delegate_begin_invoke (klass);
3425 create_gsharedvt_inst (acfg, method, &ctx);
3427 inst = mono_class_inflate_generic_method (method, &ctx);
3429 m = mono_marshal_get_delegate_begin_invoke (inst);
3430 g_assert (m->is_inflated);
3432 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3433 add_extra_method (acfg, gshared);
3436 method = mono_get_delegate_end_invoke (klass);
3437 create_gsharedvt_inst (acfg, method, &ctx);
3439 inst = mono_class_inflate_generic_method (method, &ctx);
3441 m = mono_marshal_get_delegate_end_invoke (inst);
3442 g_assert (m->is_inflated);
3444 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3445 add_extra_method (acfg, gshared);
3450 /* Synchronized wrappers */
3451 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3452 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3453 method = mono_get_method (acfg->image, token, NULL);
3455 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
3456 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3459 /* pinvoke wrappers */
3460 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3462 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3464 method = mono_get_method (acfg->image, token, NULL);
3466 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3467 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3468 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3472 /* native-to-managed wrappers */
3473 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3475 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3476 MonoCustomAttrInfo *cattr;
3479 method = mono_get_method (acfg->image, token, NULL);
3482 * Only generate native-to-managed wrappers for methods which have an
3483 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3484 * name to avoid defining a new assembly to contain it.
3486 cattr = mono_custom_attrs_from_method (method);
3489 for (j = 0; j < cattr->num_attrs; ++j)
3490 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3492 if (j < cattr->num_attrs) {
3493 MonoCustomAttrEntry *e = &cattr->attrs [j];
3494 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3495 const char *p = (const char*)e->data;
3497 int slen, num_named, named_type, data_type;
3501 char *export_name = NULL;
3502 MonoMethod *wrapper;
3504 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3505 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3506 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3507 mono_method_full_name (method, TRUE));
3511 g_assert (sig->param_count == 1);
3512 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3515 * Decode the cattr manually since we can't create objects
3516 * during aot compilation.
3522 /* From load_cattr_value () in reflection.c */
3523 slen = mono_metadata_decode_value (p, &p);
3524 n = g_memdup (p, slen + 1);
3526 t = mono_reflection_type_from_name (n, acfg->image);
3530 klass = mono_class_from_mono_type (t);
3531 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3535 num_named = read16 (p);
3538 g_assert (num_named < 2);
3539 if (num_named == 1) {
3542 MonoType *prop_type;
3544 /* parse ExportSymbol attribute */
3546 named_type = *named;
3551 name_len = mono_metadata_decode_blob_size (named, &named);
3552 name = g_malloc (name_len + 1);
3553 memcpy (name, named, name_len);
3554 name [name_len] = 0;
3557 g_assert (named_type == 0x54);
3558 g_assert (!strcmp (name, "ExportSymbol"));
3560 prop_type = &mono_defaults.string_class->byval_arg;
3562 /* load_cattr_value (), string case */
3563 g_assert (*named != (char)0xff);
3564 slen = mono_metadata_decode_value (named, &named);
3565 export_name = g_malloc (slen + 1);
3566 memcpy (export_name, named, slen);
3567 export_name [slen] = 0;
3571 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3572 add_method (acfg, wrapper);
3574 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3578 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3579 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3580 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3584 /* StructureToPtr/PtrToStructure wrappers */
3585 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3588 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3589 klass = mono_class_get (acfg->image, token);
3592 mono_loader_clear_error ();
3596 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3597 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3598 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3599 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3605 has_type_vars (MonoClass *klass)
3607 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3610 return has_type_vars (klass->element_class);
3611 if (klass->generic_class) {
3612 MonoGenericContext *context = &klass->generic_class->context;
3613 if (context->class_inst) {
3616 for (i = 0; i < context->class_inst->type_argc; ++i)
3617 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3625 is_vt_inst (MonoGenericInst *inst)
3629 for (i = 0; i < inst->type_argc; ++i) {
3630 MonoType *t = inst->type_argv [i];
3631 if (t->type == MONO_TYPE_VALUETYPE)
3638 method_has_type_vars (MonoMethod *method)
3640 if (has_type_vars (method->klass))
3643 if (method->is_inflated) {
3644 MonoGenericContext *context = mono_method_get_context (method);
3645 if (context->method_inst) {
3648 for (i = 0; i < context->method_inst->type_argc; ++i)
3649 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3656 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3659 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3661 /* This might lead to a huge code blowup so only do it if neccesary */
3662 if (!acfg->aot_opts.full_aot && !force)
3665 add_generic_class_with_depth (acfg, klass, 0, ref);
3669 check_type_depth (MonoType *t, int depth)
3677 case MONO_TYPE_GENERICINST: {
3678 MonoGenericClass *gklass = t->data.generic_class;
3679 MonoGenericInst *ginst = gklass->context.class_inst;
3682 for (i = 0; i < ginst->type_argc; ++i) {
3683 if (check_type_depth (ginst->type_argv [i], depth + 1))
3697 * add_generic_class:
3699 * Add all methods of a generic class.
3702 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3705 MonoClassField *field;
3707 gboolean use_gsharedvt = FALSE;
3709 if (!acfg->ginst_hash)
3710 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3712 mono_class_init (klass);
3714 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3717 if (has_type_vars (klass))
3720 if (!klass->generic_class && !klass->rank)
3723 if (klass->exception_type)
3726 if (!acfg->ginst_hash)
3727 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3729 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3732 if (check_type_depth (&klass->byval_arg, 0))
3735 if (acfg->aot_opts.log_generics)
3736 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3738 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3741 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3742 * Enable this only for some classes since gsharedvt might not support all methods.
3744 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && klass->generic_class && klass->generic_class->context.class_inst && is_vt_inst (klass->generic_class->context.class_inst) && (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1")))
3745 use_gsharedvt = TRUE;
3748 while ((method = mono_class_get_methods (klass, &iter))) {
3749 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt))
3753 if (method->is_generic)
3758 * FIXME: Instances which are referenced by these methods are not added,
3759 * for example Array.Resize<int> for List<int>.Add ().
3761 add_extra_method_with_depth (acfg, method, depth + 1);
3765 while ((field = mono_class_get_fields (klass, &iter))) {
3766 if (field->type->type == MONO_TYPE_GENERICINST)
3767 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3770 if (klass->delegate) {
3771 method = mono_get_delegate_invoke (klass);
3773 method = mono_marshal_get_delegate_invoke (method, NULL);
3775 if (acfg->aot_opts.log_generics)
3776 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3778 add_method (acfg, method);
3781 /* Add superclasses */
3783 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3786 * For ICollection<T>, add instances of the helper methods
3787 * in Array, since a T[] could be cast to ICollection<T>.
3789 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3790 (!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"))) {
3791 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3792 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3796 if (!strcmp (klass->name, "IEnumerator`1"))
3797 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3799 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3801 /* Add the T[]/InternalEnumerator class */
3802 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3806 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3807 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3811 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3812 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3816 while ((method = mono_class_get_methods (array_class, &iter))) {
3817 if (strstr (method->name, name_prefix)) {
3818 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3820 add_extra_method_with_depth (acfg, m, depth);
3824 g_free (name_prefix);
3827 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3828 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3829 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3830 MonoClass *icomparable, *gcomparer;
3831 MonoGenericContext ctx;
3832 MonoType *args [16];
3834 memset (&ctx, 0, sizeof (ctx));
3836 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3837 g_assert (icomparable);
3838 args [0] = &tclass->byval_arg;
3839 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3841 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3842 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3843 g_assert (gcomparer);
3844 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3848 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3849 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3850 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3851 MonoClass *iface, *gcomparer;
3852 MonoGenericContext ctx;
3853 MonoType *args [16];
3855 memset (&ctx, 0, sizeof (ctx));
3857 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3859 args [0] = &tclass->byval_arg;
3860 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3862 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3863 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3864 g_assert (gcomparer);
3865 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3871 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3874 MonoGenericContext ctx;
3875 MonoType *args [16];
3877 if (acfg->aot_opts.no_instances)
3880 memset (&ctx, 0, sizeof (ctx));
3882 for (i = 0; i < ninsts; ++i) {
3883 args [0] = insts [i];
3884 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3885 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3890 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3892 MonoMethodHeader *header;
3893 MonoMethodSignature *sig;
3896 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3898 sig = mono_method_signature (method);
3901 for (j = 0; j < sig->param_count; ++j)
3902 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3903 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3906 header = mono_method_get_header (method);
3909 for (j = 0; j < header->num_locals; ++j)
3910 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3911 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3916 * add_generic_instances:
3918 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3921 add_generic_instances (MonoAotCompile *acfg)
3926 MonoGenericContext *context;
3928 if (acfg->aot_opts.no_instances)
3931 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3932 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3933 method = mono_get_method (acfg->image, token, NULL);
3938 if (method->klass->image != acfg->image)
3941 context = mono_method_get_context (method);
3943 if (context && ((context->class_inst && context->class_inst->is_open)))
3947 * For open methods, create an instantiation which can be passed to the JIT.
3948 * FIXME: Handle class_inst as well.
3950 if (context && context->method_inst && context->method_inst->is_open) {
3951 MonoGenericContext shared_context;
3952 MonoGenericInst *inst;
3953 MonoType **type_argv;
3955 MonoMethod *declaring_method;
3956 gboolean supported = TRUE;
3958 /* Check that the context doesn't contain open constructed types */
3959 if (context->class_inst) {
3960 inst = context->class_inst;
3961 for (i = 0; i < inst->type_argc; ++i) {
3962 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)
3964 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3968 if (context->method_inst) {
3969 inst = context->method_inst;
3970 for (i = 0; i < inst->type_argc; ++i) {
3971 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)
3973 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3981 memset (&shared_context, 0, sizeof (MonoGenericContext));
3983 inst = context->class_inst;
3985 type_argv = g_new0 (MonoType*, inst->type_argc);
3986 for (i = 0; i < inst->type_argc; ++i) {
3987 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)
3988 type_argv [i] = &mono_defaults.object_class->byval_arg;
3990 type_argv [i] = inst->type_argv [i];
3993 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3997 inst = context->method_inst;
3999 type_argv = g_new0 (MonoType*, inst->type_argc);
4000 for (i = 0; i < inst->type_argc; ++i) {
4001 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)
4002 type_argv [i] = &mono_defaults.object_class->byval_arg;
4004 type_argv [i] = inst->type_argv [i];
4007 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4011 if (method->is_generic || method->klass->generic_container)
4012 declaring_method = method;
4014 declaring_method = mono_method_get_declaring_generic_method (method);
4016 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4020 * If the method is fully sharable, it was already added in place of its
4021 * generic definition.
4023 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4027 * FIXME: Partially shared methods are not shared here, so we end up with
4028 * many identical methods.
4030 add_extra_method (acfg, method);
4033 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4036 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4038 klass = mono_class_get (acfg->image, token);
4039 if (!klass || klass->rank) {
4040 mono_loader_clear_error ();
4044 add_generic_class (acfg, klass, FALSE, "typespec");
4047 /* Add types of args/locals */
4048 for (i = 0; i < acfg->methods->len; ++i) {
4049 method = g_ptr_array_index (acfg->methods, i);
4050 add_types_from_method_header (acfg, method);
4053 if (acfg->image == mono_defaults.corlib) {
4055 MonoType *insts [256];
4058 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4059 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4060 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4061 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4062 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4063 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4064 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4065 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4066 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4067 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4068 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4069 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4071 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4072 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4074 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4075 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4077 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4079 /* Add instances of the array generic interfaces for primitive types */
4080 /* This will add instances of the InternalArray_ helper methods in Array too */
4081 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4083 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4084 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4086 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4087 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4089 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4092 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4093 * used for all instances of GetGenericValueImpl by the AOT runtime.
4096 MonoGenericContext ctx;
4097 MonoType *args [16];
4098 MonoMethod *get_method;
4099 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4101 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4104 memset (&ctx, 0, sizeof (ctx));
4105 args [0] = &mono_defaults.object_class->byval_arg;
4106 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4107 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4111 /* Same for CompareExchange<T>/Exchange<T> */
4113 MonoGenericContext ctx;
4114 MonoType *args [16];
4116 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4117 gpointer iter = NULL;
4119 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4120 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4121 memset (&ctx, 0, sizeof (ctx));
4122 args [0] = &mono_defaults.object_class->byval_arg;
4123 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4124 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4129 /* Same for Volatile.Read/Write<T> */
4131 MonoGenericContext ctx;
4132 MonoType *args [16];
4134 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4135 gpointer iter = NULL;
4137 if (volatile_klass) {
4138 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4139 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4140 memset (&ctx, 0, sizeof (ctx));
4141 args [0] = &mono_defaults.object_class->byval_arg;
4142 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4143 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4152 * is_direct_callable:
4154 * Return whenever the method identified by JI is directly callable without
4155 * going through the PLT.
4158 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4160 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4161 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4163 gboolean direct_callable = TRUE;
4165 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4166 direct_callable = FALSE;
4167 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4168 // FIXME: Maybe call the wrapper directly ?
4169 direct_callable = FALSE;
4171 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4172 /* Disable this so all calls go through load_method (), see the
4173 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4174 * mono_debugger_agent_init ().
4176 direct_callable = FALSE;
4179 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4180 /* sgen does some initialization when the allocator method is created */
4181 direct_callable = FALSE;
4183 if (direct_callable)
4186 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4187 if (acfg->aot_opts.direct_pinvoke)
4189 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4190 if (acfg->aot_opts.direct_icalls)
4199 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4201 MonoImage *image = method->klass->image;
4202 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4203 MonoTableInfo *tables = image->tables;
4204 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4205 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4206 guint32 im_cols [MONO_IMPLMAP_SIZE];
4209 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4213 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4216 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4218 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4221 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4223 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4229 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4231 if (a->native_offset == b->native_offset)
4232 return a->il_offset - b->il_offset;
4234 return a->native_offset - b->native_offset;
4238 * compute_line_numbers:
4240 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4243 static MonoDebugSourceLocation**
4244 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4246 MonoDebugMethodInfo *minfo;
4247 MonoDebugLineNumberEntry *ln_array;
4248 MonoDebugSourceLocation *loc;
4249 int i, prev_line, prev_il_offset;
4250 int *native_to_il_offset = NULL;
4251 MonoDebugSourceLocation **res;
4254 minfo = mono_debug_lookup_method (method);
4257 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4258 if (debug_info->code_size != code_size)
4261 g_assert (code_size);
4263 /* Compute the native->IL offset mapping */
4265 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4266 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4268 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4270 native_to_il_offset = g_new0 (int, code_size + 1);
4272 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4274 MonoDebugLineNumberEntry *lne = &ln_array [i];
4277 for (j = 0; j < lne->native_offset; ++j)
4278 native_to_il_offset [j] = -1;
4281 if (i < debug_info->num_line_numbers - 1) {
4282 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4284 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4285 native_to_il_offset [j] = lne->il_offset;
4287 for (j = lne->native_offset; j < code_size; ++j)
4288 native_to_il_offset [j] = lne->il_offset;
4293 /* Compute the native->line number mapping */
4294 res = g_new0 (MonoDebugSourceLocation*, code_size);
4295 prev_il_offset = -1;
4298 for (i = 0; i < code_size; ++i) {
4299 int il_offset = native_to_il_offset [i];
4301 if (il_offset == -1 || il_offset == prev_il_offset)
4303 prev_il_offset = il_offset;
4304 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4305 if (!(loc && loc->source_file))
4307 if (loc->row == prev_line) {
4308 mono_debug_symfile_free_location (loc);
4311 prev_line = loc->row;
4312 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4314 /* This will cover the prolog too */
4324 get_file_index (MonoAotCompile *acfg, const char *source_file)
4328 // FIXME: Free these
4329 if (!acfg->dwarf_ln_filenames)
4330 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4331 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4333 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4334 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4335 img_writer_emit_unset_mode (acfg->w);
4336 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, source_file);
4342 * emit_and_reloc_code:
4344 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4345 * is true, calls are made through the GOT too. This is used for emitting trampolines
4346 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4347 * since trampolines are needed to make PTL work.
4350 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4352 int i, pindex, start_index, method_index;
4354 MonoJumpInfo *patch_info;
4355 MonoMethodHeader *header;
4356 MonoDebugSourceLocation **locs = NULL;
4357 gboolean skip, direct_call, external_call;
4359 const char *direct_call_target;
4360 const char *direct_pinvoke;
4363 header = mono_method_get_header (method);
4365 method_index = get_method_index (acfg, method);
4368 if (acfg->gas_line_numbers && method && debug_info) {
4369 locs = compute_line_numbers (method, code_len, debug_info);
4371 int findex = get_file_index (acfg, "<unknown>");
4372 img_writer_emit_unset_mode (acfg->w);
4373 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4377 /* Collect and sort relocations */
4378 patches = g_ptr_array_new ();
4379 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4380 g_ptr_array_add (patches, patch_info);
4381 g_ptr_array_sort (patches, compare_patches);
4384 for (i = 0; i < code_len; i++) {
4386 for (pindex = start_index; pindex < patches->len; ++pindex) {
4387 patch_info = g_ptr_array_index (patches, pindex);
4388 if (patch_info->ip.i >= i)
4392 if (locs && locs [i]) {
4393 MonoDebugSourceLocation *loc = locs [i];
4396 findex = get_file_index (acfg, loc->source_file);
4397 img_writer_emit_unset_mode (acfg->w);
4398 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4399 mono_debug_symfile_free_location (loc);
4402 #ifdef MONO_ARCH_AOT_SUPPORTED
4404 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4405 start_index = pindex;
4407 switch (patch_info->type) {
4408 case MONO_PATCH_INFO_NONE:
4410 case MONO_PATCH_INFO_GOT_OFFSET: {
4413 arch_emit_got_offset (acfg, code + i, &code_size);
4416 patch_info->type = MONO_PATCH_INFO_NONE;
4421 * If this patch is a call, try emitting a direct call instead of
4422 * through a PLT entry. This is possible if the called method is in
4423 * the same assembly and requires no initialization.
4425 direct_call = FALSE;
4426 external_call = FALSE;
4427 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4428 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4429 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4430 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4432 direct_call_target = callee_cfg->asm_symbol;
4433 patch_info->type = MONO_PATCH_INFO_NONE;
4434 acfg->stats.direct_calls ++;
4437 acfg->stats.all_calls ++;
4438 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4439 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4440 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4441 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4443 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4444 if (direct_pinvoke) {
4446 g_assert (strlen (direct_pinvoke) < 1000);
4447 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4450 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4451 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4452 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4453 /* Call to a C function implementing a jit icall */
4455 external_call = TRUE;
4456 g_assert (strlen (sym) < 1000);
4457 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4459 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4460 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4461 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4462 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4463 /* Call to a jit icall without a wrapper */
4465 external_call = TRUE;
4466 g_assert (strlen (sym) < 1000);
4467 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4472 patch_info->type = MONO_PATCH_INFO_NONE;
4473 acfg->stats.direct_calls ++;
4476 if (!got_only && !direct_call) {
4477 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4479 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4481 direct_call_target = plt_entry->symbol;
4483 /* Nullify the patch */
4484 patch_info->type = MONO_PATCH_INFO_NONE;
4485 plt_entry->jit_used = TRUE;
4492 arch_emit_direct_call (acfg, direct_call_target, external_call, &call_size);
4497 got_slot = get_got_offset (acfg, patch_info);
4499 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4506 #endif /* MONO_ARCH_AOT_SUPPORTED */
4509 /* Find next patch */
4511 for (pindex = start_index; pindex < patches->len; ++pindex) {
4512 patch_info = g_ptr_array_index (patches, pindex);
4513 if (patch_info->ip.i >= i)
4517 /* Try to emit multiple bytes at once */
4518 if (pindex < patches->len && patch_info->ip.i > i) {
4521 for (limit = i + 1; limit < patch_info->ip.i; ++limit) {
4522 if (locs && locs [limit])
4526 emit_bytes (acfg, code + i, limit - i);
4529 emit_bytes (acfg, code + i, 1);
4540 * Modify SYMBOL so it only includes characters permissible in symbols.
4543 sanitize_symbol (char *symbol)
4545 int i, len = strlen (symbol);
4547 for (i = 0; i < len; ++i)
4548 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
4553 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4555 char *name1, *name2, *cached;
4556 int i, j, len, count;
4559 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4560 if (!prefix || !*prefix)
4564 name1 = mono_method_full_name (method, TRUE);
4565 len = strlen (name1);
4566 name2 = malloc (strlen (prefix) + len + 16);
4567 memcpy (name2, prefix, strlen (prefix));
4568 j = strlen (prefix);
4569 for (i = 0; i < len; ++i) {
4570 if (isalnum (name1 [i])) {
4571 name2 [j ++] = name1 [i];
4572 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4574 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4577 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4586 while (g_hash_table_lookup (cache, name2)) {
4587 sprintf (name2 + j, "_%d", count);
4591 cached = g_strdup (name2);
4592 g_hash_table_insert (cache, cached, cached);
4598 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4603 char *debug_sym = NULL;
4604 char *symbol = NULL;
4605 int func_alignment = AOT_FUNC_ALIGNMENT;
4606 MonoMethodHeader *header;
4609 method = cfg->orig_method;
4610 code = cfg->native_code;
4611 header = cfg->header;
4613 method_index = get_method_index (acfg, method);
4614 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4617 /* Make the labels local */
4618 emit_section_change (acfg, ".text", 0);
4619 emit_alignment (acfg, func_alignment);
4621 if (acfg->global_symbols && acfg->need_no_dead_strip)
4622 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4624 emit_label (acfg, cfg->asm_symbol);
4626 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4628 * Write a C style symbol for every method, this has two uses:
4629 * - it works on platforms where the dwarf debugging info is not
4631 * - it allows the setting of breakpoints of aot-ed methods.
4633 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4635 if (acfg->need_no_dead_strip)
4636 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4637 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4638 emit_label (acfg, debug_sym);
4641 export_name = g_hash_table_lookup (acfg->export_names, method);
4643 /* Emit a global symbol for the method */
4644 emit_global_inner (acfg, export_name, TRUE);
4645 emit_label (acfg, export_name);
4648 if (cfg->verbose_level > 0)
4649 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4651 acfg->stats.code_size += cfg->code_len;
4653 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4655 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
4659 if (acfg->aot_opts.write_symbols) {
4660 emit_symbol_size (acfg, debug_sym, ".");
4664 emit_label (acfg, symbol);
4671 * Encode PATCH_INFO into its disk representation.
4674 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4678 switch (patch_info->type) {
4679 case MONO_PATCH_INFO_NONE:
4681 case MONO_PATCH_INFO_IMAGE:
4682 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4684 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4685 case MONO_PATCH_INFO_JIT_TLS_ID:
4686 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4687 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4689 case MONO_PATCH_INFO_METHOD_REL:
4690 encode_value ((gint)patch_info->data.offset, p, &p);
4692 case MONO_PATCH_INFO_SWITCH: {
4693 gpointer *table = (gpointer *)patch_info->data.table->table;
4696 encode_value (patch_info->data.table->table_size, p, &p);
4697 for (k = 0; k < patch_info->data.table->table_size; k++)
4698 encode_value ((int)(gssize)table [k], p, &p);
4701 case MONO_PATCH_INFO_METHODCONST:
4702 case MONO_PATCH_INFO_METHOD:
4703 case MONO_PATCH_INFO_METHOD_JUMP:
4704 case MONO_PATCH_INFO_ICALL_ADDR:
4705 case MONO_PATCH_INFO_METHOD_RGCTX:
4706 encode_method_ref (acfg, patch_info->data.method, p, &p);
4708 case MONO_PATCH_INFO_INTERNAL_METHOD:
4709 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4710 guint32 len = strlen (patch_info->data.name);
4712 encode_value (len, p, &p);
4714 memcpy (p, patch_info->data.name, len);
4719 case MONO_PATCH_INFO_LDSTR: {
4720 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4721 guint32 token = patch_info->data.token->token;
4722 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4723 encode_value (image_index, p, &p);
4724 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4727 case MONO_PATCH_INFO_RVA:
4728 case MONO_PATCH_INFO_DECLSEC:
4729 case MONO_PATCH_INFO_LDTOKEN:
4730 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4731 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4732 encode_value (patch_info->data.token->token, p, &p);
4733 encode_value (patch_info->data.token->has_context, p, &p);
4734 if (patch_info->data.token->has_context)
4735 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4737 case MONO_PATCH_INFO_EXC_NAME: {
4738 MonoClass *ex_class;
4741 mono_class_from_name (mono_defaults.exception_class->image,
4742 "System", patch_info->data.target);
4743 g_assert (ex_class);
4744 encode_klass_ref (acfg, ex_class, p, &p);
4747 case MONO_PATCH_INFO_R4:
4748 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4750 case MONO_PATCH_INFO_R8:
4751 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4752 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4754 case MONO_PATCH_INFO_VTABLE:
4755 case MONO_PATCH_INFO_CLASS:
4756 case MONO_PATCH_INFO_IID:
4757 case MONO_PATCH_INFO_ADJUSTED_IID:
4758 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4760 case MONO_PATCH_INFO_CLASS_INIT:
4761 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4762 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4764 case MONO_PATCH_INFO_FIELD:
4765 case MONO_PATCH_INFO_SFLDA:
4766 encode_field_info (acfg, patch_info->data.field, p, &p);
4768 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4770 case MONO_PATCH_INFO_RGCTX_FETCH: {
4771 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4776 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4777 * reference the same method, so encode the method only once.
4779 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4781 buf2 = g_malloc (1024);
4784 encode_method_ref (acfg, entry->method, p2, &p2);
4785 g_assert (p2 - buf2 < 1024);
4787 offset = add_to_blob (acfg, buf2, p2 - buf2);
4790 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4795 encode_value (offset, p, &p);
4796 g_assert ((int)entry->info_type < 256);
4797 g_assert (entry->data->type < 256);
4798 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4799 encode_patch (acfg, entry->data, p, &p);
4802 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4803 case MONO_PATCH_INFO_MONITOR_ENTER:
4804 case MONO_PATCH_INFO_MONITOR_EXIT:
4805 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4807 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4808 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4809 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4811 case MONO_PATCH_INFO_SIGNATURE:
4812 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4814 case MONO_PATCH_INFO_TLS_OFFSET:
4815 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
4817 case MONO_PATCH_INFO_GSHAREDVT_CALL:
4818 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
4819 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
4821 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
4822 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
4825 encode_method_ref (acfg, info->method, p, &p);
4826 encode_value (info->entries->len, p, &p);
4827 for (i = 0; i < info->entries->len; ++i) {
4828 MonoRuntimeGenericContextInfoTemplate *template = g_ptr_array_index (info->entries, i);
4830 encode_value (template->info_type, p, &p);
4831 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
4832 case MONO_PATCH_INFO_CLASS:
4833 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
4835 case MONO_PATCH_INFO_FIELD:
4836 encode_field_info (acfg, template->data, p, &p);
4839 g_assert_not_reached ();
4846 g_warning ("unable to handle jump info %d", patch_info->type);
4847 g_assert_not_reached ();
4854 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4857 guint32 pindex, offset;
4858 MonoJumpInfo *patch_info;
4860 encode_value (n_patches, p, &p);
4862 for (pindex = 0; pindex < patches->len; ++pindex) {
4863 patch_info = g_ptr_array_index (patches, pindex);
4865 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4869 offset = get_got_offset (acfg, patch_info);
4870 encode_value (offset, p, &p);
4877 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4881 int pindex, buf_size, n_patches;
4883 MonoJumpInfo *patch_info;
4884 MonoMethodHeader *header;
4885 guint32 method_index;
4887 guint32 first_got_offset;
4889 method = cfg->orig_method;
4890 header = mono_method_get_header (method);
4892 method_index = get_method_index (acfg, method);
4894 /* Sort relocations */
4895 patches = g_ptr_array_new ();
4896 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4897 g_ptr_array_add (patches, patch_info);
4898 g_ptr_array_sort (patches, compare_patches);
4900 first_got_offset = acfg->cfgs [method_index]->got_offset;
4902 /**********************/
4903 /* Encode method info */
4904 /**********************/
4906 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4907 p = buf = g_malloc (buf_size);
4909 if (mono_class_get_cctor (method->klass))
4910 encode_klass_ref (acfg, method->klass, p, &p);
4912 /* Not needed when loading the method */
4913 encode_value (0, p, &p);
4916 if (cfg->opt & MONO_OPT_SHARED) {
4917 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4918 for (l = cfg->ldstr_list; l; l = l->next) {
4919 encode_value ((long)l->data, p, &p);
4923 /* Used only in shared mode */
4924 g_assert (!cfg->ldstr_list);
4927 for (pindex = 0; pindex < patches->len; ++pindex) {
4928 patch_info = g_ptr_array_index (patches, pindex);
4930 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4931 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4932 patch_info->type = MONO_PATCH_INFO_NONE;
4937 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4938 /* Stored in a GOT slot initialized at module load time */
4939 patch_info->type = MONO_PATCH_INFO_NONE;
4943 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4944 /* Stored in a GOT slot initialized at module load time */
4945 patch_info->type = MONO_PATCH_INFO_NONE;
4949 if (is_plt_patch (patch_info)) {
4950 /* Calls are made through the PLT */
4951 patch_info->type = MONO_PATCH_INFO_NONE;
4959 g_assert (cfg->has_got_slots);
4961 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4963 acfg->stats.info_size += p - buf;
4965 g_assert (p - buf < buf_size);
4967 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4972 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4974 guint32 cache_index;
4977 /* Reuse the unwind module to canonize and store unwind info entries */
4978 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4980 /* Use +/- 1 to distinguish 0s from missing entries */
4981 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4989 * It would be easier to use assembler symbols, but the caller needs an
4992 offset = acfg->unwind_info_offset;
4993 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4994 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4997 encode_value (encoded_len, p, &p);
4999 acfg->unwind_info_offset += encoded_len + (p - buf);
5005 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5008 int i, k, buf_size, method_index;
5009 guint32 debug_info_size;
5011 MonoMethodHeader *header;
5012 guint8 *p, *buf, *debug_info;
5013 MonoJitInfo *jinfo = cfg->jit_info;
5015 gboolean use_unwind_ops = FALSE;
5016 MonoSeqPointInfo *seq_points;
5018 method = cfg->orig_method;
5019 code = cfg->native_code;
5020 header = cfg->header;
5022 method_index = get_method_index (acfg, method);
5024 if (!acfg->aot_opts.nodebug) {
5025 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5028 debug_info_size = 0;
5031 seq_points = cfg->seq_point_info;
5033 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
5034 p = buf = g_malloc (buf_size);
5036 #ifdef MONO_ARCH_HAVE_XP_UNWIND
5037 use_unwind_ops = cfg->unwind_ops != NULL;
5040 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);
5042 encode_value (flags, p, &p);
5044 if (use_unwind_ops) {
5045 guint32 encoded_len;
5049 * This is a duplicate of the data in the .debug_frame section, but that
5050 * section cannot be accessed using the dl interface.
5052 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5053 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5056 encode_value (jinfo->used_regs, p, &p);
5059 /*Encode the number of holes before the number of clauses to make decoding easier*/
5060 if (jinfo->has_try_block_holes) {
5061 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5062 encode_value (table->num_holes, p, &p);
5065 /* Exception table */
5066 if (cfg->compile_llvm) {
5068 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5069 * since the information is only available to llc. Instead, we let llc save the data
5070 * into the LSDA, and read it from there at runtime.
5072 /* The assembly might be CIL stripped so emit the data ourselves */
5073 if (header->num_clauses)
5074 encode_value (header->num_clauses, p, &p);
5076 for (k = 0; k < header->num_clauses; ++k) {
5077 MonoExceptionClause *clause;
5079 clause = &header->clauses [k];
5081 encode_value (clause->flags, p, &p);
5082 if (clause->data.catch_class) {
5083 encode_value (1, p, &p);
5084 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5086 encode_value (0, p, &p);
5089 /* Emit a list of nesting clauses */
5090 for (i = 0; i < header->num_clauses; ++i) {
5092 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5094 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5096 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5097 encode_value (i, p, &p);
5099 encode_value (-1, p, &p);
5102 if (jinfo->num_clauses)
5103 encode_value (jinfo->num_clauses, p, &p);
5105 for (k = 0; k < jinfo->num_clauses; ++k) {
5106 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5108 encode_value (ei->flags, p, &p);
5109 encode_value (ei->exvar_offset, p, &p);
5111 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5112 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5114 if (ei->data.catch_class) {
5115 encode_value (1, p, &p);
5116 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
5118 encode_value (0, p, &p);
5122 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5123 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5124 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5128 if (jinfo->has_generic_jit_info) {
5129 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5130 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5134 encode_value (gi->nlocs, p, &p);
5136 for (i = 0; i < gi->nlocs; ++i) {
5137 MonoDwarfLocListEntry *entry = &gi->locations [i];
5139 encode_value (entry->is_reg ? 1 : 0, p, &p);
5140 encode_value (entry->reg, p, &p);
5142 encode_value (entry->offset, p, &p);
5144 g_assert (entry->from == 0);
5146 encode_value (entry->from, p, &p);
5147 encode_value (entry->to, p, &p);
5150 if (!cfg->compile_llvm) {
5151 encode_value (gi->has_this ? 1 : 0, p, &p);
5152 encode_value (gi->this_reg, p, &p);
5153 encode_value (gi->this_offset, p, &p);
5158 * Need to encode jinfo->method too, since it is not equal to 'method'
5159 * when using generic sharing.
5161 encode_method_ref (acfg, jinfo->method, p, &p);
5163 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5164 MonoMethodInflated *inflated;
5165 MonoGenericContext *context;
5166 MonoGenericInst *inst;
5168 g_assert (jinfo->method->is_inflated);
5169 inflated = (MonoMethodInflated*)jinfo->method;
5170 context = &inflated->context;
5172 encode_value (1, p, &p);
5173 if (context->class_inst) {
5174 inst = context->class_inst;
5176 encode_value (inst->type_argc, p, &p);
5177 for (i = 0; i < inst->type_argc; ++i)
5178 encode_value (gsctx->var_is_vt [i], p, &p);
5180 encode_value (0, p, &p);
5182 if (context->method_inst) {
5183 inst = context->method_inst;
5185 encode_value (inst->type_argc, p, &p);
5186 for (i = 0; i < inst->type_argc; ++i)
5187 encode_value (gsctx->mvar_is_vt [i], p, &p);
5189 encode_value (0, p, &p);
5192 encode_value (0, p, &p);
5196 if (jinfo->has_try_block_holes) {
5197 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5198 for (i = 0; i < table->num_holes; ++i) {
5199 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5200 encode_value (hole->clause, p, &p);
5201 encode_value (hole->length, p, &p);
5202 encode_value (hole->offset, p, &p);
5206 if (jinfo->has_arch_eh_info) {
5207 MonoArchEHJitInfo *eh_info;
5209 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5210 encode_value (eh_info->stack_size, p, &p);
5214 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5216 encode_value (seq_points->len, p, &p);
5217 last_il_offset = last_native_offset = 0;
5218 for (i = 0; i < seq_points->len; ++i) {
5219 SeqPoint *sp = &seq_points->seq_points [i];
5220 il_offset = sp->il_offset;
5221 native_offset = sp->native_offset;
5222 encode_value (il_offset - last_il_offset, p, &p);
5223 encode_value (native_offset - last_native_offset, p, &p);
5224 last_il_offset = il_offset;
5225 last_native_offset = native_offset;
5227 encode_value (sp->next_len, p, &p);
5228 for (j = 0; j < sp->next_len; ++j)
5229 encode_value (sp->next [j], p, &p);
5233 g_assert (debug_info_size < buf_size);
5235 encode_value (debug_info_size, p, &p);
5236 if (debug_info_size) {
5237 memcpy (p, debug_info, debug_info_size);
5238 p += debug_info_size;
5239 g_free (debug_info);
5244 encode_value (cfg->gc_map_size, p, &p);
5245 /* The GC map requires 4 bytes of alignment */
5246 while ((gsize)p % 4)
5248 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5249 p += cfg->gc_map_size;
5252 acfg->stats.ex_info_size += p - buf;
5254 g_assert (p - buf < buf_size);
5257 /* The GC Map requires 4 byte alignment */
5258 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5263 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5265 MonoClass *klass = mono_class_get (acfg->image, token);
5267 int i, buf_size, res;
5268 gboolean no_special_static, cant_encode;
5269 gpointer iter = NULL;
5272 mono_loader_clear_error ();
5276 p = buf = g_malloc (buf_size);
5278 /* Mark as unusable */
5279 encode_value (-1, p, &p);
5281 res = add_to_blob (acfg, buf, p - buf);
5287 buf_size = 10240 + (klass->vtable_size * 16);
5288 p = buf = g_malloc (buf_size);
5292 mono_class_init (klass);
5294 mono_class_get_nested_types (klass, &iter);
5295 g_assert (klass->nested_classes_inited);
5297 mono_class_setup_vtable (klass);
5300 * Emit all the information which is required for creating vtables so
5301 * the runtime does not need to create the MonoMethod structures which
5302 * take up a lot of space.
5305 no_special_static = !mono_class_has_special_static_fields (klass);
5307 /* Check whenever we have enough info to encode the vtable */
5308 cant_encode = FALSE;
5309 for (i = 0; i < klass->vtable_size; ++i) {
5310 MonoMethod *cm = klass->vtable [i];
5312 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5316 mono_class_has_finalizer (klass);
5318 if (klass->generic_container || cant_encode) {
5319 encode_value (-1, p, &p);
5321 encode_value (klass->vtable_size, p, &p);
5322 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);
5323 if (klass->has_cctor)
5324 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5325 if (klass->has_finalize)
5326 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5328 encode_value (klass->instance_size, p, &p);
5329 encode_value (mono_class_data_size (klass), p, &p);
5330 encode_value (klass->packing_size, p, &p);
5331 encode_value (klass->min_align, p, &p);
5333 for (i = 0; i < klass->vtable_size; ++i) {
5334 MonoMethod *cm = klass->vtable [i];
5337 encode_method_ref (acfg, cm, p, &p);
5339 encode_value (0, p, &p);
5343 acfg->stats.class_info_size += p - buf;
5345 g_assert (p - buf < buf_size);
5346 res = add_to_blob (acfg, buf, p - buf);
5353 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5355 char *debug_sym = NULL;
5358 case MONO_PATCH_INFO_METHOD:
5359 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5361 case MONO_PATCH_INFO_INTERNAL_METHOD:
5362 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5364 case MONO_PATCH_INFO_CLASS_INIT:
5365 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
5366 sanitize_symbol (debug_sym);
5368 case MONO_PATCH_INFO_RGCTX_FETCH:
5369 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5371 case MONO_PATCH_INFO_ICALL_ADDR: {
5372 char *s = get_debug_sym (ji->data.method, "", cache);
5374 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5378 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5379 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5381 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5382 debug_sym = g_strdup_printf ("plt__generic_class_init");
5392 * Calls made from AOTed code are routed through a table of jumps similar to the
5393 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5394 * control to the AOT runtime through a trampoline.
5397 emit_plt (MonoAotCompile *acfg)
5403 sprintf (symbol, "plt");
5405 emit_section_change (acfg, ".text", 0);
5406 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5407 emit_label (acfg, symbol);
5408 emit_label (acfg, acfg->plt_symbol);
5410 for (i = 0; i < acfg->plt_offset; ++i) {
5411 char *debug_sym = NULL;
5412 MonoPltEntry *plt_entry = NULL;
5417 * The first plt entry is unused.
5421 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5426 * If the target is directly callable, alias the plt symbol to point to
5428 * FIXME: Use this to simplify emit_and_reloc_code ().
5429 * FIXME: Avoid the got slot.
5430 * FIXME: Add support to the binary writer.
5432 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5433 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5436 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5437 /* LLVM calls the PLT entries using bl, so emit a stub */
5438 fprintf (acfg->fp, "\n.thumb_func\n");
5439 emit_label (acfg, plt_entry->llvm_symbol);
5440 fprintf (acfg->fp, "bx pc\n");
5441 fprintf (acfg->fp, "nop\n");
5442 fprintf (acfg->fp, ".arm\n");
5443 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5445 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5452 debug_sym = plt_entry->debug_sym;
5454 if (acfg->thumb_mixed && !plt_entry->jit_used)
5455 /* Emit only a thumb version */
5458 if (acfg->llvm && !acfg->thumb_mixed)
5459 emit_label (acfg, plt_entry->llvm_symbol);
5462 if (acfg->need_no_dead_strip) {
5463 img_writer_emit_unset_mode (acfg->w);
5464 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5466 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5467 emit_label (acfg, debug_sym);
5470 emit_label (acfg, plt_entry->symbol);
5472 arch_emit_plt_entry (acfg, i);
5475 emit_symbol_size (acfg, debug_sym, ".");
5478 if (acfg->thumb_mixed) {
5479 /* Make sure the ARM symbols don't alias the thumb ones */
5480 emit_zero_bytes (acfg, 16);
5483 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5486 for (i = 0; i < acfg->plt_offset; ++i) {
5487 char *debug_sym = NULL;
5488 MonoPltEntry *plt_entry = NULL;
5494 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5497 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5500 /* Skip plt entries not actually called by LLVM code */
5501 if (!plt_entry->llvm_used)
5504 if (acfg->aot_opts.write_symbols) {
5505 if (plt_entry->debug_sym)
5506 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5510 #if defined(TARGET_MACH)
5511 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5512 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5514 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5515 emit_label (acfg, debug_sym);
5517 fprintf (acfg->fp, "\n.thumb_func\n");
5519 emit_label (acfg, plt_entry->llvm_symbol);
5521 arch_emit_llvm_plt_entry (acfg, i);
5524 emit_symbol_size (acfg, debug_sym, ".");
5530 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5532 sprintf (symbol, "plt_end");
5533 emit_label (acfg, symbol);
5537 * emit_trampoline_full:
5539 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5540 * create_jit_info_for_trampoline ().
5542 static G_GNUC_UNUSED void
5543 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5545 char start_symbol [256];
5546 char end_symbol [256];
5548 guint32 buf_size, info_offset;
5549 MonoJumpInfo *patch_info;
5560 code_size = info->code_size;
5562 unwind_ops = info->unwind_ops;
5564 #ifdef __native_client_codegen__
5565 mono_nacl_fix_patches (code, ji);
5570 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5572 emit_section_change (acfg, ".text", 0);
5573 emit_global (acfg, start_symbol, TRUE);
5574 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5575 emit_label (acfg, start_symbol);
5577 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5578 emit_label (acfg, symbol);
5581 * The code should access everything through the GOT, so we pass
5584 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5586 emit_symbol_size (acfg, start_symbol, ".");
5589 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5590 emit_label (acfg, end_symbol);
5595 /* Sort relocations */
5596 patches = g_ptr_array_new ();
5597 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5598 if (patch_info->type != MONO_PATCH_INFO_NONE)
5599 g_ptr_array_add (patches, patch_info);
5600 g_ptr_array_sort (patches, compare_patches);
5602 buf_size = patches->len * 128 + 128;
5603 buf = g_malloc (buf_size);
5606 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5607 g_assert (p - buf < buf_size);
5609 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5611 info_offset = add_to_blob (acfg, buf, p - buf);
5613 emit_section_change (acfg, RODATA_SECT, 0);
5614 emit_global (acfg, symbol, FALSE);
5615 emit_label (acfg, symbol);
5617 emit_int32 (acfg, info_offset);
5621 guint32 encoded_len;
5625 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5627 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5628 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5631 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5632 emit_int32 (acfg, uw_offset);
5635 /* Emit debug info */
5639 sprintf (symbol, "%s", name);
5640 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5643 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5647 static G_GNUC_UNUSED void
5648 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5650 emit_trampoline_full (acfg, got_offset, info, FALSE);
5654 emit_trampolines (MonoAotCompile *acfg)
5657 char end_symbol [256];
5658 int i, tramp_got_offset;
5659 MonoAotTrampoline ntype;
5660 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5664 if (!acfg->aot_opts.full_aot)
5667 g_assert (acfg->image->assembly);
5669 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5670 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5671 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5672 MonoTrampInfo *info;
5675 * Emit the generic trampolines.
5677 * We could save some code by treating the generic trampolines as a wrapper
5678 * method, but that approach has its own complexities, so we choose the simpler
5681 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5682 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5683 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5684 emit_trampoline (acfg, acfg->got_offset, info);
5687 mono_arch_get_nullified_class_init_trampoline (&info);
5688 emit_trampoline (acfg, acfg->got_offset, info);
5689 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5690 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5691 emit_trampoline (acfg, acfg->got_offset, info);
5692 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5693 emit_trampoline (acfg, acfg->got_offset, info);
5696 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5697 emit_trampoline (acfg, acfg->got_offset, info);
5699 /* Emit the exception related code pieces */
5700 mono_arch_get_restore_context (&info, TRUE);
5701 emit_trampoline (acfg, acfg->got_offset, info);
5702 mono_arch_get_call_filter (&info, TRUE);
5703 emit_trampoline (acfg, acfg->got_offset, info);
5704 mono_arch_get_throw_exception (&info, TRUE);
5705 emit_trampoline (acfg, acfg->got_offset, info);
5706 mono_arch_get_rethrow_exception (&info, TRUE);
5707 emit_trampoline (acfg, acfg->got_offset, info);
5708 mono_arch_get_throw_corlib_exception (&info, TRUE);
5709 emit_trampoline (acfg, acfg->got_offset, info);
5711 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5712 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5714 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5716 /* Create a separate out trampoline for more information in stack traces */
5717 info->name = g_strdup ("gsharedvt_out_trampoline");
5718 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5722 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5724 GSList *l = mono_arch_get_trampolines (TRUE);
5727 MonoTrampInfo *info = l->data;
5729 emit_trampoline (acfg, acfg->got_offset, info);
5735 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5738 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5739 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5740 emit_trampoline (acfg, acfg->got_offset, info);
5742 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5743 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5744 emit_trampoline (acfg, acfg->got_offset, info);
5747 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
5748 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
5749 emit_trampoline (acfg, acfg->got_offset, info);
5755 /* delegate_invoke_impl trampolines */
5756 l = mono_arch_get_delegate_invoke_impls ();
5758 MonoTrampInfo *info = l->data;
5760 emit_trampoline (acfg, acfg->got_offset, info);
5765 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5767 /* Emit trampolines which are numerous */
5770 * These include the following:
5771 * - specific trampolines
5772 * - static rgctx invoke trampolines
5774 * These trampolines have the same code, they are parameterized by GOT
5776 * They are defined in this file, in the arch_... routines instead of
5777 * in tramp-<ARCH>.c, since it is easier to do it this way.
5781 * When running in aot-only mode, we can't create specific trampolines at
5782 * runtime, so we create a few, and save them in the AOT file.
5783 * Normal trampolines embed their argument as a literal inside the
5784 * trampoline code, we can't do that here, so instead we embed an offset
5785 * which needs to be added to the trampoline address to get the address of
5786 * the GOT slot which contains the argument value.
5787 * The generated trampolines jump to the generic trampolines using another
5788 * GOT slot, which will be setup by the AOT loader to point to the
5789 * generic trampoline code of the given type.
5793 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5797 emit_section_change (acfg, ".text", 0);
5799 tramp_got_offset = acfg->got_offset;
5801 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5803 case MONO_AOT_TRAMP_SPECIFIC:
5804 sprintf (symbol, "specific_trampolines");
5806 case MONO_AOT_TRAMP_STATIC_RGCTX:
5807 sprintf (symbol, "static_rgctx_trampolines");
5809 case MONO_AOT_TRAMP_IMT_THUNK:
5810 sprintf (symbol, "imt_thunks");
5812 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5813 sprintf (symbol, "gsharedvt_arg_trampolines");
5816 g_assert_not_reached ();
5819 sprintf (end_symbol, "%s_e", symbol);
5821 if (acfg->aot_opts.write_symbols)
5822 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5824 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5825 emit_label (acfg, symbol);
5827 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5829 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5833 case MONO_AOT_TRAMP_SPECIFIC:
5834 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5835 tramp_got_offset += 2;
5837 case MONO_AOT_TRAMP_STATIC_RGCTX:
5838 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
5839 tramp_got_offset += 2;
5841 case MONO_AOT_TRAMP_IMT_THUNK:
5842 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5843 tramp_got_offset += 1;
5845 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5846 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
5847 tramp_got_offset += 2;
5850 g_assert_not_reached ();
5852 #ifdef __native_client_codegen__
5853 /* align to avoid 32-byte boundary crossings */
5854 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5857 if (!acfg->trampoline_size [ntype]) {
5858 g_assert (tramp_size);
5859 acfg->trampoline_size [ntype] = tramp_size;
5863 emit_label (acfg, end_symbol);
5866 arch_emit_specific_trampoline_pages (acfg);
5868 /* Reserve some entries at the end of the GOT for our use */
5869 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5872 acfg->got_offset += acfg->num_trampoline_got_entries;
5876 str_begins_with (const char *str1, const char *str2)
5878 int len = strlen (str2);
5879 return strncmp (str1, str2, len) == 0;
5883 mono_aot_readonly_field_override (MonoClassField *field)
5886 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5887 char *p = rdv->name;
5889 len = strlen (field->parent->name_space);
5890 if (strncmp (p, field->parent->name_space, len))
5895 len = strlen (field->parent->name);
5896 if (strncmp (p, field->parent->name, len))
5901 if (strcmp (p, field->name))
5903 switch (rdv->type) {
5905 return &rdv->value.i1;
5907 return &rdv->value.i2;
5909 return &rdv->value.i4;
5918 add_readonly_value (MonoAotOptions *opts, const char *val)
5923 /* the format of val is:
5924 * namespace.typename.fieldname=type/value
5925 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5927 fval = strrchr (val, '/');
5929 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5932 tval = strrchr (val, '=');
5934 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5937 rdv = g_new0 (ReadOnlyValue, 1);
5938 rdv->name = g_malloc0 (tval - val + 1);
5939 memcpy (rdv->name, val, tval - val);
5942 if (strncmp (tval, "i1", 2) == 0) {
5943 rdv->value.i1 = atoi (fval);
5944 rdv->type = MONO_TYPE_I1;
5945 } else if (strncmp (tval, "i2", 2) == 0) {
5946 rdv->value.i2 = atoi (fval);
5947 rdv->type = MONO_TYPE_I2;
5948 } else if (strncmp (tval, "i4", 2) == 0) {
5949 rdv->value.i4 = atoi (fval);
5950 rdv->type = MONO_TYPE_I4;
5952 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5955 rdv->next = readonly_values;
5956 readonly_values = rdv;
5960 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5962 gchar **args, **ptr;
5964 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5965 for (ptr = args; ptr && *ptr; ptr ++) {
5966 const char *arg = *ptr;
5968 if (str_begins_with (arg, "outfile=")) {
5969 opts->outfile = g_strdup (arg + strlen ("outfile="));
5970 } else if (str_begins_with (arg, "save-temps")) {
5971 opts->save_temps = TRUE;
5972 } else if (str_begins_with (arg, "keep-temps")) {
5973 opts->save_temps = TRUE;
5974 } else if (str_begins_with (arg, "write-symbols")) {
5975 opts->write_symbols = TRUE;
5976 } else if (str_begins_with (arg, "no-write-symbols")) {
5977 opts->write_symbols = FALSE;
5978 } else if (str_begins_with (arg, "metadata-only")) {
5979 opts->metadata_only = TRUE;
5980 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5981 opts->bind_to_runtime_version = TRUE;
5982 } else if (str_begins_with (arg, "full")) {
5983 opts->full_aot = TRUE;
5984 } else if (str_begins_with (arg, "threads=")) {
5985 opts->nthreads = atoi (arg + strlen ("threads="));
5986 } else if (str_begins_with (arg, "static")) {
5987 opts->static_link = TRUE;
5988 opts->no_dlsym = TRUE;
5989 } else if (str_begins_with (arg, "asmonly")) {
5990 opts->asm_only = TRUE;
5991 } else if (str_begins_with (arg, "asmwriter")) {
5992 opts->asm_writer = TRUE;
5993 } else if (str_begins_with (arg, "nodebug")) {
5994 opts->nodebug = TRUE;
5995 } else if (str_begins_with (arg, "dwarfdebug")) {
5996 opts->dwarf_debug = TRUE;
5997 } else if (str_begins_with (arg, "nopagetrampolines")) {
5998 opts->use_trampolines_page = FALSE;
5999 } else if (str_begins_with (arg, "ntrampolines=")) {
6000 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6001 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6002 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6003 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6004 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6005 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6006 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6007 } else if (str_begins_with (arg, "autoreg")) {
6008 opts->autoreg = TRUE;
6009 } else if (str_begins_with (arg, "tool-prefix=")) {
6010 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6011 } else if (str_begins_with (arg, "soft-debug")) {
6012 opts->soft_debug = TRUE;
6013 } else if (str_begins_with (arg, "direct-pinvoke")) {
6014 opts->direct_pinvoke = TRUE;
6015 } else if (str_begins_with (arg, "direct-icalls")) {
6016 opts->direct_icalls = TRUE;
6017 #if defined(TARGET_ARM)
6018 } else if (str_begins_with (arg, "iphone-abi")) {
6019 // older full-aot users did depend on this.
6021 } else if (str_begins_with (arg, "no-direct-calls")) {
6022 opts->no_direct_calls = TRUE;
6023 } else if (str_begins_with (arg, "print-skipped")) {
6024 opts->print_skipped_methods = TRUE;
6025 } else if (str_begins_with (arg, "stats")) {
6027 } else if (str_begins_with (arg, "no-instances")) {
6028 opts->no_instances = TRUE;
6029 } else if (str_begins_with (arg, "log-generics")) {
6030 opts->log_generics = TRUE;
6031 } else if (str_begins_with (arg, "mtriple=")) {
6032 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6033 } else if (str_begins_with (arg, "llvm-path=")) {
6034 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6035 } else if (str_begins_with (arg, "readonly-value=")) {
6036 add_readonly_value (opts, arg + strlen ("readonly-value="));
6037 } else if (str_begins_with (arg, "info")) {
6038 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6040 } else if (str_begins_with (arg, "gc-maps")) {
6041 mini_gc_enable_gc_maps_for_aot ();
6042 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6043 printf ("Supported options for --aot:\n");
6044 printf (" outfile=\n");
6045 printf (" save-temps\n");
6046 printf (" keep-temps\n");
6047 printf (" write-symbols\n");
6048 printf (" metadata-only\n");
6049 printf (" bind-to-runtime-version\n");
6051 printf (" threads=\n");
6052 printf (" static\n");
6053 printf (" asmonly\n");
6054 printf (" asmwriter\n");
6055 printf (" nodebug\n");
6056 printf (" dwarfdebug\n");
6057 printf (" ntrampolines=\n");
6058 printf (" nrgctx-trampolines=\n");
6059 printf (" nimt-trampolines=\n");
6060 printf (" ngsharedvt-trampolines=\n");
6061 printf (" autoreg\n");
6062 printf (" tool-prefix=\n");
6063 printf (" readonly-value=\n");
6064 printf (" soft-debug\n");
6065 printf (" gc-maps\n");
6066 printf (" print-skipped\n");
6067 printf (" no-instances\n");
6068 printf (" stats\n");
6070 printf (" help/?\n");
6073 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6078 if (opts->use_trampolines_page) {
6079 opts->ntrampolines = 0;
6080 opts->nrgctx_trampolines = 0;
6081 opts->nimt_trampolines = 0;
6082 opts->ngsharedvt_arg_trampolines = 0;
6088 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6090 MonoMethod *method = (MonoMethod*)key;
6091 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6092 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6093 MonoAotCompile *acfg = user_data;
6095 new_ji->image = ji->image;
6096 new_ji->token = ji->token;
6097 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6101 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6103 if (klass->type_token)
6105 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6108 return can_encode_class (acfg, klass->element_class);
6113 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6115 if (method->wrapper_type) {
6116 switch (method->wrapper_type) {
6117 case MONO_WRAPPER_NONE:
6118 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6119 case MONO_WRAPPER_XDOMAIN_INVOKE:
6120 case MONO_WRAPPER_STFLD:
6121 case MONO_WRAPPER_LDFLD:
6122 case MONO_WRAPPER_LDFLDA:
6123 case MONO_WRAPPER_LDFLD_REMOTE:
6124 case MONO_WRAPPER_STFLD_REMOTE:
6125 case MONO_WRAPPER_STELEMREF:
6126 case MONO_WRAPPER_ISINST:
6127 case MONO_WRAPPER_PROXY_ISINST:
6128 case MONO_WRAPPER_ALLOC:
6129 case MONO_WRAPPER_REMOTING_INVOKE:
6130 case MONO_WRAPPER_UNKNOWN:
6131 case MONO_WRAPPER_WRITE_BARRIER:
6132 case MONO_WRAPPER_DELEGATE_INVOKE:
6133 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6134 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6136 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6137 case MONO_WRAPPER_CASTCLASS: {
6138 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6147 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6151 if (!method->token) {
6152 /* The method is part of a constructed type like Int[,].Set (). */
6153 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6154 if (method->klass->rank)
6164 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6166 switch (patch_info->type) {
6167 case MONO_PATCH_INFO_METHOD:
6168 case MONO_PATCH_INFO_METHODCONST: {
6169 MonoMethod *method = patch_info->data.method;
6171 return can_encode_method (acfg, method);
6173 case MONO_PATCH_INFO_VTABLE:
6174 case MONO_PATCH_INFO_CLASS_INIT:
6175 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6176 case MONO_PATCH_INFO_CLASS:
6177 case MONO_PATCH_INFO_IID:
6178 case MONO_PATCH_INFO_ADJUSTED_IID:
6179 if (!can_encode_class (acfg, patch_info->data.klass)) {
6180 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6184 case MONO_PATCH_INFO_RGCTX_FETCH: {
6185 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6187 if (!can_encode_method (acfg, entry->method))
6189 if (!can_encode_patch (acfg, entry->data))
6203 * AOT compile a given method.
6204 * This function might be called by multiple threads, so it must be thread-safe.
6207 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6210 MonoJumpInfo *patch_info;
6213 MonoMethod *wrapped;
6215 if (acfg->aot_opts.metadata_only)
6218 mono_acfg_lock (acfg);
6219 index = get_method_index (acfg, method);
6220 mono_acfg_unlock (acfg);
6222 /* fixme: maybe we can also precompile wrapper methods */
6223 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6224 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6225 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6226 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6230 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6233 wrapped = mono_marshal_method_from_wrapper (method);
6234 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6235 // FIXME: The wrapper should be generic too, but it is not
6238 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6241 InterlockedIncrement (&acfg->stats.mcount);
6244 if (method->is_generic || method->klass->generic_container) {
6245 InterlockedIncrement (&acfg->stats.genericcount);
6250 //acfg->aot_opts.print_skipped_methods = TRUE;
6253 * Since these methods are the only ones which are compiled with
6254 * AOT support, and they are not used by runtime startup/shutdown code,
6255 * the runtime will not see AOT methods during AOT compilation,so it
6256 * does not need to support them by creating a fake GOT etc.
6258 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
6259 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6260 if (acfg->aot_opts.print_skipped_methods)
6261 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6262 InterlockedIncrement (&acfg->stats.genericcount);
6265 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6266 if (acfg->aot_opts.print_skipped_methods)
6267 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6268 /* Let the exception happen at runtime */
6272 if (cfg->disable_aot) {
6273 if (acfg->aot_opts.print_skipped_methods)
6274 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6275 InterlockedIncrement (&acfg->stats.ocount);
6276 mono_destroy_compile (cfg);
6279 cfg->method_index = index;
6281 /* Nullify patches which need no aot processing */
6282 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6283 switch (patch_info->type) {
6284 case MONO_PATCH_INFO_LABEL:
6285 case MONO_PATCH_INFO_BB:
6286 patch_info->type = MONO_PATCH_INFO_NONE;
6293 /* Collect method->token associations from the cfg */
6294 mono_acfg_lock (acfg);
6295 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6296 mono_acfg_unlock (acfg);
6299 * Check for absolute addresses.
6302 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6303 switch (patch_info->type) {
6304 case MONO_PATCH_INFO_ABS:
6305 /* unable to handle this */
6314 if (acfg->aot_opts.print_skipped_methods)
6315 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6316 InterlockedIncrement (&acfg->stats.abscount);
6317 mono_destroy_compile (cfg);
6321 /* Lock for the rest of the code */
6322 mono_acfg_lock (acfg);
6325 * Check for methods/klasses we can't encode.
6328 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6329 if (!can_encode_patch (acfg, patch_info))
6334 if (acfg->aot_opts.print_skipped_methods)
6335 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6336 acfg->stats.ocount++;
6337 mono_destroy_compile (cfg);
6338 mono_acfg_unlock (acfg);
6342 /* Adds generic instances referenced by this method */
6344 * The depth is used to avoid infinite loops when generic virtual recursion is
6347 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6348 if (!acfg->aot_opts.no_instances && depth < 32) {
6349 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6350 switch (patch_info->type) {
6351 case MONO_PATCH_INFO_METHOD: {
6352 MonoMethod *m = patch_info->data.method;
6353 if (m->is_inflated) {
6354 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6355 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6356 !method_has_type_vars (m)) {
6357 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6358 if (acfg->aot_opts.full_aot)
6359 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6361 add_extra_method_with_depth (acfg, m, depth + 1);
6362 add_types_from_method_header (acfg, m);
6365 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6367 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6368 add_extra_method_with_depth (acfg, m, depth + 1);
6371 case MONO_PATCH_INFO_VTABLE: {
6372 MonoClass *klass = patch_info->data.klass;
6374 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6375 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6378 case MONO_PATCH_INFO_SFLDA: {
6379 MonoClass *klass = patch_info->data.field->parent;
6381 /* The .cctor needs to run at runtime. */
6382 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6383 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6392 /* Determine whenever the method has GOT slots */
6393 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6394 switch (patch_info->type) {
6395 case MONO_PATCH_INFO_GOT_OFFSET:
6396 case MONO_PATCH_INFO_NONE:
6397 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6399 case MONO_PATCH_INFO_IMAGE:
6400 /* The assembly is stored in GOT slot 0 */
6401 if (patch_info->data.image != acfg->image)
6402 cfg->has_got_slots = TRUE;
6405 if (!is_plt_patch (patch_info))
6406 cfg->has_got_slots = TRUE;
6411 if (!cfg->has_got_slots)
6412 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6415 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6417 /* Make a copy of the patch info which is in the mempool */
6419 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6421 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6422 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6425 patches = new_patch_info;
6427 patches_end->next = new_patch_info;
6428 patches_end = new_patch_info;
6430 cfg->patch_info = patches;
6432 /* Make a copy of the unwind info */
6434 GSList *l, *unwind_ops;
6438 for (l = cfg->unwind_ops; l; l = l->next) {
6439 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6440 memcpy (op, l->data, sizeof (MonoUnwindOp));
6441 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6443 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6445 /* Make a copy of the argument/local info */
6447 MonoInst **args, **locals;
6448 MonoMethodSignature *sig;
6449 MonoMethodHeader *header;
6452 sig = mono_method_signature (method);
6453 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6454 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6455 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6456 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6460 header = mono_method_get_header (method);
6461 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6462 for (i = 0; i < header->num_locals; ++i) {
6463 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6464 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6466 cfg->locals = locals;
6469 /* Free some fields used by cfg to conserve memory */
6470 mono_mempool_destroy (cfg->mempool);
6471 cfg->mempool = NULL;
6472 g_free (cfg->varinfo);
6473 cfg->varinfo = NULL;
6477 mono_regstate_free (cfg->rs);
6481 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6483 while (index >= acfg->cfgs_size) {
6484 MonoCompile **new_cfgs;
6487 new_size = acfg->cfgs_size * 2;
6488 new_cfgs = g_new0 (MonoCompile*, new_size);
6489 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6490 g_free (acfg->cfgs);
6491 acfg->cfgs = new_cfgs;
6492 acfg->cfgs_size = new_size;
6494 acfg->cfgs [index] = cfg;
6496 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6499 if (cfg->orig_method->wrapper_type)
6500 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6503 mono_acfg_unlock (acfg);
6505 InterlockedIncrement (&acfg->stats.ccount);
6509 compile_thread_main (gpointer *user_data)
6511 MonoDomain *domain = user_data [0];
6512 MonoAotCompile *acfg = user_data [1];
6513 GPtrArray *methods = user_data [2];
6516 mono_thread_attach (domain);
6518 for (i = 0; i < methods->len; ++i)
6519 compile_method (acfg, g_ptr_array_index (methods, i));
6523 load_profile_files (MonoAotCompile *acfg)
6527 int file_index, res, method_index, i;
6530 GList *unordered, *l;
6535 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6537 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6542 infile = fopen (tmp, "r");
6545 printf ("Using profile data file '%s'\n", tmp);
6550 res = fscanf (infile, "%32s\n", ver);
6551 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6552 printf ("Profile file has wrong version or invalid.\n");
6559 MonoMethodDesc *desc;
6562 if (fgets (name, 1023, infile) == NULL)
6565 /* Kill the newline */
6566 if (strlen (name) > 0)
6567 name [strlen (name) - 1] = '\0';
6569 desc = mono_method_desc_new (name, TRUE);
6571 method = mono_method_desc_search_in_image (desc, acfg->image);
6573 if (method && mono_method_get_token (method)) {
6574 token = mono_method_get_token (method);
6575 method_index = mono_metadata_token_index (token) - 1;
6578 for (i = 0; i < acfg->method_order->len; ++i) {
6579 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6585 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6587 //printf ("No method found matching '%s'.\n", name);
6593 /* Add missing methods */
6595 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6597 for (i = 0; i < acfg->method_order->len; ++i) {
6598 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6604 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6606 unordered = g_list_reverse (unordered);
6607 for (l = unordered; l; l = l->next)
6608 g_ptr_array_add (acfg->method_order, l->data);
6611 /* Used by the LLVM backend */
6613 mono_aot_get_got_offset (MonoJumpInfo *ji)
6615 return get_got_offset (llvm_acfg, ji);
6619 mono_aot_get_method_name (MonoCompile *cfg)
6621 if (llvm_acfg->aot_opts.static_link)
6622 /* Include the assembly name too to avoid duplicate symbol errors */
6623 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6625 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6629 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6631 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6632 MonoPltEntry *plt_entry;
6635 ji->data.target = data;
6637 if (!can_encode_patch (llvm_acfg, ji))
6640 plt_entry = get_plt_entry (llvm_acfg, ji);
6641 plt_entry->llvm_used = TRUE;
6643 #if defined(TARGET_MACH)
6644 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6646 return g_strdup_printf (plt_entry->llvm_symbol);
6651 mono_aot_get_method_index (MonoMethod *method)
6653 g_assert (llvm_acfg);
6654 return get_method_index (llvm_acfg, method);
6658 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6662 mono_acfg_lock (llvm_acfg);
6663 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6664 mono_acfg_unlock (llvm_acfg);
6674 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6678 emit_llvm_file (MonoAotCompile *acfg)
6680 char *command, *opts, *tempbc;
6682 MonoJumpInfo *patch_info;
6685 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6689 /* Compute the final size of the got */
6690 for (i = 0; i < acfg->nmethods; ++i) {
6691 if (acfg->cfgs [i]) {
6692 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6693 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6694 if (!is_plt_patch (patch_info))
6695 get_got_offset (acfg, patch_info);
6697 get_plt_entry (acfg, patch_info);
6703 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6705 if (acfg->aot_opts.full_aot) {
6709 * Need to add the got entries used by the trampolines.
6710 * This is only a conservative approximation.
6712 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6713 /* For the generic + rgctx trampolines */
6714 acfg->final_got_size += 400;
6715 /* For the specific trampolines */
6716 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6717 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6722 tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
6723 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6727 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6728 * a lot of time, and doesn't seem to save much space.
6729 * The following optimizations cannot be enabled:
6731 * - 'jump-threading' changes our blockaddress references to int constants.
6732 * - 'basiccg' fails because it contains:
6733 * if (CS && !isa<IntrinsicInst>(II)) {
6734 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
6735 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
6736 * The opt list below was produced by taking the output of:
6737 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
6738 * then removing tailcallelim + the global opts, and adding a second gvn.
6740 opts = g_strdup ("-instcombine -simplifycfg");
6741 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
6743 command = g_strdup_printf ("%sopt -f %s -o %s.opt.bc %s.bc", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
6744 printf ("Executing opt: %s\n", command);
6745 if (system (command) != 0) {
6751 if (!acfg->llc_args)
6752 acfg->llc_args = g_string_new ("");
6754 /* Verbose asm slows down llc greatly */
6755 g_string_append (acfg->llc_args, " -asm-verbose=false");
6757 if (acfg->aot_opts.mtriple)
6758 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
6760 #if defined(TARGET_MACH) && defined(TARGET_ARM)
6761 /* ios requires PIC code now */
6762 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6764 if (llvm_acfg->aot_opts.static_link)
6765 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
6767 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6769 unlink (acfg->tmpfname);
6771 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o %s %s.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpfname);
6773 printf ("Executing llc: %s\n", command);
6775 if (system (command) != 0) {
6782 emit_code (MonoAotCompile *acfg)
6784 int oindex, i, prev_index;
6786 char end_symbol [256];
6788 #if defined(TARGET_POWERPC64)
6789 sprintf (symbol, ".Lgot_addr");
6790 emit_section_change (acfg, ".text", 0);
6791 emit_alignment (acfg, 8);
6792 emit_label (acfg, symbol);
6793 emit_pointer (acfg, acfg->got_symbol);
6797 * This global symbol is used to compute the address of each method using the
6798 * code_offsets array. It is also used to compute the memory ranges occupied by
6799 * AOT code, so it must be equal to the address of the first emitted method.
6801 sprintf (symbol, "methods");
6802 emit_section_change (acfg, ".text", 0);
6803 emit_alignment (acfg, 8);
6805 for (i = 0; i < acfg->nmethods; ++i) {
6806 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
6807 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
6811 if (i == acfg->nmethods)
6812 /* No LLVM compiled methods */
6813 emit_label (acfg, symbol);
6815 emit_label (acfg, symbol);
6819 * Emit some padding so the local symbol for the first method doesn't have the
6820 * same address as 'methods'.
6822 #if defined(__default_codegen__)
6823 emit_zero_bytes (acfg, 16);
6824 #elif defined(__native_client_codegen__)
6826 const int kPaddingSize = 16;
6827 guint8 pad_buffer[kPaddingSize];
6828 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
6829 emit_bytes (acfg, pad_buffer, kPaddingSize);
6833 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6837 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6839 cfg = acfg->cfgs [i];
6844 method = cfg->orig_method;
6846 /* Emit unbox trampoline */
6847 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
6848 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
6850 emit_section_change (acfg, ".text", 0);
6851 #ifdef __native_client_codegen__
6852 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6855 if (acfg->thumb_mixed && cfg->compile_llvm)
6856 fprintf (acfg->fp, "\n.thumb_func\n");
6858 emit_label (acfg, symbol);
6860 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
6863 if (cfg->compile_llvm)
6864 acfg->stats.llvm_count ++;
6866 emit_method_code (acfg, cfg);
6869 sprintf (symbol, "methods_end");
6870 emit_section_change (acfg, ".text", 0);
6871 emit_alignment (acfg, 8);
6872 emit_label (acfg, symbol);
6873 /* To distinguish it from the next symbol */
6874 emit_int32 (acfg, 0);
6877 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6878 * from optimizing them away, since it doesn't see that code_offsets references them.
6879 * JITted methods don't need this since they are referenced using assembler local
6881 * FIXME: This is why write-symbols doesn't work on OSX ?
6883 if (acfg->llvm && acfg->need_no_dead_strip) {
6884 fprintf (acfg->fp, "\n");
6885 for (i = 0; i < acfg->nmethods; ++i) {
6886 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6887 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6892 if (acfg->direct_method_addresses) {
6893 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
6896 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
6897 * This is PIE code, and the linker can update it if needed.
6899 sprintf (symbol, "method_addresses");
6900 emit_section_change (acfg, RODATA_SECT, 1);
6901 emit_alignment (acfg, 8);
6902 emit_label (acfg, symbol);
6903 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
6904 img_writer_emit_unset_mode (acfg->w);
6905 if (acfg->need_no_dead_strip)
6906 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
6908 for (i = 0; i < acfg->nmethods; ++i) {
6909 if (acfg->cfgs [i]) {
6910 if (acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm)
6911 fprintf (acfg->fp, "\tblx %s\n", acfg->cfgs [i]->asm_symbol);
6913 fprintf (acfg->fp, "\tbl %s\n", acfg->cfgs [i]->asm_symbol);
6915 fprintf (acfg->fp, "\tbl method_addresses\n");
6919 sprintf (symbol, "method_addresses_end");
6920 emit_label (acfg, symbol);
6923 sprintf (symbol, "code_offsets");
6924 emit_section_change (acfg, RODATA_SECT, 1);
6925 emit_alignment (acfg, 8);
6926 emit_label (acfg, symbol);
6927 emit_int32 (acfg, 0);
6929 sprintf (symbol, "code_offsets");
6930 emit_section_change (acfg, RODATA_SECT, 1);
6931 emit_alignment (acfg, 8);
6932 emit_label (acfg, symbol);
6934 acfg->stats.offsets_size += acfg->nmethods * 4;
6936 sprintf (end_symbol, "methods");
6937 for (i = 0; i < acfg->nmethods; ++i) {
6938 if (acfg->cfgs [i]) {
6939 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6941 emit_int32 (acfg, 0xffffffff);
6946 sprintf (symbol, "code_offsets");
6947 emit_section_change (acfg, RODATA_SECT, 1);
6948 emit_alignment (acfg, 8);
6949 emit_label (acfg, symbol);
6951 acfg->stats.offsets_size += acfg->nmethods * 4;
6953 sprintf (end_symbol, "methods");
6954 for (i = 0; i < acfg->nmethods; ++i) {
6955 if (acfg->cfgs [i]) {
6956 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6958 emit_int32 (acfg, 0xffffffff);
6964 /* Emit a sorted table mapping methods to their unbox trampolines */
6965 sprintf (symbol, "unbox_trampolines");
6966 emit_section_change (acfg, RODATA_SECT, 1);
6967 emit_alignment (acfg, 8);
6968 emit_label (acfg, symbol);
6970 sprintf (end_symbol, "methods");
6972 for (i = 0; i < acfg->nmethods; ++i) {
6977 cfg = acfg->cfgs [i];
6981 method = cfg->orig_method;
6983 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
6984 index = get_method_index (acfg, method);
6985 sprintf (symbol, "ut_%d", index);
6987 emit_int32 (acfg, index);
6988 if (acfg->direct_method_addresses) {
6989 img_writer_emit_unset_mode (acfg->w);
6990 if (acfg->thumb_mixed && cfg->compile_llvm)
6991 fprintf (acfg->fp, "\n\tblx %s\n", symbol);
6993 fprintf (acfg->fp, "\n\tbl %s\n", symbol);
6995 emit_symbol_diff (acfg, symbol, end_symbol, 0);
6997 /* Make sure the table is sorted by index */
6998 g_assert (index > prev_index);
7002 sprintf (symbol, "unbox_trampolines_end");
7003 emit_label (acfg, symbol);
7007 emit_info (MonoAotCompile *acfg)
7013 offsets = g_new0 (gint32, acfg->nmethods);
7015 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7016 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7018 if (acfg->cfgs [i]) {
7019 emit_method_info (acfg, acfg->cfgs [i]);
7020 offsets [i] = acfg->cfgs [i]->method_info_offset;
7026 sprintf (symbol, "method_info_offsets");
7027 emit_section_change (acfg, RODATA_SECT, 1);
7028 emit_alignment (acfg, 8);
7029 emit_label (acfg, symbol);
7031 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7036 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7038 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7039 #define mix(a,b,c) { \
7040 a -= c; a ^= rot(c, 4); c += b; \
7041 b -= a; b ^= rot(a, 6); a += c; \
7042 c -= b; c ^= rot(b, 8); b += a; \
7043 a -= c; a ^= rot(c,16); c += b; \
7044 b -= a; b ^= rot(a,19); a += c; \
7045 c -= b; c ^= rot(b, 4); b += a; \
7047 #define final(a,b,c) { \
7048 c ^= b; c -= rot(b,14); \
7049 a ^= c; a -= rot(c,11); \
7050 b ^= a; b -= rot(a,25); \
7051 c ^= b; c -= rot(b,16); \
7052 a ^= c; a -= rot(c,4); \
7053 b ^= a; b -= rot(a,14); \
7054 c ^= b; c -= rot(b,24); \
7058 mono_aot_type_hash (MonoType *t1)
7060 guint hash = t1->type;
7062 hash |= t1->byref << 6; /* do not collide with t1->type values */
7064 case MONO_TYPE_VALUETYPE:
7065 case MONO_TYPE_CLASS:
7066 case MONO_TYPE_SZARRAY:
7067 /* check if the distribution is good enough */
7068 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7070 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7071 case MONO_TYPE_ARRAY:
7072 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7073 case MONO_TYPE_GENERICINST:
7074 return ((hash << 5) - hash) ^ 0;
7081 * mono_aot_method_hash:
7083 * Return a hash code for methods which only depends on metadata.
7086 mono_aot_method_hash (MonoMethod *method)
7088 MonoMethodSignature *sig;
7092 guint32 *hashes_start, *hashes;
7094 MonoGenericInst *ginst = NULL;
7096 /* Similar to the hash in mono_method_get_imt_slot () */
7098 sig = mono_method_signature (method);
7100 if (method->is_inflated)
7101 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7103 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7104 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7105 hashes = hashes_start;
7107 /* Some wrappers are assigned to random classes */
7108 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7109 klass = method->klass;
7111 klass = mono_defaults.object_class;
7113 if (!method->wrapper_type) {
7114 char *full_name = mono_type_full_name (&klass->byval_arg);
7116 hashes [0] = mono_metadata_str_hash (full_name);
7120 hashes [0] = mono_metadata_str_hash (klass->name);
7121 hashes [1] = mono_metadata_str_hash (klass->name_space);
7123 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7124 /* The method name includes a stringified pointer */
7127 hashes [2] = mono_metadata_str_hash (method->name);
7128 hashes [3] = method->wrapper_type;
7129 hashes [4] = mono_aot_type_hash (sig->ret);
7131 for (i = 0; i < sig->param_count; i++) {
7132 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7135 for (i = 0; i < ginst->type_argc; ++i)
7136 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7138 g_assert (hindex == hashes_count);
7140 /* Setup internal state */
7141 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7143 /* Handle most of the hashes */
7144 while (hashes_count > 3) {
7153 /* Handle the last 3 hashes (all the case statements fall through) */
7154 switch (hashes_count) {
7155 case 3 : c += hashes [2];
7156 case 2 : b += hashes [1];
7157 case 1 : a += hashes [0];
7159 case 0: /* nothing left to add */
7163 free (hashes_start);
7172 * mono_aot_get_array_helper_from_wrapper;
7174 * Get the helper method in Array called by an array wrapper method.
7177 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7181 MonoGenericContext ctx;
7182 MonoType *args [16];
7183 char *mname, *iname, *s, *s2, *helper_name = NULL;
7185 prefix = "System.Collections.Generic";
7186 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7187 s2 = strstr (s, "`1.");
7193 //printf ("X: %s %s\n", iname, mname);
7195 if (!strcmp (iname, "IList"))
7196 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7198 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7199 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7201 g_free (helper_name);
7204 if (m->is_generic) {
7205 memset (&ctx, 0, sizeof (ctx));
7206 args [0] = &method->klass->element_class->byval_arg;
7207 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7208 m = mono_class_inflate_generic_method (m, &ctx);
7214 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7216 typedef struct HashEntry {
7217 guint32 key, value, index;
7218 struct HashEntry *next;
7222 * emit_extra_methods:
7224 * Emit methods which are not in the METHOD table, like wrappers.
7227 emit_extra_methods (MonoAotCompile *acfg)
7229 int i, table_size, buf_size;
7232 guint32 *info_offsets;
7235 HashEntry *entry, *new_entry;
7236 int nmethods, max_chain_length;
7239 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7241 /* Emit method info */
7243 for (i = 0; i < acfg->extra_methods->len; ++i) {
7244 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7245 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7251 p = buf = g_malloc (buf_size);
7255 method = cfg->method_to_register;
7257 encode_method_ref (acfg, method, p, &p);
7259 g_assert ((p - buf) < buf_size);
7261 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7266 * Construct a chained hash table for mapping indexes in extra_method_info to
7269 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7270 table = g_ptr_array_sized_new (table_size);
7271 for (i = 0; i < table_size; ++i)
7272 g_ptr_array_add (table, NULL);
7273 chain_lengths = g_new0 (int, table_size);
7274 max_chain_length = 0;
7275 for (i = 0; i < acfg->extra_methods->len; ++i) {
7276 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7277 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7283 key = info_offsets [i];
7284 value = get_method_index (acfg, method);
7286 hash = mono_aot_method_hash (method) % table_size;
7288 chain_lengths [hash] ++;
7289 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7291 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7292 new_entry->key = key;
7293 new_entry->value = value;
7295 entry = g_ptr_array_index (table, hash);
7296 if (entry == NULL) {
7297 new_entry->index = hash;
7298 g_ptr_array_index (table, hash) = new_entry;
7301 entry = entry->next;
7303 entry->next = new_entry;
7304 new_entry->index = table->len;
7305 g_ptr_array_add (table, new_entry);
7309 //printf ("MAX: %d\n", max_chain_length);
7311 /* Emit the table */
7312 sprintf (symbol, "extra_method_table");
7313 emit_section_change (acfg, RODATA_SECT, 0);
7314 emit_alignment (acfg, 8);
7315 emit_label (acfg, symbol);
7317 emit_int32 (acfg, table_size);
7318 for (i = 0; i < table->len; ++i) {
7319 HashEntry *entry = g_ptr_array_index (table, i);
7321 if (entry == NULL) {
7322 emit_int32 (acfg, 0);
7323 emit_int32 (acfg, 0);
7324 emit_int32 (acfg, 0);
7326 //g_assert (entry->key > 0);
7327 emit_int32 (acfg, entry->key);
7328 emit_int32 (acfg, entry->value);
7330 emit_int32 (acfg, entry->next->index);
7332 emit_int32 (acfg, 0);
7337 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7338 * This is used by mono_aot_find_jit_info ().
7340 sprintf (symbol, "extra_method_info_offsets");
7341 emit_section_change (acfg, RODATA_SECT, 0);
7342 emit_alignment (acfg, 8);
7343 emit_label (acfg, symbol);
7345 emit_int32 (acfg, acfg->extra_methods->len);
7346 for (i = 0; i < acfg->extra_methods->len; ++i) {
7347 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7349 emit_int32 (acfg, get_method_index (acfg, method));
7350 emit_int32 (acfg, info_offsets [i]);
7355 emit_exception_info (MonoAotCompile *acfg)
7361 offsets = g_new0 (gint32, acfg->nmethods);
7362 for (i = 0; i < acfg->nmethods; ++i) {
7363 if (acfg->cfgs [i]) {
7364 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7365 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7371 sprintf (symbol, "ex_info_offsets");
7372 emit_section_change (acfg, RODATA_SECT, 1);
7373 emit_alignment (acfg, 8);
7374 emit_label (acfg, symbol);
7376 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7381 emit_unwind_info (MonoAotCompile *acfg)
7387 * The unwind info contains a lot of duplicates so we emit each unique
7388 * entry once, and only store the offset from the start of the table in the
7392 sprintf (symbol, "unwind_info");
7393 emit_section_change (acfg, RODATA_SECT, 1);
7394 emit_alignment (acfg, 8);
7395 emit_label (acfg, symbol);
7397 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7398 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7399 guint8 *unwind_info;
7400 guint32 unwind_info_len;
7404 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7407 encode_value (unwind_info_len, p, &p);
7408 emit_bytes (acfg, buf, p - buf);
7409 emit_bytes (acfg, unwind_info, unwind_info_len);
7411 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7416 emit_class_info (MonoAotCompile *acfg)
7422 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7423 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7424 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7426 sprintf (symbol, "class_info_offsets");
7427 emit_section_change (acfg, RODATA_SECT, 1);
7428 emit_alignment (acfg, 8);
7429 emit_label (acfg, symbol);
7431 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7435 typedef struct ClassNameTableEntry {
7436 guint32 token, index;
7437 struct ClassNameTableEntry *next;
7438 } ClassNameTableEntry;
7441 emit_class_name_table (MonoAotCompile *acfg)
7444 guint32 token, hash;
7449 ClassNameTableEntry *entry, *new_entry;
7452 * Construct a chained hash table for mapping class names to typedef tokens.
7454 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7455 table = g_ptr_array_sized_new (table_size);
7456 for (i = 0; i < table_size; ++i)
7457 g_ptr_array_add (table, NULL);
7458 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7459 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7460 klass = mono_class_get (acfg->image, token);
7462 mono_loader_clear_error ();
7465 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7466 hash = mono_metadata_str_hash (full_name) % table_size;
7469 /* FIXME: Allocate from the mempool */
7470 new_entry = g_new0 (ClassNameTableEntry, 1);
7471 new_entry->token = token;
7473 entry = g_ptr_array_index (table, hash);
7474 if (entry == NULL) {
7475 new_entry->index = hash;
7476 g_ptr_array_index (table, hash) = new_entry;
7479 entry = entry->next;
7481 entry->next = new_entry;
7482 new_entry->index = table->len;
7483 g_ptr_array_add (table, new_entry);
7487 /* Emit the table */
7488 sprintf (symbol, "class_name_table");
7489 emit_section_change (acfg, RODATA_SECT, 0);
7490 emit_alignment (acfg, 8);
7491 emit_label (acfg, symbol);
7493 /* FIXME: Optimize memory usage */
7494 g_assert (table_size < 65000);
7495 emit_int16 (acfg, table_size);
7496 g_assert (table->len < 65000);
7497 for (i = 0; i < table->len; ++i) {
7498 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7500 if (entry == NULL) {
7501 emit_int16 (acfg, 0);
7502 emit_int16 (acfg, 0);
7504 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7506 emit_int16 (acfg, entry->next->index);
7508 emit_int16 (acfg, 0);
7514 emit_image_table (MonoAotCompile *acfg)
7520 * The image table is small but referenced in a lot of places.
7521 * So we emit it at once, and reference its elements by an index.
7524 sprintf (symbol, "image_table");
7525 emit_section_change (acfg, RODATA_SECT, 1);
7526 emit_alignment (acfg, 8);
7527 emit_label (acfg, symbol);
7529 emit_int32 (acfg, acfg->image_table->len);
7530 for (i = 0; i < acfg->image_table->len; i++) {
7531 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7532 MonoAssemblyName *aname = &image->assembly->aname;
7534 /* FIXME: Support multi-module assemblies */
7535 g_assert (image->assembly->image == image);
7537 emit_string (acfg, image->assembly_name);
7538 emit_string (acfg, image->guid);
7539 emit_string (acfg, aname->culture ? aname->culture : "");
7540 emit_string (acfg, (const char*)aname->public_key_token);
7542 emit_alignment (acfg, 8);
7543 emit_int32 (acfg, aname->flags);
7544 emit_int32 (acfg, aname->major);
7545 emit_int32 (acfg, aname->minor);
7546 emit_int32 (acfg, aname->build);
7547 emit_int32 (acfg, aname->revision);
7552 emit_got_info (MonoAotCompile *acfg)
7555 int i, first_plt_got_patch, buf_size;
7557 guint32 *got_info_offsets;
7559 /* Add the patches needed by the PLT to the GOT */
7560 acfg->plt_got_offset_base = acfg->got_offset;
7561 first_plt_got_patch = acfg->got_patches->len;
7562 for (i = 1; i < acfg->plt_offset; ++i) {
7563 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7565 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7567 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7570 acfg->got_offset += acfg->plt_offset;
7574 * - optimize offsets table.
7575 * - reduce number of exported symbols.
7576 * - emit info for a klass only once.
7577 * - determine when a method uses a GOT slot which is guaranteed to be already
7579 * - clean up and document the code.
7580 * - use String.Empty in class libs.
7583 /* Encode info required to decode shared GOT entries */
7584 buf_size = acfg->got_patches->len * 128;
7585 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7586 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7587 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7589 if (acfg->plt_offset)
7590 acfg->plt_got_info_offsets [0] = 0;
7591 for (i = 0; i < acfg->got_patches->len; ++i) {
7592 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7597 encode_value (ji->type, p, &p);
7599 encode_patch (acfg, ji, p, &p);
7600 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7601 g_assert (p - buf <= buf_size);
7602 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7604 if (i >= first_plt_got_patch)
7605 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7606 acfg->stats.got_info_size += p - buf;
7609 /* Emit got_info_offsets table */
7610 sprintf (symbol, "got_info_offsets");
7611 emit_section_change (acfg, RODATA_SECT, 1);
7612 emit_alignment (acfg, 8);
7613 emit_label (acfg, symbol);
7615 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7616 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7620 emit_got (MonoAotCompile *acfg)
7625 /* Don't make GOT global so accesses to it don't need relocations */
7626 sprintf (symbol, "%s", acfg->got_symbol);
7627 emit_section_change (acfg, ".bss", 0);
7628 emit_alignment (acfg, 8);
7629 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7630 emit_label (acfg, symbol);
7631 if (acfg->got_offset > 0)
7632 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7634 sprintf (symbol, "got_end");
7635 emit_label (acfg, symbol);
7639 typedef struct GlobalsTableEntry {
7640 guint32 value, index;
7641 struct GlobalsTableEntry *next;
7642 } GlobalsTableEntry;
7645 emit_globals (MonoAotCompile *acfg)
7651 GlobalsTableEntry *entry, *new_entry;
7653 if (!acfg->aot_opts.static_link)
7657 * When static linking, we emit a table containing our globals.
7661 * Construct a chained hash table for mapping global names to their index in
7662 * the globals table.
7664 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7665 table = g_ptr_array_sized_new (table_size);
7666 for (i = 0; i < table_size; ++i)
7667 g_ptr_array_add (table, NULL);
7668 for (i = 0; i < acfg->globals->len; ++i) {
7669 char *name = g_ptr_array_index (acfg->globals, i);
7671 hash = mono_metadata_str_hash (name) % table_size;
7673 /* FIXME: Allocate from the mempool */
7674 new_entry = g_new0 (GlobalsTableEntry, 1);
7675 new_entry->value = i;
7677 entry = g_ptr_array_index (table, hash);
7678 if (entry == NULL) {
7679 new_entry->index = hash;
7680 g_ptr_array_index (table, hash) = new_entry;
7683 entry = entry->next;
7685 entry->next = new_entry;
7686 new_entry->index = table->len;
7687 g_ptr_array_add (table, new_entry);
7691 /* Emit the table */
7692 sprintf (symbol, ".Lglobals_hash");
7693 emit_section_change (acfg, RODATA_SECT, 0);
7694 emit_alignment (acfg, 8);
7695 emit_label (acfg, symbol);
7697 /* FIXME: Optimize memory usage */
7698 g_assert (table_size < 65000);
7699 emit_int16 (acfg, table_size);
7700 for (i = 0; i < table->len; ++i) {
7701 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7703 if (entry == NULL) {
7704 emit_int16 (acfg, 0);
7705 emit_int16 (acfg, 0);
7707 emit_int16 (acfg, entry->value + 1);
7709 emit_int16 (acfg, entry->next->index);
7711 emit_int16 (acfg, 0);
7715 /* Emit the names */
7716 for (i = 0; i < acfg->globals->len; ++i) {
7717 char *name = g_ptr_array_index (acfg->globals, i);
7719 sprintf (symbol, "name_%d", i);
7720 emit_section_change (acfg, RODATA_SECT, 1);
7722 emit_alignment (acfg, 4);
7724 emit_label (acfg, symbol);
7725 emit_string (acfg, name);
7728 /* Emit the globals table */
7729 sprintf (symbol, "globals");
7730 emit_section_change (acfg, ".data", 0);
7731 /* This is not a global, since it is accessed by the init function */
7732 emit_alignment (acfg, 8);
7733 emit_label (acfg, symbol);
7735 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
7736 emit_pointer (acfg, symbol);
7738 for (i = 0; i < acfg->globals->len; ++i) {
7739 char *name = g_ptr_array_index (acfg->globals, i);
7741 sprintf (symbol, "name_%d", i);
7742 emit_pointer (acfg, symbol);
7744 sprintf (symbol, "%s", name);
7745 emit_pointer (acfg, symbol);
7747 /* Null terminate the table */
7748 emit_int32 (acfg, 0);
7749 emit_int32 (acfg, 0);
7753 emit_autoreg (MonoAotCompile *acfg)
7758 * Emit a function into the .ctor section which will be called by the ELF
7759 * loader to register this module with the runtime.
7761 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
7764 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
7766 arch_emit_autoreg (acfg, symbol);
7772 emit_mem_end (MonoAotCompile *acfg)
7776 sprintf (symbol, "mem_end");
7777 emit_section_change (acfg, ".text", 1);
7778 emit_alignment (acfg, 8);
7779 emit_label (acfg, symbol);
7783 * Emit a structure containing all the information not stored elsewhere.
7786 emit_file_info (MonoAotCompile *acfg)
7791 const char *gc_name;
7794 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
7796 if (acfg->aot_opts.bind_to_runtime_version) {
7797 build_info = mono_get_runtime_build_info ();
7798 emit_string_symbol (acfg, "runtime_version", build_info);
7799 g_free (build_info);
7801 emit_string_symbol (acfg, "runtime_version", "");
7804 /* Emit a string holding the assembly name */
7805 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
7808 * The managed allocators are GC specific, so can't use an AOT image created by one GC
7811 gc_name = mono_gc_get_gc_name ();
7812 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
7814 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
7815 emit_section_change (acfg, ".data", 0);
7816 emit_alignment (acfg, 8);
7817 emit_label (acfg, symbol);
7818 if (!acfg->aot_opts.static_link)
7819 emit_global (acfg, symbol, FALSE);
7821 /* The data emitted here must match MonoAotFileInfo. */
7823 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
7824 emit_int32 (acfg, 0);
7827 * We emit pointers to our data structures instead of emitting global symbols which
7828 * point to them, to reduce the number of globals, and because using globals leads to
7829 * various problems (i.e. arm/thumb).
7831 emit_pointer (acfg, acfg->got_symbol);
7832 emit_pointer (acfg, "methods");
7835 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
7837 emit_pointer (acfg, "mono_eh_frame");
7839 emit_pointer (acfg, NULL);
7841 emit_pointer (acfg, "blob");
7842 emit_pointer (acfg, "class_name_table");
7843 emit_pointer (acfg, "class_info_offsets");
7844 emit_pointer (acfg, "method_info_offsets");
7845 emit_pointer (acfg, "ex_info_offsets");
7846 emit_pointer (acfg, "code_offsets");
7847 if (acfg->direct_method_addresses)
7848 emit_pointer (acfg, "method_addresses");
7850 emit_pointer (acfg, NULL);
7851 emit_pointer (acfg, "extra_method_info_offsets");
7852 emit_pointer (acfg, "extra_method_table");
7853 emit_pointer (acfg, "got_info_offsets");
7854 emit_pointer (acfg, "methods_end");
7855 emit_pointer (acfg, "unwind_info");
7856 emit_pointer (acfg, "mem_end");
7857 emit_pointer (acfg, "image_table");
7858 emit_pointer (acfg, "plt");
7859 emit_pointer (acfg, "plt_end");
7860 emit_pointer (acfg, "assembly_guid");
7861 emit_pointer (acfg, "runtime_version");
7862 if (acfg->num_trampoline_got_entries) {
7863 emit_pointer (acfg, "specific_trampolines");
7864 emit_pointer (acfg, "static_rgctx_trampolines");
7865 emit_pointer (acfg, "imt_thunks");
7866 emit_pointer (acfg, "gsharedvt_arg_trampolines");
7868 emit_pointer (acfg, NULL);
7869 emit_pointer (acfg, NULL);
7870 emit_pointer (acfg, NULL);
7871 emit_pointer (acfg, NULL);
7873 if (acfg->thumb_mixed) {
7874 emit_pointer (acfg, "thumb_end");
7876 emit_pointer (acfg, NULL);
7878 if (acfg->aot_opts.static_link) {
7879 emit_pointer (acfg, "globals");
7881 emit_pointer (acfg, NULL);
7883 emit_pointer (acfg, "assembly_name");
7884 emit_pointer (acfg, "unbox_trampolines");
7885 emit_pointer (acfg, "unbox_trampolines_end");
7887 emit_int32 (acfg, acfg->plt_got_offset_base);
7888 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7889 emit_int32 (acfg, acfg->plt_offset);
7890 emit_int32 (acfg, acfg->nmethods);
7891 emit_int32 (acfg, acfg->flags);
7892 emit_int32 (acfg, acfg->opts);
7893 emit_int32 (acfg, acfg->simd_opts);
7894 emit_int32 (acfg, gc_name_offset);
7896 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7897 emit_int32 (acfg, acfg->num_trampolines [i]);
7898 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7899 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
7900 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7901 emit_int32 (acfg, acfg->trampoline_size [i]);
7902 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
7904 #if defined (TARGET_ARM) && defined (TARGET_MACH)
7909 memset (&t, 0, sizeof (MonoType));
7910 t.type = MONO_TYPE_R8;
7911 mono_type_size (&t, &align);
7912 emit_int32 (acfg, align);
7914 memset (&t, 0, sizeof (MonoType));
7915 t.type = MONO_TYPE_I8;
7916 mono_type_size (&t, &align);
7918 emit_int32 (acfg, align);
7921 emit_int32 (acfg, __alignof__ (double));
7922 emit_int32 (acfg, __alignof__ (gint64));
7925 if (acfg->aot_opts.static_link) {
7929 * Emit a global symbol which can be passed by an embedding app to
7930 * mono_aot_register_module (). The symbol points to a pointer to the the file info
7933 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
7935 /* Get rid of characters which cannot occur in symbols */
7937 for (p = symbol; *p; ++p) {
7938 if (!(isalnum (*p) || *p == '_'))
7941 acfg->static_linking_symbol = g_strdup (symbol);
7942 emit_global_inner (acfg, symbol, FALSE);
7943 emit_label (acfg, symbol);
7944 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
7949 emit_blob (MonoAotCompile *acfg)
7953 sprintf (symbol, "blob");
7954 emit_section_change (acfg, RODATA_SECT, 1);
7955 emit_alignment (acfg, 8);
7956 emit_label (acfg, symbol);
7958 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7962 emit_dwarf_info (MonoAotCompile *acfg)
7964 #ifdef EMIT_DWARF_INFO
7968 /* DIEs for methods */
7969 for (i = 0; i < acfg->nmethods; ++i) {
7970 MonoCompile *cfg = acfg->cfgs [i];
7975 // FIXME: LLVM doesn't define .Lme_...
7976 if (cfg->compile_llvm)
7979 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7981 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
7987 collect_methods (MonoAotCompile *acfg)
7990 MonoImage *image = acfg->image;
7992 /* Collect methods */
7993 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7995 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7997 method = mono_get_method (acfg->image, token, NULL);
8000 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8004 /* Load all methods eagerly to skip the slower lazy loading code */
8005 mono_class_setup_methods (method->klass);
8007 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8008 /* Compile the wrapper instead */
8009 /* We do this here instead of add_wrappers () because it is easy to do it here */
8010 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8014 /* FIXME: Some mscorlib methods don't have debug info */
8016 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8017 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8018 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8019 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8020 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8021 if (!mono_debug_lookup_method (method)) {
8022 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8029 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8030 add_method_with_index (acfg, method, i, FALSE);
8031 acfg->method_index ++;
8034 /* gsharedvt methods */
8035 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8037 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8039 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8042 method = mono_get_method (acfg->image, token, NULL);
8046 if (strcmp (method->name, "gshared2"))
8050 if (!strstr (method->klass->image->name, "mini"))
8053 if (method->is_generic || method->klass->generic_container) {
8054 MonoMethod *gshared;
8056 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8057 add_extra_method (acfg, gshared);
8061 add_generic_instances (acfg);
8063 if (acfg->aot_opts.full_aot)
8064 add_wrappers (acfg);
8068 compile_methods (MonoAotCompile *acfg)
8072 if (acfg->aot_opts.nthreads > 0) {
8077 gpointer *user_data;
8078 MonoMethod **methods;
8080 methods_len = acfg->methods->len;
8082 len = acfg->methods->len / acfg->aot_opts.nthreads;
8085 * Partition the list of methods into fragments, and hand it to threads to
8088 threads = g_ptr_array_new ();
8089 /* Make a copy since acfg->methods is modified by compile_method () */
8090 methods = g_new0 (MonoMethod*, methods_len);
8091 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8092 for (i = 0; i < methods_len; ++i)
8093 methods [i] = g_ptr_array_index (acfg->methods, i);
8095 while (i < methods_len) {
8096 frag = g_ptr_array_new ();
8097 for (j = 0; j < len; ++j) {
8098 if (i < methods_len) {
8099 g_ptr_array_add (frag, methods [i]);
8104 user_data = g_new0 (gpointer, 3);
8105 user_data [0] = mono_domain_get ();
8106 user_data [1] = acfg;
8107 user_data [2] = frag;
8109 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
8110 g_ptr_array_add (threads, handle);
8114 for (i = 0; i < threads->len; ++i) {
8115 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8121 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8122 for (i = methods_len; i < acfg->methods->len; ++i) {
8123 /* This can new methods to acfg->methods */
8124 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8129 compile_asm (MonoAotCompile *acfg)
8131 char *command, *objfile;
8132 char *outfile_name, *tmp_outfile_name;
8133 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8135 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8136 #define AS_OPTIONS "--64"
8137 #elif defined(TARGET_POWERPC64)
8138 #define AS_OPTIONS "-a64 -mppc64"
8139 #define LD_OPTIONS "-m elf64ppc"
8140 #elif defined(sparc) && SIZEOF_VOID_P == 8
8141 #define AS_OPTIONS "-xarch=v9"
8142 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8143 #define AS_OPTIONS "-arch i386 -W"
8145 #define AS_OPTIONS ""
8148 #ifdef __native_client_codegen__
8149 #if defined(TARGET_AMD64)
8150 #define AS_NAME "nacl64-as"
8152 #define AS_NAME "nacl-as"
8155 #define AS_NAME "as"
8159 #define LD_OPTIONS ""
8162 #define EH_LD_OPTIONS ""
8164 if (acfg->aot_opts.asm_only) {
8165 printf ("Output file: '%s'.\n", acfg->tmpfname);
8166 if (acfg->aot_opts.static_link)
8167 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8171 if (acfg->aot_opts.static_link) {
8172 if (acfg->aot_opts.outfile)
8173 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8175 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8177 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8179 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);
8180 printf ("Executing the native assembler: %s\n", command);
8181 if (system (command) != 0) {
8189 if (acfg->aot_opts.static_link) {
8190 printf ("Output file: '%s'.\n", objfile);
8191 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8196 if (acfg->aot_opts.outfile)
8197 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8199 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8201 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8204 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8205 #elif defined(__ppc__) && defined(TARGET_MACH)
8206 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8207 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8208 command = g_strdup_printf ("gcc --shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8209 #elif defined(HOST_WIN32)
8210 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8211 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8212 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8214 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8216 printf ("Executing the native linker: %s\n", command);
8217 if (system (command) != 0) {
8218 g_free (tmp_outfile_name);
8219 g_free (outfile_name);
8227 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8228 printf ("Stripping the binary: %s\n", com);
8232 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8234 * gas generates 'mapping symbols' each time code and data is mixed, which
8235 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8237 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8238 printf ("Stripping the binary: %s\n", command);
8239 if (system (command) != 0) {
8240 g_free (tmp_outfile_name);
8241 g_free (outfile_name);
8248 rename (tmp_outfile_name, outfile_name);
8250 #if defined(TARGET_MACH)
8251 command = g_strdup_printf ("dsymutil %s", outfile_name);
8252 printf ("Generating debug symbols: %s\n", command);
8253 if (system (command) != 0) {
8258 if (!acfg->aot_opts.save_temps)
8261 g_free (tmp_outfile_name);
8262 g_free (outfile_name);
8265 if (acfg->aot_opts.save_temps)
8266 printf ("Retained input file.\n");
8268 unlink (acfg->tmpfname);
8273 static MonoAotCompile*
8274 acfg_create (MonoAssembly *ass, guint32 opts)
8276 MonoImage *image = ass->image;
8277 MonoAotCompile *acfg;
8280 acfg = g_new0 (MonoAotCompile, 1);
8281 acfg->methods = g_ptr_array_new ();
8282 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8283 acfg->method_depth = g_hash_table_new (NULL, NULL);
8284 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8285 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8286 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8287 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8288 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8289 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8290 acfg->got_patches = g_ptr_array_new ();
8291 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8292 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8293 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8294 acfg->image_hash = g_hash_table_new (NULL, NULL);
8295 acfg->image_table = g_ptr_array_new ();
8296 acfg->globals = g_ptr_array_new ();
8297 acfg->image = image;
8299 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8300 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8301 acfg->mempool = mono_mempool_new ();
8302 acfg->extra_methods = g_ptr_array_new ();
8303 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8304 acfg->unwind_ops = g_ptr_array_new ();
8305 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8306 acfg->method_order = g_ptr_array_new ();
8307 acfg->export_names = g_hash_table_new (NULL, NULL);
8308 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8309 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8310 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8311 InitializeCriticalSection (&acfg->mutex);
8317 acfg_free (MonoAotCompile *acfg)
8321 img_writer_destroy (acfg->w);
8322 for (i = 0; i < acfg->nmethods; ++i)
8324 g_free (acfg->cfgs [i]);
8325 g_free (acfg->cfgs);
8326 g_free (acfg->static_linking_symbol);
8327 g_free (acfg->got_symbol);
8328 g_free (acfg->plt_symbol);
8329 g_ptr_array_free (acfg->methods, TRUE);
8330 g_ptr_array_free (acfg->got_patches, TRUE);
8331 g_ptr_array_free (acfg->image_table, TRUE);
8332 g_ptr_array_free (acfg->globals, TRUE);
8333 g_ptr_array_free (acfg->unwind_ops, TRUE);
8334 g_hash_table_destroy (acfg->method_indexes);
8335 g_hash_table_destroy (acfg->method_depth);
8336 g_hash_table_destroy (acfg->plt_offset_to_entry);
8337 g_hash_table_destroy (acfg->patch_to_plt_entry);
8338 g_hash_table_destroy (acfg->patch_to_got_offset);
8339 g_hash_table_destroy (acfg->method_to_cfg);
8340 g_hash_table_destroy (acfg->token_info_hash);
8341 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8342 g_hash_table_destroy (acfg->image_hash);
8343 g_hash_table_destroy (acfg->unwind_info_offsets);
8344 g_hash_table_destroy (acfg->method_label_hash);
8345 g_hash_table_destroy (acfg->export_names);
8346 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8347 g_hash_table_destroy (acfg->klass_blob_hash);
8348 g_hash_table_destroy (acfg->method_blob_hash);
8349 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8350 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8351 g_free (acfg->patch_to_got_offset_by_type);
8352 mono_mempool_destroy (acfg->mempool);
8357 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8359 MonoImage *image = ass->image;
8361 MonoAotCompile *acfg;
8362 char *outfile_name, *tmp_outfile_name, *p;
8363 char llvm_stats_msg [256];
8367 #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
8368 opts &= ~MONO_OPT_GSHAREDVT;
8371 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8373 acfg = acfg_create (ass, opts);
8375 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8376 acfg->aot_opts.write_symbols = TRUE;
8377 acfg->aot_opts.ntrampolines = 1024;
8378 acfg->aot_opts.nrgctx_trampolines = 1024;
8379 acfg->aot_opts.nimt_trampolines = 128;
8380 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8381 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8382 acfg->aot_opts.llvm_path = g_strdup ("");
8384 acfg->aot_opts.use_trampolines_page = TRUE;
8387 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8389 if (acfg->aot_opts.static_link)
8390 acfg->aot_opts.autoreg = TRUE;
8392 //acfg->aot_opts.print_skipped_methods = TRUE;
8394 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8395 if (acfg->aot_opts.full_aot) {
8396 printf ("--aot=full is not supported on this platform.\n");
8401 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8402 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8406 if (acfg->aot_opts.static_link)
8407 acfg->aot_opts.asm_writer = TRUE;
8409 if (acfg->aot_opts.soft_debug) {
8410 MonoDebugOptions *opt = mini_get_debug_options ();
8412 opt->mdb_optimizations = TRUE;
8413 opt->gen_seq_points = TRUE;
8415 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8416 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8419 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8422 if (mono_use_llvm) {
8424 acfg->aot_opts.asm_writer = TRUE;
8425 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8427 if (acfg->aot_opts.soft_debug) {
8428 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8433 if (acfg->aot_opts.full_aot)
8434 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8436 load_profile_files (acfg);
8438 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8439 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8440 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8442 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8443 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8444 if (acfg->opts & MONO_OPT_GSHAREDVT)
8445 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8448 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8452 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8453 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8454 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8456 /* Get rid of characters which cannot occur in symbols */
8457 for (p = acfg->got_symbol_base; *p; ++p) {
8458 if (!(isalnum (*p) || *p == '_'))
8461 for (p = acfg->plt_symbol; *p; ++p) {
8462 if (!(isalnum (*p) || *p == '_'))
8465 for (p = acfg->assembly_name_sym; *p; ++p) {
8466 if (!(isalnum (*p) || *p == '_'))
8470 acfg->method_index = 1;
8474 if (acfg->aot_opts.full_aot)
8475 mono_set_partial_sharing_supported (TRUE);
8478 collect_methods (acfg);
8480 acfg->cfgs_size = acfg->methods->len + 32;
8481 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8483 /* PLT offset 0 is reserved for the PLT trampoline */
8484 acfg->plt_offset = 1;
8489 mono_llvm_create_aot_module (acfg->got_symbol_base);
8493 /* GOT offset 0 is reserved for the address of the current assembly */
8497 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8498 ji->type = MONO_PATCH_INFO_IMAGE;
8499 ji->data.image = acfg->image;
8501 get_got_offset (acfg, ji);
8503 /* Slot 1 is reserved for the mscorlib got addr */
8504 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8505 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8506 get_got_offset (acfg, ji);
8508 /* This is very common */
8509 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8510 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8511 get_got_offset (acfg, ji);
8513 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8514 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8515 get_got_offset (acfg, ji);
8520 compile_methods (acfg);
8524 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8530 if (acfg->aot_opts.asm_only) {
8531 if (acfg->aot_opts.outfile)
8532 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8534 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8536 acfg->tmpfname = g_strdup ("temp.s");
8539 emit_llvm_file (acfg);
8543 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8544 if (acfg->aot_opts.outfile)
8545 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8547 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8550 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8551 * it might be in another file system so the rename () won't work.
8553 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8555 acfg->fp = fopen (tmp_outfile_name, "w");
8557 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8561 acfg->w = img_writer_create (acfg->fp, TRUE);
8562 acfg->use_bin_writer = TRUE;
8565 /* Append to the .s file created by llvm */
8566 /* FIXME: Use multiple files instead */
8567 acfg->fp = fopen (acfg->tmpfname, "a+");
8569 if (acfg->aot_opts.asm_only) {
8570 if (acfg->aot_opts.outfile)
8571 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8573 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8574 acfg->fp = fopen (acfg->tmpfname, "w+");
8576 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8577 acfg->fp = fdopen (i, "w+");
8579 if (acfg->fp == 0) {
8580 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8584 acfg->w = img_writer_create (acfg->fp, FALSE);
8586 tmp_outfile_name = NULL;
8587 outfile_name = NULL;
8590 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8592 /* Compute symbols for methods */
8593 for (i = 0; i < acfg->nmethods; ++i) {
8594 if (acfg->cfgs [i]) {
8595 MonoCompile *cfg = acfg->cfgs [i];
8596 int method_index = get_method_index (acfg, cfg->orig_method);
8598 if (COMPILE_LLVM (cfg))
8599 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8600 else if (acfg->global_symbols)
8601 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8603 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8607 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
8609 * CLANG supports GAS .file/.loc directives, so emit line number information this way
8611 acfg->gas_line_numbers = TRUE;
8614 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8615 if (acfg->aot_opts.dwarf_debug && mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8616 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8619 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
8622 img_writer_emit_start (acfg->w);
8625 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
8627 if (acfg->thumb_mixed) {
8630 * This global symbol marks the end of THUMB code, and the beginning of ARM
8631 * code generated by our JIT.
8633 sprintf (symbol, "thumb_end");
8634 emit_section_change (acfg, ".text", 0);
8635 emit_alignment (acfg, 8);
8636 emit_label (acfg, symbol);
8637 emit_zero_bytes (acfg, 16);
8639 fprintf (acfg->fp, ".arm\n");
8646 emit_extra_methods (acfg);
8648 emit_trampolines (acfg);
8650 emit_class_name_table (acfg);
8652 emit_got_info (acfg);
8654 emit_exception_info (acfg);
8656 emit_unwind_info (acfg);
8658 emit_class_info (acfg);
8662 emit_image_table (acfg);
8666 emit_file_info (acfg);
8670 emit_globals (acfg);
8672 emit_autoreg (acfg);
8675 emit_dwarf_info (acfg);
8676 mono_dwarf_writer_close (acfg->dwarf);
8679 emit_mem_end (acfg);
8681 if (acfg->need_pt_gnu_stack) {
8682 /* This is required so the .so doesn't have an executable stack */
8683 /* The bin writer already emits this */
8684 if (!acfg->use_bin_writer)
8685 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
8690 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
8693 g_assert (acfg->got_offset <= acfg->final_got_size);
8696 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
8698 strcpy (llvm_stats_msg, "");
8699 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
8700 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
8701 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
8703 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
8704 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
8705 if (acfg->stats.genericcount)
8706 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
8707 if (acfg->stats.abscount)
8708 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
8709 if (acfg->stats.lmfcount)
8710 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
8711 if (acfg->stats.ocount)
8712 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
8715 res = img_writer_emit_writeout (acfg->w);
8720 if (acfg->use_bin_writer) {
8721 int err = rename (tmp_outfile_name, outfile_name);
8724 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
8728 res = compile_asm (acfg);
8735 acfg->stats.link_time = TV_ELAPSED (atv, btv);
8737 if (acfg->aot_opts.stats) {
8740 printf ("GOT slot distribution:\n");
8741 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
8742 if (acfg->stats.got_slot_types [i])
8743 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
8746 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);
8758 mono_aot_readonly_field_override (MonoClassField *field)
8764 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)