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;
136 int nrgctx_trampolines;
137 int nimt_trampolines;
138 int ngsharedvt_arg_trampolines;
139 int nrgctx_fetch_trampolines;
140 gboolean print_skipped_methods;
148 typedef struct MonoAotStats {
149 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
150 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
151 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
152 int got_slots, offsets_size;
153 int got_slot_types [MONO_PATCH_INFO_NONE];
154 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
155 int jit_time, gen_time, link_time;
158 typedef struct MonoAotCompile {
161 GHashTable *method_indexes;
162 GHashTable *method_depth;
165 GHashTable *patch_to_plt_entry;
166 GHashTable *plt_offset_to_entry;
167 GHashTable *patch_to_got_offset;
168 GHashTable **patch_to_got_offset_by_type;
169 GPtrArray *got_patches;
170 GHashTable *image_hash;
171 GHashTable *method_to_cfg;
172 GHashTable *token_info_hash;
173 GHashTable *method_to_pinvoke_import;
174 GPtrArray *extra_methods;
175 GPtrArray *image_table;
177 GPtrArray *method_order;
178 GHashTable *export_names;
179 /* Maps MonoClass* -> blob offset */
180 GHashTable *klass_blob_hash;
181 /* Maps MonoMethod* -> blob offset */
182 GHashTable *method_blob_hash;
183 guint32 *plt_got_info_offsets;
184 guint32 got_offset, plt_offset, plt_got_offset_base;
185 guint32 final_got_size;
186 /* Number of GOT entries reserved for trampolines */
187 guint32 num_trampoline_got_entries;
189 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
190 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
191 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
193 MonoAotOptions aot_opts;
197 MonoMemPool *mempool;
200 char *static_linking_symbol;
201 CRITICAL_SECTION mutex;
202 gboolean use_bin_writer;
204 MonoDwarfWriter *dwarf;
208 GHashTable *unwind_info_offsets;
209 GPtrArray *unwind_ops;
210 guint32 unwind_info_offset;
211 char *got_symbol_base;
214 GHashTable *method_label_hash;
215 const char *temp_prefix;
216 const char *user_symbol_prefix;
217 const char *llvm_label_prefix;
218 guint32 label_generator;
220 MonoAotFileFlags flags;
221 MonoDynamicStream blob;
222 MonoClass **typespec_classes;
225 char *assembly_name_sym;
226 GHashTable *plt_entry_debug_sym_cache;
227 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
228 GHashTable *ginst_hash;
229 gboolean global_symbols;
230 gboolean direct_method_addresses;
235 char *symbol, *llvm_symbol, *debug_sym;
237 gboolean jit_used, llvm_used;
240 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
241 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
243 /* This points to the current acfg in LLVM mode */
244 static MonoAotCompile *llvm_acfg;
246 #ifdef HAVE_ARRAY_ELEM_INIT
247 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
248 #define MSGSTRFIELD1(line) str##line
249 static const struct msgstr_t {
250 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
251 #include "patch-info.h"
254 #define PATCH_INFO(a,b) b,
255 #include "patch-info.h"
258 static const gint16 opidx [] = {
259 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
260 #include "patch-info.h"
264 static G_GNUC_UNUSED const char*
265 get_patch_name (int info)
267 return (const char*)&opstr + opidx [info];
271 #define PATCH_INFO(a,b) b,
272 static const char* const
273 patch_types [MONO_PATCH_INFO_NUM + 1] = {
274 #include "patch-info.h"
278 static G_GNUC_UNUSED const char*
279 get_patch_name (int info)
281 return patch_types [info];
287 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
289 /* Wrappers around the image writer functions */
292 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
294 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
298 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
300 img_writer_emit_push_section (acfg->w, section_name, subsection);
304 emit_pop_section (MonoAotCompile *acfg)
306 img_writer_emit_pop_section (acfg->w);
310 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
312 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
316 emit_label (MonoAotCompile *acfg, const char *name)
318 img_writer_emit_label (acfg->w, name);
322 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
324 img_writer_emit_bytes (acfg->w, buf, size);
328 emit_string (MonoAotCompile *acfg, const char *value)
330 img_writer_emit_string (acfg->w, value);
334 emit_line (MonoAotCompile *acfg)
336 img_writer_emit_line (acfg->w);
340 emit_alignment (MonoAotCompile *acfg, int size)
342 img_writer_emit_alignment (acfg->w, size);
346 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
348 img_writer_emit_pointer_unaligned (acfg->w, target);
352 emit_pointer (MonoAotCompile *acfg, const char *target)
354 img_writer_emit_pointer (acfg->w, target);
358 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
360 if (prefix [0] != '\0') {
361 char *s = g_strdup_printf ("%s%s", prefix, target);
362 img_writer_emit_pointer (acfg->w, s);
365 img_writer_emit_pointer (acfg->w, target);
370 emit_int16 (MonoAotCompile *acfg, int value)
372 img_writer_emit_int16 (acfg->w, value);
376 emit_int32 (MonoAotCompile *acfg, int value)
378 img_writer_emit_int32 (acfg->w, value);
382 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
384 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
388 emit_zero_bytes (MonoAotCompile *acfg, int num)
390 img_writer_emit_zero_bytes (acfg->w, num);
394 emit_byte (MonoAotCompile *acfg, guint8 val)
396 img_writer_emit_byte (acfg->w, val);
399 #ifdef __native_client_codegen__
401 emit_nacl_call_alignment (MonoAotCompile *acfg)
403 img_writer_emit_nacl_call_alignment (acfg->w);
407 static G_GNUC_UNUSED void
408 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
410 img_writer_emit_global (acfg->w, name, func);
414 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
416 if (acfg->aot_opts.no_dlsym) {
417 g_ptr_array_add (acfg->globals, g_strdup (name));
418 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
420 img_writer_emit_global (acfg->w, name, func);
425 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
427 img_writer_emit_symbol_size (acfg->w, name, end_label);
431 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
433 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
435 /* On apple, all symbols need to be aligned to avoid warnings from ld */
436 emit_alignment (acfg, 4);
438 img_writer_emit_label (acfg->w, name);
439 img_writer_emit_string (acfg->w, value);
442 static G_GNUC_UNUSED void
443 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
446 guint8 b = value & 0x7f;
448 if (value != 0) /* more bytes to come */
454 static G_GNUC_UNUSED void
455 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
458 gboolean negative = (value < 0);
465 /* the following is unnecessary if the
466 * implementation of >>= uses an arithmetic rather
467 * than logical shift for a signed left operand
471 value |= - ((gint64)1 <<(size - 7));
472 /* sign bit of byte is second high order bit (0x40) */
473 if ((value == 0 && !(byte & 0x40)) ||
474 (value == -1 && (byte & 0x40)))
478 emit_byte (acfg, byte);
482 static G_GNUC_UNUSED void
483 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
488 guint8 b = value & 0x7f;
490 if (value != 0) /* more bytes to come */
498 static G_GNUC_UNUSED void
499 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
502 gboolean negative = (value < 0);
510 /* the following is unnecessary if the
511 * implementation of >>= uses an arithmetic rather
512 * than logical shift for a signed left operand
516 value |= - (1 <<(size - 7));
517 /* sign bit of byte is second high order bit (0x40) */
518 if ((value == 0 && !(byte & 0x40)) ||
519 (value == -1 && (byte & 0x40)))
529 /* ARCHITECTURE SPECIFIC CODE */
531 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
532 #define EMIT_DWARF_INFO 1
535 #if defined(TARGET_ARM)
536 #define AOT_FUNC_ALIGNMENT 4
538 #define AOT_FUNC_ALIGNMENT 16
540 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
541 #undef AOT_FUNC_ALIGNMENT
542 #define AOT_FUNC_ALIGNMENT 32
545 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
546 #define PPC_LD_OP "ld"
547 #define PPC_LDX_OP "ldx"
549 #define PPC_LD_OP "lwz"
550 #define PPC_LDX_OP "lwzx"
554 #define AOT_TARGET_STR "AMD64"
559 #define AOT_TARGET_STR "ARM (MACH)"
561 #define AOT_TARGET_STR "ARM (!MACH)"
565 #ifdef TARGET_POWERPC64
566 #ifdef __mono_ilp32__
567 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
569 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
572 #ifdef TARGET_POWERPC
573 #ifdef __mono_ilp32__
574 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
576 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
583 #define AOT_TARGET_STR "X86 (WIN32)"
584 #elif defined(__native_client_codegen__)
585 #define AOT_TARGET_STR "X86 (native client codegen)"
587 #define AOT_TARGET_STR "X86 (!native client codegen)"
591 #ifndef AOT_TARGET_STR
592 #define AOT_TARGET_STR ""
596 arch_init (MonoAotCompile *acfg)
598 acfg->llc_args = g_string_new ("");
599 acfg->as_args = g_string_new ("");
602 * The prefix LLVM likes to put in front of symbol names on darwin.
603 * The mach-os specs require this for globals, but LLVM puts them in front of all
604 * symbols. We need to handle this, since we need to refer to LLVM generated
607 acfg->llvm_label_prefix = "";
608 acfg->user_symbol_prefix = "";
611 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
612 g_string_append (acfg->llc_args, "-mattr=+v6");
615 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
616 g_string_append (acfg->as_args, " -mfpu=vfp3");
618 g_string_append (acfg->llc_args, " -soft-float");
621 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
622 acfg->thumb_mixed = TRUE;
624 if (acfg->aot_opts.mtriple)
625 mono_arch_set_target (acfg->aot_opts.mtriple);
629 acfg->user_symbol_prefix = "_";
630 acfg->llvm_label_prefix = "_";
631 acfg->need_no_dead_strip = TRUE;
634 #if defined(__linux__) && !defined(TARGET_ARM)
635 acfg->need_pt_gnu_stack = TRUE;
639 acfg->direct_method_addresses = TRUE;
640 acfg->global_symbols = TRUE;
645 * arch_emit_direct_call:
647 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
651 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, int *call_size)
653 #if defined(TARGET_X86) || defined(TARGET_AMD64)
654 /* Need to make sure this is exactly 5 bytes long */
655 if (external && !acfg->use_bin_writer) {
656 img_writer_emit_unset_mode (acfg->w);
657 fprintf (acfg->fp, "call %s\n", target);
659 emit_byte (acfg, '\xe8');
660 emit_symbol_diff (acfg, target, ".", -4);
663 #elif defined(TARGET_ARM)
664 if (acfg->use_bin_writer) {
671 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
672 emit_bytes (acfg, buf, 4);
674 img_writer_emit_unset_mode (acfg->w);
675 fprintf (acfg->fp, "bl %s\n", target);
678 #elif defined(TARGET_POWERPC)
679 if (acfg->use_bin_writer) {
680 g_assert_not_reached ();
682 img_writer_emit_unset_mode (acfg->w);
683 fprintf (acfg->fp, "bl %s\n", target);
687 g_assert_not_reached ();
693 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
695 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
696 * in in the 2. slot of every GOT, and require every method to place the GOT
697 * address in r30, even when it doesn't access the GOT otherwise. This way,
698 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
703 * PPC64 uses function descriptors which greatly complicate all code, since
704 * these are used very inconsistently in the runtime. Some functions like
705 * mono_compile_method () return ftn descriptors, while others like the
706 * trampoline creation functions do not.
707 * We assume that all GOT slots contain function descriptors, and create
708 * descriptors in aot-runtime.c when needed.
709 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
710 * from function descriptors, we could do the same, but it would require
711 * rewriting all the ppc/aot code to handle function descriptors properly.
712 * So instead, we use the same approach as on PPC32.
713 * This is a horrible mess, but fixing it would probably lead to an even bigger
719 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
722 #ifdef MONO_ARCH_AOT_SUPPORTED
724 * arch_emit_got_offset:
726 * The memory pointed to by CODE should hold native code for computing the GOT
727 * address. Emit this code while patching it with the offset between code and
728 * the GOT. CODE_SIZE is set to the number of bytes emitted.
731 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
733 #if defined(TARGET_POWERPC64)
734 g_assert (!acfg->use_bin_writer);
735 img_writer_emit_unset_mode (acfg->w);
737 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
738 * unsupported relocations. So we store the got address into the .Lgot_addr
739 * symbol which is in the text segment, compute its address, and load it.
741 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
742 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
743 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
744 fprintf (acfg->fp, "add 30, 30, 0\n");
745 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
746 acfg->label_generator ++;
748 #elif defined(TARGET_POWERPC)
749 g_assert (!acfg->use_bin_writer);
750 img_writer_emit_unset_mode (acfg->w);
751 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
752 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
753 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
754 acfg->label_generator ++;
757 guint32 offset = mono_arch_get_patch_offset (code);
758 emit_bytes (acfg, code, offset);
759 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
761 *code_size = offset + 4;
766 * arch_emit_got_access:
768 * The memory pointed to by CODE should hold native code for loading a GOT
769 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
770 * CODE_SIZE is set to the number of bytes emitted.
773 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
775 /* Emit beginning of instruction */
776 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
778 /* Emit the offset */
780 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
781 *code_size = mono_arch_get_patch_offset (code) + 4;
782 #elif defined(TARGET_X86)
783 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
784 *code_size = mono_arch_get_patch_offset (code) + 4;
785 #elif defined(TARGET_ARM)
786 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
787 *code_size = mono_arch_get_patch_offset (code) + 4;
788 #elif defined(TARGET_POWERPC)
794 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
795 g_assert (code - buf == 8);
796 emit_bytes (acfg, buf, code - buf);
797 *code_size = code - buf;
800 g_assert_not_reached ();
807 * arch_emit_plt_entry:
809 * Emit code for the PLT entry with index INDEX.
812 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
814 #if defined(TARGET_X86)
815 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
816 #if defined(__default_codegen__)
817 /* jmp *<offset>(%ebx) */
818 emit_byte (acfg, 0xff);
819 emit_byte (acfg, 0xa3);
820 emit_int32 (acfg, offset);
821 /* Used by mono_aot_get_plt_info_offset */
822 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
823 #elif defined(__native_client_codegen__)
824 const guint8 kSizeOfNaClJmp = 11;
825 guint8 bytes[kSizeOfNaClJmp];
826 guint8 *pbytes = &bytes[0];
828 x86_jump_membase32 (pbytes, X86_EBX, offset);
829 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
830 /* four bytes of data, used by mono_arch_patch_plt_entry */
831 /* For Native Client, make this work with data embedded in push. */
832 emit_byte (acfg, 0x68); /* hide data in a push */
833 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
834 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
835 #endif /*__native_client_codegen__*/
836 #elif defined(TARGET_AMD64)
837 #if defined(__default_codegen__)
839 * We can't emit jumps because they are 32 bits only so they can't be patched.
840 * So we make indirect calls through GOT entries which are patched by the AOT
841 * loader to point to .Lpd entries.
843 /* jmpq *<offset>(%rip) */
844 emit_byte (acfg, '\xff');
845 emit_byte (acfg, '\x25');
846 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
847 /* Used by mono_aot_get_plt_info_offset */
848 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
849 #elif defined(__native_client_codegen__)
851 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
852 guint8 *code = buf_aligned;
854 /* mov <OFFSET>(%rip), %r11d */
855 emit_byte (acfg, '\x45');
856 emit_byte (acfg, '\x8b');
857 emit_byte (acfg, '\x1d');
858 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
860 amd64_jump_reg (code, AMD64_R11);
861 /* This should be constant for the plt patch */
862 g_assert ((size_t)(code-buf_aligned) == 10);
863 emit_bytes (acfg, buf_aligned, code - buf_aligned);
865 /* Hide data in a push imm32 so it passes validation */
866 emit_byte (acfg, 0x68); /* push */
867 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
868 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
869 #endif /*__native_client_codegen__*/
870 #elif defined(TARGET_ARM)
875 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
876 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
877 emit_bytes (acfg, buf, code - buf);
878 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
879 /* Used by mono_aot_get_plt_info_offset */
880 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
881 #elif defined(TARGET_POWERPC)
882 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
884 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
885 g_assert (!acfg->use_bin_writer);
886 img_writer_emit_unset_mode (acfg->w);
887 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
888 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
889 fprintf (acfg->fp, "add 11, 11, 30\n");
890 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
891 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
892 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
893 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
895 fprintf (acfg->fp, "mtctr 11\n");
896 fprintf (acfg->fp, "bctr\n");
897 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
899 g_assert_not_reached ();
904 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
906 #if defined(TARGET_ARM)
908 /* LLVM calls the PLT entries using bl, so emit a stub */
909 /* FIXME: Too much overhead on every call */
910 fprintf (acfg->fp, ".thumb_func\n");
911 fprintf (acfg->fp, "bx pc\n");
912 fprintf (acfg->fp, "nop\n");
913 fprintf (acfg->fp, ".arm\n");
915 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
916 /* The caller already transitioned to thumb */
917 /* The code below should be 12 bytes long */
918 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
919 /* thumb can't encode ld pc, [pc, ip] */
920 fprintf (acfg->fp, "add ip, pc, ip\n");
921 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
922 fprintf (acfg->fp, "bx ip\n");
923 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
924 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
926 g_assert_not_reached ();
931 * arch_emit_specific_trampoline_pages:
933 * Emits a page full of trampolines: each trampoline uses its own address to
934 * lookup both the generic trampoline code and the data argument.
935 * This page can be remapped in process multiple times so we can get an
936 * unlimited number of trampolines.
937 * Specifically this implementation uses the following trick: two memory pages
938 * are allocated, with the first containing the data and the second containing the trampolines.
939 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
940 * implementation does all the lifting.
941 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
942 * on the arm 32 bit system.
945 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
947 #if defined(TARGET_ARM)
950 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
952 #define COMMON_TRAMP_SIZE 16
953 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
954 int imm8, rot_amount;
957 if (!acfg->aot_opts.use_trampolines_page)
960 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
961 emit_alignment (acfg, mono_pagesize ());
962 emit_global (acfg, symbol, TRUE);
963 emit_label (acfg, symbol);
965 /* emit the generic code first, the trampoline address + 8 is in the lr register */
967 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
968 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
969 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
970 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
972 g_assert (code - buf == COMMON_TRAMP_SIZE);
975 emit_bytes (acfg, buf, code - buf);
977 for (i = 0; i < count; ++i) {
979 ARM_PUSH (code, 0x5fff);
981 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
982 g_assert (code - buf == 8);
983 emit_bytes (acfg, buf, code - buf);
986 /* now the rgctx trampolines: each specific trampolines puts in the ip register
987 * the instruction pointer address, so the generic trampoline at the start of the page
988 * subtracts 4096 to get to the data page and loads the values
989 * We again fit the generic trampiline in 16 bytes.
991 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
992 emit_global (acfg, symbol, TRUE);
993 emit_label (acfg, symbol);
995 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
996 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
997 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
998 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1000 g_assert (code - buf == COMMON_TRAMP_SIZE);
1003 emit_bytes (acfg, buf, code - buf);
1005 for (i = 0; i < count; ++i) {
1007 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1009 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1010 g_assert (code - buf == 8);
1011 emit_bytes (acfg, buf, code - buf);
1015 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1017 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1018 emit_global (acfg, symbol, TRUE);
1019 emit_label (acfg, symbol);
1021 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1022 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1023 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1024 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1025 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1026 g_assert (code - buf == COMMON_TRAMP_SIZE);
1028 emit_bytes (acfg, buf, code - buf);
1030 for (i = 0; i < count; ++i) {
1032 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1034 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1035 g_assert (code - buf == 8);
1036 emit_bytes (acfg, buf, code - buf);
1039 /* now the imt trampolines: each specific trampolines puts in the ip register
1040 * the instruction pointer address, so the generic trampoline at the start of the page
1041 * subtracts 4096 to get to the data page and loads the values
1042 * We again fit the generic trampiline in 16 bytes.
1044 #define IMT_TRAMP_SIZE 72
1045 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1046 emit_global (acfg, symbol, TRUE);
1047 emit_label (acfg, symbol);
1049 /* Need at least two free registers, plus a slot for storing the pc */
1050 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1052 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1053 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1054 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1056 /* The IMT method is in v5, r0 has the imt array address */
1059 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1060 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1061 imt_found_check = code;
1062 ARM_B_COND (code, ARMCOND_EQ, 0);
1064 /* End-of-loop check */
1065 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1066 loop_end_check = code;
1067 ARM_B_COND (code, ARMCOND_EQ, 0);
1070 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1071 loop_branch_back = code;
1073 arm_patch (loop_branch_back, loop_start);
1076 arm_patch (imt_found_check, code);
1077 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1078 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1079 /* Save it to the third stack slot */
1080 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1081 /* Restore the registers and branch */
1082 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1085 arm_patch (loop_end_check, code);
1086 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1087 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1088 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1092 g_assert (code - buf == IMT_TRAMP_SIZE);
1093 emit_bytes (acfg, buf, code - buf);
1095 for (i = 0; i < count; ++i) {
1097 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1099 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1100 g_assert (code - buf == 8);
1101 emit_bytes (acfg, buf, code - buf);
1107 * arch_emit_specific_trampoline:
1109 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1110 * two GOT slots which contain the generic trampoline address and the trampoline
1111 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1114 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1117 * The trampolines created here are variations of the specific
1118 * trampolines created in mono_arch_create_specific_trampoline (). The
1120 * - the generic trampoline address is taken from a got slot.
1121 * - the offset of the got slot where the trampoline argument is stored
1122 * is embedded in the instruction stream, and the generic trampoline
1123 * can load the argument by loading the offset, adding it to the
1124 * address of the trampoline to get the address of the got slot, and
1125 * loading the argument from there.
1126 * - all the trampolines should be of the same length.
1128 #if defined(TARGET_AMD64)
1129 #if defined(__default_codegen__)
1130 /* This should be exactly 16 bytes long */
1132 /* call *<offset>(%rip) */
1133 emit_byte (acfg, '\x41');
1134 emit_byte (acfg, '\xff');
1135 emit_byte (acfg, '\x15');
1136 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1137 /* This should be relative to the start of the trampoline */
1138 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1139 emit_zero_bytes (acfg, 5);
1140 #elif defined(__native_client_codegen__)
1142 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1143 guint8 *code = buf_aligned;
1148 /* Emit this call in 'code' so we can find out how long it is. */
1149 amd64_call_reg (code, AMD64_R11);
1150 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1151 call_len = code - call_start;
1153 /* The tramp_size is twice the NaCl alignment because it starts with */
1154 /* a call which needs to be aligned to the end of the boundary. */
1155 *tramp_size = kNaClAlignment*2;
1157 /* Emit nops to align call site below which is 7 bytes plus */
1158 /* the length of the call sequence emitted above. */
1159 /* Note: this requires the specific trampoline starts on a */
1160 /* kNaclAlignedment aligned address, which it does because */
1161 /* it's its own function that is aligned. */
1162 guint8 nop_buf[256];
1163 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1164 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1165 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1167 /* The trampoline is stored at the offset'th pointer, the -4 is */
1168 /* present because RIP relative addressing starts at the end of */
1169 /* the current instruction, while the label "." is relative to */
1170 /* the beginning of the current asm location, which in this case */
1171 /* is not the mov instruction, but the offset itself, due to the */
1172 /* way the bytes and ints are emitted here. */
1173 got_offset = (offset * sizeof(gpointer)) - 4;
1175 /* mov <OFFSET>(%rip), %r11d */
1176 emit_byte (acfg, '\x45');
1177 emit_byte (acfg, '\x8b');
1178 emit_byte (acfg, '\x1d');
1179 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1182 emit_bytes (acfg, call_start, call_len);
1184 /* The arg is stored at the offset+1 pointer, relative to beginning */
1185 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1186 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1188 /* We can't emit this data directly, hide in a "push imm32" */
1189 emit_byte (acfg, '\x68'); /* push */
1190 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1191 emit_alignment (acfg, kNaClAlignment);
1192 #endif /*__native_client_codegen__*/
1193 #elif defined(TARGET_ARM)
1197 /* This should be exactly 20 bytes long */
1200 ARM_PUSH (code, 0x5fff);
1201 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1202 /* Load the value from the GOT */
1203 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1205 ARM_BLX_REG (code, ARMREG_R1);
1207 g_assert (code - buf == 16);
1210 emit_bytes (acfg, buf, code - buf);
1212 * Only one offset is needed, since the second one would be equal to the
1215 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1216 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1217 #elif defined(TARGET_POWERPC)
1224 g_assert (!acfg->use_bin_writer);
1227 * PPC has no ip relative addressing, so we need to compute the address
1228 * of the mscorlib got. That is slow and complex, so instead, we store it
1229 * in the second got slot of every aot image. The caller already computed
1230 * the address of its got and placed it into r30.
1232 img_writer_emit_unset_mode (acfg->w);
1233 /* Load mscorlib got address */
1234 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1235 /* Load generic trampoline address */
1236 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1237 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1238 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1239 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1240 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1242 fprintf (acfg->fp, "mtctr 11\n");
1243 /* Load trampoline argument */
1244 /* On ppc, we pass it normally to the generic trampoline */
1245 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1246 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1247 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1248 /* Branch to generic trampoline */
1249 fprintf (acfg->fp, "bctr\n");
1251 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1252 *tramp_size = 10 * 4;
1254 *tramp_size = 9 * 4;
1256 #elif defined(TARGET_X86)
1260 /* Similar to the PPC code above */
1262 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1264 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1265 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1266 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1270 /* Load mscorlib got address */
1271 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1272 /* Push trampoline argument */
1273 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1274 /* Load generic trampoline address */
1275 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1276 /* Branch to generic trampoline */
1277 x86_jump_reg (code, X86_ECX);
1279 #ifdef __native_client_codegen__
1281 /* emit nops to next 32 byte alignment */
1282 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1283 while (code < (buf + a)) x86_nop(code);
1286 emit_bytes (acfg, buf, code - buf);
1288 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1289 g_assert (code - buf == *tramp_size);
1291 g_assert_not_reached ();
1296 * arch_emit_unbox_trampoline:
1298 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1299 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1302 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1304 #if defined(TARGET_AMD64)
1309 this_reg = mono_arch_get_this_arg_reg (NULL);
1311 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1313 emit_bytes (acfg, buf, code - buf);
1315 emit_byte (acfg, '\xe9');
1316 emit_symbol_diff (acfg, call_target, ".", -4);
1317 #elif defined(TARGET_X86)
1324 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1326 emit_bytes (acfg, buf, code - buf);
1329 emit_byte (acfg, '\xe9');
1330 emit_symbol_diff (acfg, call_target, ".", -4);
1331 #elif defined(TARGET_ARM)
1335 if (acfg->thumb_mixed && cfg->compile_llvm) {
1336 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1337 fprintf (acfg->fp, "b %s\n", call_target);
1338 fprintf (acfg->fp, ".arm\n");
1344 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1346 emit_bytes (acfg, buf, code - buf);
1347 /* jump to method */
1348 if (acfg->use_bin_writer) {
1355 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1356 emit_bytes (acfg, buf, 4);
1358 if (acfg->thumb_mixed && cfg->compile_llvm)
1359 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1361 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1363 #elif defined(TARGET_POWERPC)
1366 g_assert (!acfg->use_bin_writer);
1368 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1369 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1371 g_assert_not_reached ();
1376 * arch_emit_static_rgctx_trampoline:
1378 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1379 * two GOT slots which contain the rgctx argument, and the method to jump to.
1380 * TRAMP_SIZE is set to the size of the emitted trampoline.
1381 * These kinds of trampolines cannot be enumerated statically, since there could
1382 * be one trampoline per method instantiation, so we emit the same code for all
1383 * trampolines, and parameterize them using two GOT slots.
1386 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1388 #if defined(TARGET_AMD64)
1389 #if defined(__default_codegen__)
1390 /* This should be exactly 13 bytes long */
1393 /* mov <OFFSET>(%rip), %r10 */
1394 emit_byte (acfg, '\x4d');
1395 emit_byte (acfg, '\x8b');
1396 emit_byte (acfg, '\x15');
1397 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1399 /* jmp *<offset>(%rip) */
1400 emit_byte (acfg, '\xff');
1401 emit_byte (acfg, '\x25');
1402 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1403 #elif defined(__native_client_codegen__)
1405 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1406 guint8 *code = buf_aligned;
1408 /* mov <OFFSET>(%rip), %r10d */
1409 emit_byte (acfg, '\x45');
1410 emit_byte (acfg, '\x8b');
1411 emit_byte (acfg, '\x15');
1412 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1414 /* mov <OFFSET>(%rip), %r11d */
1415 emit_byte (acfg, '\x45');
1416 emit_byte (acfg, '\x8b');
1417 emit_byte (acfg, '\x1d');
1418 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1421 amd64_jump_reg (code, AMD64_R11);
1422 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1424 emit_alignment (acfg, kNaClAlignment);
1425 *tramp_size = kNaClAlignment;
1426 #endif /*__native_client_codegen__*/
1428 #elif defined(TARGET_ARM)
1432 /* This should be exactly 24 bytes long */
1435 /* Load rgctx value */
1436 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1437 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1438 /* Load branch addr + branch */
1439 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1440 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1442 g_assert (code - buf == 16);
1445 emit_bytes (acfg, buf, code - buf);
1446 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1447 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1448 #elif defined(TARGET_POWERPC)
1455 g_assert (!acfg->use_bin_writer);
1458 * PPC has no ip relative addressing, so we need to compute the address
1459 * of the mscorlib got. That is slow and complex, so instead, we store it
1460 * in the second got slot of every aot image. The caller already computed
1461 * the address of its got and placed it into r30.
1463 img_writer_emit_unset_mode (acfg->w);
1464 /* Load mscorlib got address */
1465 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1467 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1468 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1469 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1470 /* Load target address */
1471 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1472 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1473 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1474 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1475 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1476 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1478 fprintf (acfg->fp, "mtctr 11\n");
1479 /* Branch to the target address */
1480 fprintf (acfg->fp, "bctr\n");
1482 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1483 *tramp_size = 11 * 4;
1485 *tramp_size = 9 * 4;
1488 #elif defined(TARGET_X86)
1492 /* Similar to the PPC code above */
1494 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1497 /* Load mscorlib got address */
1498 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1500 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1501 /* Branch to the target address */
1502 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1504 #ifdef __native_client_codegen__
1506 /* emit nops to next 32 byte alignment */
1507 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1508 while (code < (buf + a)) x86_nop(code);
1512 emit_bytes (acfg, buf, code - buf);
1514 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1515 g_assert (code - buf == *tramp_size);
1517 g_assert_not_reached ();
1522 * arch_emit_imt_thunk:
1524 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1525 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1526 * key is the IMT key, and ptr holds the address of a memory location holding
1527 * the address to branch to if the IMT arg matches the key. The array is
1528 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1530 * TRAMP_SIZE is set to the size of the emitted trampoline.
1533 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1535 #if defined(TARGET_AMD64)
1537 #if defined(__native_client_codegen__)
1540 guint8 *labels [16];
1542 guint8 *mov_buf_ptr = mov_buf;
1544 const int kSizeOfMove = 7;
1545 #if defined(__default_codegen__)
1546 code = buf = g_malloc (256);
1547 #elif defined(__native_client_codegen__)
1548 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1549 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1550 /* The RIP relative move below is emitted first */
1555 /* FIXME: Optimize this, i.e. use binary search etc. */
1556 /* Maybe move the body into a separate function (slower, but much smaller) */
1558 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1561 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1563 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1566 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1568 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1571 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1572 amd64_jump_code (code, labels [0]);
1575 mono_amd64_patch (labels [2], code);
1576 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1577 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1580 mono_amd64_patch (labels [1], code);
1581 /* Load fail tramp */
1582 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1583 /* Check if there is a fail tramp */
1584 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1586 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1587 /* Jump to fail tramp */
1588 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1591 mono_amd64_patch (labels [3], code);
1592 x86_breakpoint (code);
1594 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1595 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1596 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1597 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1598 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1599 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1601 emit_bytes (acfg, buf, code - buf);
1603 *tramp_size = code - buf + kSizeOfMove;
1604 #if defined(__native_client_codegen__)
1605 /* The tramp will be padded to the next kNaClAlignment bundle. */
1606 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1609 #if defined(__default_codegen__)
1611 #elif defined(__native_client_codegen__)
1615 #elif defined(TARGET_X86)
1617 #ifdef __native_client_codegen__
1620 guint8 *labels [16];
1622 #if defined(__default_codegen__)
1623 code = buf = g_malloc (256);
1624 #elif defined(__native_client_codegen__)
1625 buf_alloc = g_malloc (256 + kNaClAlignment);
1626 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1629 /* Allocate a temporary stack slot */
1630 x86_push_reg (code, X86_EAX);
1632 x86_push_reg (code, X86_EAX);
1634 /* Load mscorlib got address */
1635 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1637 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1640 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1642 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1645 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1647 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1650 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1651 x86_jump_code (code, labels [0]);
1654 mono_x86_patch (labels [2], code);
1655 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1656 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1657 /* Save the target address to the temporary stack location */
1658 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1660 x86_pop_reg (code, X86_EAX);
1661 /* Jump to the target address */
1665 mono_x86_patch (labels [1], code);
1666 /* Load fail tramp */
1667 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1668 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1670 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1671 /* Jump to fail tramp */
1672 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1673 x86_pop_reg (code, X86_EAX);
1677 mono_x86_patch (labels [3], code);
1678 x86_breakpoint (code);
1680 #ifdef __native_client_codegen__
1682 /* emit nops to next 32 byte alignment */
1683 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1684 while (code < (buf + a)) x86_nop(code);
1687 emit_bytes (acfg, buf, code - buf);
1689 *tramp_size = code - buf;
1691 #if defined(__default_codegen__)
1693 #elif defined(__native_client_codegen__)
1697 #elif defined(TARGET_ARM)
1699 guint8 *code, *code2, *labels [16];
1703 /* The IMT method is in v5 */
1705 /* Need at least two free registers, plus a slot for storing the pc */
1706 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1708 /* Load the parameter from the GOT */
1709 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1710 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1713 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1714 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1716 ARM_B_COND (code, ARMCOND_EQ, 0);
1718 /* End-of-loop check */
1719 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1721 ARM_B_COND (code, ARMCOND_EQ, 0);
1724 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1727 arm_patch (labels [4], labels [1]);
1730 arm_patch (labels [2], code);
1731 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1732 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1733 /* Save it to the third stack slot */
1734 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1735 /* Restore the registers and branch */
1736 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1739 arm_patch (labels [3], code);
1740 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1741 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1742 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1746 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1748 emit_bytes (acfg, buf, code - buf);
1749 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1751 *tramp_size = code - buf + 4;
1752 #elif defined(TARGET_POWERPC)
1754 guint8 *code, *labels [16];
1758 /* Load the mscorlib got address */
1759 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1760 /* Load the parameter from the GOT */
1761 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1762 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1764 /* Load and check key */
1766 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1767 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1769 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1771 /* End-of-loop check */
1772 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1774 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1777 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1780 mono_ppc_patch (labels [4], labels [1]);
1783 mono_ppc_patch (labels [2], code);
1784 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1785 /* r11 now contains the value of the vtable slot */
1786 /* this is not a function descriptor on ppc64 */
1787 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1788 ppc_mtctr (code, ppc_r11);
1789 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1792 mono_ppc_patch (labels [3], code);
1796 *tramp_size = code - buf;
1798 emit_bytes (acfg, buf, code - buf);
1800 g_assert_not_reached ();
1805 * arch_emit_gsharedvt_arg_trampoline:
1807 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1808 * two GOT slots which contain the argument, and the code to jump to.
1809 * TRAMP_SIZE is set to the size of the emitted trampoline.
1810 * These kinds of trampolines cannot be enumerated statically, since there could
1811 * be one trampoline per method instantiation, so we emit the same code for all
1812 * trampolines, and parameterize them using two GOT slots.
1815 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1817 #if defined(TARGET_X86)
1821 /* Similar to the PPC code above */
1823 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1826 /* Load mscorlib got address */
1827 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1829 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1830 /* Branch to the target address */
1831 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1833 #ifdef __native_client_codegen__
1835 /* emit nops to next 32 byte alignment */
1836 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1837 while (code < (buf + a)) x86_nop(code);
1841 emit_bytes (acfg, buf, code - buf);
1843 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1844 g_assert (code - buf == *tramp_size);
1845 #elif defined(TARGET_ARM)
1849 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1850 /* Similar to arch_emit_specific_trampoline () */
1853 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1854 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1855 /* Load the arg value from the GOT */
1856 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1857 /* Load the addr from the GOT */
1858 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1860 ARM_BX (code, ARMREG_R1);
1862 g_assert (code - buf == 20);
1865 emit_bytes (acfg, buf, code - buf);
1866 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1868 g_assert_not_reached ();
1873 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1875 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1876 /* Based on code generated by gcc */
1877 img_writer_emit_unset_mode (acfg->w);
1880 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1881 ".section .ctors,\"aw\",@progbits\n"
1885 ".section .opd,\"aw\"\n"
1888 ".long .%s,.TOC.@tocbase32\n"
1891 ".type .%s,@function\n"
1893 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1895 ".section .ctors,\"aw\",@progbits\n"
1899 ".section .opd,\"aw\"\n"
1902 ".long .%1$s,.TOC.@tocbase32\n"
1903 ".size %1$s,.-%1$s\n"
1905 ".type .%1$s,@function\n"
1907 ".%1$s:\n", symbol);
1918 "lis 3, .Lglobals@h\n"
1919 "ori 3, 3, .Lglobals@l\n"
1920 "bl .mono_aot_register_module\n"
1928 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1930 ".size .%s,.-.%s\n", symbol, symbol);
1933 ".size .%1$s,.-.%1$s\n", symbol);
1939 /* END OF ARCH SPECIFIC CODE */
1942 mono_get_field_token (MonoClassField *field)
1944 MonoClass *klass = field->parent;
1947 for (i = 0; i < klass->field.count; ++i) {
1948 if (field == &klass->fields [i])
1949 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1952 g_assert_not_reached ();
1957 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1961 //printf ("ENCODE: %d 0x%x.\n", value, value);
1964 * Same encoding as the one used in the metadata, extended to handle values
1965 * greater than 0x1fffffff.
1967 if ((value >= 0) && (value <= 127))
1969 else if ((value >= 0) && (value <= 16383)) {
1970 p [0] = 0x80 | (value >> 8);
1971 p [1] = value & 0xff;
1973 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1974 p [0] = (value >> 24) | 0xc0;
1975 p [1] = (value >> 16) & 0xff;
1976 p [2] = (value >> 8) & 0xff;
1977 p [3] = value & 0xff;
1982 p [1] = (value >> 24) & 0xff;
1983 p [2] = (value >> 16) & 0xff;
1984 p [3] = (value >> 8) & 0xff;
1985 p [4] = value & 0xff;
1993 stream_init (MonoDynamicStream *sh)
1996 sh->alloc_size = 4096;
1997 sh->data = g_malloc (4096);
1999 /* So offsets are > 0 */
2005 make_room_in_stream (MonoDynamicStream *stream, int size)
2007 if (size <= stream->alloc_size)
2010 while (stream->alloc_size <= size) {
2011 if (stream->alloc_size < 4096)
2012 stream->alloc_size = 4096;
2014 stream->alloc_size *= 2;
2017 stream->data = g_realloc (stream->data, stream->alloc_size);
2021 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2025 make_room_in_stream (stream, stream->index + len);
2026 memcpy (stream->data + stream->index, data, len);
2027 idx = stream->index;
2028 stream->index += len;
2035 * Add data to the binary blob inside the aot image. Returns the offset inside the
2036 * blob where the data was stored.
2039 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2041 if (acfg->blob.alloc_size == 0)
2042 stream_init (&acfg->blob);
2044 return add_stream_data (&acfg->blob, (char*)data, data_len);
2048 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2053 if (acfg->blob.alloc_size == 0)
2054 stream_init (&acfg->blob);
2056 count = acfg->blob.index % align;
2058 /* we assume the stream data will be aligned */
2060 add_stream_data (&acfg->blob, buf, 4 - count);
2062 return add_stream_data (&acfg->blob, (char*)data, data_len);
2066 * emit_offset_table:
2068 * Emit a table of increasing offsets in a compact form using differential encoding.
2069 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2070 * group size, the more compact the table becomes, but the slower it becomes to compute
2071 * a given entry. Returns the size of the table.
2074 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2076 gint32 current_offset;
2077 int i, buf_size, ngroups, index_entry_size;
2079 guint32 *index_offsets;
2081 ngroups = (noffsets + (group_size - 1)) / group_size;
2083 index_offsets = g_new0 (guint32, ngroups);
2085 buf_size = noffsets * 4;
2086 p = buf = g_malloc0 (buf_size);
2089 for (i = 0; i < noffsets; ++i) {
2090 //printf ("D: %d -> %d\n", i, offsets [i]);
2091 if ((i % group_size) == 0) {
2092 index_offsets [i / group_size] = p - buf;
2093 /* Emit the full value for these entries */
2094 encode_value (offsets [i], p, &p);
2096 /* The offsets are allowed to be non-increasing */
2097 //g_assert (offsets [i] >= current_offset);
2098 encode_value (offsets [i] - current_offset, p, &p);
2100 current_offset = offsets [i];
2103 if (ngroups && index_offsets [ngroups - 1] < 65000)
2104 index_entry_size = 2;
2106 index_entry_size = 4;
2108 /* Emit the header */
2109 emit_int32 (acfg, noffsets);
2110 emit_int32 (acfg, group_size);
2111 emit_int32 (acfg, ngroups);
2112 emit_int32 (acfg, index_entry_size);
2114 /* Emit the index */
2115 for (i = 0; i < ngroups; ++i) {
2116 if (index_entry_size == 2)
2117 emit_int16 (acfg, index_offsets [i]);
2119 emit_int32 (acfg, index_offsets [i]);
2123 emit_bytes (acfg, buf, p - buf);
2125 return (int)(p - buf) + (ngroups * 4);
2129 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2133 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2137 index = g_hash_table_size (cfg->image_hash);
2138 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2139 g_ptr_array_add (cfg->image_table, image);
2145 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2148 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2150 /* FIXME: Search referenced images as well */
2151 if (!acfg->typespec_classes) {
2152 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2153 for (i = 0; i < len; ++i) {
2154 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2157 for (i = 0; i < len; ++i) {
2158 if (acfg->typespec_classes [i] == klass)
2163 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2169 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2172 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2175 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2178 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2181 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2186 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2190 if (klass->generic_class) {
2192 g_assert (klass->type_token);
2194 /* Find a typespec for a class if possible */
2195 token = find_typespec_for_class (acfg, klass);
2197 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2198 encode_value (token, p, &p);
2200 MonoClass *gclass = klass->generic_class->container_class;
2201 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2202 static int count = 0;
2205 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2206 encode_klass_ref (acfg, gclass, p, &p);
2207 encode_ginst (acfg, inst, p, &p);
2211 } else if (klass->type_token) {
2212 int iindex = get_image_index (acfg, klass->image);
2214 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2216 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2217 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2219 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2220 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2221 encode_value (get_image_index (acfg, klass->image), p, &p);
2223 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2224 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2225 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2227 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2228 encode_value (klass->byval_arg.type, p, &p);
2229 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2231 encode_value (container ? 1 : 0, p, &p);
2233 encode_value (container->is_method, p, &p);
2234 g_assert (par->serial == 0);
2235 if (container->is_method)
2236 encode_method_ref (acfg, container->owner.method, p, &p);
2238 encode_klass_ref (acfg, container->owner.klass, p, &p);
2240 encode_value (par->serial, p, &p);
2242 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2243 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2244 encode_type (acfg, &klass->byval_arg, p, &p);
2247 g_assert (klass->rank > 0);
2248 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2249 encode_value (klass->rank, p, &p);
2250 encode_klass_ref (acfg, klass->element_class, p, &p);
2258 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2259 * standard metadata encoding.
2262 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2264 gboolean shared = FALSE;
2267 * The encoding of generic instances is large so emit them only once.
2269 if (klass->generic_class) {
2271 g_assert (klass->type_token);
2273 /* Find a typespec for a class if possible */
2274 token = find_typespec_for_class (acfg, klass);
2277 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2282 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2286 buf2 = g_malloc (1024);
2289 encode_klass_ref_inner (acfg, klass, p, &p);
2290 g_assert (p - buf2 < 1024);
2292 offset = add_to_blob (acfg, buf2, p - buf2);
2295 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2301 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2302 encode_value (offset, p, &p);
2307 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2311 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2313 guint32 token = mono_get_field_token (field);
2316 encode_klass_ref (cfg, field->parent, p, &p);
2317 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2318 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2323 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2328 encode_value (inst->type_argc, p, &p);
2329 for (i = 0; i < inst->type_argc; ++i)
2330 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2335 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2338 MonoGenericInst *inst;
2340 inst = context->class_inst;
2342 g_assert (inst->type_argc);
2343 encode_ginst (acfg, inst, p, &p);
2345 encode_value (0, p, &p);
2347 inst = context->method_inst;
2349 g_assert (inst->type_argc);
2350 encode_ginst (acfg, inst, p, &p);
2352 encode_value (0, p, &p);
2358 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2362 g_assert (t->num_mods == 0);
2363 /* t->attrs can be ignored */
2364 //g_assert (t->attrs == 0);
2367 *p = MONO_TYPE_PINNED;
2371 *p = MONO_TYPE_BYREF;
2379 case MONO_TYPE_VOID:
2380 case MONO_TYPE_BOOLEAN:
2381 case MONO_TYPE_CHAR:
2394 case MONO_TYPE_STRING:
2395 case MONO_TYPE_OBJECT:
2396 case MONO_TYPE_TYPEDBYREF:
2398 case MONO_TYPE_VALUETYPE:
2399 case MONO_TYPE_CLASS:
2400 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2402 case MONO_TYPE_SZARRAY:
2403 encode_klass_ref (acfg, t->data.klass, p, &p);
2406 encode_type (acfg, t->data.type, p, &p);
2408 case MONO_TYPE_GENERICINST: {
2409 MonoClass *gclass = t->data.generic_class->container_class;
2410 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2412 encode_klass_ref (acfg, gclass, p, &p);
2413 encode_ginst (acfg, inst, p, &p);
2416 case MONO_TYPE_ARRAY: {
2417 MonoArrayType *array = t->data.array;
2420 encode_klass_ref (acfg, array->eklass, p, &p);
2421 encode_value (array->rank, p, &p);
2422 encode_value (array->numsizes, p, &p);
2423 for (i = 0; i < array->numsizes; ++i)
2424 encode_value (array->sizes [i], p, &p);
2425 encode_value (array->numlobounds, p, &p);
2426 for (i = 0; i < array->numlobounds; ++i)
2427 encode_value (array->lobounds [i], p, &p);
2431 case MONO_TYPE_MVAR:
2432 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2435 g_assert_not_reached ();
2442 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2448 /* Similar to the metadata encoding */
2449 if (sig->generic_param_count)
2453 if (sig->explicit_this)
2455 flags |= (sig->call_convention & 0x0F);
2459 if (sig->generic_param_count)
2460 encode_value (sig->generic_param_count, p, &p);
2461 encode_value (sig->param_count, p, &p);
2463 encode_type (acfg, sig->ret, p, &p);
2464 for (i = 0; i < sig->param_count; ++i) {
2465 if (sig->sentinelpos == i) {
2466 *p = MONO_TYPE_SENTINEL;
2469 encode_type (acfg, sig->params [i], p, &p);
2475 #define MAX_IMAGE_INDEX 250
2478 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2480 guint32 image_index = get_image_index (acfg, method->klass->image);
2481 guint32 token = method->token;
2482 MonoJumpInfoToken *ji;
2486 * The encoding for most methods is as follows:
2487 * - image index encoded as a leb128
2488 * - token index encoded as a leb128
2489 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2490 * types of method encodings.
2493 /* Mark methods which can't use aot trampolines because they need the further
2494 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2496 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2497 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2498 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2500 if (method->wrapper_type) {
2501 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2503 encode_value (method->wrapper_type, p, &p);
2505 switch (method->wrapper_type) {
2506 case MONO_WRAPPER_REMOTING_INVOKE:
2507 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2508 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2511 m = mono_marshal_method_from_wrapper (method);
2513 encode_method_ref (acfg, m, p, &p);
2516 case MONO_WRAPPER_PROXY_ISINST:
2517 case MONO_WRAPPER_LDFLD:
2518 case MONO_WRAPPER_LDFLDA:
2519 case MONO_WRAPPER_STFLD:
2520 case MONO_WRAPPER_ISINST: {
2521 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2522 encode_klass_ref (acfg, proxy_class, p, &p);
2525 case MONO_WRAPPER_LDFLD_REMOTE:
2526 case MONO_WRAPPER_STFLD_REMOTE:
2528 case MONO_WRAPPER_ALLOC: {
2529 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2531 /* The GC name is saved once in MonoAotFileInfo */
2532 g_assert (info->alloc_type != -1);
2533 encode_value (info->alloc_type, p, &p);
2536 case MONO_WRAPPER_WRITE_BARRIER:
2538 case MONO_WRAPPER_STELEMREF: {
2539 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2542 encode_value (info->subtype, p, &p);
2543 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2544 encode_value (info->d.virtual_stelemref.kind, p, &p);
2547 case MONO_WRAPPER_UNKNOWN: {
2548 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2551 encode_value (info->subtype, p, &p);
2552 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2553 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2554 encode_klass_ref (acfg, method->klass, p, &p);
2555 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2556 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2559 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2560 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2563 encode_value (info->subtype, p, &p);
2564 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2565 strcpy ((char*)p, method->name);
2566 p += strlen (method->name) + 1;
2567 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2568 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2570 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2571 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2575 case MONO_WRAPPER_SYNCHRONIZED: {
2578 m = mono_marshal_method_from_wrapper (method);
2580 g_assert (m != method);
2581 encode_method_ref (acfg, m, p, &p);
2584 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2585 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2588 encode_value (info->subtype, p, &p);
2590 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2591 encode_value (info->d.element_addr.rank, p, &p);
2592 encode_value (info->d.element_addr.elem_size, p, &p);
2593 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2594 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2596 g_assert_not_reached ();
2600 case MONO_WRAPPER_CASTCLASS: {
2601 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2604 encode_value (info->subtype, p, &p);
2607 case MONO_WRAPPER_RUNTIME_INVOKE: {
2608 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2611 encode_value (info->subtype, p, &p);
2612 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2613 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2614 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2615 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2618 case MONO_WRAPPER_DELEGATE_INVOKE:
2619 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2620 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2621 if (method->is_inflated) {
2622 /* These wrappers are identified by their class */
2623 encode_value (1, p, &p);
2624 encode_klass_ref (acfg, method->klass, p, &p);
2626 MonoMethodSignature *sig = mono_method_signature (method);
2628 encode_value (0, p, &p);
2629 encode_signature (acfg, sig, p, &p);
2633 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2634 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2637 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2638 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2642 g_assert_not_reached ();
2644 } else if (mono_method_signature (method)->is_inflated) {
2646 * This is a generic method, find the original token which referenced it and
2648 * Obtain the token from information recorded by the JIT.
2650 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2652 image_index = get_image_index (acfg, ji->image);
2653 g_assert (image_index < MAX_IMAGE_INDEX);
2656 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2657 encode_value (image_index, p, &p);
2658 encode_value (token, p, &p);
2660 MonoMethod *declaring;
2661 MonoGenericContext *context = mono_method_get_context (method);
2663 g_assert (method->is_inflated);
2664 declaring = ((MonoMethodInflated*)method)->declaring;
2667 * This might be a non-generic method of a generic instance, which
2668 * doesn't have a token since the reference is generated by the JIT
2669 * like Nullable:Box/Unbox, or by generic sharing.
2671 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2672 /* Encode the klass */
2673 encode_klass_ref (acfg, method->klass, p, &p);
2674 /* Encode the method */
2675 image_index = get_image_index (acfg, method->klass->image);
2676 g_assert (image_index < MAX_IMAGE_INDEX);
2677 g_assert (declaring->token);
2678 token = declaring->token;
2679 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2680 encode_value (image_index, p, &p);
2681 encode_value (token, p, &p);
2682 encode_generic_context (acfg, context, p, &p);
2684 } else if (token == 0) {
2685 /* This might be a method of a constructed type like int[,].Set */
2686 /* Obtain the token from information recorded by the JIT */
2687 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2689 image_index = get_image_index (acfg, ji->image);
2690 g_assert (image_index < MAX_IMAGE_INDEX);
2693 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2694 encode_value (image_index, p, &p);
2695 encode_value (token, p, &p);
2698 g_assert (method->klass->rank);
2700 /* Encode directly */
2701 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2702 encode_klass_ref (acfg, method->klass, p, &p);
2703 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2704 encode_value (0, p, &p);
2705 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2706 encode_value (1, p, &p);
2707 else if (!strcmp (method->name, "Get"))
2708 encode_value (2, p, &p);
2709 else if (!strcmp (method->name, "Address"))
2710 encode_value (3, p, &p);
2711 else if (!strcmp (method->name, "Set"))
2712 encode_value (4, p, &p);
2714 g_assert_not_reached ();
2717 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2719 if (image_index >= MONO_AOT_METHODREF_MIN) {
2720 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2721 encode_value (image_index, p, &p);
2722 encode_value (mono_metadata_token_index (token), p, &p);
2724 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2731 compare_patches (gconstpointer a, gconstpointer b)
2735 i = (*(MonoJumpInfo**)a)->ip.i;
2736 j = (*(MonoJumpInfo**)b)->ip.i;
2747 static G_GNUC_UNUSED char*
2748 patch_to_string (MonoJumpInfo *patch_info)
2752 str = g_string_new ("");
2754 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2756 switch (patch_info->type) {
2757 case MONO_PATCH_INFO_VTABLE:
2758 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2763 g_string_append_printf (str, ")");
2764 return g_string_free (str, FALSE);
2770 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2773 static inline gboolean
2774 is_plt_patch (MonoJumpInfo *patch_info)
2776 switch (patch_info->type) {
2777 case MONO_PATCH_INFO_METHOD:
2778 case MONO_PATCH_INFO_INTERNAL_METHOD:
2779 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2780 case MONO_PATCH_INFO_ICALL_ADDR:
2781 case MONO_PATCH_INFO_CLASS_INIT:
2782 case MONO_PATCH_INFO_RGCTX_FETCH:
2783 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2784 case MONO_PATCH_INFO_MONITOR_ENTER:
2785 case MONO_PATCH_INFO_MONITOR_EXIT:
2786 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2796 * Return the symbol identifying the plt entry PLT_OFFSET.
2799 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2803 * The Apple linker reorganizes object files, so it doesn't like branches to local
2804 * labels, since those have no relocations.
2806 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2808 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2815 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2817 static MonoPltEntry*
2818 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2822 if (!is_plt_patch (patch_info))
2825 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2827 // FIXME: This breaks the calculation of final_got_size
2828 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2830 * Allocate a separate PLT slot for each such patch, since some plt
2831 * entries will refer to the method itself, and some will refer to the
2838 MonoJumpInfo *new_ji;
2840 g_assert (!acfg->final_got_size);
2842 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2844 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2845 res->plt_offset = acfg->plt_offset;
2847 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2848 if (acfg->aot_opts.write_symbols)
2849 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2851 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2853 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2855 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2857 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2859 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2860 //mono_print_ji (patch_info); printf ("\n");
2861 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2863 acfg->plt_offset ++;
2872 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2873 * JI could be found if it exists, otherwise allocates a new one.
2876 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2880 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2882 return got_offset - 1;
2884 got_offset = acfg->got_offset;
2885 acfg->got_offset ++;
2887 if (acfg->final_got_size)
2888 g_assert (got_offset < acfg->final_got_size);
2890 acfg->stats.got_slots ++;
2891 acfg->stats.got_slot_types [ji->type] ++;
2893 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2894 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2895 g_ptr_array_add (acfg->got_patches, ji);
2900 /* Add a method to the list of methods which need to be emitted */
2902 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2905 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2906 g_ptr_array_add (acfg->methods, method);
2907 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2908 acfg->nmethods = acfg->methods->len + 1;
2911 if (method->wrapper_type || extra)
2912 g_ptr_array_add (acfg->extra_methods, method);
2916 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2918 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2926 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2930 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2934 index = acfg->method_index;
2935 add_method_with_index (acfg, method, index, extra);
2937 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2939 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2941 acfg->method_index ++;
2947 add_method (MonoAotCompile *acfg, MonoMethod *method)
2949 return add_method_full (acfg, method, FALSE, 0);
2953 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2955 add_method_full (acfg, method, TRUE, 0);
2959 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2961 if (acfg->aot_opts.log_generics)
2962 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2964 add_method_full (acfg, method, TRUE, depth);
2968 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2970 MonoAotCompile *acfg = user_data;
2971 MonoJitICallInfo *callinfo = value;
2972 MonoMethod *wrapper;
2978 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2979 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2982 add_method (acfg, wrapper);
2986 get_runtime_invoke_sig (MonoMethodSignature *sig)
2988 MonoMethodBuilder *mb;
2991 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2992 m = mono_mb_create_method (mb, sig, 16);
2993 return mono_marshal_get_runtime_invoke (m, FALSE);
2997 can_marshal_struct (MonoClass *klass)
2999 MonoClassField *field;
3000 gboolean can_marshal = TRUE;
3001 gpointer iter = NULL;
3002 MonoMarshalType *info;
3005 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3008 info = mono_marshal_load_type_info (klass);
3010 /* Only allow a few field types to avoid asserts in the marshalling code */
3011 while ((field = mono_class_get_fields (klass, &iter))) {
3012 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3015 switch (field->type->type) {
3020 case MONO_TYPE_BOOLEAN:
3023 case MONO_TYPE_CHAR:
3031 case MONO_TYPE_STRING:
3033 case MONO_TYPE_VALUETYPE:
3034 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3035 can_marshal = FALSE;
3037 case MONO_TYPE_SZARRAY: {
3038 gboolean has_mspec = FALSE;
3041 for (i = 0; i < info->num_fields; ++i) {
3042 if (info->fields [i].field == field && info->fields [i].mspec)
3047 can_marshal = FALSE;
3051 can_marshal = FALSE;
3057 /* Its hard to compute whenever these can be marshalled or not */
3058 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3065 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3067 /* Create a vtype instantiation */
3068 MonoGenericContext shared_context;
3070 MonoGenericInst *inst;
3071 MonoGenericContainer *container;
3072 MonoClass **constraints;
3075 memset (ctx, 0, sizeof (MonoGenericContext));
3077 if (method->klass->generic_container) {
3078 shared_context = method->klass->generic_container->context;
3079 inst = shared_context.class_inst;
3081 args = g_new0 (MonoType*, inst->type_argc);
3082 for (i = 0; i < inst->type_argc; ++i) {
3083 args [i] = &mono_defaults.int_class->byval_arg;
3085 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3087 if (method->is_generic) {
3088 container = mono_method_get_generic_container (method);
3089 shared_context = container->context;
3090 inst = shared_context.method_inst;
3092 args = g_new0 (MonoType*, inst->type_argc);
3093 for (i = 0; i < container->type_argc; ++i) {
3094 MonoGenericParamInfo *info = &container->type_params [i].info;
3095 gboolean ref_only = FALSE;
3097 if (info && info->constraints) {
3098 constraints = info->constraints;
3100 while (*constraints) {
3101 MonoClass *cklass = *constraints;
3102 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3103 /* Inflaring the method with our vtype would not be valid */
3110 args [i] = &mono_defaults.object_class->byval_arg;
3112 args [i] = &mono_defaults.int_class->byval_arg;
3114 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3119 add_wrappers (MonoAotCompile *acfg)
3121 MonoMethod *method, *m;
3123 MonoMethodSignature *sig, *csig;
3127 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3128 * so there is only one wrapper of a given type, or inlining their contents into their
3133 * FIXME: This depends on the fact that different wrappers have different
3137 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3139 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3140 gboolean skip = FALSE;
3142 method = mono_get_method (acfg->image, token, NULL);
3144 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3145 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3146 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3149 if (method->is_generic || method->klass->generic_container)
3152 /* Skip methods which can not be handled by get_runtime_invoke () */
3153 sig = mono_method_signature (method);
3156 if ((sig->ret->type == MONO_TYPE_PTR) ||
3157 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3160 for (j = 0; j < sig->param_count; j++) {
3161 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3165 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3166 if (!mono_class_is_contextbound (method->klass)) {
3167 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3168 gboolean has_nullable = FALSE;
3170 for (j = 0; j < sig->param_count; j++) {
3171 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3172 has_nullable = TRUE;
3175 if (info && !has_nullable) {
3176 /* Supported by the dynamic runtime-invoke wrapper */
3184 //printf ("%s\n", mono_method_full_name (method, TRUE));
3185 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3189 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3190 #ifdef MONO_ARCH_HAVE_TLS_GET
3191 MonoMethodDesc *desc;
3192 MonoMethod *orig_method;
3196 /* Runtime invoke wrappers */
3198 /* void runtime-invoke () [.cctor] */
3199 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3200 csig->ret = &mono_defaults.void_class->byval_arg;
3201 add_method (acfg, get_runtime_invoke_sig (csig));
3203 /* void runtime-invoke () [Finalize] */
3204 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3206 csig->ret = &mono_defaults.void_class->byval_arg;
3207 add_method (acfg, get_runtime_invoke_sig (csig));
3209 /* void runtime-invoke (string) [exception ctor] */
3210 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3212 csig->ret = &mono_defaults.void_class->byval_arg;
3213 csig->params [0] = &mono_defaults.string_class->byval_arg;
3214 add_method (acfg, get_runtime_invoke_sig (csig));
3216 /* void runtime-invoke (string, string) [exception ctor] */
3217 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3219 csig->ret = &mono_defaults.void_class->byval_arg;
3220 csig->params [0] = &mono_defaults.string_class->byval_arg;
3221 csig->params [1] = &mono_defaults.string_class->byval_arg;
3222 add_method (acfg, get_runtime_invoke_sig (csig));
3224 /* string runtime-invoke () [Exception.ToString ()] */
3225 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3227 csig->ret = &mono_defaults.string_class->byval_arg;
3228 add_method (acfg, get_runtime_invoke_sig (csig));
3230 /* void runtime-invoke (string, Exception) [exception ctor] */
3231 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3233 csig->ret = &mono_defaults.void_class->byval_arg;
3234 csig->params [0] = &mono_defaults.string_class->byval_arg;
3235 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3236 add_method (acfg, get_runtime_invoke_sig (csig));
3238 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3239 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3241 csig->ret = &(mono_class_from_name (
3242 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3243 csig->params [0] = &mono_defaults.string_class->byval_arg;
3244 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3245 add_method (acfg, get_runtime_invoke_sig (csig));
3247 /* runtime-invoke used by finalizers */
3248 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3250 /* This is used by mono_runtime_capture_context () */
3251 method = mono_get_context_capture_method ();
3253 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3255 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3256 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3259 /* JIT icall wrappers */
3260 /* FIXME: locking */
3261 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3264 add_method (acfg, mono_marshal_get_stelemref ());
3266 #ifdef MONO_ARCH_HAVE_TLS_GET
3267 /* Managed Allocators */
3268 nallocators = mono_gc_get_managed_allocator_types ();
3269 for (i = 0; i < nallocators; ++i) {
3270 m = mono_gc_get_managed_allocator_by_type (i);
3272 add_method (acfg, m);
3275 /* Monitor Enter/Exit */
3276 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3277 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3278 /* This is a v4 method */
3280 method = mono_monitor_get_fast_path (orig_method);
3282 add_method (acfg, method);
3284 mono_method_desc_free (desc);
3286 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3287 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3288 g_assert (orig_method);
3289 mono_method_desc_free (desc);
3290 method = mono_monitor_get_fast_path (orig_method);
3292 add_method (acfg, method);
3295 /* Stelemref wrappers */
3297 MonoMethod **wrappers;
3300 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3301 for (i = 0; i < nwrappers; ++i)
3302 add_method (acfg, wrappers [i]);
3306 /* castclass_with_check wrapper */
3307 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3308 /* isinst_with_check wrapper */
3309 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3311 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3313 MonoMethodDesc *desc;
3316 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3317 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3318 mono_method_desc_free (desc);
3320 m = mono_monitor_get_fast_path (m);
3322 add_method (acfg, m);
3329 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3330 * we use the original method instead at runtime.
3331 * Since full-aot doesn't support remoting, this is not a problem.
3334 /* remoting-invoke wrappers */
3335 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3336 MonoMethodSignature *sig;
3338 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3339 method = mono_get_method (acfg->image, token, NULL);
3341 sig = mono_method_signature (method);
3343 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3344 m = mono_marshal_get_remoting_invoke_with_check (method);
3346 add_method (acfg, m);
3351 /* delegate-invoke wrappers */
3352 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3354 MonoCustomAttrInfo *cattr;
3356 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3357 klass = mono_class_get (acfg->image, token);
3360 mono_loader_clear_error ();
3364 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3367 if (!klass->generic_container) {
3368 method = mono_get_delegate_invoke (klass);
3370 m = mono_marshal_get_delegate_invoke (method, NULL);
3372 add_method (acfg, m);
3374 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3376 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3378 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3380 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3382 cattr = mono_custom_attrs_from_class (klass);
3387 for (j = 0; j < cattr->num_attrs; ++j)
3388 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3390 if (j < cattr->num_attrs)
3391 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3393 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3394 MonoGenericContext ctx;
3395 MonoMethod *inst, *gshared;
3398 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3401 method = mono_get_delegate_invoke (klass);
3402 create_gsharedvt_inst (acfg, method, &ctx);
3404 inst = mono_class_inflate_generic_method (method, &ctx);
3406 m = mono_marshal_get_delegate_invoke (inst, NULL);
3407 g_assert (m->is_inflated);
3409 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3410 add_extra_method (acfg, gshared);
3413 method = mono_get_delegate_begin_invoke (klass);
3414 create_gsharedvt_inst (acfg, method, &ctx);
3416 inst = mono_class_inflate_generic_method (method, &ctx);
3418 m = mono_marshal_get_delegate_begin_invoke (inst);
3419 g_assert (m->is_inflated);
3421 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3422 add_extra_method (acfg, gshared);
3425 method = mono_get_delegate_end_invoke (klass);
3426 create_gsharedvt_inst (acfg, method, &ctx);
3428 inst = mono_class_inflate_generic_method (method, &ctx);
3430 m = mono_marshal_get_delegate_end_invoke (inst);
3431 g_assert (m->is_inflated);
3433 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3434 add_extra_method (acfg, gshared);
3439 /* Synchronized wrappers */
3440 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3441 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3442 method = mono_get_method (acfg->image, token, NULL);
3444 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
3445 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3448 /* pinvoke wrappers */
3449 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3451 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3453 method = mono_get_method (acfg->image, token, NULL);
3455 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3456 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3457 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3461 /* native-to-managed wrappers */
3462 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3464 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3465 MonoCustomAttrInfo *cattr;
3468 method = mono_get_method (acfg->image, token, NULL);
3471 * Only generate native-to-managed wrappers for methods which have an
3472 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3473 * name to avoid defining a new assembly to contain it.
3475 cattr = mono_custom_attrs_from_method (method);
3478 for (j = 0; j < cattr->num_attrs; ++j)
3479 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3481 if (j < cattr->num_attrs) {
3482 MonoCustomAttrEntry *e = &cattr->attrs [j];
3483 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3484 const char *p = (const char*)e->data;
3486 int slen, num_named, named_type, data_type;
3490 char *export_name = NULL;
3491 MonoMethod *wrapper;
3493 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3494 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3495 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3496 mono_method_full_name (method, TRUE));
3500 g_assert (sig->param_count == 1);
3501 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3504 * Decode the cattr manually since we can't create objects
3505 * during aot compilation.
3511 /* From load_cattr_value () in reflection.c */
3512 slen = mono_metadata_decode_value (p, &p);
3513 n = g_memdup (p, slen + 1);
3515 t = mono_reflection_type_from_name (n, acfg->image);
3519 klass = mono_class_from_mono_type (t);
3520 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3524 num_named = read16 (p);
3527 g_assert (num_named < 2);
3528 if (num_named == 1) {
3531 MonoType *prop_type;
3533 /* parse ExportSymbol attribute */
3535 named_type = *named;
3540 name_len = mono_metadata_decode_blob_size (named, &named);
3541 name = g_malloc (name_len + 1);
3542 memcpy (name, named, name_len);
3543 name [name_len] = 0;
3546 g_assert (named_type == 0x54);
3547 g_assert (!strcmp (name, "ExportSymbol"));
3549 prop_type = &mono_defaults.string_class->byval_arg;
3551 /* load_cattr_value (), string case */
3552 g_assert (*named != (char)0xff);
3553 slen = mono_metadata_decode_value (named, &named);
3554 export_name = g_malloc (slen + 1);
3555 memcpy (export_name, named, slen);
3556 export_name [slen] = 0;
3560 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3561 add_method (acfg, wrapper);
3563 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3567 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3568 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3569 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3573 /* StructureToPtr/PtrToStructure wrappers */
3574 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3577 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3578 klass = mono_class_get (acfg->image, token);
3581 mono_loader_clear_error ();
3585 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3586 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3587 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3588 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3594 has_type_vars (MonoClass *klass)
3596 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3599 return has_type_vars (klass->element_class);
3600 if (klass->generic_class) {
3601 MonoGenericContext *context = &klass->generic_class->context;
3602 if (context->class_inst) {
3605 for (i = 0; i < context->class_inst->type_argc; ++i)
3606 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3614 method_has_type_vars (MonoMethod *method)
3616 if (has_type_vars (method->klass))
3619 if (method->is_inflated) {
3620 MonoGenericContext *context = mono_method_get_context (method);
3621 if (context->method_inst) {
3624 for (i = 0; i < context->method_inst->type_argc; ++i)
3625 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3632 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3635 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3637 /* This might lead to a huge code blowup so only do it if neccesary */
3638 if (!acfg->aot_opts.full_aot && !force)
3641 add_generic_class_with_depth (acfg, klass, 0, ref);
3645 check_type_depth (MonoType *t, int depth)
3653 case MONO_TYPE_GENERICINST: {
3654 MonoGenericClass *gklass = t->data.generic_class;
3655 MonoGenericInst *ginst = gklass->context.class_inst;
3658 for (i = 0; i < ginst->type_argc; ++i) {
3659 if (check_type_depth (ginst->type_argv [i], depth + 1))
3673 * add_generic_class:
3675 * Add all methods of a generic class.
3678 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3681 MonoClassField *field;
3684 if (!acfg->ginst_hash)
3685 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3687 mono_class_init (klass);
3689 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3692 if (has_type_vars (klass))
3695 if (!klass->generic_class && !klass->rank)
3698 if (klass->exception_type)
3701 if (!acfg->ginst_hash)
3702 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3704 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3707 if (check_type_depth (&klass->byval_arg, 0))
3710 if (acfg->aot_opts.log_generics)
3711 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3713 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3716 while ((method = mono_class_get_methods (klass, &iter))) {
3717 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, FALSE))
3721 if (method->is_generic)
3726 * FIXME: Instances which are referenced by these methods are not added,
3727 * for example Array.Resize<int> for List<int>.Add ().
3729 add_extra_method_with_depth (acfg, method, depth + 1);
3733 while ((field = mono_class_get_fields (klass, &iter))) {
3734 if (field->type->type == MONO_TYPE_GENERICINST)
3735 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3738 if (klass->delegate) {
3739 method = mono_get_delegate_invoke (klass);
3741 method = mono_marshal_get_delegate_invoke (method, NULL);
3743 if (acfg->aot_opts.log_generics)
3744 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3746 add_method (acfg, method);
3749 /* Add superclasses */
3751 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3754 * For ICollection<T>, add instances of the helper methods
3755 * in Array, since a T[] could be cast to ICollection<T>.
3757 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3758 (!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"))) {
3759 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3760 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3764 if (!strcmp (klass->name, "IEnumerator`1"))
3765 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3767 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3769 /* Add the T[]/InternalEnumerator class */
3770 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3774 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3775 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3779 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3780 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3784 while ((method = mono_class_get_methods (array_class, &iter))) {
3785 if (strstr (method->name, name_prefix)) {
3786 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3788 add_extra_method_with_depth (acfg, m, depth);
3792 g_free (name_prefix);
3795 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3796 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3797 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3798 MonoClass *icomparable, *gcomparer;
3799 MonoGenericContext ctx;
3800 MonoType *args [16];
3802 memset (&ctx, 0, sizeof (ctx));
3804 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3805 g_assert (icomparable);
3806 args [0] = &tclass->byval_arg;
3807 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3809 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3810 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3811 g_assert (gcomparer);
3812 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3816 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3817 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3818 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3819 MonoClass *iface, *gcomparer;
3820 MonoGenericContext ctx;
3821 MonoType *args [16];
3823 memset (&ctx, 0, sizeof (ctx));
3825 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3827 args [0] = &tclass->byval_arg;
3828 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3830 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3831 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3832 g_assert (gcomparer);
3833 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3839 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3842 MonoGenericContext ctx;
3843 MonoType *args [16];
3845 if (acfg->aot_opts.no_instances)
3848 memset (&ctx, 0, sizeof (ctx));
3850 for (i = 0; i < ninsts; ++i) {
3851 args [0] = insts [i];
3852 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3853 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3858 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3860 MonoMethodHeader *header;
3861 MonoMethodSignature *sig;
3864 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3866 sig = mono_method_signature (method);
3869 for (j = 0; j < sig->param_count; ++j)
3870 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3871 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3874 header = mono_method_get_header (method);
3877 for (j = 0; j < header->num_locals; ++j)
3878 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3879 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3884 * add_generic_instances:
3886 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3889 add_generic_instances (MonoAotCompile *acfg)
3894 MonoGenericContext *context;
3896 if (acfg->aot_opts.no_instances)
3899 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3900 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3901 method = mono_get_method (acfg->image, token, NULL);
3906 if (method->klass->image != acfg->image)
3909 context = mono_method_get_context (method);
3911 if (context && ((context->class_inst && context->class_inst->is_open)))
3915 * For open methods, create an instantiation which can be passed to the JIT.
3916 * FIXME: Handle class_inst as well.
3918 if (context && context->method_inst && context->method_inst->is_open) {
3919 MonoGenericContext shared_context;
3920 MonoGenericInst *inst;
3921 MonoType **type_argv;
3923 MonoMethod *declaring_method;
3924 gboolean supported = TRUE;
3926 /* Check that the context doesn't contain open constructed types */
3927 if (context->class_inst) {
3928 inst = context->class_inst;
3929 for (i = 0; i < inst->type_argc; ++i) {
3930 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)
3932 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3936 if (context->method_inst) {
3937 inst = context->method_inst;
3938 for (i = 0; i < inst->type_argc; ++i) {
3939 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)
3941 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3949 memset (&shared_context, 0, sizeof (MonoGenericContext));
3951 inst = context->class_inst;
3953 type_argv = g_new0 (MonoType*, inst->type_argc);
3954 for (i = 0; i < inst->type_argc; ++i) {
3955 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)
3956 type_argv [i] = &mono_defaults.object_class->byval_arg;
3958 type_argv [i] = inst->type_argv [i];
3961 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3965 inst = context->method_inst;
3967 type_argv = g_new0 (MonoType*, inst->type_argc);
3968 for (i = 0; i < inst->type_argc; ++i) {
3969 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)
3970 type_argv [i] = &mono_defaults.object_class->byval_arg;
3972 type_argv [i] = inst->type_argv [i];
3975 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3979 if (method->is_generic || method->klass->generic_container)
3980 declaring_method = method;
3982 declaring_method = mono_method_get_declaring_generic_method (method);
3984 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3988 * If the method is fully sharable, it was already added in place of its
3989 * generic definition.
3991 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, FALSE))
3995 * FIXME: Partially shared methods are not shared here, so we end up with
3996 * many identical methods.
3998 add_extra_method (acfg, method);
4001 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4004 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4006 klass = mono_class_get (acfg->image, token);
4007 if (!klass || klass->rank) {
4008 mono_loader_clear_error ();
4012 add_generic_class (acfg, klass, FALSE, "typespec");
4015 /* Add types of args/locals */
4016 for (i = 0; i < acfg->methods->len; ++i) {
4017 method = g_ptr_array_index (acfg->methods, i);
4018 add_types_from_method_header (acfg, method);
4021 if (acfg->image == mono_defaults.corlib) {
4023 MonoType *insts [256];
4026 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4027 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4028 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4029 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4030 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4031 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4032 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4033 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4034 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4035 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4036 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4037 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4039 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4040 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4042 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4043 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4045 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4047 /* Add instances of the array generic interfaces for primitive types */
4048 /* This will add instances of the InternalArray_ helper methods in Array too */
4049 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4051 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4052 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4054 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4055 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4057 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4060 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4061 * used for all instances of GetGenericValueImpl by the AOT runtime.
4064 MonoGenericContext ctx;
4065 MonoType *args [16];
4066 MonoMethod *get_method;
4067 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4069 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4072 memset (&ctx, 0, sizeof (ctx));
4073 args [0] = &mono_defaults.object_class->byval_arg;
4074 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4075 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4079 /* Same for CompareExchange<T>/Exchange<T> */
4081 MonoGenericContext ctx;
4082 MonoType *args [16];
4084 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4085 gpointer iter = NULL;
4087 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4088 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4089 memset (&ctx, 0, sizeof (ctx));
4090 args [0] = &mono_defaults.object_class->byval_arg;
4091 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4092 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4097 /* Same for Volatile.Read/Write<T> */
4099 MonoGenericContext ctx;
4100 MonoType *args [16];
4102 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4103 gpointer iter = NULL;
4105 if (volatile_klass) {
4106 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4107 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4108 memset (&ctx, 0, sizeof (ctx));
4109 args [0] = &mono_defaults.object_class->byval_arg;
4110 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4111 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4120 * is_direct_callable:
4122 * Return whenever the method identified by JI is directly callable without
4123 * going through the PLT.
4126 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4128 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4129 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4131 gboolean direct_callable = TRUE;
4133 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4134 direct_callable = FALSE;
4135 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4136 // FIXME: Maybe call the wrapper directly ?
4137 direct_callable = FALSE;
4139 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4140 /* Disable this so all calls go through load_method (), see the
4141 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4142 * mono_debugger_agent_init ().
4144 direct_callable = FALSE;
4147 if (direct_callable)
4150 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4151 if (acfg->aot_opts.direct_pinvoke)
4153 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4154 if (acfg->aot_opts.direct_icalls)
4163 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4165 MonoImage *image = method->klass->image;
4166 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4167 MonoTableInfo *tables = image->tables;
4168 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4169 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4170 guint32 im_cols [MONO_IMPLMAP_SIZE];
4173 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4177 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4180 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4182 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4185 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4187 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4193 * emit_and_reloc_code:
4195 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4196 * is true, calls are made through the GOT too. This is used for emitting trampolines
4197 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4198 * since trampolines are needed to make PTL work.
4201 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
4203 int i, pindex, start_index, method_index;
4205 MonoJumpInfo *patch_info;
4206 MonoMethodHeader *header;
4207 gboolean skip, direct_call, external_call;
4209 const char *direct_call_target;
4210 const char *direct_pinvoke;
4213 header = mono_method_get_header (method);
4215 method_index = get_method_index (acfg, method);
4218 /* Collect and sort relocations */
4219 patches = g_ptr_array_new ();
4220 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4221 g_ptr_array_add (patches, patch_info);
4222 g_ptr_array_sort (patches, compare_patches);
4225 for (i = 0; i < code_len; i++) {
4227 for (pindex = start_index; pindex < patches->len; ++pindex) {
4228 patch_info = g_ptr_array_index (patches, pindex);
4229 if (patch_info->ip.i >= i)
4233 #ifdef MONO_ARCH_AOT_SUPPORTED
4235 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4236 start_index = pindex;
4238 switch (patch_info->type) {
4239 case MONO_PATCH_INFO_NONE:
4241 case MONO_PATCH_INFO_GOT_OFFSET: {
4244 arch_emit_got_offset (acfg, code + i, &code_size);
4247 patch_info->type = MONO_PATCH_INFO_NONE;
4252 * If this patch is a call, try emitting a direct call instead of
4253 * through a PLT entry. This is possible if the called method is in
4254 * the same assembly and requires no initialization.
4256 direct_call = FALSE;
4257 external_call = FALSE;
4258 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4259 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4260 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4261 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4263 direct_call_target = callee_cfg->asm_symbol;
4264 patch_info->type = MONO_PATCH_INFO_NONE;
4265 acfg->stats.direct_calls ++;
4268 acfg->stats.all_calls ++;
4269 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4270 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4271 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4272 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4274 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4275 if (direct_pinvoke) {
4277 g_assert (strlen (direct_pinvoke) < 1000);
4278 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4281 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4282 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4283 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4284 /* Call to a C function implementing a jit icall */
4286 external_call = TRUE;
4287 g_assert (strlen (sym) < 1000);
4288 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4290 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4291 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4292 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4293 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4294 /* Call to a jit icall without a wrapper */
4296 external_call = TRUE;
4297 g_assert (strlen (sym) < 1000);
4298 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4303 patch_info->type = MONO_PATCH_INFO_NONE;
4304 acfg->stats.direct_calls ++;
4307 if (!got_only && !direct_call) {
4308 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4310 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4312 direct_call_target = plt_entry->symbol;
4314 /* Nullify the patch */
4315 patch_info->type = MONO_PATCH_INFO_NONE;
4316 plt_entry->jit_used = TRUE;
4323 arch_emit_direct_call (acfg, direct_call_target, external_call, &call_size);
4328 got_slot = get_got_offset (acfg, patch_info);
4330 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4337 #endif /* MONO_ARCH_AOT_SUPPORTED */
4340 /* Find next patch */
4342 for (pindex = start_index; pindex < patches->len; ++pindex) {
4343 patch_info = g_ptr_array_index (patches, pindex);
4344 if (patch_info->ip.i >= i)
4348 /* Try to emit multiple bytes at once */
4349 if (pindex < patches->len && patch_info->ip.i > i) {
4350 emit_bytes (acfg, code + i, patch_info->ip.i - i);
4351 i = patch_info->ip.i - 1;
4353 emit_bytes (acfg, code + i, 1);
4362 * Modify SYMBOL so it only includes characters permissible in symbols.
4365 sanitize_symbol (char *symbol)
4367 int i, len = strlen (symbol);
4369 for (i = 0; i < len; ++i)
4370 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
4375 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4377 char *name1, *name2, *cached;
4378 int i, j, len, count;
4381 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4382 if (!prefix || !*prefix)
4386 name1 = mono_method_full_name (method, TRUE);
4387 len = strlen (name1);
4388 name2 = malloc (strlen (prefix) + len + 16);
4389 memcpy (name2, prefix, strlen (prefix));
4390 j = strlen (prefix);
4391 for (i = 0; i < len; ++i) {
4392 if (isalnum (name1 [i])) {
4393 name2 [j ++] = name1 [i];
4394 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4396 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4399 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4408 while (g_hash_table_lookup (cache, name2)) {
4409 sprintf (name2 + j, "_%d", count);
4413 cached = g_strdup (name2);
4414 g_hash_table_insert (cache, cached, cached);
4420 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4425 char *debug_sym = NULL;
4426 char *symbol = NULL;
4427 int func_alignment = AOT_FUNC_ALIGNMENT;
4428 MonoMethodHeader *header;
4431 method = cfg->orig_method;
4432 code = cfg->native_code;
4433 header = cfg->header;
4435 method_index = get_method_index (acfg, method);
4436 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4439 /* Make the labels local */
4440 emit_section_change (acfg, ".text", 0);
4441 emit_alignment (acfg, func_alignment);
4443 if (acfg->global_symbols && acfg->need_no_dead_strip)
4444 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4446 emit_label (acfg, cfg->asm_symbol);
4448 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4450 * Write a C style symbol for every method, this has two uses:
4451 * - it works on platforms where the dwarf debugging info is not
4453 * - it allows the setting of breakpoints of aot-ed methods.
4455 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4457 if (acfg->need_no_dead_strip)
4458 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4459 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4460 emit_label (acfg, debug_sym);
4463 export_name = g_hash_table_lookup (acfg->export_names, method);
4465 /* Emit a global symbol for the method */
4466 emit_global_inner (acfg, export_name, TRUE);
4467 emit_label (acfg, export_name);
4470 if (cfg->verbose_level > 0)
4471 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4473 acfg->stats.code_size += cfg->code_len;
4475 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4477 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
4481 if (acfg->aot_opts.write_symbols) {
4482 emit_symbol_size (acfg, debug_sym, ".");
4486 emit_label (acfg, symbol);
4493 * Encode PATCH_INFO into its disk representation.
4496 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4500 switch (patch_info->type) {
4501 case MONO_PATCH_INFO_NONE:
4503 case MONO_PATCH_INFO_IMAGE:
4504 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4506 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4507 case MONO_PATCH_INFO_JIT_TLS_ID:
4508 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4509 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4511 case MONO_PATCH_INFO_METHOD_REL:
4512 encode_value ((gint)patch_info->data.offset, p, &p);
4514 case MONO_PATCH_INFO_SWITCH: {
4515 gpointer *table = (gpointer *)patch_info->data.table->table;
4518 encode_value (patch_info->data.table->table_size, p, &p);
4519 for (k = 0; k < patch_info->data.table->table_size; k++)
4520 encode_value ((int)(gssize)table [k], p, &p);
4523 case MONO_PATCH_INFO_METHODCONST:
4524 case MONO_PATCH_INFO_METHOD:
4525 case MONO_PATCH_INFO_METHOD_JUMP:
4526 case MONO_PATCH_INFO_ICALL_ADDR:
4527 case MONO_PATCH_INFO_METHOD_RGCTX:
4528 encode_method_ref (acfg, patch_info->data.method, p, &p);
4530 case MONO_PATCH_INFO_INTERNAL_METHOD:
4531 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4532 guint32 len = strlen (patch_info->data.name);
4534 encode_value (len, p, &p);
4536 memcpy (p, patch_info->data.name, len);
4541 case MONO_PATCH_INFO_LDSTR: {
4542 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4543 guint32 token = patch_info->data.token->token;
4544 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4545 encode_value (image_index, p, &p);
4546 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4549 case MONO_PATCH_INFO_RVA:
4550 case MONO_PATCH_INFO_DECLSEC:
4551 case MONO_PATCH_INFO_LDTOKEN:
4552 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4553 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4554 encode_value (patch_info->data.token->token, p, &p);
4555 encode_value (patch_info->data.token->has_context, p, &p);
4556 if (patch_info->data.token->has_context)
4557 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4559 case MONO_PATCH_INFO_EXC_NAME: {
4560 MonoClass *ex_class;
4563 mono_class_from_name (mono_defaults.exception_class->image,
4564 "System", patch_info->data.target);
4565 g_assert (ex_class);
4566 encode_klass_ref (acfg, ex_class, p, &p);
4569 case MONO_PATCH_INFO_R4:
4570 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4572 case MONO_PATCH_INFO_R8:
4573 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4574 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4576 case MONO_PATCH_INFO_VTABLE:
4577 case MONO_PATCH_INFO_CLASS:
4578 case MONO_PATCH_INFO_IID:
4579 case MONO_PATCH_INFO_ADJUSTED_IID:
4580 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4582 case MONO_PATCH_INFO_CLASS_INIT:
4583 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4584 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4586 case MONO_PATCH_INFO_FIELD:
4587 case MONO_PATCH_INFO_SFLDA:
4588 encode_field_info (acfg, patch_info->data.field, p, &p);
4590 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4592 case MONO_PATCH_INFO_RGCTX_FETCH: {
4593 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4598 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4599 * reference the same method, so encode the method only once.
4601 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4603 buf2 = g_malloc (1024);
4606 encode_method_ref (acfg, entry->method, p2, &p2);
4607 g_assert (p2 - buf2 < 1024);
4609 offset = add_to_blob (acfg, buf2, p2 - buf2);
4612 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4617 encode_value (offset, p, &p);
4618 g_assert (entry->info_type < 256);
4619 g_assert (entry->data->type < 256);
4620 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4621 encode_patch (acfg, entry->data, p, &p);
4624 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4625 case MONO_PATCH_INFO_MONITOR_ENTER:
4626 case MONO_PATCH_INFO_MONITOR_EXIT:
4627 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4629 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4630 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4631 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4633 case MONO_PATCH_INFO_SIGNATURE:
4634 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4636 case MONO_PATCH_INFO_GSHAREDVT_CALL:
4637 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
4638 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
4641 g_warning ("unable to handle jump info %d", patch_info->type);
4642 g_assert_not_reached ();
4649 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4652 guint32 pindex, offset;
4653 MonoJumpInfo *patch_info;
4655 encode_value (n_patches, p, &p);
4657 for (pindex = 0; pindex < patches->len; ++pindex) {
4658 patch_info = g_ptr_array_index (patches, pindex);
4660 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4664 offset = get_got_offset (acfg, patch_info);
4665 encode_value (offset, p, &p);
4672 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4676 int pindex, buf_size, n_patches;
4678 MonoJumpInfo *patch_info;
4679 MonoMethodHeader *header;
4680 guint32 method_index;
4682 guint32 first_got_offset;
4684 method = cfg->orig_method;
4685 header = mono_method_get_header (method);
4687 method_index = get_method_index (acfg, method);
4689 /* Sort relocations */
4690 patches = g_ptr_array_new ();
4691 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4692 g_ptr_array_add (patches, patch_info);
4693 g_ptr_array_sort (patches, compare_patches);
4695 first_got_offset = acfg->cfgs [method_index]->got_offset;
4697 /**********************/
4698 /* Encode method info */
4699 /**********************/
4701 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4702 p = buf = g_malloc (buf_size);
4704 if (mono_class_get_cctor (method->klass))
4705 encode_klass_ref (acfg, method->klass, p, &p);
4707 /* Not needed when loading the method */
4708 encode_value (0, p, &p);
4711 if (cfg->opt & MONO_OPT_SHARED) {
4712 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4713 for (l = cfg->ldstr_list; l; l = l->next) {
4714 encode_value ((long)l->data, p, &p);
4718 /* Used only in shared mode */
4719 g_assert (!cfg->ldstr_list);
4722 for (pindex = 0; pindex < patches->len; ++pindex) {
4723 patch_info = g_ptr_array_index (patches, pindex);
4725 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4726 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4727 patch_info->type = MONO_PATCH_INFO_NONE;
4732 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4733 /* Stored in a GOT slot initialized at module load time */
4734 patch_info->type = MONO_PATCH_INFO_NONE;
4738 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4739 /* Stored in a GOT slot initialized at module load time */
4740 patch_info->type = MONO_PATCH_INFO_NONE;
4744 if (is_plt_patch (patch_info)) {
4745 /* Calls are made through the PLT */
4746 patch_info->type = MONO_PATCH_INFO_NONE;
4754 g_assert (cfg->has_got_slots);
4756 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4758 acfg->stats.info_size += p - buf;
4760 g_assert (p - buf < buf_size);
4762 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4767 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4769 guint32 cache_index;
4772 /* Reuse the unwind module to canonize and store unwind info entries */
4773 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4775 /* Use +/- 1 to distinguish 0s from missing entries */
4776 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4784 * It would be easier to use assembler symbols, but the caller needs an
4787 offset = acfg->unwind_info_offset;
4788 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4789 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4792 encode_value (encoded_len, p, &p);
4794 acfg->unwind_info_offset += encoded_len + (p - buf);
4800 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4803 int i, k, buf_size, method_index;
4804 guint32 debug_info_size;
4806 MonoMethodHeader *header;
4807 guint8 *p, *buf, *debug_info;
4808 MonoJitInfo *jinfo = cfg->jit_info;
4810 gboolean use_unwind_ops = FALSE;
4811 MonoSeqPointInfo *seq_points;
4813 method = cfg->orig_method;
4814 code = cfg->native_code;
4815 header = cfg->header;
4817 method_index = get_method_index (acfg, method);
4819 if (!acfg->aot_opts.nodebug) {
4820 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4823 debug_info_size = 0;
4826 seq_points = cfg->seq_point_info;
4828 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4829 p = buf = g_malloc (buf_size);
4831 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4832 use_unwind_ops = cfg->unwind_ops != NULL;
4835 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);
4837 encode_value (flags, p, &p);
4839 if (use_unwind_ops) {
4840 guint32 encoded_len;
4844 * This is a duplicate of the data in the .debug_frame section, but that
4845 * section cannot be accessed using the dl interface.
4847 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4848 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4851 encode_value (jinfo->used_regs, p, &p);
4854 /*Encode the number of holes before the number of clauses to make decoding easier*/
4855 if (jinfo->has_try_block_holes) {
4856 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4857 encode_value (table->num_holes, p, &p);
4860 /* Exception table */
4861 if (cfg->compile_llvm) {
4863 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4864 * since the information is only available to llc. Instead, we let llc save the data
4865 * into the LSDA, and read it from there at runtime.
4867 /* The assembly might be CIL stripped so emit the data ourselves */
4868 if (header->num_clauses)
4869 encode_value (header->num_clauses, p, &p);
4871 for (k = 0; k < header->num_clauses; ++k) {
4872 MonoExceptionClause *clause;
4874 clause = &header->clauses [k];
4876 encode_value (clause->flags, p, &p);
4877 if (clause->data.catch_class) {
4878 encode_value (1, p, &p);
4879 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4881 encode_value (0, p, &p);
4884 /* Emit a list of nesting clauses */
4885 for (i = 0; i < header->num_clauses; ++i) {
4887 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4889 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4891 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4892 encode_value (i, p, &p);
4894 encode_value (-1, p, &p);
4897 if (jinfo->num_clauses)
4898 encode_value (jinfo->num_clauses, p, &p);
4900 for (k = 0; k < jinfo->num_clauses; ++k) {
4901 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4903 encode_value (ei->flags, p, &p);
4904 encode_value (ei->exvar_offset, p, &p);
4906 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4907 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4909 if (ei->data.catch_class) {
4910 encode_value (1, p, &p);
4911 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4913 encode_value (0, p, &p);
4917 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4918 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4919 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4923 if (jinfo->has_generic_jit_info) {
4924 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4925 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
4929 encode_value (gi->nlocs, p, &p);
4931 for (i = 0; i < gi->nlocs; ++i) {
4932 MonoDwarfLocListEntry *entry = &gi->locations [i];
4934 encode_value (entry->is_reg ? 1 : 0, p, &p);
4935 encode_value (entry->reg, p, &p);
4937 encode_value (entry->offset, p, &p);
4939 g_assert (entry->from == 0);
4941 encode_value (entry->from, p, &p);
4942 encode_value (entry->to, p, &p);
4945 if (!cfg->compile_llvm) {
4946 encode_value (gi->has_this ? 1 : 0, p, &p);
4947 encode_value (gi->this_reg, p, &p);
4948 encode_value (gi->this_offset, p, &p);
4953 * Need to encode jinfo->method too, since it is not equal to 'method'
4954 * when using generic sharing.
4956 encode_method_ref (acfg, jinfo->method, p, &p);
4958 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
4959 MonoMethodInflated *inflated;
4960 MonoGenericContext *context;
4961 MonoGenericInst *inst;
4963 g_assert (jinfo->method->is_inflated);
4964 inflated = (MonoMethodInflated*)jinfo->method;
4965 context = &inflated->context;
4967 encode_value (1, p, &p);
4968 if (context->class_inst) {
4969 inst = context->class_inst;
4971 encode_value (inst->type_argc, p, &p);
4972 for (i = 0; i < inst->type_argc; ++i)
4973 encode_value (gsctx->var_is_vt [i], p, &p);
4975 encode_value (0, p, &p);
4977 if (context->method_inst) {
4978 inst = context->method_inst;
4980 encode_value (inst->type_argc, p, &p);
4981 for (i = 0; i < inst->type_argc; ++i)
4982 encode_value (gsctx->mvar_is_vt [i], p, &p);
4984 encode_value (0, p, &p);
4987 encode_value (0, p, &p);
4991 if (jinfo->has_try_block_holes) {
4992 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4993 for (i = 0; i < table->num_holes; ++i) {
4994 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4995 encode_value (hole->clause, p, &p);
4996 encode_value (hole->length, p, &p);
4997 encode_value (hole->offset, p, &p);
5001 if (jinfo->has_arch_eh_info) {
5002 MonoArchEHJitInfo *eh_info;
5004 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5005 encode_value (eh_info->stack_size, p, &p);
5009 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5011 encode_value (seq_points->len, p, &p);
5012 last_il_offset = last_native_offset = 0;
5013 for (i = 0; i < seq_points->len; ++i) {
5014 SeqPoint *sp = &seq_points->seq_points [i];
5015 il_offset = sp->il_offset;
5016 native_offset = sp->native_offset;
5017 encode_value (il_offset - last_il_offset, p, &p);
5018 encode_value (native_offset - last_native_offset, p, &p);
5019 last_il_offset = il_offset;
5020 last_native_offset = native_offset;
5022 encode_value (sp->next_len, p, &p);
5023 for (j = 0; j < sp->next_len; ++j)
5024 encode_value (sp->next [j], p, &p);
5028 g_assert (debug_info_size < buf_size);
5030 encode_value (debug_info_size, p, &p);
5031 if (debug_info_size) {
5032 memcpy (p, debug_info, debug_info_size);
5033 p += debug_info_size;
5034 g_free (debug_info);
5039 encode_value (cfg->gc_map_size, p, &p);
5040 /* The GC map requires 4 bytes of alignment */
5041 while ((gsize)p % 4)
5043 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5044 p += cfg->gc_map_size;
5047 acfg->stats.ex_info_size += p - buf;
5049 g_assert (p - buf < buf_size);
5052 /* The GC Map requires 4 byte alignment */
5053 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5058 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5060 MonoClass *klass = mono_class_get (acfg->image, token);
5062 int i, buf_size, res;
5063 gboolean no_special_static, cant_encode;
5064 gpointer iter = NULL;
5067 mono_loader_clear_error ();
5071 p = buf = g_malloc (buf_size);
5073 /* Mark as unusable */
5074 encode_value (-1, p, &p);
5076 res = add_to_blob (acfg, buf, p - buf);
5082 buf_size = 10240 + (klass->vtable_size * 16);
5083 p = buf = g_malloc (buf_size);
5087 mono_class_init (klass);
5089 mono_class_get_nested_types (klass, &iter);
5090 g_assert (klass->nested_classes_inited);
5092 mono_class_setup_vtable (klass);
5095 * Emit all the information which is required for creating vtables so
5096 * the runtime does not need to create the MonoMethod structures which
5097 * take up a lot of space.
5100 no_special_static = !mono_class_has_special_static_fields (klass);
5102 /* Check whenever we have enough info to encode the vtable */
5103 cant_encode = FALSE;
5104 for (i = 0; i < klass->vtable_size; ++i) {
5105 MonoMethod *cm = klass->vtable [i];
5107 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5111 mono_class_has_finalizer (klass);
5113 if (klass->generic_container || cant_encode) {
5114 encode_value (-1, p, &p);
5116 encode_value (klass->vtable_size, p, &p);
5117 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);
5118 if (klass->has_cctor)
5119 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5120 if (klass->has_finalize)
5121 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5123 encode_value (klass->instance_size, p, &p);
5124 encode_value (mono_class_data_size (klass), p, &p);
5125 encode_value (klass->packing_size, p, &p);
5126 encode_value (klass->min_align, p, &p);
5128 for (i = 0; i < klass->vtable_size; ++i) {
5129 MonoMethod *cm = klass->vtable [i];
5132 encode_method_ref (acfg, cm, p, &p);
5134 encode_value (0, p, &p);
5138 acfg->stats.class_info_size += p - buf;
5140 g_assert (p - buf < buf_size);
5141 res = add_to_blob (acfg, buf, p - buf);
5148 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5150 char *debug_sym = NULL;
5153 case MONO_PATCH_INFO_METHOD:
5154 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5156 case MONO_PATCH_INFO_INTERNAL_METHOD:
5157 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5159 case MONO_PATCH_INFO_CLASS_INIT:
5160 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
5161 sanitize_symbol (debug_sym);
5163 case MONO_PATCH_INFO_RGCTX_FETCH:
5164 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5166 case MONO_PATCH_INFO_ICALL_ADDR: {
5167 char *s = get_debug_sym (ji->data.method, "", cache);
5169 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5173 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5174 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5176 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5177 debug_sym = g_strdup_printf ("plt__generic_class_init");
5187 * Calls made from AOTed code are routed through a table of jumps similar to the
5188 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5189 * control to the AOT runtime through a trampoline.
5192 emit_plt (MonoAotCompile *acfg)
5198 sprintf (symbol, "plt");
5200 emit_section_change (acfg, ".text", 0);
5201 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5202 emit_label (acfg, symbol);
5203 emit_label (acfg, acfg->plt_symbol);
5205 for (i = 0; i < acfg->plt_offset; ++i) {
5206 char *debug_sym = NULL;
5207 MonoPltEntry *plt_entry = NULL;
5212 * The first plt entry is unused.
5216 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5221 * If the target is directly callable, alias the plt symbol to point to
5223 * FIXME: Use this to simplify emit_and_reloc_code ().
5224 * FIXME: Avoid the got slot.
5225 * FIXME: Add support to the binary writer.
5227 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5228 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5231 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5232 /* LLVM calls the PLT entries using bl, so emit a stub */
5233 fprintf (acfg->fp, "\n.thumb_func\n");
5234 emit_label (acfg, plt_entry->llvm_symbol);
5235 fprintf (acfg->fp, "bx pc\n");
5236 fprintf (acfg->fp, "nop\n");
5237 fprintf (acfg->fp, ".arm\n");
5238 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5240 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5247 debug_sym = plt_entry->debug_sym;
5249 if (acfg->thumb_mixed && !plt_entry->jit_used)
5250 /* Emit only a thumb version */
5253 if (acfg->llvm && !acfg->thumb_mixed)
5254 emit_label (acfg, plt_entry->llvm_symbol);
5257 if (acfg->need_no_dead_strip) {
5258 img_writer_emit_unset_mode (acfg->w);
5259 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5261 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5262 emit_label (acfg, debug_sym);
5265 emit_label (acfg, plt_entry->symbol);
5267 arch_emit_plt_entry (acfg, i);
5270 emit_symbol_size (acfg, debug_sym, ".");
5273 if (acfg->thumb_mixed) {
5274 /* Make sure the ARM symbols don't alias the thumb ones */
5275 emit_zero_bytes (acfg, 16);
5278 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5281 for (i = 0; i < acfg->plt_offset; ++i) {
5282 char *debug_sym = NULL;
5283 MonoPltEntry *plt_entry = NULL;
5289 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5292 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5295 /* Skip plt entries not actually called by LLVM code */
5296 if (!plt_entry->llvm_used)
5299 if (acfg->aot_opts.write_symbols) {
5300 if (plt_entry->debug_sym)
5301 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5305 #if defined(TARGET_MACH)
5306 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5307 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5309 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5310 emit_label (acfg, debug_sym);
5312 fprintf (acfg->fp, "\n.thumb_func\n");
5314 emit_label (acfg, plt_entry->llvm_symbol);
5316 arch_emit_llvm_plt_entry (acfg, i);
5319 emit_symbol_size (acfg, debug_sym, ".");
5325 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5327 sprintf (symbol, "plt_end");
5328 emit_label (acfg, symbol);
5332 * emit_trampoline_full:
5334 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5335 * create_jit_info_for_trampoline ().
5337 static G_GNUC_UNUSED void
5338 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5340 char start_symbol [256];
5341 char end_symbol [256];
5343 guint32 buf_size, info_offset;
5344 MonoJumpInfo *patch_info;
5355 code_size = info->code_size;
5357 unwind_ops = info->unwind_ops;
5359 #ifdef __native_client_codegen__
5360 mono_nacl_fix_patches (code, ji);
5365 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5367 emit_section_change (acfg, ".text", 0);
5368 emit_global (acfg, start_symbol, TRUE);
5369 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5370 emit_label (acfg, start_symbol);
5372 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5373 emit_label (acfg, symbol);
5376 * The code should access everything through the GOT, so we pass
5379 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
5381 emit_symbol_size (acfg, start_symbol, ".");
5384 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5385 emit_label (acfg, end_symbol);
5390 /* Sort relocations */
5391 patches = g_ptr_array_new ();
5392 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5393 if (patch_info->type != MONO_PATCH_INFO_NONE)
5394 g_ptr_array_add (patches, patch_info);
5395 g_ptr_array_sort (patches, compare_patches);
5397 buf_size = patches->len * 128 + 128;
5398 buf = g_malloc (buf_size);
5401 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5402 g_assert (p - buf < buf_size);
5404 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5406 info_offset = add_to_blob (acfg, buf, p - buf);
5408 emit_section_change (acfg, RODATA_SECT, 0);
5409 emit_global (acfg, symbol, FALSE);
5410 emit_label (acfg, symbol);
5412 emit_int32 (acfg, info_offset);
5416 guint32 encoded_len;
5420 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5422 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5423 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5426 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5427 emit_int32 (acfg, uw_offset);
5430 /* Emit debug info */
5434 sprintf (symbol, "%s", name);
5435 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5438 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5442 static G_GNUC_UNUSED void
5443 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5445 emit_trampoline_full (acfg, got_offset, info, FALSE);
5449 emit_trampolines (MonoAotCompile *acfg)
5452 char end_symbol [256];
5453 int i, tramp_got_offset;
5454 MonoAotTrampoline ntype;
5455 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5459 if (!acfg->aot_opts.full_aot)
5462 g_assert (acfg->image->assembly);
5464 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5465 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5466 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5467 MonoTrampInfo *info;
5470 * Emit the generic trampolines.
5472 * We could save some code by treating the generic trampolines as a wrapper
5473 * method, but that approach has its own complexities, so we choose the simpler
5476 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5477 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5478 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5479 emit_trampoline (acfg, acfg->got_offset, info);
5482 mono_arch_get_nullified_class_init_trampoline (&info);
5483 emit_trampoline (acfg, acfg->got_offset, info);
5484 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5485 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5486 emit_trampoline (acfg, acfg->got_offset, info);
5487 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5488 emit_trampoline (acfg, acfg->got_offset, info);
5491 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5492 emit_trampoline (acfg, acfg->got_offset, info);
5494 /* Emit the exception related code pieces */
5495 mono_arch_get_restore_context (&info, TRUE);
5496 emit_trampoline (acfg, acfg->got_offset, info);
5497 mono_arch_get_call_filter (&info, TRUE);
5498 emit_trampoline (acfg, acfg->got_offset, info);
5499 mono_arch_get_throw_exception (&info, TRUE);
5500 emit_trampoline (acfg, acfg->got_offset, info);
5501 mono_arch_get_rethrow_exception (&info, TRUE);
5502 emit_trampoline (acfg, acfg->got_offset, info);
5503 mono_arch_get_throw_corlib_exception (&info, TRUE);
5504 emit_trampoline (acfg, acfg->got_offset, info);
5506 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5507 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5509 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5511 /* Create a separate out trampoline for more information in stack traces */
5512 info->name = g_strdup ("gsharedvt_out_trampoline");
5513 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5517 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5519 GSList *l = mono_arch_get_trampolines (TRUE);
5522 MonoTrampInfo *info = l->data;
5524 emit_trampoline (acfg, acfg->got_offset, info);
5530 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5533 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5534 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5535 emit_trampoline (acfg, acfg->got_offset, info);
5537 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5538 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5539 emit_trampoline (acfg, acfg->got_offset, info);
5542 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
5543 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
5544 emit_trampoline (acfg, acfg->got_offset, info);
5550 /* delegate_invoke_impl trampolines */
5551 l = mono_arch_get_delegate_invoke_impls ();
5553 MonoTrampInfo *info = l->data;
5555 emit_trampoline (acfg, acfg->got_offset, info);
5560 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5562 /* Emit trampolines which are numerous */
5565 * These include the following:
5566 * - specific trampolines
5567 * - static rgctx invoke trampolines
5569 * These trampolines have the same code, they are parameterized by GOT
5571 * They are defined in this file, in the arch_... routines instead of
5572 * in tramp-<ARCH>.c, since it is easier to do it this way.
5576 * When running in aot-only mode, we can't create specific trampolines at
5577 * runtime, so we create a few, and save them in the AOT file.
5578 * Normal trampolines embed their argument as a literal inside the
5579 * trampoline code, we can't do that here, so instead we embed an offset
5580 * which needs to be added to the trampoline address to get the address of
5581 * the GOT slot which contains the argument value.
5582 * The generated trampolines jump to the generic trampolines using another
5583 * GOT slot, which will be setup by the AOT loader to point to the
5584 * generic trampoline code of the given type.
5588 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5592 emit_section_change (acfg, ".text", 0);
5594 tramp_got_offset = acfg->got_offset;
5596 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5598 case MONO_AOT_TRAMP_SPECIFIC:
5599 sprintf (symbol, "specific_trampolines");
5601 case MONO_AOT_TRAMP_STATIC_RGCTX:
5602 sprintf (symbol, "static_rgctx_trampolines");
5604 case MONO_AOT_TRAMP_IMT_THUNK:
5605 sprintf (symbol, "imt_thunks");
5607 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5608 sprintf (symbol, "gsharedvt_arg_trampolines");
5611 g_assert_not_reached ();
5614 sprintf (end_symbol, "%s_e", symbol);
5616 if (acfg->aot_opts.write_symbols)
5617 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5619 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5620 emit_label (acfg, symbol);
5622 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5624 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5628 case MONO_AOT_TRAMP_SPECIFIC:
5629 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5630 tramp_got_offset += 2;
5632 case MONO_AOT_TRAMP_STATIC_RGCTX:
5633 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
5634 tramp_got_offset += 2;
5636 case MONO_AOT_TRAMP_IMT_THUNK:
5637 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5638 tramp_got_offset += 1;
5640 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5641 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
5642 tramp_got_offset += 2;
5645 g_assert_not_reached ();
5647 #ifdef __native_client_codegen__
5648 /* align to avoid 32-byte boundary crossings */
5649 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5652 if (!acfg->trampoline_size [ntype]) {
5653 g_assert (tramp_size);
5654 acfg->trampoline_size [ntype] = tramp_size;
5658 emit_label (acfg, end_symbol);
5661 arch_emit_specific_trampoline_pages (acfg);
5663 /* Reserve some entries at the end of the GOT for our use */
5664 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5667 acfg->got_offset += acfg->num_trampoline_got_entries;
5671 str_begins_with (const char *str1, const char *str2)
5673 int len = strlen (str2);
5674 return strncmp (str1, str2, len) == 0;
5678 mono_aot_readonly_field_override (MonoClassField *field)
5681 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5682 char *p = rdv->name;
5684 len = strlen (field->parent->name_space);
5685 if (strncmp (p, field->parent->name_space, len))
5690 len = strlen (field->parent->name);
5691 if (strncmp (p, field->parent->name, len))
5696 if (strcmp (p, field->name))
5698 switch (rdv->type) {
5700 return &rdv->value.i1;
5702 return &rdv->value.i2;
5704 return &rdv->value.i4;
5713 add_readonly_value (MonoAotOptions *opts, const char *val)
5718 /* the format of val is:
5719 * namespace.typename.fieldname=type/value
5720 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5722 fval = strrchr (val, '/');
5724 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5727 tval = strrchr (val, '=');
5729 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5732 rdv = g_new0 (ReadOnlyValue, 1);
5733 rdv->name = g_malloc0 (tval - val + 1);
5734 memcpy (rdv->name, val, tval - val);
5737 if (strncmp (tval, "i1", 2) == 0) {
5738 rdv->value.i1 = atoi (fval);
5739 rdv->type = MONO_TYPE_I1;
5740 } else if (strncmp (tval, "i2", 2) == 0) {
5741 rdv->value.i2 = atoi (fval);
5742 rdv->type = MONO_TYPE_I2;
5743 } else if (strncmp (tval, "i4", 2) == 0) {
5744 rdv->value.i4 = atoi (fval);
5745 rdv->type = MONO_TYPE_I4;
5747 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5750 rdv->next = readonly_values;
5751 readonly_values = rdv;
5755 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5757 gchar **args, **ptr;
5759 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5760 for (ptr = args; ptr && *ptr; ptr ++) {
5761 const char *arg = *ptr;
5763 if (str_begins_with (arg, "outfile=")) {
5764 opts->outfile = g_strdup (arg + strlen ("outfile="));
5765 } else if (str_begins_with (arg, "save-temps")) {
5766 opts->save_temps = TRUE;
5767 } else if (str_begins_with (arg, "keep-temps")) {
5768 opts->save_temps = TRUE;
5769 } else if (str_begins_with (arg, "write-symbols")) {
5770 opts->write_symbols = TRUE;
5771 } else if (str_begins_with (arg, "no-write-symbols")) {
5772 opts->write_symbols = FALSE;
5773 } else if (str_begins_with (arg, "metadata-only")) {
5774 opts->metadata_only = TRUE;
5775 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5776 opts->bind_to_runtime_version = TRUE;
5777 } else if (str_begins_with (arg, "full")) {
5778 opts->full_aot = TRUE;
5779 } else if (str_begins_with (arg, "threads=")) {
5780 opts->nthreads = atoi (arg + strlen ("threads="));
5781 } else if (str_begins_with (arg, "static")) {
5782 opts->static_link = TRUE;
5783 opts->no_dlsym = TRUE;
5784 } else if (str_begins_with (arg, "asmonly")) {
5785 opts->asm_only = TRUE;
5786 } else if (str_begins_with (arg, "asmwriter")) {
5787 opts->asm_writer = TRUE;
5788 } else if (str_begins_with (arg, "nodebug")) {
5789 opts->nodebug = TRUE;
5790 } else if (str_begins_with (arg, "dwarfdebug")) {
5791 opts->dwarf_debug = TRUE;
5792 } else if (str_begins_with (arg, "nopagetrampolines")) {
5793 opts->use_trampolines_page = FALSE;
5794 } else if (str_begins_with (arg, "ntrampolines=")) {
5795 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5796 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5797 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5798 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5799 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5800 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
5801 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
5802 } else if (str_begins_with (arg, "autoreg")) {
5803 opts->autoreg = TRUE;
5804 } else if (str_begins_with (arg, "tool-prefix=")) {
5805 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5806 } else if (str_begins_with (arg, "soft-debug")) {
5807 opts->soft_debug = TRUE;
5808 } else if (str_begins_with (arg, "direct-pinvoke")) {
5809 opts->direct_pinvoke = TRUE;
5810 } else if (str_begins_with (arg, "direct-icalls")) {
5811 opts->direct_icalls = TRUE;
5812 #if defined(TARGET_ARM)
5813 } else if (str_begins_with (arg, "iphone-abi")) {
5814 // older full-aot users did depend on this.
5816 } else if (str_begins_with (arg, "no-direct-calls")) {
5817 opts->no_direct_calls = TRUE;
5818 } else if (str_begins_with (arg, "print-skipped")) {
5819 opts->print_skipped_methods = TRUE;
5820 } else if (str_begins_with (arg, "stats")) {
5822 } else if (str_begins_with (arg, "no-instances")) {
5823 opts->no_instances = TRUE;
5824 } else if (str_begins_with (arg, "log-generics")) {
5825 opts->log_generics = TRUE;
5826 } else if (str_begins_with (arg, "mtriple=")) {
5827 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5828 } else if (str_begins_with (arg, "llvm-path=")) {
5829 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5830 } else if (str_begins_with (arg, "readonly-value=")) {
5831 add_readonly_value (opts, arg + strlen ("readonly-value="));
5832 } else if (str_begins_with (arg, "info")) {
5833 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5835 } else if (str_begins_with (arg, "gc-maps")) {
5836 mini_gc_enable_gc_maps_for_aot ();
5837 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5838 printf ("Supported options for --aot:\n");
5839 printf (" outfile=\n");
5840 printf (" save-temps\n");
5841 printf (" keep-temps\n");
5842 printf (" write-symbols\n");
5843 printf (" metadata-only\n");
5844 printf (" bind-to-runtime-version\n");
5846 printf (" threads=\n");
5847 printf (" static\n");
5848 printf (" asmonly\n");
5849 printf (" asmwriter\n");
5850 printf (" nodebug\n");
5851 printf (" dwarfdebug\n");
5852 printf (" ntrampolines=\n");
5853 printf (" nrgctx-trampolines=\n");
5854 printf (" nimt-trampolines=\n");
5855 printf (" ngsharedvt-trampolines=\n");
5856 printf (" autoreg\n");
5857 printf (" tool-prefix=\n");
5858 printf (" readonly-value=\n");
5859 printf (" soft-debug\n");
5860 printf (" gc-maps\n");
5861 printf (" print-skipped\n");
5862 printf (" no-instances\n");
5863 printf (" stats\n");
5865 printf (" help/?\n");
5868 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5873 if (opts->use_trampolines_page) {
5874 opts->ntrampolines = 0;
5875 opts->nrgctx_trampolines = 0;
5876 opts->nimt_trampolines = 0;
5877 opts->ngsharedvt_arg_trampolines = 0;
5883 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5885 MonoMethod *method = (MonoMethod*)key;
5886 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5887 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5888 MonoAotCompile *acfg = user_data;
5890 new_ji->image = ji->image;
5891 new_ji->token = ji->token;
5892 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5896 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5898 if (klass->type_token)
5900 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5903 return can_encode_class (acfg, klass->element_class);
5908 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
5910 if (method->wrapper_type) {
5911 switch (method->wrapper_type) {
5912 case MONO_WRAPPER_NONE:
5913 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5914 case MONO_WRAPPER_XDOMAIN_INVOKE:
5915 case MONO_WRAPPER_STFLD:
5916 case MONO_WRAPPER_LDFLD:
5917 case MONO_WRAPPER_LDFLDA:
5918 case MONO_WRAPPER_LDFLD_REMOTE:
5919 case MONO_WRAPPER_STFLD_REMOTE:
5920 case MONO_WRAPPER_STELEMREF:
5921 case MONO_WRAPPER_ISINST:
5922 case MONO_WRAPPER_PROXY_ISINST:
5923 case MONO_WRAPPER_ALLOC:
5924 case MONO_WRAPPER_REMOTING_INVOKE:
5925 case MONO_WRAPPER_UNKNOWN:
5926 case MONO_WRAPPER_WRITE_BARRIER:
5927 case MONO_WRAPPER_DELEGATE_INVOKE:
5928 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
5929 case MONO_WRAPPER_DELEGATE_END_INVOKE:
5931 case MONO_WRAPPER_MANAGED_TO_MANAGED:
5932 case MONO_WRAPPER_CASTCLASS: {
5933 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5942 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5946 if (!method->token) {
5947 /* The method is part of a constructed type like Int[,].Set (). */
5948 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5949 if (method->klass->rank)
5959 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5961 switch (patch_info->type) {
5962 case MONO_PATCH_INFO_METHOD:
5963 case MONO_PATCH_INFO_METHODCONST: {
5964 MonoMethod *method = patch_info->data.method;
5966 return can_encode_method (acfg, method);
5968 case MONO_PATCH_INFO_VTABLE:
5969 case MONO_PATCH_INFO_CLASS_INIT:
5970 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5971 case MONO_PATCH_INFO_CLASS:
5972 case MONO_PATCH_INFO_IID:
5973 case MONO_PATCH_INFO_ADJUSTED_IID:
5974 if (!can_encode_class (acfg, patch_info->data.klass)) {
5975 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5979 case MONO_PATCH_INFO_RGCTX_FETCH: {
5980 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5982 if (!can_encode_method (acfg, entry->method))
5984 if (!can_encode_patch (acfg, entry->data))
5998 * AOT compile a given method.
5999 * This function might be called by multiple threads, so it must be thread-safe.
6002 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6005 MonoJumpInfo *patch_info;
6008 MonoMethod *wrapped;
6010 if (acfg->aot_opts.metadata_only)
6013 mono_acfg_lock (acfg);
6014 index = get_method_index (acfg, method);
6015 mono_acfg_unlock (acfg);
6017 /* fixme: maybe we can also precompile wrapper methods */
6018 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6019 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6020 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6021 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6025 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6028 wrapped = mono_marshal_method_from_wrapper (method);
6029 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6030 // FIXME: The wrapper should be generic too, but it is not
6033 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6036 InterlockedIncrement (&acfg->stats.mcount);
6039 if (method->is_generic || method->klass->generic_container) {
6040 InterlockedIncrement (&acfg->stats.genericcount);
6045 //acfg->aot_opts.print_skipped_methods = TRUE;
6048 * Since these methods are the only ones which are compiled with
6049 * AOT support, and they are not used by runtime startup/shutdown code,
6050 * the runtime will not see AOT methods during AOT compilation,so it
6051 * does not need to support them by creating a fake GOT etc.
6053 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
6054 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6055 if (acfg->aot_opts.print_skipped_methods)
6056 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6057 InterlockedIncrement (&acfg->stats.genericcount);
6060 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6061 if (acfg->aot_opts.print_skipped_methods)
6062 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6063 /* Let the exception happen at runtime */
6067 if (cfg->disable_aot) {
6068 if (acfg->aot_opts.print_skipped_methods)
6069 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6070 InterlockedIncrement (&acfg->stats.ocount);
6071 mono_destroy_compile (cfg);
6075 /* Nullify patches which need no aot processing */
6076 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6077 switch (patch_info->type) {
6078 case MONO_PATCH_INFO_LABEL:
6079 case MONO_PATCH_INFO_BB:
6080 patch_info->type = MONO_PATCH_INFO_NONE;
6087 /* Collect method->token associations from the cfg */
6088 mono_acfg_lock (acfg);
6089 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6090 mono_acfg_unlock (acfg);
6093 * Check for absolute addresses.
6096 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6097 switch (patch_info->type) {
6098 case MONO_PATCH_INFO_ABS:
6099 /* unable to handle this */
6108 if (acfg->aot_opts.print_skipped_methods)
6109 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6110 InterlockedIncrement (&acfg->stats.abscount);
6111 mono_destroy_compile (cfg);
6115 /* Lock for the rest of the code */
6116 mono_acfg_lock (acfg);
6119 * Check for methods/klasses we can't encode.
6122 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6123 if (!can_encode_patch (acfg, patch_info))
6128 if (acfg->aot_opts.print_skipped_methods)
6129 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6130 acfg->stats.ocount++;
6131 mono_destroy_compile (cfg);
6132 mono_acfg_unlock (acfg);
6136 /* Adds generic instances referenced by this method */
6138 * The depth is used to avoid infinite loops when generic virtual recursion is
6141 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6142 if (!acfg->aot_opts.no_instances && depth < 32) {
6143 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6144 switch (patch_info->type) {
6145 case MONO_PATCH_INFO_METHOD: {
6146 MonoMethod *m = patch_info->data.method;
6147 if (m->is_inflated) {
6148 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6149 mono_method_is_generic_sharable_impl_full (m, FALSE, FALSE, FALSE)) &&
6150 !method_has_type_vars (m)) {
6151 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6152 if (acfg->aot_opts.full_aot)
6153 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6155 add_extra_method_with_depth (acfg, m, depth + 1);
6156 add_types_from_method_header (acfg, m);
6159 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6161 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6162 add_extra_method_with_depth (acfg, m, depth + 1);
6165 case MONO_PATCH_INFO_VTABLE: {
6166 MonoClass *klass = patch_info->data.klass;
6168 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6169 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6172 case MONO_PATCH_INFO_SFLDA: {
6173 MonoClass *klass = patch_info->data.field->parent;
6175 /* The .cctor needs to run at runtime. */
6176 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6177 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6186 /* Determine whenever the method has GOT slots */
6187 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6188 switch (patch_info->type) {
6189 case MONO_PATCH_INFO_GOT_OFFSET:
6190 case MONO_PATCH_INFO_NONE:
6191 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6193 case MONO_PATCH_INFO_IMAGE:
6194 /* The assembly is stored in GOT slot 0 */
6195 if (patch_info->data.image != acfg->image)
6196 cfg->has_got_slots = TRUE;
6199 if (!is_plt_patch (patch_info))
6200 cfg->has_got_slots = TRUE;
6205 if (!cfg->has_got_slots)
6206 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6209 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6211 /* Make a copy of the patch info which is in the mempool */
6213 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6215 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6216 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6219 patches = new_patch_info;
6221 patches_end->next = new_patch_info;
6222 patches_end = new_patch_info;
6224 cfg->patch_info = patches;
6226 /* Make a copy of the unwind info */
6228 GSList *l, *unwind_ops;
6232 for (l = cfg->unwind_ops; l; l = l->next) {
6233 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6234 memcpy (op, l->data, sizeof (MonoUnwindOp));
6235 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6237 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6239 /* Make a copy of the argument/local info */
6241 MonoInst **args, **locals;
6242 MonoMethodSignature *sig;
6243 MonoMethodHeader *header;
6246 sig = mono_method_signature (method);
6247 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6248 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6249 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6250 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6254 header = mono_method_get_header (method);
6255 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6256 for (i = 0; i < header->num_locals; ++i) {
6257 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6258 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6260 cfg->locals = locals;
6263 /* Free some fields used by cfg to conserve memory */
6264 mono_mempool_destroy (cfg->mempool);
6265 cfg->mempool = NULL;
6266 g_free (cfg->varinfo);
6267 cfg->varinfo = NULL;
6271 mono_regstate_free (cfg->rs);
6275 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6277 while (index >= acfg->cfgs_size) {
6278 MonoCompile **new_cfgs;
6281 new_size = acfg->cfgs_size * 2;
6282 new_cfgs = g_new0 (MonoCompile*, new_size);
6283 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6284 g_free (acfg->cfgs);
6285 acfg->cfgs = new_cfgs;
6286 acfg->cfgs_size = new_size;
6288 acfg->cfgs [index] = cfg;
6290 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6293 if (cfg->orig_method->wrapper_type)
6294 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6297 mono_acfg_unlock (acfg);
6299 InterlockedIncrement (&acfg->stats.ccount);
6303 compile_thread_main (gpointer *user_data)
6305 MonoDomain *domain = user_data [0];
6306 MonoAotCompile *acfg = user_data [1];
6307 GPtrArray *methods = user_data [2];
6310 mono_thread_attach (domain);
6312 for (i = 0; i < methods->len; ++i)
6313 compile_method (acfg, g_ptr_array_index (methods, i));
6317 load_profile_files (MonoAotCompile *acfg)
6321 int file_index, res, method_index, i;
6324 GList *unordered, *l;
6329 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6331 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6336 infile = fopen (tmp, "r");
6339 printf ("Using profile data file '%s'\n", tmp);
6344 res = fscanf (infile, "%32s\n", ver);
6345 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6346 printf ("Profile file has wrong version or invalid.\n");
6353 MonoMethodDesc *desc;
6356 if (fgets (name, 1023, infile) == NULL)
6359 /* Kill the newline */
6360 if (strlen (name) > 0)
6361 name [strlen (name) - 1] = '\0';
6363 desc = mono_method_desc_new (name, TRUE);
6365 method = mono_method_desc_search_in_image (desc, acfg->image);
6367 if (method && mono_method_get_token (method)) {
6368 token = mono_method_get_token (method);
6369 method_index = mono_metadata_token_index (token) - 1;
6372 for (i = 0; i < acfg->method_order->len; ++i) {
6373 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6379 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6381 //printf ("No method found matching '%s'.\n", name);
6387 /* Add missing methods */
6389 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6391 for (i = 0; i < acfg->method_order->len; ++i) {
6392 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6398 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6400 unordered = g_list_reverse (unordered);
6401 for (l = unordered; l; l = l->next)
6402 g_ptr_array_add (acfg->method_order, l->data);
6405 /* Used by the LLVM backend */
6407 mono_aot_get_got_offset (MonoJumpInfo *ji)
6409 return get_got_offset (llvm_acfg, ji);
6413 mono_aot_get_method_name (MonoCompile *cfg)
6415 if (llvm_acfg->aot_opts.static_link)
6416 /* Include the assembly name too to avoid duplicate symbol errors */
6417 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6419 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6423 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6425 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6426 MonoPltEntry *plt_entry;
6429 ji->data.target = data;
6431 if (!can_encode_patch (llvm_acfg, ji))
6434 plt_entry = get_plt_entry (llvm_acfg, ji);
6435 plt_entry->llvm_used = TRUE;
6437 #if defined(TARGET_MACH)
6438 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6440 return g_strdup_printf (plt_entry->llvm_symbol);
6445 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6449 mono_acfg_lock (llvm_acfg);
6450 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6451 mono_acfg_unlock (llvm_acfg);
6461 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6465 emit_llvm_file (MonoAotCompile *acfg)
6467 char *command, *opts, *tempbc;
6469 MonoJumpInfo *patch_info;
6472 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6476 /* Compute the final size of the got */
6477 for (i = 0; i < acfg->nmethods; ++i) {
6478 if (acfg->cfgs [i]) {
6479 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6480 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6481 if (!is_plt_patch (patch_info))
6482 get_got_offset (acfg, patch_info);
6484 get_plt_entry (acfg, patch_info);
6490 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6492 if (acfg->aot_opts.full_aot) {
6496 * Need to add the got entries used by the trampolines.
6497 * This is only a conservative approximation.
6499 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6500 /* For the generic + rgctx trampolines */
6501 acfg->final_got_size += 400;
6502 /* For the specific trampolines */
6503 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6504 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6509 tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
6510 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6514 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6515 * a lot of time, and doesn't seem to save much space.
6516 * The following optimizations cannot be enabled:
6518 * - 'jump-threading' changes our blockaddress references to int constants.
6519 * - 'basiccg' fails because it contains:
6520 * if (CS && !isa<IntrinsicInst>(II)) {
6521 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
6522 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
6523 * The opt list below was produced by taking the output of:
6524 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
6525 * then removing tailcallelim + the global opts, and adding a second gvn.
6527 opts = g_strdup ("-instcombine -simplifycfg");
6528 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");
6530 command = g_strdup_printf ("%sopt -f %s -o %s.opt.bc %s.bc", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
6531 printf ("Executing opt: %s\n", command);
6532 if (system (command) != 0) {
6538 if (!acfg->llc_args)
6539 acfg->llc_args = g_string_new ("");
6541 /* Verbose asm slows down llc greatly */
6542 g_string_append (acfg->llc_args, " -asm-verbose=false");
6544 if (acfg->aot_opts.mtriple)
6545 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
6547 if (llvm_acfg->aot_opts.static_link)
6548 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
6550 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6551 unlink (acfg->tmpfname);
6553 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);
6555 printf ("Executing llc: %s\n", command);
6557 if (system (command) != 0) {
6564 emit_code (MonoAotCompile *acfg)
6566 int oindex, i, prev_index;
6568 char end_symbol [256];
6570 #if defined(TARGET_POWERPC64)
6571 sprintf (symbol, ".Lgot_addr");
6572 emit_section_change (acfg, ".text", 0);
6573 emit_alignment (acfg, 8);
6574 emit_label (acfg, symbol);
6575 emit_pointer (acfg, acfg->got_symbol);
6579 * This global symbol is used to compute the address of each method using the
6580 * code_offsets array. It is also used to compute the memory ranges occupied by
6581 * AOT code, so it must be equal to the address of the first emitted method.
6583 sprintf (symbol, "methods");
6584 emit_section_change (acfg, ".text", 0);
6585 emit_alignment (acfg, 8);
6587 for (i = 0; i < acfg->nmethods; ++i) {
6588 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
6589 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
6593 if (i == acfg->nmethods)
6594 /* No LLVM compiled methods */
6595 emit_label (acfg, symbol);
6597 emit_label (acfg, symbol);
6601 * Emit some padding so the local symbol for the first method doesn't have the
6602 * same address as 'methods'.
6604 #if defined(__default_codegen__)
6605 emit_zero_bytes (acfg, 16);
6606 #elif defined(__native_client_codegen__)
6608 const int kPaddingSize = 16;
6609 guint8 pad_buffer[kPaddingSize];
6610 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
6611 emit_bytes (acfg, pad_buffer, kPaddingSize);
6615 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6619 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6621 cfg = acfg->cfgs [i];
6626 method = cfg->orig_method;
6628 /* Emit unbox trampoline */
6629 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
6630 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
6632 emit_section_change (acfg, ".text", 0);
6633 #ifdef __native_client_codegen__
6634 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6637 if (acfg->thumb_mixed && cfg->compile_llvm)
6638 fprintf (acfg->fp, "\n.thumb_func\n");
6640 emit_label (acfg, symbol);
6642 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
6645 if (cfg->compile_llvm)
6646 acfg->stats.llvm_count ++;
6648 emit_method_code (acfg, cfg);
6651 sprintf (symbol, "methods_end");
6652 emit_section_change (acfg, ".text", 0);
6653 emit_alignment (acfg, 8);
6654 emit_label (acfg, symbol);
6657 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6658 * from optimizing them away, since it doesn't see that code_offsets references them.
6659 * JITted methods don't need this since they are referenced using assembler local
6661 * FIXME: This is why write-symbols doesn't work on OSX ?
6663 if (acfg->llvm && acfg->need_no_dead_strip) {
6664 fprintf (acfg->fp, "\n");
6665 for (i = 0; i < acfg->nmethods; ++i) {
6666 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6667 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6672 if (acfg->direct_method_addresses) {
6673 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
6675 sprintf (symbol, "method_addresses");
6676 emit_section_change (acfg, RODATA_SECT, 1);
6677 emit_alignment (acfg, 8);
6678 emit_label (acfg, symbol);
6680 for (i = 0; i < acfg->nmethods; ++i) {
6681 if (acfg->cfgs [i]) {
6682 emit_pointer (acfg, acfg->cfgs [i]->asm_symbol);
6684 emit_pointer (acfg, NULL);
6689 sprintf (symbol, "code_offsets");
6690 emit_section_change (acfg, RODATA_SECT, 1);
6691 emit_alignment (acfg, 8);
6692 emit_label (acfg, symbol);
6694 sprintf (symbol, "code_offsets");
6695 emit_section_change (acfg, RODATA_SECT, 1);
6696 emit_alignment (acfg, 8);
6697 emit_label (acfg, symbol);
6699 acfg->stats.offsets_size += acfg->nmethods * 4;
6701 sprintf (end_symbol, "methods");
6702 for (i = 0; i < acfg->nmethods; ++i) {
6703 if (acfg->cfgs [i]) {
6704 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6706 emit_int32 (acfg, 0xffffffff);
6711 sprintf (symbol, "code_offsets");
6712 emit_section_change (acfg, RODATA_SECT, 1);
6713 emit_alignment (acfg, 8);
6714 emit_label (acfg, symbol);
6716 acfg->stats.offsets_size += acfg->nmethods * 4;
6718 sprintf (end_symbol, "methods");
6719 for (i = 0; i < acfg->nmethods; ++i) {
6720 if (acfg->cfgs [i]) {
6721 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6723 emit_int32 (acfg, 0xffffffff);
6729 /* Emit a sorted table mapping methods to their unbox trampolines */
6730 sprintf (symbol, "unbox_trampolines");
6731 emit_section_change (acfg, RODATA_SECT, 1);
6732 emit_alignment (acfg, 8);
6733 emit_label (acfg, symbol);
6735 sprintf (end_symbol, "methods");
6737 for (i = 0; i < acfg->nmethods; ++i) {
6742 cfg = acfg->cfgs [i];
6746 method = cfg->orig_method;
6748 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
6749 index = get_method_index (acfg, method);
6750 sprintf (symbol, "ut_%d", index);
6752 emit_int32 (acfg, index);
6753 if (acfg->direct_method_addresses)
6754 emit_pointer (acfg, symbol);
6756 emit_symbol_diff (acfg, symbol, end_symbol, 0);
6757 /* Make sure the table is sorted by index */
6758 g_assert (index > prev_index);
6762 sprintf (symbol, "unbox_trampolines_end");
6763 emit_label (acfg, symbol);
6767 emit_info (MonoAotCompile *acfg)
6773 offsets = g_new0 (gint32, acfg->nmethods);
6775 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6776 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6778 if (acfg->cfgs [i]) {
6779 emit_method_info (acfg, acfg->cfgs [i]);
6780 offsets [i] = acfg->cfgs [i]->method_info_offset;
6786 sprintf (symbol, "method_info_offsets");
6787 emit_section_change (acfg, RODATA_SECT, 1);
6788 emit_alignment (acfg, 8);
6789 emit_label (acfg, symbol);
6791 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6796 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6798 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6799 #define mix(a,b,c) { \
6800 a -= c; a ^= rot(c, 4); c += b; \
6801 b -= a; b ^= rot(a, 6); a += c; \
6802 c -= b; c ^= rot(b, 8); b += a; \
6803 a -= c; a ^= rot(c,16); c += b; \
6804 b -= a; b ^= rot(a,19); a += c; \
6805 c -= b; c ^= rot(b, 4); b += a; \
6807 #define final(a,b,c) { \
6808 c ^= b; c -= rot(b,14); \
6809 a ^= c; a -= rot(c,11); \
6810 b ^= a; b -= rot(a,25); \
6811 c ^= b; c -= rot(b,16); \
6812 a ^= c; a -= rot(c,4); \
6813 b ^= a; b -= rot(a,14); \
6814 c ^= b; c -= rot(b,24); \
6818 mono_aot_type_hash (MonoType *t1)
6820 guint hash = t1->type;
6822 hash |= t1->byref << 6; /* do not collide with t1->type values */
6824 case MONO_TYPE_VALUETYPE:
6825 case MONO_TYPE_CLASS:
6826 case MONO_TYPE_SZARRAY:
6827 /* check if the distribution is good enough */
6828 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6830 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6831 case MONO_TYPE_ARRAY:
6832 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6833 case MONO_TYPE_GENERICINST:
6834 return ((hash << 5) - hash) ^ 0;
6841 * mono_aot_method_hash:
6843 * Return a hash code for methods which only depends on metadata.
6846 mono_aot_method_hash (MonoMethod *method)
6848 MonoMethodSignature *sig;
6852 guint32 *hashes_start, *hashes;
6854 MonoGenericInst *ginst = NULL;
6856 /* Similar to the hash in mono_method_get_imt_slot () */
6858 sig = mono_method_signature (method);
6860 if (method->is_inflated)
6861 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6863 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6864 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6865 hashes = hashes_start;
6867 /* Some wrappers are assigned to random classes */
6868 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6869 klass = method->klass;
6871 klass = mono_defaults.object_class;
6873 if (!method->wrapper_type) {
6874 char *full_name = mono_type_full_name (&klass->byval_arg);
6876 hashes [0] = mono_metadata_str_hash (full_name);
6880 hashes [0] = mono_metadata_str_hash (klass->name);
6881 hashes [1] = mono_metadata_str_hash (klass->name_space);
6883 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6884 /* The method name includes a stringified pointer */
6887 hashes [2] = mono_metadata_str_hash (method->name);
6888 hashes [3] = method->wrapper_type;
6889 hashes [4] = mono_aot_type_hash (sig->ret);
6891 for (i = 0; i < sig->param_count; i++) {
6892 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6895 for (i = 0; i < ginst->type_argc; ++i)
6896 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6898 g_assert (hindex == hashes_count);
6900 /* Setup internal state */
6901 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6903 /* Handle most of the hashes */
6904 while (hashes_count > 3) {
6913 /* Handle the last 3 hashes (all the case statements fall through) */
6914 switch (hashes_count) {
6915 case 3 : c += hashes [2];
6916 case 2 : b += hashes [1];
6917 case 1 : a += hashes [0];
6919 case 0: /* nothing left to add */
6923 free (hashes_start);
6932 * mono_aot_get_array_helper_from_wrapper;
6934 * Get the helper method in Array called by an array wrapper method.
6937 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6941 MonoGenericContext ctx;
6942 MonoType *args [16];
6943 char *mname, *iname, *s, *s2, *helper_name = NULL;
6945 prefix = "System.Collections.Generic";
6946 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6947 s2 = strstr (s, "`1.");
6953 //printf ("X: %s %s\n", iname, mname);
6955 if (!strcmp (iname, "IList"))
6956 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6958 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6959 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6961 g_free (helper_name);
6964 if (m->is_generic) {
6965 memset (&ctx, 0, sizeof (ctx));
6966 args [0] = &method->klass->element_class->byval_arg;
6967 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6968 m = mono_class_inflate_generic_method (m, &ctx);
6974 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6976 typedef struct HashEntry {
6977 guint32 key, value, index;
6978 struct HashEntry *next;
6982 * emit_extra_methods:
6984 * Emit methods which are not in the METHOD table, like wrappers.
6987 emit_extra_methods (MonoAotCompile *acfg)
6989 int i, table_size, buf_size;
6992 guint32 *info_offsets;
6995 HashEntry *entry, *new_entry;
6996 int nmethods, max_chain_length;
6999 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7001 /* Emit method info */
7003 for (i = 0; i < acfg->extra_methods->len; ++i) {
7004 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7005 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7011 p = buf = g_malloc (buf_size);
7015 method = cfg->method_to_register;
7017 encode_method_ref (acfg, method, p, &p);
7019 g_assert ((p - buf) < buf_size);
7021 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7026 * Construct a chained hash table for mapping indexes in extra_method_info to
7029 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7030 table = g_ptr_array_sized_new (table_size);
7031 for (i = 0; i < table_size; ++i)
7032 g_ptr_array_add (table, NULL);
7033 chain_lengths = g_new0 (int, table_size);
7034 max_chain_length = 0;
7035 for (i = 0; i < acfg->extra_methods->len; ++i) {
7036 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7037 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7043 key = info_offsets [i];
7044 value = get_method_index (acfg, method);
7046 hash = mono_aot_method_hash (method) % table_size;
7048 chain_lengths [hash] ++;
7049 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7051 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7052 new_entry->key = key;
7053 new_entry->value = value;
7055 entry = g_ptr_array_index (table, hash);
7056 if (entry == NULL) {
7057 new_entry->index = hash;
7058 g_ptr_array_index (table, hash) = new_entry;
7061 entry = entry->next;
7063 entry->next = new_entry;
7064 new_entry->index = table->len;
7065 g_ptr_array_add (table, new_entry);
7069 //printf ("MAX: %d\n", max_chain_length);
7071 /* Emit the table */
7072 sprintf (symbol, "extra_method_table");
7073 emit_section_change (acfg, RODATA_SECT, 0);
7074 emit_alignment (acfg, 8);
7075 emit_label (acfg, symbol);
7077 emit_int32 (acfg, table_size);
7078 for (i = 0; i < table->len; ++i) {
7079 HashEntry *entry = g_ptr_array_index (table, i);
7081 if (entry == NULL) {
7082 emit_int32 (acfg, 0);
7083 emit_int32 (acfg, 0);
7084 emit_int32 (acfg, 0);
7086 //g_assert (entry->key > 0);
7087 emit_int32 (acfg, entry->key);
7088 emit_int32 (acfg, entry->value);
7090 emit_int32 (acfg, entry->next->index);
7092 emit_int32 (acfg, 0);
7097 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7098 * This is used by mono_aot_find_jit_info ().
7100 sprintf (symbol, "extra_method_info_offsets");
7101 emit_section_change (acfg, RODATA_SECT, 0);
7102 emit_alignment (acfg, 8);
7103 emit_label (acfg, symbol);
7105 emit_int32 (acfg, acfg->extra_methods->len);
7106 for (i = 0; i < acfg->extra_methods->len; ++i) {
7107 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7109 emit_int32 (acfg, get_method_index (acfg, method));
7110 emit_int32 (acfg, info_offsets [i]);
7115 emit_exception_info (MonoAotCompile *acfg)
7121 offsets = g_new0 (gint32, acfg->nmethods);
7122 for (i = 0; i < acfg->nmethods; ++i) {
7123 if (acfg->cfgs [i]) {
7124 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7125 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7131 sprintf (symbol, "ex_info_offsets");
7132 emit_section_change (acfg, RODATA_SECT, 1);
7133 emit_alignment (acfg, 8);
7134 emit_label (acfg, symbol);
7136 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7141 emit_unwind_info (MonoAotCompile *acfg)
7147 * The unwind info contains a lot of duplicates so we emit each unique
7148 * entry once, and only store the offset from the start of the table in the
7152 sprintf (symbol, "unwind_info");
7153 emit_section_change (acfg, RODATA_SECT, 1);
7154 emit_alignment (acfg, 8);
7155 emit_label (acfg, symbol);
7157 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7158 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7159 guint8 *unwind_info;
7160 guint32 unwind_info_len;
7164 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7167 encode_value (unwind_info_len, p, &p);
7168 emit_bytes (acfg, buf, p - buf);
7169 emit_bytes (acfg, unwind_info, unwind_info_len);
7171 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7176 emit_class_info (MonoAotCompile *acfg)
7182 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7183 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7184 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7186 sprintf (symbol, "class_info_offsets");
7187 emit_section_change (acfg, RODATA_SECT, 1);
7188 emit_alignment (acfg, 8);
7189 emit_label (acfg, symbol);
7191 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7195 typedef struct ClassNameTableEntry {
7196 guint32 token, index;
7197 struct ClassNameTableEntry *next;
7198 } ClassNameTableEntry;
7201 emit_class_name_table (MonoAotCompile *acfg)
7204 guint32 token, hash;
7209 ClassNameTableEntry *entry, *new_entry;
7212 * Construct a chained hash table for mapping class names to typedef tokens.
7214 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7215 table = g_ptr_array_sized_new (table_size);
7216 for (i = 0; i < table_size; ++i)
7217 g_ptr_array_add (table, NULL);
7218 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7219 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7220 klass = mono_class_get (acfg->image, token);
7222 mono_loader_clear_error ();
7225 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7226 hash = mono_metadata_str_hash (full_name) % table_size;
7229 /* FIXME: Allocate from the mempool */
7230 new_entry = g_new0 (ClassNameTableEntry, 1);
7231 new_entry->token = token;
7233 entry = g_ptr_array_index (table, hash);
7234 if (entry == NULL) {
7235 new_entry->index = hash;
7236 g_ptr_array_index (table, hash) = new_entry;
7239 entry = entry->next;
7241 entry->next = new_entry;
7242 new_entry->index = table->len;
7243 g_ptr_array_add (table, new_entry);
7247 /* Emit the table */
7248 sprintf (symbol, "class_name_table");
7249 emit_section_change (acfg, RODATA_SECT, 0);
7250 emit_alignment (acfg, 8);
7251 emit_label (acfg, symbol);
7253 /* FIXME: Optimize memory usage */
7254 g_assert (table_size < 65000);
7255 emit_int16 (acfg, table_size);
7256 g_assert (table->len < 65000);
7257 for (i = 0; i < table->len; ++i) {
7258 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7260 if (entry == NULL) {
7261 emit_int16 (acfg, 0);
7262 emit_int16 (acfg, 0);
7264 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7266 emit_int16 (acfg, entry->next->index);
7268 emit_int16 (acfg, 0);
7274 emit_image_table (MonoAotCompile *acfg)
7280 * The image table is small but referenced in a lot of places.
7281 * So we emit it at once, and reference its elements by an index.
7284 sprintf (symbol, "image_table");
7285 emit_section_change (acfg, RODATA_SECT, 1);
7286 emit_alignment (acfg, 8);
7287 emit_label (acfg, symbol);
7289 emit_int32 (acfg, acfg->image_table->len);
7290 for (i = 0; i < acfg->image_table->len; i++) {
7291 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7292 MonoAssemblyName *aname = &image->assembly->aname;
7294 /* FIXME: Support multi-module assemblies */
7295 g_assert (image->assembly->image == image);
7297 emit_string (acfg, image->assembly_name);
7298 emit_string (acfg, image->guid);
7299 emit_string (acfg, aname->culture ? aname->culture : "");
7300 emit_string (acfg, (const char*)aname->public_key_token);
7302 emit_alignment (acfg, 8);
7303 emit_int32 (acfg, aname->flags);
7304 emit_int32 (acfg, aname->major);
7305 emit_int32 (acfg, aname->minor);
7306 emit_int32 (acfg, aname->build);
7307 emit_int32 (acfg, aname->revision);
7312 emit_got_info (MonoAotCompile *acfg)
7315 int i, first_plt_got_patch, buf_size;
7317 guint32 *got_info_offsets;
7319 /* Add the patches needed by the PLT to the GOT */
7320 acfg->plt_got_offset_base = acfg->got_offset;
7321 first_plt_got_patch = acfg->got_patches->len;
7322 for (i = 1; i < acfg->plt_offset; ++i) {
7323 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7325 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7327 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7330 acfg->got_offset += acfg->plt_offset;
7334 * - optimize offsets table.
7335 * - reduce number of exported symbols.
7336 * - emit info for a klass only once.
7337 * - determine when a method uses a GOT slot which is guaranteed to be already
7339 * - clean up and document the code.
7340 * - use String.Empty in class libs.
7343 /* Encode info required to decode shared GOT entries */
7344 buf_size = acfg->got_patches->len * 128;
7345 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7346 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7347 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7349 if (acfg->plt_offset)
7350 acfg->plt_got_info_offsets [0] = 0;
7351 for (i = 0; i < acfg->got_patches->len; ++i) {
7352 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7357 encode_value (ji->type, p, &p);
7359 encode_patch (acfg, ji, p, &p);
7360 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7361 g_assert (p - buf <= buf_size);
7362 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7364 if (i >= first_plt_got_patch)
7365 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7366 acfg->stats.got_info_size += p - buf;
7369 /* Emit got_info_offsets table */
7370 sprintf (symbol, "got_info_offsets");
7371 emit_section_change (acfg, RODATA_SECT, 1);
7372 emit_alignment (acfg, 8);
7373 emit_label (acfg, symbol);
7375 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7376 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7380 emit_got (MonoAotCompile *acfg)
7385 /* Don't make GOT global so accesses to it don't need relocations */
7386 sprintf (symbol, "%s", acfg->got_symbol);
7387 emit_section_change (acfg, ".bss", 0);
7388 emit_alignment (acfg, 8);
7389 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7390 emit_label (acfg, symbol);
7391 if (acfg->got_offset > 0)
7392 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7394 sprintf (symbol, "got_end");
7395 emit_label (acfg, symbol);
7399 typedef struct GlobalsTableEntry {
7400 guint32 value, index;
7401 struct GlobalsTableEntry *next;
7402 } GlobalsTableEntry;
7405 emit_globals (MonoAotCompile *acfg)
7411 GlobalsTableEntry *entry, *new_entry;
7413 if (!acfg->aot_opts.static_link)
7417 * When static linking, we emit a table containing our globals.
7421 * Construct a chained hash table for mapping global names to their index in
7422 * the globals table.
7424 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7425 table = g_ptr_array_sized_new (table_size);
7426 for (i = 0; i < table_size; ++i)
7427 g_ptr_array_add (table, NULL);
7428 for (i = 0; i < acfg->globals->len; ++i) {
7429 char *name = g_ptr_array_index (acfg->globals, i);
7431 hash = mono_metadata_str_hash (name) % table_size;
7433 /* FIXME: Allocate from the mempool */
7434 new_entry = g_new0 (GlobalsTableEntry, 1);
7435 new_entry->value = i;
7437 entry = g_ptr_array_index (table, hash);
7438 if (entry == NULL) {
7439 new_entry->index = hash;
7440 g_ptr_array_index (table, hash) = new_entry;
7443 entry = entry->next;
7445 entry->next = new_entry;
7446 new_entry->index = table->len;
7447 g_ptr_array_add (table, new_entry);
7451 /* Emit the table */
7452 sprintf (symbol, ".Lglobals_hash");
7453 emit_section_change (acfg, RODATA_SECT, 0);
7454 emit_alignment (acfg, 8);
7455 emit_label (acfg, symbol);
7457 /* FIXME: Optimize memory usage */
7458 g_assert (table_size < 65000);
7459 emit_int16 (acfg, table_size);
7460 for (i = 0; i < table->len; ++i) {
7461 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7463 if (entry == NULL) {
7464 emit_int16 (acfg, 0);
7465 emit_int16 (acfg, 0);
7467 emit_int16 (acfg, entry->value + 1);
7469 emit_int16 (acfg, entry->next->index);
7471 emit_int16 (acfg, 0);
7475 /* Emit the names */
7476 for (i = 0; i < acfg->globals->len; ++i) {
7477 char *name = g_ptr_array_index (acfg->globals, i);
7479 sprintf (symbol, "name_%d", i);
7480 emit_section_change (acfg, RODATA_SECT, 1);
7482 emit_alignment (acfg, 4);
7484 emit_label (acfg, symbol);
7485 emit_string (acfg, name);
7488 /* Emit the globals table */
7489 sprintf (symbol, "globals");
7490 emit_section_change (acfg, ".data", 0);
7491 /* This is not a global, since it is accessed by the init function */
7492 emit_alignment (acfg, 8);
7493 emit_label (acfg, symbol);
7495 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
7496 emit_pointer (acfg, symbol);
7498 for (i = 0; i < acfg->globals->len; ++i) {
7499 char *name = g_ptr_array_index (acfg->globals, i);
7501 sprintf (symbol, "name_%d", i);
7502 emit_pointer (acfg, symbol);
7504 sprintf (symbol, "%s", name);
7505 emit_pointer (acfg, symbol);
7507 /* Null terminate the table */
7508 emit_int32 (acfg, 0);
7509 emit_int32 (acfg, 0);
7513 emit_autoreg (MonoAotCompile *acfg)
7518 * Emit a function into the .ctor section which will be called by the ELF
7519 * loader to register this module with the runtime.
7521 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
7524 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
7526 arch_emit_autoreg (acfg, symbol);
7532 emit_mem_end (MonoAotCompile *acfg)
7536 sprintf (symbol, "mem_end");
7537 emit_section_change (acfg, ".text", 1);
7538 emit_alignment (acfg, 8);
7539 emit_label (acfg, symbol);
7543 * Emit a structure containing all the information not stored elsewhere.
7546 emit_file_info (MonoAotCompile *acfg)
7551 const char *gc_name;
7554 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
7556 if (acfg->aot_opts.bind_to_runtime_version) {
7557 build_info = mono_get_runtime_build_info ();
7558 emit_string_symbol (acfg, "runtime_version", build_info);
7559 g_free (build_info);
7561 emit_string_symbol (acfg, "runtime_version", "");
7564 /* Emit a string holding the assembly name */
7565 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
7568 * The managed allocators are GC specific, so can't use an AOT image created by one GC
7571 gc_name = mono_gc_get_gc_name ();
7572 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
7574 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
7575 emit_section_change (acfg, ".data", 0);
7576 emit_alignment (acfg, 8);
7577 emit_label (acfg, symbol);
7578 if (!acfg->aot_opts.static_link)
7579 emit_global (acfg, symbol, FALSE);
7581 /* The data emitted here must match MonoAotFileInfo. */
7583 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
7584 emit_int32 (acfg, 0);
7587 * We emit pointers to our data structures instead of emitting global symbols which
7588 * point to them, to reduce the number of globals, and because using globals leads to
7589 * various problems (i.e. arm/thumb).
7591 emit_pointer (acfg, acfg->got_symbol);
7592 emit_pointer (acfg, "methods");
7595 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
7597 emit_pointer (acfg, "mono_eh_frame");
7599 emit_pointer (acfg, NULL);
7601 emit_pointer (acfg, "blob");
7602 emit_pointer (acfg, "class_name_table");
7603 emit_pointer (acfg, "class_info_offsets");
7604 emit_pointer (acfg, "method_info_offsets");
7605 emit_pointer (acfg, "ex_info_offsets");
7606 emit_pointer (acfg, "code_offsets");
7608 emit_pointer (acfg, "method_addresses");
7610 emit_pointer (acfg, "extra_method_info_offsets");
7611 emit_pointer (acfg, "extra_method_table");
7612 emit_pointer (acfg, "got_info_offsets");
7613 emit_pointer (acfg, "methods_end");
7614 emit_pointer (acfg, "unwind_info");
7615 emit_pointer (acfg, "mem_end");
7616 emit_pointer (acfg, "image_table");
7617 emit_pointer (acfg, "plt");
7618 emit_pointer (acfg, "plt_end");
7619 emit_pointer (acfg, "assembly_guid");
7620 emit_pointer (acfg, "runtime_version");
7621 if (acfg->num_trampoline_got_entries) {
7622 emit_pointer (acfg, "specific_trampolines");
7623 emit_pointer (acfg, "static_rgctx_trampolines");
7624 emit_pointer (acfg, "imt_thunks");
7625 emit_pointer (acfg, "gsharedvt_arg_trampolines");
7627 emit_pointer (acfg, NULL);
7628 emit_pointer (acfg, NULL);
7629 emit_pointer (acfg, NULL);
7630 emit_pointer (acfg, NULL);
7632 if (acfg->thumb_mixed) {
7633 emit_pointer (acfg, "thumb_end");
7635 emit_pointer (acfg, NULL);
7637 if (acfg->aot_opts.static_link) {
7638 emit_pointer (acfg, "globals");
7640 emit_pointer (acfg, NULL);
7642 emit_pointer (acfg, "assembly_name");
7643 emit_pointer (acfg, "unbox_trampolines");
7644 emit_pointer (acfg, "unbox_trampolines_end");
7646 emit_int32 (acfg, acfg->plt_got_offset_base);
7647 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7648 emit_int32 (acfg, acfg->plt_offset);
7649 emit_int32 (acfg, acfg->nmethods);
7650 emit_int32 (acfg, acfg->flags);
7651 emit_int32 (acfg, acfg->opts);
7652 emit_int32 (acfg, acfg->simd_opts);
7653 emit_int32 (acfg, gc_name_offset);
7655 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7656 emit_int32 (acfg, acfg->num_trampolines [i]);
7657 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7658 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
7659 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7660 emit_int32 (acfg, acfg->trampoline_size [i]);
7661 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
7663 #if defined (TARGET_ARM) && defined (TARGET_MACH)
7668 memset (&t, 0, sizeof (MonoType));
7669 t.type = MONO_TYPE_R8;
7670 mono_type_size (&t, &align);
7672 emit_int32 (acfg, align);
7674 memset (&t, 0, sizeof (MonoType));
7675 t.type = MONO_TYPE_I8;
7676 mono_type_size (&t, &align);
7678 emit_int32 (acfg, align);
7681 emit_int32 (acfg, __alignof__ (double));
7682 emit_int32 (acfg, __alignof__ (gint64));
7685 if (acfg->aot_opts.static_link) {
7689 * Emit a global symbol which can be passed by an embedding app to
7690 * mono_aot_register_module (). The symbol points to a pointer to the the file info
7693 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
7695 /* Get rid of characters which cannot occur in symbols */
7697 for (p = symbol; *p; ++p) {
7698 if (!(isalnum (*p) || *p == '_'))
7701 acfg->static_linking_symbol = g_strdup (symbol);
7702 emit_global_inner (acfg, symbol, FALSE);
7703 emit_label (acfg, symbol);
7704 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
7709 emit_blob (MonoAotCompile *acfg)
7713 sprintf (symbol, "blob");
7714 emit_section_change (acfg, RODATA_SECT, 1);
7715 emit_alignment (acfg, 8);
7716 emit_label (acfg, symbol);
7718 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7722 emit_dwarf_info (MonoAotCompile *acfg)
7724 #ifdef EMIT_DWARF_INFO
7728 /* DIEs for methods */
7729 for (i = 0; i < acfg->nmethods; ++i) {
7730 MonoCompile *cfg = acfg->cfgs [i];
7735 // FIXME: LLVM doesn't define .Lme_...
7736 if (cfg->compile_llvm)
7739 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7741 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 ()));
7747 collect_methods (MonoAotCompile *acfg)
7750 MonoImage *image = acfg->image;
7752 /* Collect methods */
7753 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7755 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7757 method = mono_get_method (acfg->image, token, NULL);
7760 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7764 /* Load all methods eagerly to skip the slower lazy loading code */
7765 mono_class_setup_methods (method->klass);
7767 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7768 /* Compile the wrapper instead */
7769 /* We do this here instead of add_wrappers () because it is easy to do it here */
7770 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7774 /* FIXME: Some mscorlib methods don't have debug info */
7776 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7777 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7778 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7779 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7780 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7781 if (!mono_debug_lookup_method (method)) {
7782 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7789 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7790 add_method_with_index (acfg, method, i, FALSE);
7791 acfg->method_index ++;
7794 /* gsharedvt methods */
7795 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
7797 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
7799 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
7802 method = mono_get_method (acfg->image, token, NULL);
7805 if (method->is_generic || method->klass->generic_container) {
7806 MonoMethod *gshared;
7808 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
7809 add_extra_method (acfg, gshared);
7813 add_generic_instances (acfg);
7815 if (acfg->aot_opts.full_aot)
7816 add_wrappers (acfg);
7820 compile_methods (MonoAotCompile *acfg)
7824 if (acfg->aot_opts.nthreads > 0) {
7829 gpointer *user_data;
7830 MonoMethod **methods;
7832 methods_len = acfg->methods->len;
7834 len = acfg->methods->len / acfg->aot_opts.nthreads;
7837 * Partition the list of methods into fragments, and hand it to threads to
7840 threads = g_ptr_array_new ();
7841 /* Make a copy since acfg->methods is modified by compile_method () */
7842 methods = g_new0 (MonoMethod*, methods_len);
7843 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7844 for (i = 0; i < methods_len; ++i)
7845 methods [i] = g_ptr_array_index (acfg->methods, i);
7847 while (i < methods_len) {
7848 frag = g_ptr_array_new ();
7849 for (j = 0; j < len; ++j) {
7850 if (i < methods_len) {
7851 g_ptr_array_add (frag, methods [i]);
7856 user_data = g_new0 (gpointer, 3);
7857 user_data [0] = mono_domain_get ();
7858 user_data [1] = acfg;
7859 user_data [2] = frag;
7861 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7862 g_ptr_array_add (threads, handle);
7866 for (i = 0; i < threads->len; ++i) {
7867 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7873 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7874 for (i = methods_len; i < acfg->methods->len; ++i) {
7875 /* This can new methods to acfg->methods */
7876 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7881 compile_asm (MonoAotCompile *acfg)
7883 char *command, *objfile;
7884 char *outfile_name, *tmp_outfile_name;
7885 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7887 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
7888 #define AS_OPTIONS "--64"
7889 #elif defined(TARGET_POWERPC64)
7890 #define AS_OPTIONS "-a64 -mppc64"
7891 #define LD_OPTIONS "-m elf64ppc"
7892 #elif defined(sparc) && SIZEOF_VOID_P == 8
7893 #define AS_OPTIONS "-xarch=v9"
7894 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7895 #define AS_OPTIONS "-arch i386 -W"
7897 #define AS_OPTIONS ""
7900 #ifdef __native_client_codegen__
7901 #if defined(TARGET_AMD64)
7902 #define AS_NAME "nacl64-as"
7904 #define AS_NAME "nacl-as"
7907 #define AS_NAME "as"
7911 #define LD_OPTIONS ""
7914 #define EH_LD_OPTIONS ""
7916 if (acfg->aot_opts.asm_only) {
7917 printf ("Output file: '%s'.\n", acfg->tmpfname);
7918 if (acfg->aot_opts.static_link)
7919 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7923 if (acfg->aot_opts.static_link) {
7924 if (acfg->aot_opts.outfile)
7925 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7927 objfile = g_strdup_printf ("%s.o", acfg->image->name);
7929 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7931 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);
7932 printf ("Executing the native assembler: %s\n", command);
7933 if (system (command) != 0) {
7941 if (acfg->aot_opts.static_link) {
7942 printf ("Output file: '%s'.\n", objfile);
7943 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7948 if (acfg->aot_opts.outfile)
7949 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7951 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7953 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7956 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7957 #elif defined(__ppc__) && defined(TARGET_MACH)
7958 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7959 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
7960 command = g_strdup_printf ("gcc --shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7961 #elif defined(HOST_WIN32)
7962 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7963 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7964 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7966 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7968 printf ("Executing the native linker: %s\n", command);
7969 if (system (command) != 0) {
7970 g_free (tmp_outfile_name);
7971 g_free (outfile_name);
7979 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7980 printf ("Stripping the binary: %s\n", com);
7984 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
7986 * gas generates 'mapping symbols' each time code and data is mixed, which
7987 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7989 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7990 printf ("Stripping the binary: %s\n", command);
7991 if (system (command) != 0) {
7992 g_free (tmp_outfile_name);
7993 g_free (outfile_name);
8000 rename (tmp_outfile_name, outfile_name);
8002 #if defined(TARGET_MACH)
8003 command = g_strdup_printf ("dsymutil %s", outfile_name);
8004 printf ("Generating debug symbols: %s\n", command);
8005 if (system (command) != 0) {
8010 if (!acfg->aot_opts.save_temps)
8013 g_free (tmp_outfile_name);
8014 g_free (outfile_name);
8017 if (acfg->aot_opts.save_temps)
8018 printf ("Retained input file.\n");
8020 unlink (acfg->tmpfname);
8025 static MonoAotCompile*
8026 acfg_create (MonoAssembly *ass, guint32 opts)
8028 MonoImage *image = ass->image;
8029 MonoAotCompile *acfg;
8032 acfg = g_new0 (MonoAotCompile, 1);
8033 acfg->methods = g_ptr_array_new ();
8034 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8035 acfg->method_depth = g_hash_table_new (NULL, NULL);
8036 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8037 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8038 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8039 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8040 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8041 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8042 acfg->got_patches = g_ptr_array_new ();
8043 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8044 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8045 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8046 acfg->image_hash = g_hash_table_new (NULL, NULL);
8047 acfg->image_table = g_ptr_array_new ();
8048 acfg->globals = g_ptr_array_new ();
8049 acfg->image = image;
8051 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8052 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8053 acfg->mempool = mono_mempool_new ();
8054 acfg->extra_methods = g_ptr_array_new ();
8055 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8056 acfg->unwind_ops = g_ptr_array_new ();
8057 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8058 acfg->method_order = g_ptr_array_new ();
8059 acfg->export_names = g_hash_table_new (NULL, NULL);
8060 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8061 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8062 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8063 InitializeCriticalSection (&acfg->mutex);
8069 acfg_free (MonoAotCompile *acfg)
8073 img_writer_destroy (acfg->w);
8074 for (i = 0; i < acfg->nmethods; ++i)
8076 g_free (acfg->cfgs [i]);
8077 g_free (acfg->cfgs);
8078 g_free (acfg->static_linking_symbol);
8079 g_free (acfg->got_symbol);
8080 g_free (acfg->plt_symbol);
8081 g_ptr_array_free (acfg->methods, TRUE);
8082 g_ptr_array_free (acfg->got_patches, TRUE);
8083 g_ptr_array_free (acfg->image_table, TRUE);
8084 g_ptr_array_free (acfg->globals, TRUE);
8085 g_ptr_array_free (acfg->unwind_ops, TRUE);
8086 g_hash_table_destroy (acfg->method_indexes);
8087 g_hash_table_destroy (acfg->method_depth);
8088 g_hash_table_destroy (acfg->plt_offset_to_entry);
8089 g_hash_table_destroy (acfg->patch_to_plt_entry);
8090 g_hash_table_destroy (acfg->patch_to_got_offset);
8091 g_hash_table_destroy (acfg->method_to_cfg);
8092 g_hash_table_destroy (acfg->token_info_hash);
8093 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8094 g_hash_table_destroy (acfg->image_hash);
8095 g_hash_table_destroy (acfg->unwind_info_offsets);
8096 g_hash_table_destroy (acfg->method_label_hash);
8097 g_hash_table_destroy (acfg->export_names);
8098 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8099 g_hash_table_destroy (acfg->klass_blob_hash);
8100 g_hash_table_destroy (acfg->method_blob_hash);
8101 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8102 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8103 g_free (acfg->patch_to_got_offset_by_type);
8104 mono_mempool_destroy (acfg->mempool);
8109 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8111 MonoImage *image = ass->image;
8113 MonoAotCompile *acfg;
8114 char *outfile_name, *tmp_outfile_name, *p;
8118 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8120 acfg = acfg_create (ass, opts);
8122 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8123 acfg->aot_opts.write_symbols = TRUE;
8124 acfg->aot_opts.ntrampolines = 1024;
8125 acfg->aot_opts.nrgctx_trampolines = 1024;
8126 acfg->aot_opts.nimt_trampolines = 128;
8127 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8128 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8129 acfg->aot_opts.llvm_path = g_strdup ("");
8131 acfg->aot_opts.use_trampolines_page = TRUE;
8134 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8136 if (acfg->aot_opts.static_link)
8137 acfg->aot_opts.autoreg = TRUE;
8139 //acfg->aot_opts.print_skipped_methods = TRUE;
8141 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8142 if (acfg->aot_opts.full_aot) {
8143 printf ("--aot=full is not supported on this platform.\n");
8148 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8149 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8153 if (acfg->aot_opts.static_link)
8154 acfg->aot_opts.asm_writer = TRUE;
8156 if (acfg->aot_opts.soft_debug) {
8157 MonoDebugOptions *opt = mini_get_debug_options ();
8159 opt->mdb_optimizations = TRUE;
8160 opt->gen_seq_points = TRUE;
8162 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8163 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8166 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8169 if (mono_use_llvm) {
8171 acfg->aot_opts.asm_writer = TRUE;
8172 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8174 if (acfg->aot_opts.soft_debug) {
8175 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8180 if (acfg->aot_opts.full_aot)
8181 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8183 load_profile_files (acfg);
8185 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8186 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8187 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8189 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8190 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8191 if (acfg->opts & MONO_OPT_GSHAREDVT)
8192 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8195 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8199 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8200 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8201 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8203 /* Get rid of characters which cannot occur in symbols */
8204 for (p = acfg->got_symbol_base; *p; ++p) {
8205 if (!(isalnum (*p) || *p == '_'))
8208 for (p = acfg->plt_symbol; *p; ++p) {
8209 if (!(isalnum (*p) || *p == '_'))
8212 for (p = acfg->assembly_name_sym; *p; ++p) {
8213 if (!(isalnum (*p) || *p == '_'))
8217 acfg->method_index = 1;
8219 collect_methods (acfg);
8221 acfg->cfgs_size = acfg->methods->len + 32;
8222 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8224 /* PLT offset 0 is reserved for the PLT trampoline */
8225 acfg->plt_offset = 1;
8230 mono_llvm_create_aot_module (acfg->got_symbol_base);
8234 /* GOT offset 0 is reserved for the address of the current assembly */
8238 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8239 ji->type = MONO_PATCH_INFO_IMAGE;
8240 ji->data.image = acfg->image;
8242 get_got_offset (acfg, ji);
8244 /* Slot 1 is reserved for the mscorlib got addr */
8245 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8246 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8247 get_got_offset (acfg, ji);
8249 /* This is very common */
8250 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8251 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8252 get_got_offset (acfg, ji);
8254 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8255 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8256 get_got_offset (acfg, ji);
8261 compile_methods (acfg);
8265 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8271 if (acfg->aot_opts.asm_only) {
8272 if (acfg->aot_opts.outfile)
8273 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8275 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8277 acfg->tmpfname = g_strdup ("temp.s");
8280 emit_llvm_file (acfg);
8284 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8285 if (acfg->aot_opts.outfile)
8286 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8288 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8291 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8292 * it might be in another file system so the rename () won't work.
8294 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8296 acfg->fp = fopen (tmp_outfile_name, "w");
8298 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8302 acfg->w = img_writer_create (acfg->fp, TRUE);
8303 acfg->use_bin_writer = TRUE;
8306 /* Append to the .s file created by llvm */
8307 /* FIXME: Use multiple files instead */
8308 acfg->fp = fopen (acfg->tmpfname, "a+");
8310 if (acfg->aot_opts.asm_only) {
8311 if (acfg->aot_opts.outfile)
8312 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8314 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8315 acfg->fp = fopen (acfg->tmpfname, "w+");
8317 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8318 acfg->fp = fdopen (i, "w+");
8320 if (acfg->fp == 0) {
8321 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8325 acfg->w = img_writer_create (acfg->fp, FALSE);
8327 tmp_outfile_name = NULL;
8328 outfile_name = NULL;
8331 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8333 /* Compute symbols for methods */
8334 for (i = 0; i < acfg->nmethods; ++i) {
8335 if (acfg->cfgs [i]) {
8336 MonoCompile *cfg = acfg->cfgs [i];
8337 int method_index = get_method_index (acfg, cfg->orig_method);
8339 if (COMPILE_LLVM (cfg))
8340 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8341 else if (acfg->global_symbols)
8342 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8344 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8348 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8349 if (acfg->aot_opts.dwarf_debug && mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8350 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8353 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
8356 img_writer_emit_start (acfg->w);
8359 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
8361 if (acfg->thumb_mixed) {
8364 * This global symbol marks the end of THUMB code, and the beginning of ARM
8365 * code generated by our JIT.
8367 sprintf (symbol, "thumb_end");
8368 emit_section_change (acfg, ".text", 0);
8369 emit_alignment (acfg, 8);
8370 emit_label (acfg, symbol);
8371 emit_zero_bytes (acfg, 16);
8373 fprintf (acfg->fp, ".arm\n");
8380 emit_extra_methods (acfg);
8382 emit_trampolines (acfg);
8384 emit_class_name_table (acfg);
8386 emit_got_info (acfg);
8388 emit_exception_info (acfg);
8390 emit_unwind_info (acfg);
8392 emit_class_info (acfg);
8396 emit_image_table (acfg);
8400 emit_file_info (acfg);
8404 emit_globals (acfg);
8406 emit_autoreg (acfg);
8409 emit_dwarf_info (acfg);
8410 mono_dwarf_writer_close (acfg->dwarf);
8413 emit_mem_end (acfg);
8415 if (acfg->need_pt_gnu_stack) {
8416 /* This is required so the .so doesn't have an executable stack */
8417 /* The bin writer already emits this */
8418 if (!acfg->use_bin_writer)
8419 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
8424 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
8427 g_assert (acfg->got_offset <= acfg->final_got_size);
8429 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);
8430 printf ("Compiled: %d/%d (%d%%), No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
8431 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
8432 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
8433 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
8434 if (acfg->stats.genericcount)
8435 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
8436 if (acfg->stats.abscount)
8437 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
8438 if (acfg->stats.lmfcount)
8439 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
8440 if (acfg->stats.ocount)
8441 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
8443 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
8446 res = img_writer_emit_writeout (acfg->w);
8451 if (acfg->use_bin_writer) {
8452 int err = rename (tmp_outfile_name, outfile_name);
8455 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
8459 res = compile_asm (acfg);
8466 acfg->stats.link_time = TV_ELAPSED (atv, btv);
8468 if (acfg->aot_opts.stats) {
8471 printf ("GOT slot distribution:\n");
8472 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
8473 if (acfg->stats.got_slot_types [i])
8474 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
8477 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);
8489 mono_aot_readonly_field_override (MonoClassField *field)
8495 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)