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)
14 #include <sys/types.h>
34 #include <mono/metadata/abi-details.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/tokentype.h>
39 #include <mono/metadata/appdomain.h>
40 #include <mono/metadata/debug-helpers.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/metadata-internals.h>
43 #include <mono/metadata/marshal.h>
44 #include <mono/metadata/gc-internal.h>
45 #include <mono/metadata/monitor.h>
46 #include <mono/metadata/mempool-internals.h>
47 #include <mono/metadata/mono-endian.h>
48 #include <mono/metadata/threads-types.h>
49 #include <mono/utils/mono-logger-internal.h>
50 #include <mono/utils/mono-compiler.h>
51 #include <mono/utils/mono-time.h>
52 #include <mono/utils/mono-mmap.h>
53 #include <mono/utils/json.h>
56 #include "seq-points.h"
57 #include "image-writer.h"
58 #include "dwarfwriter.h"
61 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
63 #if defined(__linux__) || defined(__native_client_codegen__)
64 #define RODATA_SECT ".rodata"
65 #elif defined(TARGET_MACH)
66 #define RODATA_SECT ".section __TEXT, __const"
68 #define RODATA_SECT ".text"
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
75 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
76 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
77 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
79 /* predefined values for static readonly fields without needed to run the .cctor */
80 typedef struct _ReadOnlyValue ReadOnlyValue;
81 struct _ReadOnlyValue {
84 int type; /* to be used later for typechecking to prevent user errors */
93 static ReadOnlyValue *readonly_values;
95 typedef struct MonoAotOptions {
99 gboolean write_symbols;
100 gboolean metadata_only;
101 gboolean bind_to_runtime_version;
104 gboolean static_link;
108 gboolean dwarf_debug;
110 gboolean log_generics;
111 gboolean log_instances;
112 gboolean gen_seq_points_file;
113 gboolean direct_pinvoke;
114 gboolean direct_icalls;
115 gboolean no_direct_calls;
116 gboolean use_trampolines_page;
117 gboolean no_instances;
122 int nrgctx_trampolines;
123 int nimt_trampolines;
124 int ngsharedvt_arg_trampolines;
125 int nrgctx_fetch_trampolines;
126 gboolean print_skipped_methods;
133 char *instances_logfile_path;
138 typedef struct MonoAotStats {
139 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
140 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
141 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
142 int got_slots, offsets_size;
143 int got_slot_types [MONO_PATCH_INFO_NONE];
144 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
145 int jit_time, gen_time, link_time;
148 typedef struct GotInfo {
149 GHashTable *patch_to_got_offset;
150 GHashTable **patch_to_got_offset_by_type;
151 GPtrArray *got_patches;
154 typedef struct MonoAotCompile {
157 GHashTable *method_indexes;
158 GHashTable *method_depth;
161 GHashTable **patch_to_plt_entry;
162 GHashTable *plt_offset_to_entry;
163 //GHashTable *patch_to_got_offset;
164 //GHashTable **patch_to_got_offset_by_type;
165 //GPtrArray *got_patches;
166 GotInfo got_info, llvm_got_info;
167 GHashTable *image_hash;
168 GHashTable *method_to_cfg;
169 GHashTable *token_info_hash;
170 GHashTable *method_to_pinvoke_import;
171 GPtrArray *extra_methods;
172 GPtrArray *image_table;
174 GPtrArray *method_order;
175 GHashTable *export_names;
176 /* Maps MonoClass* -> blob offset */
177 GHashTable *klass_blob_hash;
178 /* Maps MonoMethod* -> blob offset */
179 GHashTable *method_blob_hash;
180 guint32 *plt_got_info_offsets;
181 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base;
182 /* Number of GOT entries reserved for trampolines */
183 guint32 num_trampoline_got_entries;
184 guint32 tramp_page_size;
186 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
187 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
188 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
189 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
191 MonoAotOptions aot_opts;
195 MonoMemPool *mempool;
198 char *static_linking_symbol;
200 gboolean use_bin_writer;
201 gboolean gas_line_numbers;
202 /* Whenever to emit an object file directly from llc */
203 gboolean llvm_owriter;
205 MonoDwarfWriter *dwarf;
212 GHashTable *unwind_info_offsets;
213 GPtrArray *unwind_ops;
214 guint32 unwind_info_offset;
215 char *got_symbol_base;
216 char *llvm_got_symbol_base;
218 char *llvm_got_symbol;
220 char *methods_symbol;
221 char *llvm_eh_frame_symbol;
222 GHashTable *method_label_hash;
223 const char *temp_prefix;
224 const char *user_symbol_prefix;
225 const char *llvm_label_prefix;
226 const char *inst_directive;
228 guint32 label_generator;
230 MonoAotFileFlags flags;
231 MonoDynamicStream blob;
232 MonoClass **typespec_classes;
235 char *assembly_name_sym;
236 GHashTable *plt_entry_debug_sym_cache;
237 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
238 GHashTable *ginst_hash;
239 GHashTable *dwarf_ln_filenames;
240 gboolean global_symbols;
241 int objc_selector_index, objc_selector_index_2;
242 GPtrArray *objc_selectors;
243 GHashTable *objc_selector_to_index;
245 FILE *instances_logfile;
250 char *symbol, *llvm_symbol, *debug_sym;
252 gboolean jit_used, llvm_used;
255 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
256 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
258 /* This points to the current acfg in LLVM mode */
259 static MonoAotCompile *llvm_acfg;
261 #ifdef HAVE_ARRAY_ELEM_INIT
262 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
263 #define MSGSTRFIELD1(line) str##line
264 static const struct msgstr_t {
265 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
266 #include "patch-info.h"
269 #define PATCH_INFO(a,b) b,
270 #include "patch-info.h"
273 static const gint16 opidx [] = {
274 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
275 #include "patch-info.h"
279 static G_GNUC_UNUSED const char*
280 get_patch_name (int info)
282 return (const char*)&opstr + opidx [info];
286 #define PATCH_INFO(a,b) b,
287 static const char* const
288 patch_types [MONO_PATCH_INFO_NUM + 1] = {
289 #include "patch-info.h"
293 static G_GNUC_UNUSED const char*
294 get_patch_name (int info)
296 return patch_types [info];
302 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
305 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
311 output = acfg->logfile;
315 va_start (args, format);
316 vfprintf (output, format, args);
321 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
327 output = acfg->logfile;
331 va_start (args, format);
332 vfprintf (output, format, args);
337 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
342 if (mono_error_ok (error))
346 output = acfg->logfile;
350 va_start (args, format);
351 vfprintf (output, format, args);
353 mono_error_cleanup (error);
355 g_error ("FullAOT cannot continue if there are loader errors");
358 /* Wrappers around the image writer functions */
361 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
363 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
367 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
369 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
373 emit_label (MonoAotCompile *acfg, const char *name)
375 img_writer_emit_label (acfg->w, name);
379 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
381 img_writer_emit_bytes (acfg->w, buf, size);
385 emit_string (MonoAotCompile *acfg, const char *value)
387 img_writer_emit_string (acfg->w, value);
391 emit_line (MonoAotCompile *acfg)
393 img_writer_emit_line (acfg->w);
397 emit_alignment (MonoAotCompile *acfg, int size)
399 img_writer_emit_alignment (acfg->w, size);
403 emit_alignment_code (MonoAotCompile *acfg, int size)
405 if (acfg->align_pad_value)
406 img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
408 img_writer_emit_alignment (acfg->w, size);
412 emit_padding (MonoAotCompile *acfg, int size)
417 if (acfg->align_pad_value) {
418 for (i = 0; i < 16; ++i)
419 buf [i] = acfg->align_pad_value;
421 memset (buf, 0, sizeof (buf));
424 for (i = 0; i < size; i += 16) {
426 emit_bytes (acfg, buf, size - i);
428 emit_bytes (acfg, buf, 16);
433 emit_pointer (MonoAotCompile *acfg, const char *target)
435 img_writer_emit_pointer (acfg->w, target);
439 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
441 if (prefix [0] != '\0') {
442 char *s = g_strdup_printf ("%s%s", prefix, target);
443 img_writer_emit_pointer (acfg->w, s);
446 img_writer_emit_pointer (acfg->w, target);
451 emit_int16 (MonoAotCompile *acfg, int value)
453 img_writer_emit_int16 (acfg->w, value);
457 emit_int32 (MonoAotCompile *acfg, int value)
459 img_writer_emit_int32 (acfg->w, value);
463 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
465 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
469 emit_zero_bytes (MonoAotCompile *acfg, int num)
471 img_writer_emit_zero_bytes (acfg->w, num);
475 emit_byte (MonoAotCompile *acfg, guint8 val)
477 img_writer_emit_byte (acfg->w, val);
480 #ifdef __native_client_codegen__
482 emit_nacl_call_alignment (MonoAotCompile *acfg)
484 img_writer_emit_nacl_call_alignment (acfg->w);
488 static G_GNUC_UNUSED void
489 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
491 img_writer_emit_global (acfg->w, name, func);
495 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
497 if (acfg->aot_opts.no_dlsym) {
498 g_ptr_array_add (acfg->globals, g_strdup (name));
499 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
501 img_writer_emit_global (acfg->w, name, func);
506 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
508 img_writer_emit_symbol_size (acfg->w, name, end_label);
512 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
514 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
516 /* On apple, all symbols need to be aligned to avoid warnings from ld */
517 emit_alignment (acfg, 4);
519 img_writer_emit_label (acfg->w, name);
520 img_writer_emit_string (acfg->w, value);
523 static G_GNUC_UNUSED void
524 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
527 guint8 b = value & 0x7f;
529 if (value != 0) /* more bytes to come */
535 static G_GNUC_UNUSED void
536 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
539 gboolean negative = (value < 0);
546 /* the following is unnecessary if the
547 * implementation of >>= uses an arithmetic rather
548 * than logical shift for a signed left operand
552 value |= - ((gint64)1 <<(size - 7));
553 /* sign bit of byte is second high order bit (0x40) */
554 if ((value == 0 && !(byte & 0x40)) ||
555 (value == -1 && (byte & 0x40)))
559 emit_byte (acfg, byte);
563 static G_GNUC_UNUSED void
564 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
569 guint8 b = value & 0x7f;
571 if (value != 0) /* more bytes to come */
579 static G_GNUC_UNUSED void
580 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
583 gboolean negative = (value < 0);
591 /* the following is unnecessary if the
592 * implementation of >>= uses an arithmetic rather
593 * than logical shift for a signed left operand
597 value |= - (1 <<(size - 7));
598 /* sign bit of byte is second high order bit (0x40) */
599 if ((value == 0 && !(byte & 0x40)) ||
600 (value == -1 && (byte & 0x40)))
611 emit_unset_mode (MonoAotCompile *acfg)
613 img_writer_emit_unset_mode (acfg->w);
616 static G_GNUC_UNUSED void
617 emit_set_thumb_mode (MonoAotCompile *acfg)
619 emit_unset_mode (acfg);
620 fprintf (acfg->fp, ".code 16\n");
623 static G_GNUC_UNUSED void
624 emit_set_arm_mode (MonoAotCompile *acfg)
626 emit_unset_mode (acfg);
627 fprintf (acfg->fp, ".code 32\n");
631 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
636 g_assert (size % 4 == 0);
637 emit_unset_mode (acfg);
638 for (i = 0; i < size; i += 4)
639 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
641 emit_bytes (acfg, buf, size);
645 /* ARCHITECTURE SPECIFIC CODE */
647 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
648 #define EMIT_DWARF_INFO 1
651 #if defined(TARGET_ARM)
652 #define AOT_FUNC_ALIGNMENT 4
654 #define AOT_FUNC_ALIGNMENT 16
656 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
657 #undef AOT_FUNC_ALIGNMENT
658 #define AOT_FUNC_ALIGNMENT 32
661 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
662 #define PPC_LD_OP "ld"
663 #define PPC_LDX_OP "ldx"
665 #define PPC_LD_OP "lwz"
666 #define PPC_LDX_OP "lwzx"
670 #define AOT_TARGET_STR "AMD64"
675 #define AOT_TARGET_STR "ARM (MACH)"
677 #define AOT_TARGET_STR "ARM (!MACH)"
683 #define AOT_TARGET_STR "ARM64 (MACH)"
685 #define AOT_TARGET_STR "ARM64 (!MACH)"
689 #ifdef TARGET_POWERPC64
690 #ifdef __mono_ilp32__
691 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
693 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
696 #ifdef TARGET_POWERPC
697 #ifdef __mono_ilp32__
698 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
700 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
707 #define AOT_TARGET_STR "X86 (WIN32)"
708 #elif defined(__native_client_codegen__)
709 #define AOT_TARGET_STR "X86 (native client codegen)"
711 #define AOT_TARGET_STR "X86 (!native client codegen)"
715 #ifndef AOT_TARGET_STR
716 #define AOT_TARGET_STR ""
720 arch_init (MonoAotCompile *acfg)
722 acfg->llc_args = g_string_new ("");
723 acfg->as_args = g_string_new ("");
726 * The prefix LLVM likes to put in front of symbol names on darwin.
727 * The mach-os specs require this for globals, but LLVM puts them in front of all
728 * symbols. We need to handle this, since we need to refer to LLVM generated
731 acfg->llvm_label_prefix = "";
732 acfg->user_symbol_prefix = "";
734 #if defined(TARGET_X86)
735 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
738 #if defined(TARGET_AMD64)
739 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
741 acfg->align_pad_value = 0x90;
745 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
746 g_string_append (acfg->llc_args, "-mattr=+v6");
749 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
750 g_string_append (acfg->as_args, " -mfpu=vfp3");
752 g_string_append (acfg->llc_args, " -soft-float");
755 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
756 acfg->thumb_mixed = TRUE;
758 if (acfg->aot_opts.mtriple)
759 mono_arch_set_target (acfg->aot_opts.mtriple);
763 acfg->inst_directive = ".inst";
764 if (acfg->aot_opts.mtriple)
765 mono_arch_set_target (acfg->aot_opts.mtriple);
769 acfg->user_symbol_prefix = "_";
770 acfg->llvm_label_prefix = "_";
771 acfg->inst_directive = ".word";
772 acfg->need_no_dead_strip = TRUE;
773 acfg->aot_opts.gnu_asm = TRUE;
776 #if defined(__linux__) && !defined(TARGET_ARM)
777 acfg->need_pt_gnu_stack = TRUE;
781 acfg->global_symbols = TRUE;
787 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
791 #ifdef MONO_ARCH_AOT_SUPPORTED
793 * arch_emit_direct_call:
795 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
799 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
801 #if defined(TARGET_X86) || defined(TARGET_AMD64)
802 /* Need to make sure this is exactly 5 bytes long */
803 if (!acfg->use_bin_writer) {
804 emit_unset_mode (acfg);
805 fprintf (acfg->fp, "call %s\n", target);
807 emit_byte (acfg, '\xe8');
808 emit_symbol_diff (acfg, target, ".", -4);
811 #elif defined(TARGET_ARM)
812 if (acfg->use_bin_writer) {
819 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
820 emit_bytes (acfg, buf, 4);
822 emit_unset_mode (acfg);
824 fprintf (acfg->fp, "blx %s\n", target);
826 fprintf (acfg->fp, "bl %s\n", target);
829 #elif defined(TARGET_ARM64)
830 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
831 #elif defined(TARGET_POWERPC)
832 if (acfg->use_bin_writer) {
833 g_assert_not_reached ();
835 emit_unset_mode (acfg);
836 fprintf (acfg->fp, "bl %s\n", target);
840 g_assert_not_reached ();
847 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
849 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
850 * in in the 2. slot of every GOT, and require every method to place the GOT
851 * address in r30, even when it doesn't access the GOT otherwise. This way,
852 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
857 * PPC64 uses function descriptors which greatly complicate all code, since
858 * these are used very inconsistently in the runtime. Some functions like
859 * mono_compile_method () return ftn descriptors, while others like the
860 * trampoline creation functions do not.
861 * We assume that all GOT slots contain function descriptors, and create
862 * descriptors in aot-runtime.c when needed.
863 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
864 * from function descriptors, we could do the same, but it would require
865 * rewriting all the ppc/aot code to handle function descriptors properly.
866 * So instead, we use the same approach as on PPC32.
867 * This is a horrible mess, but fixing it would probably lead to an even bigger
873 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
876 #ifdef MONO_ARCH_AOT_SUPPORTED
878 * arch_emit_got_offset:
880 * The memory pointed to by CODE should hold native code for computing the GOT
881 * address. Emit this code while patching it with the offset between code and
882 * the GOT. CODE_SIZE is set to the number of bytes emitted.
885 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
887 #if defined(TARGET_POWERPC64)
888 g_assert (!acfg->use_bin_writer);
889 emit_unset_mode (acfg);
891 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
892 * unsupported relocations. So we store the got address into the .Lgot_addr
893 * symbol which is in the text segment, compute its address, and load it.
895 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
896 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
897 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
898 fprintf (acfg->fp, "add 30, 30, 0\n");
899 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
900 acfg->label_generator ++;
902 #elif defined(TARGET_POWERPC)
903 g_assert (!acfg->use_bin_writer);
904 emit_unset_mode (acfg);
905 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
906 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
907 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
908 acfg->label_generator ++;
911 guint32 offset = mono_arch_get_patch_offset (code);
912 emit_bytes (acfg, code, offset);
913 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
915 *code_size = offset + 4;
920 * arch_emit_got_access:
922 * The memory pointed to by CODE should hold native code for loading a GOT
923 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
924 * CODE_SIZE is set to the number of bytes emitted.
927 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
929 /* This needs to emit the same code as OP_AOTCONST */
932 /* mov reg, got+offset(%rip) */
934 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
938 /* Decode reg, see amd64_mov_reg_membase () */
939 rex_r = code [0] & AMD64_REX_R;
940 g_assert (code [0] == 0x49 + rex_r);
941 g_assert (code [1] == 0x8b);
942 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
944 emit_unset_mode (acfg);
945 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
948 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
949 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
950 *code_size = mono_arch_get_patch_offset (code) + 4;
952 #elif defined(TARGET_X86)
953 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
954 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
955 *code_size = mono_arch_get_patch_offset (code) + 4;
956 #elif defined(TARGET_ARM)
957 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
958 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
959 *code_size = mono_arch_get_patch_offset (code) + 4;
960 #elif defined(TARGET_ARM64)
961 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
962 arm64_emit_got_access (acfg, code, got_slot, code_size);
963 #elif defined(TARGET_POWERPC)
968 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
970 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
971 g_assert (code - buf == 8);
972 emit_bytes (acfg, buf, code - buf);
973 *code_size = code - buf;
976 g_assert_not_reached ();
982 #ifdef MONO_ARCH_AOT_SUPPORTED
984 * arch_emit_objc_selector_ref:
986 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
989 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
991 #if defined(TARGET_ARM)
994 int lindex = acfg->objc_selector_index_2 ++;
997 emit_bytes (acfg, code, 8);
999 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1000 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1002 emit_label (acfg, symbol1);
1003 img_writer_emit_unset_mode (acfg->w);
1004 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1007 #elif defined(TARGET_ARM64)
1008 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1010 g_assert_not_reached ();
1016 * arch_emit_plt_entry:
1018 * Emit code for the PLT entry with index INDEX.
1021 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
1023 #if defined(TARGET_X86)
1024 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1025 #if defined(__default_codegen__)
1026 /* jmp *<offset>(%ebx) */
1027 emit_byte (acfg, 0xff);
1028 emit_byte (acfg, 0xa3);
1029 emit_int32 (acfg, offset);
1030 /* Used by mono_aot_get_plt_info_offset */
1031 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1032 #elif defined(__native_client_codegen__)
1033 const guint8 kSizeOfNaClJmp = 11;
1034 guint8 bytes[kSizeOfNaClJmp];
1035 guint8 *pbytes = &bytes[0];
1037 x86_jump_membase32 (pbytes, X86_EBX, offset);
1038 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1039 /* four bytes of data, used by mono_arch_patch_plt_entry */
1040 /* For Native Client, make this work with data embedded in push. */
1041 emit_byte (acfg, 0x68); /* hide data in a push */
1042 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1043 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1044 #endif /*__native_client_codegen__*/
1045 #elif defined(TARGET_AMD64)
1046 #if defined(__default_codegen__)
1047 if (acfg->use_bin_writer) {
1048 emit_byte (acfg, '\xff');
1049 emit_byte (acfg, '\x25');
1050 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1052 emit_unset_mode (acfg);
1053 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
1055 /* Used by mono_aot_get_plt_info_offset */
1056 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1057 acfg->stats.plt_size += 10;
1058 #elif defined(__native_client_codegen__)
1060 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1061 guint8 *code = buf_aligned;
1063 /* mov <OFFSET>(%rip), %r11d */
1064 emit_byte (acfg, '\x45');
1065 emit_byte (acfg, '\x8b');
1066 emit_byte (acfg, '\x1d');
1067 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1069 amd64_jump_reg (code, AMD64_R11);
1070 /* This should be constant for the plt patch */
1071 g_assert ((size_t)(code-buf_aligned) == 10);
1072 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1074 /* Hide data in a push imm32 so it passes validation */
1075 emit_byte (acfg, 0x68); /* push */
1076 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1077 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1078 #endif /*__native_client_codegen__*/
1079 #elif defined(TARGET_ARM)
1084 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1085 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1086 emit_bytes (acfg, buf, code - buf);
1087 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
1088 /* Used by mono_aot_get_plt_info_offset */
1089 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1090 #elif defined(TARGET_ARM64)
1091 arm64_emit_plt_entry (acfg, index);
1092 #elif defined(TARGET_POWERPC)
1093 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1095 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1096 g_assert (!acfg->use_bin_writer);
1097 emit_unset_mode (acfg);
1098 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1099 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1100 fprintf (acfg->fp, "add 11, 11, 30\n");
1101 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1102 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1103 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1104 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1106 fprintf (acfg->fp, "mtctr 11\n");
1107 fprintf (acfg->fp, "bctr\n");
1108 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1110 g_assert_not_reached ();
1115 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
1117 #if defined(TARGET_ARM)
1119 /* LLVM calls the PLT entries using bl, so emit a stub */
1120 /* FIXME: Too much overhead on every call */
1121 fprintf (acfg->fp, ".thumb_func\n");
1122 fprintf (acfg->fp, "bx pc\n");
1123 fprintf (acfg->fp, "nop\n");
1124 fprintf (acfg->fp, ".arm\n");
1126 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1127 /* The caller already transitioned to thumb */
1128 /* The code below should be 12 bytes long */
1129 /* clang has trouble encoding these instructions, so emit the binary */
1131 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1132 /* thumb can't encode ld pc, [pc, ip] */
1133 fprintf (acfg->fp, "add ip, pc, ip\n");
1134 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1135 fprintf (acfg->fp, "bx ip\n");
1137 emit_set_thumb_mode (acfg);
1138 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1139 fprintf (acfg->fp, ".2byte 0x44fc\n");
1140 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1141 fprintf (acfg->fp, ".2byte 0x4760\n");
1142 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1143 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1144 emit_unset_mode (acfg);
1145 emit_set_arm_mode (acfg);
1147 g_assert_not_reached ();
1152 * arch_emit_specific_trampoline_pages:
1154 * Emits a page full of trampolines: each trampoline uses its own address to
1155 * lookup both the generic trampoline code and the data argument.
1156 * This page can be remapped in process multiple times so we can get an
1157 * unlimited number of trampolines.
1158 * Specifically this implementation uses the following trick: two memory pages
1159 * are allocated, with the first containing the data and the second containing the trampolines.
1160 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1161 * implementation does all the lifting.
1162 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1163 * on the arm 32 bit system.
1166 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1168 #if defined(TARGET_ARM)
1171 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1173 #define COMMON_TRAMP_SIZE 16
1174 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1175 int imm8, rot_amount;
1178 if (!acfg->aot_opts.use_trampolines_page)
1181 acfg->tramp_page_size = mono_pagesize ();
1183 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1184 emit_alignment (acfg, mono_pagesize ());
1185 emit_global (acfg, symbol, TRUE);
1186 emit_label (acfg, symbol);
1188 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1190 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1191 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1192 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1193 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1195 g_assert (code - buf == COMMON_TRAMP_SIZE);
1198 emit_bytes (acfg, buf, code - buf);
1200 for (i = 0; i < count; ++i) {
1202 ARM_PUSH (code, 0x5fff);
1204 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1205 g_assert (code - buf == 8);
1206 emit_bytes (acfg, buf, code - buf);
1209 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1210 * the instruction pointer address, so the generic trampoline at the start of the page
1211 * subtracts 4096 to get to the data page and loads the values
1212 * We again fit the generic trampiline in 16 bytes.
1214 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1215 emit_global (acfg, symbol, TRUE);
1216 emit_label (acfg, symbol);
1218 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1219 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1220 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1221 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1223 g_assert (code - buf == COMMON_TRAMP_SIZE);
1226 emit_bytes (acfg, buf, code - buf);
1228 for (i = 0; i < count; ++i) {
1230 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1232 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1233 g_assert (code - buf == 8);
1234 emit_bytes (acfg, buf, code - buf);
1238 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1240 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1241 emit_global (acfg, symbol, TRUE);
1242 emit_label (acfg, symbol);
1244 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1245 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1246 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1247 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1248 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1249 g_assert (code - buf == COMMON_TRAMP_SIZE);
1251 emit_bytes (acfg, buf, code - buf);
1253 for (i = 0; i < count; ++i) {
1255 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1257 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1258 g_assert (code - buf == 8);
1259 emit_bytes (acfg, buf, code - buf);
1262 /* now the imt trampolines: each specific trampolines puts in the ip register
1263 * the instruction pointer address, so the generic trampoline at the start of the page
1264 * subtracts 4096 to get to the data page and loads the values
1265 * We again fit the generic trampiline in 16 bytes.
1267 #define IMT_TRAMP_SIZE 72
1268 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1269 emit_global (acfg, symbol, TRUE);
1270 emit_label (acfg, symbol);
1272 /* Need at least two free registers, plus a slot for storing the pc */
1273 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1275 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1276 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1277 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1279 /* The IMT method is in v5, r0 has the imt array address */
1282 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1283 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1284 imt_found_check = code;
1285 ARM_B_COND (code, ARMCOND_EQ, 0);
1287 /* End-of-loop check */
1288 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1289 loop_end_check = code;
1290 ARM_B_COND (code, ARMCOND_EQ, 0);
1293 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1294 loop_branch_back = code;
1296 arm_patch (loop_branch_back, loop_start);
1299 arm_patch (imt_found_check, code);
1300 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1301 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1302 /* Save it to the third stack slot */
1303 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1304 /* Restore the registers and branch */
1305 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1308 arm_patch (loop_end_check, code);
1309 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1310 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1311 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1315 g_assert (code - buf == IMT_TRAMP_SIZE);
1316 emit_bytes (acfg, buf, code - buf);
1318 for (i = 0; i < count; ++i) {
1320 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1322 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1323 g_assert (code - buf == 8);
1324 emit_bytes (acfg, buf, code - buf);
1327 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1328 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1329 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1330 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1331 #elif defined(TARGET_ARM64)
1332 arm64_emit_specific_trampoline_pages (acfg);
1337 * arch_emit_specific_trampoline:
1339 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1340 * two GOT slots which contain the generic trampoline address and the trampoline
1341 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1344 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1347 * The trampolines created here are variations of the specific
1348 * trampolines created in mono_arch_create_specific_trampoline (). The
1350 * - the generic trampoline address is taken from a got slot.
1351 * - the offset of the got slot where the trampoline argument is stored
1352 * is embedded in the instruction stream, and the generic trampoline
1353 * can load the argument by loading the offset, adding it to the
1354 * address of the trampoline to get the address of the got slot, and
1355 * loading the argument from there.
1356 * - all the trampolines should be of the same length.
1358 #if defined(TARGET_AMD64)
1359 #if defined(__default_codegen__)
1360 /* This should be exactly 8 bytes long */
1362 /* call *<offset>(%rip) */
1364 emit_unset_mode (acfg);
1365 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1366 emit_zero_bytes (acfg, 2);
1368 emit_byte (acfg, '\x41');
1369 emit_byte (acfg, '\xff');
1370 emit_byte (acfg, '\x15');
1371 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1372 emit_zero_bytes (acfg, 1);
1374 #elif defined(__native_client_codegen__)
1376 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1377 guint8 *code = buf_aligned;
1382 /* Emit this call in 'code' so we can find out how long it is. */
1383 amd64_call_reg (code, AMD64_R11);
1384 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1385 call_len = code - call_start;
1387 /* The tramp_size is twice the NaCl alignment because it starts with */
1388 /* a call which needs to be aligned to the end of the boundary. */
1389 *tramp_size = kNaClAlignment*2;
1391 /* Emit nops to align call site below which is 7 bytes plus */
1392 /* the length of the call sequence emitted above. */
1393 /* Note: this requires the specific trampoline starts on a */
1394 /* kNaclAlignedment aligned address, which it does because */
1395 /* it's its own function that is aligned. */
1396 guint8 nop_buf[256];
1397 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1398 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1399 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1401 /* The trampoline is stored at the offset'th pointer, the -4 is */
1402 /* present because RIP relative addressing starts at the end of */
1403 /* the current instruction, while the label "." is relative to */
1404 /* the beginning of the current asm location, which in this case */
1405 /* is not the mov instruction, but the offset itself, due to the */
1406 /* way the bytes and ints are emitted here. */
1407 got_offset = (offset * sizeof(gpointer)) - 4;
1409 /* mov <OFFSET>(%rip), %r11d */
1410 emit_byte (acfg, '\x45');
1411 emit_byte (acfg, '\x8b');
1412 emit_byte (acfg, '\x1d');
1413 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1416 emit_bytes (acfg, call_start, call_len);
1418 /* The arg is stored at the offset+1 pointer, relative to beginning */
1419 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1420 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1422 /* We can't emit this data directly, hide in a "push imm32" */
1423 emit_byte (acfg, '\x68'); /* push */
1424 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1425 emit_alignment (acfg, kNaClAlignment);
1426 #endif /*__native_client_codegen__*/
1427 #elif defined(TARGET_ARM)
1431 /* This should be exactly 20 bytes long */
1434 ARM_PUSH (code, 0x5fff);
1435 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1436 /* Load the value from the GOT */
1437 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1439 ARM_BLX_REG (code, ARMREG_R1);
1441 g_assert (code - buf == 16);
1444 emit_bytes (acfg, buf, code - buf);
1446 * Only one offset is needed, since the second one would be equal to the
1449 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1450 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1451 #elif defined(TARGET_ARM64)
1452 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1453 #elif defined(TARGET_POWERPC)
1460 g_assert (!acfg->use_bin_writer);
1463 * PPC has no ip relative addressing, so we need to compute the address
1464 * of the mscorlib got. That is slow and complex, so instead, we store it
1465 * in the second got slot of every aot image. The caller already computed
1466 * the address of its got and placed it into r30.
1468 emit_unset_mode (acfg);
1469 /* Load mscorlib got address */
1470 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1471 /* Load generic trampoline address */
1472 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1473 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1474 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1475 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1476 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1478 fprintf (acfg->fp, "mtctr 11\n");
1479 /* Load trampoline argument */
1480 /* On ppc, we pass it normally to the generic trampoline */
1481 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1482 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1483 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1484 /* Branch to generic trampoline */
1485 fprintf (acfg->fp, "bctr\n");
1487 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1488 *tramp_size = 10 * 4;
1490 *tramp_size = 9 * 4;
1492 #elif defined(TARGET_X86)
1496 /* Similar to the PPC code above */
1498 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1500 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1501 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1502 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1503 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1504 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1509 /* Load mscorlib got address */
1510 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1511 /* Push trampoline argument */
1512 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1513 /* Load generic trampoline address */
1514 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1515 /* Branch to generic trampoline */
1516 x86_jump_reg (code, X86_ECX);
1518 #ifdef __native_client_codegen__
1520 /* emit nops to next 32 byte alignment */
1521 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1522 while (code < (buf + a)) x86_nop(code);
1525 emit_bytes (acfg, buf, code - buf);
1527 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1528 g_assert (code - buf == *tramp_size);
1530 g_assert_not_reached ();
1535 * arch_emit_unbox_trampoline:
1537 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1538 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1541 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1543 #if defined(TARGET_AMD64)
1548 this_reg = mono_arch_get_this_arg_reg (NULL);
1550 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1552 emit_bytes (acfg, buf, code - buf);
1555 emit_unset_mode (acfg);
1556 fprintf (acfg->fp, "jmp %s\n", call_target);
1558 emit_byte (acfg, '\xe9');
1559 emit_symbol_diff (acfg, call_target, ".", -4);
1561 #elif defined(TARGET_X86)
1568 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1570 emit_bytes (acfg, buf, code - buf);
1573 emit_byte (acfg, '\xe9');
1574 emit_symbol_diff (acfg, call_target, ".", -4);
1575 #elif defined(TARGET_ARM)
1579 if (acfg->thumb_mixed && cfg->compile_llvm) {
1580 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1581 fprintf (acfg->fp, "b %s\n", call_target);
1582 fprintf (acfg->fp, ".arm\n");
1583 fprintf (acfg->fp, ".align 2\n");
1589 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1591 emit_bytes (acfg, buf, code - buf);
1592 /* jump to method */
1593 if (acfg->use_bin_writer) {
1600 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1601 emit_bytes (acfg, buf, 4);
1603 if (acfg->thumb_mixed && cfg->compile_llvm)
1604 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1606 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1608 #elif defined(TARGET_ARM64)
1609 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1610 #elif defined(TARGET_POWERPC)
1613 g_assert (!acfg->use_bin_writer);
1615 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1616 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1618 g_assert_not_reached ();
1623 * arch_emit_static_rgctx_trampoline:
1625 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1626 * two GOT slots which contain the rgctx argument, and the method to jump to.
1627 * TRAMP_SIZE is set to the size of the emitted trampoline.
1628 * These kinds of trampolines cannot be enumerated statically, since there could
1629 * be one trampoline per method instantiation, so we emit the same code for all
1630 * trampolines, and parameterize them using two GOT slots.
1633 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1635 #if defined(TARGET_AMD64)
1636 #if defined(__default_codegen__)
1637 /* This should be exactly 13 bytes long */
1641 emit_unset_mode (acfg);
1642 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1643 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1645 /* mov <OFFSET>(%rip), %r10 */
1646 emit_byte (acfg, '\x4d');
1647 emit_byte (acfg, '\x8b');
1648 emit_byte (acfg, '\x15');
1649 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1651 /* jmp *<offset>(%rip) */
1652 emit_byte (acfg, '\xff');
1653 emit_byte (acfg, '\x25');
1654 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1656 #elif defined(__native_client_codegen__)
1658 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1659 guint8 *code = buf_aligned;
1661 /* mov <OFFSET>(%rip), %r10d */
1662 emit_byte (acfg, '\x45');
1663 emit_byte (acfg, '\x8b');
1664 emit_byte (acfg, '\x15');
1665 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1667 /* mov <OFFSET>(%rip), %r11d */
1668 emit_byte (acfg, '\x45');
1669 emit_byte (acfg, '\x8b');
1670 emit_byte (acfg, '\x1d');
1671 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1674 amd64_jump_reg (code, AMD64_R11);
1675 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1677 emit_alignment (acfg, kNaClAlignment);
1678 *tramp_size = kNaClAlignment;
1679 #endif /*__native_client_codegen__*/
1681 #elif defined(TARGET_ARM)
1685 /* This should be exactly 24 bytes long */
1688 /* Load rgctx value */
1689 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1690 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1691 /* Load branch addr + branch */
1692 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1693 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1695 g_assert (code - buf == 16);
1698 emit_bytes (acfg, buf, code - buf);
1699 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1700 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1701 #elif defined(TARGET_ARM64)
1702 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1703 #elif defined(TARGET_POWERPC)
1710 g_assert (!acfg->use_bin_writer);
1713 * PPC has no ip relative addressing, so we need to compute the address
1714 * of the mscorlib got. That is slow and complex, so instead, we store it
1715 * in the second got slot of every aot image. The caller already computed
1716 * the address of its got and placed it into r30.
1718 emit_unset_mode (acfg);
1719 /* Load mscorlib got address */
1720 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1722 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1723 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1724 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1725 /* Load target address */
1726 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1727 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1728 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1729 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1730 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1731 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1733 fprintf (acfg->fp, "mtctr 11\n");
1734 /* Branch to the target address */
1735 fprintf (acfg->fp, "bctr\n");
1737 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1738 *tramp_size = 11 * 4;
1740 *tramp_size = 9 * 4;
1743 #elif defined(TARGET_X86)
1747 /* Similar to the PPC code above */
1749 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1752 /* Load mscorlib got address */
1753 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1755 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1756 /* Branch to the target address */
1757 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1759 #ifdef __native_client_codegen__
1761 /* emit nops to next 32 byte alignment */
1762 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1763 while (code < (buf + a)) x86_nop(code);
1767 emit_bytes (acfg, buf, code - buf);
1769 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1770 g_assert (code - buf == *tramp_size);
1772 g_assert_not_reached ();
1777 * arch_emit_imt_thunk:
1779 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1780 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1781 * key is the IMT key, and ptr holds the address of a memory location holding
1782 * the address to branch to if the IMT arg matches the key. The array is
1783 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1785 * TRAMP_SIZE is set to the size of the emitted trampoline.
1788 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1790 #if defined(TARGET_AMD64)
1792 #if defined(__native_client_codegen__)
1795 guint8 *labels [16];
1797 guint8 *mov_buf_ptr = mov_buf;
1799 const int kSizeOfMove = 7;
1800 #if defined(__default_codegen__)
1801 code = buf = g_malloc (256);
1802 #elif defined(__native_client_codegen__)
1803 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1804 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1805 /* The RIP relative move below is emitted first */
1810 /* FIXME: Optimize this, i.e. use binary search etc. */
1811 /* Maybe move the body into a separate function (slower, but much smaller) */
1813 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1816 emit_unset_mode (acfg);
1817 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1821 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1823 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1826 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1828 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1831 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1832 amd64_jump_code (code, labels [0]);
1835 mono_amd64_patch (labels [2], code);
1836 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1837 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1840 mono_amd64_patch (labels [1], code);
1841 /* Load fail tramp */
1842 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1843 /* Check if there is a fail tramp */
1844 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1846 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1847 /* Jump to fail tramp */
1848 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1851 mono_amd64_patch (labels [3], code);
1852 x86_breakpoint (code);
1855 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1856 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1857 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1858 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1859 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1860 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1862 emit_bytes (acfg, buf, code - buf);
1864 *tramp_size = code - buf + kSizeOfMove;
1865 #if defined(__native_client_codegen__)
1866 /* The tramp will be padded to the next kNaClAlignment bundle. */
1867 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1870 #if defined(__default_codegen__)
1872 #elif defined(__native_client_codegen__)
1876 #elif defined(TARGET_X86)
1878 #ifdef __native_client_codegen__
1881 guint8 *labels [16];
1883 #if defined(__default_codegen__)
1884 code = buf = g_malloc (256);
1885 #elif defined(__native_client_codegen__)
1886 buf_alloc = g_malloc (256 + kNaClAlignment);
1887 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1890 /* Allocate a temporary stack slot */
1891 x86_push_reg (code, X86_EAX);
1893 x86_push_reg (code, X86_EAX);
1895 /* Load mscorlib got address */
1896 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1898 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1901 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1903 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1906 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1908 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1911 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1912 x86_jump_code (code, labels [0]);
1915 mono_x86_patch (labels [2], code);
1916 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1917 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1918 /* Save the target address to the temporary stack location */
1919 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1921 x86_pop_reg (code, X86_EAX);
1922 /* Jump to the target address */
1926 mono_x86_patch (labels [1], code);
1927 /* Load fail tramp */
1928 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1929 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1931 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1932 /* Jump to fail tramp */
1933 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1934 x86_pop_reg (code, X86_EAX);
1938 mono_x86_patch (labels [3], code);
1939 x86_breakpoint (code);
1941 #ifdef __native_client_codegen__
1943 /* emit nops to next 32 byte alignment */
1944 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1945 while (code < (buf + a)) x86_nop(code);
1948 emit_bytes (acfg, buf, code - buf);
1950 *tramp_size = code - buf;
1952 #if defined(__default_codegen__)
1954 #elif defined(__native_client_codegen__)
1958 #elif defined(TARGET_ARM)
1960 guint8 *code, *code2, *labels [16];
1964 /* The IMT method is in v5 */
1966 /* Need at least two free registers, plus a slot for storing the pc */
1967 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1969 /* Load the parameter from the GOT */
1970 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1971 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1974 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1975 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1977 ARM_B_COND (code, ARMCOND_EQ, 0);
1979 /* End-of-loop check */
1980 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1982 ARM_B_COND (code, ARMCOND_EQ, 0);
1985 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1988 arm_patch (labels [4], labels [1]);
1991 arm_patch (labels [2], code);
1992 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1993 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1994 /* Save it to the third stack slot */
1995 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1996 /* Restore the registers and branch */
1997 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2000 arm_patch (labels [3], code);
2001 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2002 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2003 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2007 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2009 emit_bytes (acfg, buf, code - buf);
2010 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2012 *tramp_size = code - buf + 4;
2013 #elif defined(TARGET_ARM64)
2014 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2015 #elif defined(TARGET_POWERPC)
2017 guint8 *code, *labels [16];
2021 /* Load the mscorlib got address */
2022 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2023 /* Load the parameter from the GOT */
2024 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2025 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2027 /* Load and check key */
2029 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2030 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2032 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2034 /* End-of-loop check */
2035 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2037 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2040 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2043 mono_ppc_patch (labels [4], labels [1]);
2046 mono_ppc_patch (labels [2], code);
2047 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2048 /* r12 now contains the value of the vtable slot */
2049 /* this is not a function descriptor on ppc64 */
2050 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2051 ppc_mtctr (code, ppc_r12);
2052 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2055 mono_ppc_patch (labels [3], code);
2059 *tramp_size = code - buf;
2061 emit_bytes (acfg, buf, code - buf);
2063 g_assert_not_reached ();
2068 * arch_emit_gsharedvt_arg_trampoline:
2070 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2071 * two GOT slots which contain the argument, and the code to jump to.
2072 * TRAMP_SIZE is set to the size of the emitted trampoline.
2073 * These kinds of trampolines cannot be enumerated statically, since there could
2074 * be one trampoline per method instantiation, so we emit the same code for all
2075 * trampolines, and parameterize them using two GOT slots.
2078 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2080 #if defined(TARGET_X86)
2084 /* Similar to the PPC code above */
2086 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2089 /* Load mscorlib got address */
2090 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2092 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2093 /* Branch to the target address */
2094 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2096 #ifdef __native_client_codegen__
2098 /* emit nops to next 32 byte alignment */
2099 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2100 while (code < (buf + a)) x86_nop(code);
2104 emit_bytes (acfg, buf, code - buf);
2106 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2107 g_assert (code - buf == *tramp_size);
2108 #elif defined(TARGET_ARM)
2112 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2113 /* Similar to arch_emit_specific_trampoline () */
2116 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2117 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2118 /* Load the arg value from the GOT */
2119 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2120 /* Load the addr from the GOT */
2121 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2123 ARM_BX (code, ARMREG_R1);
2125 g_assert (code - buf == 20);
2128 emit_bytes (acfg, buf, code - buf);
2129 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2130 #elif defined(TARGET_ARM64)
2131 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2133 g_assert_not_reached ();
2138 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2140 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2141 /* Based on code generated by gcc */
2142 emit_unset_mode (acfg);
2145 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2146 ".section .ctors,\"aw\",@progbits\n"
2150 ".section .opd,\"aw\"\n"
2153 ".long .%s,.TOC.@tocbase32\n"
2156 ".type .%s,@function\n"
2158 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2160 ".section .ctors,\"aw\",@progbits\n"
2164 ".section .opd,\"aw\"\n"
2167 ".long .%1$s,.TOC.@tocbase32\n"
2168 ".size %1$s,.-%1$s\n"
2170 ".type .%1$s,@function\n"
2172 ".%1$s:\n", symbol);
2183 "lis 3, .Lglobals@h\n"
2184 "ori 3, 3, .Lglobals@l\n"
2185 "bl .mono_aot_register_module\n"
2193 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2195 ".size .%s,.-.%s\n", symbol, symbol);
2198 ".size .%1$s,.-.%1$s\n", symbol);
2204 /* END OF ARCH SPECIFIC CODE */
2207 mono_get_field_token (MonoClassField *field)
2209 MonoClass *klass = field->parent;
2212 for (i = 0; i < klass->field.count; ++i) {
2213 if (field == &klass->fields [i])
2214 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2217 g_assert_not_reached ();
2222 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2226 //printf ("ENCODE: %d 0x%x.\n", value, value);
2229 * Same encoding as the one used in the metadata, extended to handle values
2230 * greater than 0x1fffffff.
2232 if ((value >= 0) && (value <= 127))
2234 else if ((value >= 0) && (value <= 16383)) {
2235 p [0] = 0x80 | (value >> 8);
2236 p [1] = value & 0xff;
2238 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2239 p [0] = (value >> 24) | 0xc0;
2240 p [1] = (value >> 16) & 0xff;
2241 p [2] = (value >> 8) & 0xff;
2242 p [3] = value & 0xff;
2247 p [1] = (value >> 24) & 0xff;
2248 p [2] = (value >> 16) & 0xff;
2249 p [3] = (value >> 8) & 0xff;
2250 p [4] = value & 0xff;
2258 stream_init (MonoDynamicStream *sh)
2261 sh->alloc_size = 4096;
2262 sh->data = g_malloc (4096);
2264 /* So offsets are > 0 */
2270 make_room_in_stream (MonoDynamicStream *stream, int size)
2272 if (size <= stream->alloc_size)
2275 while (stream->alloc_size <= size) {
2276 if (stream->alloc_size < 4096)
2277 stream->alloc_size = 4096;
2279 stream->alloc_size *= 2;
2282 stream->data = g_realloc (stream->data, stream->alloc_size);
2286 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2290 make_room_in_stream (stream, stream->index + len);
2291 memcpy (stream->data + stream->index, data, len);
2292 idx = stream->index;
2293 stream->index += len;
2300 * Add data to the binary blob inside the aot image. Returns the offset inside the
2301 * blob where the data was stored.
2304 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2306 if (acfg->blob.alloc_size == 0)
2307 stream_init (&acfg->blob);
2309 return add_stream_data (&acfg->blob, (char*)data, data_len);
2313 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2318 if (acfg->blob.alloc_size == 0)
2319 stream_init (&acfg->blob);
2321 count = acfg->blob.index % align;
2323 /* we assume the stream data will be aligned */
2325 add_stream_data (&acfg->blob, buf, 4 - count);
2327 return add_stream_data (&acfg->blob, (char*)data, data_len);
2331 * emit_offset_table:
2333 * Emit a table of increasing offsets in a compact form using differential encoding.
2334 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2335 * group size, the more compact the table becomes, but the slower it becomes to compute
2336 * a given entry. Returns the size of the table.
2339 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2341 gint32 current_offset;
2342 int i, buf_size, ngroups, index_entry_size;
2344 guint32 *index_offsets;
2346 ngroups = (noffsets + (group_size - 1)) / group_size;
2348 index_offsets = g_new0 (guint32, ngroups);
2350 buf_size = noffsets * 4;
2351 p = buf = g_malloc0 (buf_size);
2354 for (i = 0; i < noffsets; ++i) {
2355 //printf ("D: %d -> %d\n", i, offsets [i]);
2356 if ((i % group_size) == 0) {
2357 index_offsets [i / group_size] = p - buf;
2358 /* Emit the full value for these entries */
2359 encode_value (offsets [i], p, &p);
2361 /* The offsets are allowed to be non-increasing */
2362 //g_assert (offsets [i] >= current_offset);
2363 encode_value (offsets [i] - current_offset, p, &p);
2365 current_offset = offsets [i];
2368 if (ngroups && index_offsets [ngroups - 1] < 65000)
2369 index_entry_size = 2;
2371 index_entry_size = 4;
2373 /* Emit the header */
2374 emit_int32 (acfg, noffsets);
2375 emit_int32 (acfg, group_size);
2376 emit_int32 (acfg, ngroups);
2377 emit_int32 (acfg, index_entry_size);
2379 /* Emit the index */
2380 for (i = 0; i < ngroups; ++i) {
2381 if (index_entry_size == 2)
2382 emit_int16 (acfg, index_offsets [i]);
2384 emit_int32 (acfg, index_offsets [i]);
2388 emit_bytes (acfg, buf, p - buf);
2390 return (int)(p - buf) + (ngroups * 4);
2394 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2398 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2402 index = g_hash_table_size (cfg->image_hash);
2403 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2404 g_ptr_array_add (cfg->image_table, image);
2410 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2413 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2415 /* FIXME: Search referenced images as well */
2416 if (!acfg->typespec_classes) {
2417 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2418 for (i = 0; i < len; ++i) {
2420 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2421 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2424 for (i = 0; i < len; ++i) {
2425 if (acfg->typespec_classes [i] == klass)
2430 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2436 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2439 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2442 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2445 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2448 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2453 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2457 if (klass->generic_class) {
2459 g_assert (klass->type_token);
2461 /* Find a typespec for a class if possible */
2462 token = find_typespec_for_class (acfg, klass);
2464 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2465 encode_value (token, p, &p);
2467 MonoClass *gclass = klass->generic_class->container_class;
2468 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2469 static int count = 0;
2472 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2473 encode_klass_ref (acfg, gclass, p, &p);
2474 encode_ginst (acfg, inst, p, &p);
2478 } else if (klass->type_token) {
2479 int iindex = get_image_index (acfg, klass->image);
2481 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2483 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2484 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2486 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2487 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2488 encode_value (get_image_index (acfg, klass->image), p, &p);
2490 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2491 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2492 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2494 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2495 encode_value (klass->byval_arg.type, p, &p);
2496 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2498 encode_value (container ? 1 : 0, p, &p);
2500 encode_value (container->is_method, p, &p);
2501 g_assert (par->gshared_constraint == 0);
2502 if (container->is_method)
2503 encode_method_ref (acfg, container->owner.method, p, &p);
2505 encode_klass_ref (acfg, container->owner.klass, p, &p);
2507 encode_value (par->gshared_constraint, p, &p);
2509 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2510 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2511 encode_type (acfg, &klass->byval_arg, p, &p);
2514 g_assert (klass->rank > 0);
2515 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2516 encode_value (klass->rank, p, &p);
2517 encode_klass_ref (acfg, klass->element_class, p, &p);
2525 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2526 * standard metadata encoding.
2529 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2531 gboolean shared = FALSE;
2534 * The encoding of generic instances is large so emit them only once.
2536 if (klass->generic_class) {
2538 g_assert (klass->type_token);
2540 /* Find a typespec for a class if possible */
2541 token = find_typespec_for_class (acfg, klass);
2544 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2549 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2553 buf2 = g_malloc (1024);
2556 encode_klass_ref_inner (acfg, klass, p, &p);
2557 g_assert (p - buf2 < 1024);
2559 offset = add_to_blob (acfg, buf2, p - buf2);
2562 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2568 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2569 encode_value (offset, p, &p);
2574 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2578 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2580 guint32 token = mono_get_field_token (field);
2583 encode_klass_ref (cfg, field->parent, p, &p);
2584 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2585 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2590 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2595 encode_value (inst->type_argc, p, &p);
2596 for (i = 0; i < inst->type_argc; ++i)
2597 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2602 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2605 MonoGenericInst *inst;
2607 inst = context->class_inst;
2609 g_assert (inst->type_argc);
2610 encode_ginst (acfg, inst, p, &p);
2612 encode_value (0, p, &p);
2614 inst = context->method_inst;
2616 g_assert (inst->type_argc);
2617 encode_ginst (acfg, inst, p, &p);
2619 encode_value (0, p, &p);
2625 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2629 g_assert (t->num_mods == 0);
2630 /* t->attrs can be ignored */
2631 //g_assert (t->attrs == 0);
2634 *p = MONO_TYPE_PINNED;
2638 *p = MONO_TYPE_BYREF;
2646 case MONO_TYPE_VOID:
2647 case MONO_TYPE_BOOLEAN:
2648 case MONO_TYPE_CHAR:
2661 case MONO_TYPE_STRING:
2662 case MONO_TYPE_OBJECT:
2663 case MONO_TYPE_TYPEDBYREF:
2665 case MONO_TYPE_VALUETYPE:
2666 case MONO_TYPE_CLASS:
2667 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2669 case MONO_TYPE_SZARRAY:
2670 encode_klass_ref (acfg, t->data.klass, p, &p);
2673 encode_type (acfg, t->data.type, p, &p);
2675 case MONO_TYPE_GENERICINST: {
2676 MonoClass *gclass = t->data.generic_class->container_class;
2677 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2679 encode_klass_ref (acfg, gclass, p, &p);
2680 encode_ginst (acfg, inst, p, &p);
2683 case MONO_TYPE_ARRAY: {
2684 MonoArrayType *array = t->data.array;
2687 encode_klass_ref (acfg, array->eklass, p, &p);
2688 encode_value (array->rank, p, &p);
2689 encode_value (array->numsizes, p, &p);
2690 for (i = 0; i < array->numsizes; ++i)
2691 encode_value (array->sizes [i], p, &p);
2692 encode_value (array->numlobounds, p, &p);
2693 for (i = 0; i < array->numlobounds; ++i)
2694 encode_value (array->lobounds [i], p, &p);
2698 case MONO_TYPE_MVAR:
2699 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2702 g_assert_not_reached ();
2709 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2715 /* Similar to the metadata encoding */
2716 if (sig->generic_param_count)
2720 if (sig->explicit_this)
2722 flags |= (sig->call_convention & 0x0F);
2726 if (sig->generic_param_count)
2727 encode_value (sig->generic_param_count, p, &p);
2728 encode_value (sig->param_count, p, &p);
2730 encode_type (acfg, sig->ret, p, &p);
2731 for (i = 0; i < sig->param_count; ++i) {
2732 if (sig->sentinelpos == i) {
2733 *p = MONO_TYPE_SENTINEL;
2736 encode_type (acfg, sig->params [i], p, &p);
2742 #define MAX_IMAGE_INDEX 250
2745 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2747 guint32 image_index = get_image_index (acfg, method->klass->image);
2748 guint32 token = method->token;
2749 MonoJumpInfoToken *ji;
2753 * The encoding for most methods is as follows:
2754 * - image index encoded as a leb128
2755 * - token index encoded as a leb128
2756 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2757 * types of method encodings.
2760 /* Mark methods which can't use aot trampolines because they need the further
2761 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2763 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2764 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2765 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2767 if (method->wrapper_type) {
2768 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2770 encode_value (method->wrapper_type, p, &p);
2772 switch (method->wrapper_type) {
2773 case MONO_WRAPPER_REMOTING_INVOKE:
2774 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2775 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2778 m = mono_marshal_method_from_wrapper (method);
2780 encode_method_ref (acfg, m, p, &p);
2783 case MONO_WRAPPER_PROXY_ISINST:
2784 case MONO_WRAPPER_LDFLD:
2785 case MONO_WRAPPER_LDFLDA:
2786 case MONO_WRAPPER_STFLD:
2787 case MONO_WRAPPER_ISINST: {
2788 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2791 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2794 case MONO_WRAPPER_LDFLD_REMOTE:
2795 case MONO_WRAPPER_STFLD_REMOTE:
2797 case MONO_WRAPPER_ALLOC: {
2798 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2800 /* The GC name is saved once in MonoAotFileInfo */
2801 g_assert (info->alloc_type != -1);
2802 encode_value (info->alloc_type, p, &p);
2805 case MONO_WRAPPER_WRITE_BARRIER:
2807 case MONO_WRAPPER_STELEMREF: {
2808 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2811 encode_value (info->subtype, p, &p);
2812 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2813 encode_value (info->d.virtual_stelemref.kind, p, &p);
2816 case MONO_WRAPPER_UNKNOWN: {
2817 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2820 encode_value (info->subtype, p, &p);
2821 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2822 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2823 encode_klass_ref (acfg, method->klass, p, &p);
2824 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2825 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2826 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2827 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2830 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2831 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2834 encode_value (info->subtype, p, &p);
2835 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2836 strcpy ((char*)p, method->name);
2837 p += strlen (method->name) + 1;
2838 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2839 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2841 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2842 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2846 case MONO_WRAPPER_SYNCHRONIZED: {
2849 m = mono_marshal_method_from_wrapper (method);
2851 g_assert (m != method);
2852 encode_method_ref (acfg, m, p, &p);
2855 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2856 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2859 encode_value (info->subtype, p, &p);
2861 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2862 encode_value (info->d.element_addr.rank, p, &p);
2863 encode_value (info->d.element_addr.elem_size, p, &p);
2864 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2865 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2867 g_assert_not_reached ();
2871 case MONO_WRAPPER_CASTCLASS: {
2872 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2875 encode_value (info->subtype, p, &p);
2878 case MONO_WRAPPER_RUNTIME_INVOKE: {
2879 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2882 encode_value (info->subtype, p, &p);
2883 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2884 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2885 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2886 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2889 case MONO_WRAPPER_DELEGATE_INVOKE:
2890 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2891 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2892 if (method->is_inflated) {
2893 /* These wrappers are identified by their class */
2894 encode_value (1, p, &p);
2895 encode_klass_ref (acfg, method->klass, p, &p);
2897 MonoMethodSignature *sig = mono_method_signature (method);
2898 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2900 encode_value (0, p, &p);
2901 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2902 encode_value (info ? info->subtype : 0, p, &p);
2903 encode_signature (acfg, sig, p, &p);
2907 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2908 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2911 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2912 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2916 g_assert_not_reached ();
2918 } else if (mono_method_signature (method)->is_inflated) {
2920 * This is a generic method, find the original token which referenced it and
2922 * Obtain the token from information recorded by the JIT.
2924 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2926 image_index = get_image_index (acfg, ji->image);
2927 g_assert (image_index < MAX_IMAGE_INDEX);
2930 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2931 encode_value (image_index, p, &p);
2932 encode_value (token, p, &p);
2934 MonoMethod *declaring;
2935 MonoGenericContext *context = mono_method_get_context (method);
2937 g_assert (method->is_inflated);
2938 declaring = ((MonoMethodInflated*)method)->declaring;
2941 * This might be a non-generic method of a generic instance, which
2942 * doesn't have a token since the reference is generated by the JIT
2943 * like Nullable:Box/Unbox, or by generic sharing.
2945 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2946 /* Encode the klass */
2947 encode_klass_ref (acfg, method->klass, p, &p);
2948 /* Encode the method */
2949 image_index = get_image_index (acfg, method->klass->image);
2950 g_assert (image_index < MAX_IMAGE_INDEX);
2951 g_assert (declaring->token);
2952 token = declaring->token;
2953 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2954 encode_value (image_index, p, &p);
2955 encode_value (token, p, &p);
2956 encode_generic_context (acfg, context, p, &p);
2958 } else if (token == 0) {
2959 /* This might be a method of a constructed type like int[,].Set */
2960 /* Obtain the token from information recorded by the JIT */
2961 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2963 image_index = get_image_index (acfg, ji->image);
2964 g_assert (image_index < MAX_IMAGE_INDEX);
2967 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2968 encode_value (image_index, p, &p);
2969 encode_value (token, p, &p);
2972 g_assert (method->klass->rank);
2974 /* Encode directly */
2975 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2976 encode_klass_ref (acfg, method->klass, p, &p);
2977 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2978 encode_value (0, p, &p);
2979 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2980 encode_value (1, p, &p);
2981 else if (!strcmp (method->name, "Get"))
2982 encode_value (2, p, &p);
2983 else if (!strcmp (method->name, "Address"))
2984 encode_value (3, p, &p);
2985 else if (!strcmp (method->name, "Set"))
2986 encode_value (4, p, &p);
2988 g_assert_not_reached ();
2991 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2993 if (image_index >= MONO_AOT_METHODREF_MIN) {
2994 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2995 encode_value (image_index, p, &p);
2996 encode_value (mono_metadata_token_index (token), p, &p);
2998 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3005 compare_patches (gconstpointer a, gconstpointer b)
3009 i = (*(MonoJumpInfo**)a)->ip.i;
3010 j = (*(MonoJumpInfo**)b)->ip.i;
3021 static G_GNUC_UNUSED char*
3022 patch_to_string (MonoJumpInfo *patch_info)
3026 str = g_string_new ("");
3028 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3030 switch (patch_info->type) {
3031 case MONO_PATCH_INFO_VTABLE:
3032 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3037 g_string_append_printf (str, ")");
3038 return g_string_free (str, FALSE);
3044 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3047 static inline gboolean
3048 is_plt_patch (MonoJumpInfo *patch_info)
3050 switch (patch_info->type) {
3051 case MONO_PATCH_INFO_METHOD:
3052 case MONO_PATCH_INFO_INTERNAL_METHOD:
3053 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3054 case MONO_PATCH_INFO_ICALL_ADDR:
3055 case MONO_PATCH_INFO_CLASS_INIT:
3056 case MONO_PATCH_INFO_RGCTX_FETCH:
3057 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3058 case MONO_PATCH_INFO_MONITOR_ENTER:
3059 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3060 case MONO_PATCH_INFO_MONITOR_EXIT:
3061 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3071 * Return the symbol identifying the plt entry PLT_OFFSET.
3074 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3078 * The Apple linker reorganizes object files, so it doesn't like branches to local
3079 * labels, since those have no relocations.
3081 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3083 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3090 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3092 static MonoPltEntry*
3093 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3096 gboolean synchronized = FALSE;
3097 static int synchronized_symbol_idx;
3099 if (!is_plt_patch (patch_info))
3102 if (!acfg->patch_to_plt_entry [patch_info->type])
3103 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3104 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3106 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3108 * Allocate a separate PLT slot for each such patch, since some plt
3109 * entries will refer to the method itself, and some will refer to the
3113 synchronized = TRUE;
3117 MonoJumpInfo *new_ji;
3119 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3121 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3122 res->plt_offset = acfg->plt_offset;
3124 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3125 if (acfg->aot_opts.write_symbols)
3126 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3128 /* Avoid duplicate symbols because we don't cache */
3129 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3131 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3132 synchronized_symbol_idx ++;
3135 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3137 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3139 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3141 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3143 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3144 //mono_print_ji (patch_info); printf ("\n");
3145 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3147 acfg->plt_offset ++;
3156 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3157 * JI could be found if it exists, otherwise allocates a new one.
3160 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3163 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3165 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3167 return got_offset - 1;
3170 got_offset = acfg->llvm_got_offset;
3171 acfg->llvm_got_offset ++;
3173 got_offset = acfg->got_offset;
3174 acfg->got_offset ++;
3177 acfg->stats.got_slots ++;
3178 acfg->stats.got_slot_types [ji->type] ++;
3180 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3181 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3182 g_ptr_array_add (info->got_patches, ji);
3187 /* Add a method to the list of methods which need to be emitted */
3189 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3192 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3193 g_ptr_array_add (acfg->methods, method);
3194 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3195 acfg->nmethods = acfg->methods->len + 1;
3198 if (method->wrapper_type || extra)
3199 g_ptr_array_add (acfg->extra_methods, method);
3203 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3205 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3213 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3217 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3221 index = acfg->method_index;
3222 add_method_with_index (acfg, method, index, extra);
3224 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3226 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3228 acfg->method_index ++;
3234 add_method (MonoAotCompile *acfg, MonoMethod *method)
3236 return add_method_full (acfg, method, FALSE, 0);
3240 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3242 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3243 method = mini_get_shared_method (method);
3245 if (acfg->aot_opts.log_generics)
3246 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3248 add_method_full (acfg, method, TRUE, depth);
3252 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3254 add_extra_method_with_depth (acfg, method, 0);
3258 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3260 MonoAotCompile *acfg = user_data;
3261 MonoJitICallInfo *callinfo = value;
3262 MonoMethod *wrapper;
3268 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3269 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3272 add_method (acfg, wrapper);
3276 get_runtime_invoke_sig (MonoMethodSignature *sig)
3278 MonoMethodBuilder *mb;
3281 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3282 m = mono_mb_create_method (mb, sig, 16);
3283 return mono_marshal_get_runtime_invoke (m, FALSE);
3287 can_marshal_struct (MonoClass *klass)
3289 MonoClassField *field;
3290 gboolean can_marshal = TRUE;
3291 gpointer iter = NULL;
3292 MonoMarshalType *info;
3295 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3298 info = mono_marshal_load_type_info (klass);
3300 /* Only allow a few field types to avoid asserts in the marshalling code */
3301 while ((field = mono_class_get_fields (klass, &iter))) {
3302 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3305 switch (field->type->type) {
3310 case MONO_TYPE_BOOLEAN:
3313 case MONO_TYPE_CHAR:
3321 case MONO_TYPE_STRING:
3323 case MONO_TYPE_VALUETYPE:
3324 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3325 can_marshal = FALSE;
3327 case MONO_TYPE_SZARRAY: {
3328 gboolean has_mspec = FALSE;
3331 for (i = 0; i < info->num_fields; ++i) {
3332 if (info->fields [i].field == field && info->fields [i].mspec)
3337 can_marshal = FALSE;
3341 can_marshal = FALSE;
3347 /* Its hard to compute whenever these can be marshalled or not */
3348 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3355 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3357 /* Create a vtype instantiation */
3358 MonoGenericContext shared_context;
3360 MonoGenericInst *inst;
3361 MonoGenericContainer *container;
3362 MonoClass **constraints;
3365 memset (ctx, 0, sizeof (MonoGenericContext));
3367 if (method->klass->generic_container) {
3368 shared_context = method->klass->generic_container->context;
3369 inst = shared_context.class_inst;
3371 args = g_new0 (MonoType*, inst->type_argc);
3372 for (i = 0; i < inst->type_argc; ++i) {
3373 args [i] = &mono_defaults.int_class->byval_arg;
3375 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3377 if (method->is_generic) {
3378 container = mono_method_get_generic_container (method);
3379 shared_context = container->context;
3380 inst = shared_context.method_inst;
3382 args = g_new0 (MonoType*, inst->type_argc);
3383 for (i = 0; i < container->type_argc; ++i) {
3384 MonoGenericParamInfo *info = &container->type_params [i].info;
3385 gboolean ref_only = FALSE;
3387 if (info && info->constraints) {
3388 constraints = info->constraints;
3390 while (*constraints) {
3391 MonoClass *cklass = *constraints;
3392 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3393 /* Inflaring the method with our vtype would not be valid */
3400 args [i] = &mono_defaults.object_class->byval_arg;
3402 args [i] = &mono_defaults.int_class->byval_arg;
3404 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3409 add_wrappers (MonoAotCompile *acfg)
3411 MonoMethod *method, *m;
3413 MonoMethodSignature *sig, *csig;
3417 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3418 * so there is only one wrapper of a given type, or inlining their contents into their
3421 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3424 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3425 gboolean skip = FALSE;
3427 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3428 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3430 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3431 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3432 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3435 /* Skip methods which can not be handled by get_runtime_invoke () */
3436 sig = mono_method_signature (method);
3439 if ((sig->ret->type == MONO_TYPE_PTR) ||
3440 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3442 if (mono_class_is_open_constructed_type (sig->ret))
3445 for (j = 0; j < sig->param_count; j++) {
3446 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3448 if (mono_class_is_open_constructed_type (sig->params [j]))
3452 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3453 if (!mono_class_is_contextbound (method->klass)) {
3454 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3455 gboolean has_nullable = FALSE;
3457 for (j = 0; j < sig->param_count; j++) {
3458 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3459 has_nullable = TRUE;
3462 if (info && !has_nullable) {
3463 /* Supported by the dynamic runtime-invoke wrapper */
3467 mono_arch_dyn_call_free (info);
3472 //printf ("%s\n", mono_method_full_name (method, TRUE));
3473 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3477 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3480 /* Runtime invoke wrappers */
3482 /* void runtime-invoke () [.cctor] */
3483 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3484 csig->ret = &mono_defaults.void_class->byval_arg;
3485 add_method (acfg, get_runtime_invoke_sig (csig));
3487 /* void runtime-invoke () [Finalize] */
3488 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3490 csig->ret = &mono_defaults.void_class->byval_arg;
3491 add_method (acfg, get_runtime_invoke_sig (csig));
3493 /* void runtime-invoke (string) [exception ctor] */
3494 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3496 csig->ret = &mono_defaults.void_class->byval_arg;
3497 csig->params [0] = &mono_defaults.string_class->byval_arg;
3498 add_method (acfg, get_runtime_invoke_sig (csig));
3500 /* void runtime-invoke (string, string) [exception ctor] */
3501 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3503 csig->ret = &mono_defaults.void_class->byval_arg;
3504 csig->params [0] = &mono_defaults.string_class->byval_arg;
3505 csig->params [1] = &mono_defaults.string_class->byval_arg;
3506 add_method (acfg, get_runtime_invoke_sig (csig));
3508 /* string runtime-invoke () [Exception.ToString ()] */
3509 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3511 csig->ret = &mono_defaults.string_class->byval_arg;
3512 add_method (acfg, get_runtime_invoke_sig (csig));
3514 /* void runtime-invoke (string, Exception) [exception ctor] */
3515 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3517 csig->ret = &mono_defaults.void_class->byval_arg;
3518 csig->params [0] = &mono_defaults.string_class->byval_arg;
3519 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3520 add_method (acfg, get_runtime_invoke_sig (csig));
3522 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3523 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3525 csig->ret = &(mono_class_from_name (
3526 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3527 csig->params [0] = &mono_defaults.string_class->byval_arg;
3528 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3529 add_method (acfg, get_runtime_invoke_sig (csig));
3531 /* runtime-invoke used by finalizers */
3532 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3534 /* This is used by mono_runtime_capture_context () */
3535 method = mono_get_context_capture_method ();
3537 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3539 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3540 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3544 add_method (acfg, mono_marshal_get_stelemref ());
3546 if (MONO_ARCH_HAVE_TLS_GET) {
3547 /* Managed Allocators */
3548 nallocators = mono_gc_get_managed_allocator_types ();
3549 for (i = 0; i < nallocators; ++i) {
3550 m = mono_gc_get_managed_allocator_by_type (i);
3552 add_method (acfg, m);
3556 /* write barriers */
3557 if (mono_gc_is_moving ()) {
3558 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3559 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3562 /* Stelemref wrappers */
3564 MonoMethod **wrappers;
3567 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3568 for (i = 0; i < nwrappers; ++i)
3569 add_method (acfg, wrappers [i]);
3573 /* castclass_with_check wrapper */
3574 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3575 /* isinst_with_check wrapper */
3576 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3578 /* JIT icall wrappers */
3579 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3580 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3584 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3585 * we use the original method instead at runtime.
3586 * Since full-aot doesn't support remoting, this is not a problem.
3589 /* remoting-invoke wrappers */
3590 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3591 MonoMethodSignature *sig;
3593 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3594 method = mono_get_method (acfg->image, token, NULL);
3596 sig = mono_method_signature (method);
3598 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3599 m = mono_marshal_get_remoting_invoke_with_check (method);
3601 add_method (acfg, m);
3606 /* delegate-invoke wrappers */
3607 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3610 MonoCustomAttrInfo *cattr;
3612 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3613 klass = mono_class_get_checked (acfg->image, token, &error);
3616 mono_error_cleanup (&error);
3620 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3623 if (!klass->generic_container) {
3624 method = mono_get_delegate_invoke (klass);
3626 m = mono_marshal_get_delegate_invoke (method, NULL);
3628 add_method (acfg, m);
3630 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3632 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3634 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3636 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3638 cattr = mono_custom_attrs_from_class (klass);
3643 for (j = 0; j < cattr->num_attrs; ++j)
3644 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3646 if (j < cattr->num_attrs)
3647 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3649 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3651 MonoGenericContext ctx;
3652 MonoMethod *inst, *gshared;
3655 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3658 method = mono_get_delegate_invoke (klass);
3659 create_gsharedvt_inst (acfg, method, &ctx);
3661 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3662 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3664 m = mono_marshal_get_delegate_invoke (inst, NULL);
3665 g_assert (m->is_inflated);
3667 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3668 add_extra_method (acfg, gshared);
3671 method = mono_get_delegate_begin_invoke (klass);
3672 create_gsharedvt_inst (acfg, method, &ctx);
3674 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3675 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3677 m = mono_marshal_get_delegate_begin_invoke (inst);
3678 g_assert (m->is_inflated);
3680 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3681 add_extra_method (acfg, gshared);
3684 method = mono_get_delegate_end_invoke (klass);
3685 create_gsharedvt_inst (acfg, method, &ctx);
3687 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3688 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3690 m = mono_marshal_get_delegate_end_invoke (inst);
3691 g_assert (m->is_inflated);
3693 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3694 add_extra_method (acfg, gshared);
3699 /* array access wrappers */
3700 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3704 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3705 klass = mono_class_get_checked (acfg->image, token, &error);
3708 mono_error_cleanup (&error);
3712 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3713 MonoMethod *m, *wrapper;
3715 /* Add runtime-invoke wrappers too */
3717 m = mono_class_get_method_from_name (klass, "Get", -1);
3719 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3720 add_extra_method (acfg, wrapper);
3721 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3723 m = mono_class_get_method_from_name (klass, "Set", -1);
3725 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3726 add_extra_method (acfg, wrapper);
3727 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3731 /* Synchronized wrappers */
3732 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3734 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3735 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3736 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3738 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3739 if (method->is_generic) {
3741 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3743 MonoGenericContext ctx;
3744 MonoMethod *inst, *gshared, *m;
3747 * Create a generic wrapper for a generic instance, and AOT that.
3749 create_gsharedvt_inst (acfg, method, &ctx);
3750 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3751 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3752 m = mono_marshal_get_synchronized_wrapper (inst);
3753 g_assert (m->is_inflated);
3754 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3755 add_method (acfg, gshared);
3757 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3762 /* pinvoke wrappers */
3763 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3766 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3768 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3769 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3771 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3772 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3773 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3777 /* native-to-managed wrappers */
3778 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3781 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3782 MonoCustomAttrInfo *cattr;
3785 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3786 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3789 * Only generate native-to-managed wrappers for methods which have an
3790 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3791 * name to avoid defining a new assembly to contain it.
3793 cattr = mono_custom_attrs_from_method (method);
3796 for (j = 0; j < cattr->num_attrs; ++j)
3797 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3799 if (j < cattr->num_attrs) {
3800 MonoCustomAttrEntry *e = &cattr->attrs [j];
3801 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3802 const char *p = (const char*)e->data;
3804 int slen, num_named, named_type;
3808 char *export_name = NULL;
3809 MonoMethod *wrapper;
3811 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3812 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3813 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3814 mono_method_full_name (method, TRUE));
3818 g_assert (sig->param_count == 1);
3819 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3822 * Decode the cattr manually since we can't create objects
3823 * during aot compilation.
3829 /* From load_cattr_value () in reflection.c */
3830 slen = mono_metadata_decode_value (p, &p);
3831 n = g_memdup (p, slen + 1);
3833 t = mono_reflection_type_from_name (n, acfg->image);
3837 klass = mono_class_from_mono_type (t);
3838 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3842 num_named = read16 (p);
3845 g_assert (num_named < 2);
3846 if (num_named == 1) {
3850 /* parse ExportSymbol attribute */
3852 named_type = *named;
3854 /* data_type = *named; */
3857 name_len = mono_metadata_decode_blob_size (named, &named);
3858 name = g_malloc (name_len + 1);
3859 memcpy (name, named, name_len);
3860 name [name_len] = 0;
3863 g_assert (named_type == 0x54);
3864 g_assert (!strcmp (name, "ExportSymbol"));
3866 /* load_cattr_value (), string case */
3867 g_assert (*named != (char)0xff);
3868 slen = mono_metadata_decode_value (named, &named);
3869 export_name = g_malloc (slen + 1);
3870 memcpy (export_name, named, slen);
3871 export_name [slen] = 0;
3875 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3876 add_method (acfg, wrapper);
3878 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3882 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3883 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3884 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3888 /* StructureToPtr/PtrToStructure wrappers */
3889 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3893 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3894 klass = mono_class_get_checked (acfg->image, token, &error);
3897 mono_error_cleanup (&error);
3901 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3902 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3903 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3904 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3910 has_type_vars (MonoClass *klass)
3912 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3915 return has_type_vars (klass->element_class);
3916 if (klass->generic_class) {
3917 MonoGenericContext *context = &klass->generic_class->context;
3918 if (context->class_inst) {
3921 for (i = 0; i < context->class_inst->type_argc; ++i)
3922 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3926 if (klass->generic_container)
3932 is_vt_inst (MonoGenericInst *inst)
3936 for (i = 0; i < inst->type_argc; ++i) {
3937 MonoType *t = inst->type_argv [i];
3938 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3945 method_has_type_vars (MonoMethod *method)
3947 if (has_type_vars (method->klass))
3950 if (method->is_inflated) {
3951 MonoGenericContext *context = mono_method_get_context (method);
3952 if (context->method_inst) {
3955 for (i = 0; i < context->method_inst->type_argc; ++i)
3956 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3963 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3966 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3968 /* This might lead to a huge code blowup so only do it if neccesary */
3969 if (!acfg->aot_opts.full_aot && !force)
3972 add_generic_class_with_depth (acfg, klass, 0, ref);
3976 check_type_depth (MonoType *t, int depth)
3984 case MONO_TYPE_GENERICINST: {
3985 MonoGenericClass *gklass = t->data.generic_class;
3986 MonoGenericInst *ginst = gklass->context.class_inst;
3989 for (i = 0; i < ginst->type_argc; ++i) {
3990 if (check_type_depth (ginst->type_argv [i], depth + 1))
4004 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4007 * add_generic_class:
4009 * Add all methods of a generic class.
4012 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4015 MonoClassField *field;
4017 gboolean use_gsharedvt = FALSE;
4019 if (!acfg->ginst_hash)
4020 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4022 mono_class_init (klass);
4024 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4027 if (has_type_vars (klass))
4030 if (!klass->generic_class && !klass->rank)
4033 if (klass->exception_type)
4036 if (!acfg->ginst_hash)
4037 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4039 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4042 if (check_type_depth (&klass->byval_arg, 0))
4045 if (acfg->aot_opts.log_generics)
4046 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4048 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4051 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4052 * Enable this only for some classes since gsharedvt might not support all methods.
4054 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && klass->generic_class && klass->generic_class->context.class_inst && is_vt_inst (klass->generic_class->context.class_inst) &&
4055 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4056 use_gsharedvt = TRUE;
4059 while ((method = mono_class_get_methods (klass, &iter))) {
4060 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4062 * This is partial sharing, and we can't handle it yet
4067 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4069 add_types_from_method_header (acfg, method);
4073 if (method->is_generic)
4078 * FIXME: Instances which are referenced by these methods are not added,
4079 * for example Array.Resize<int> for List<int>.Add ().
4081 add_extra_method_with_depth (acfg, method, depth + 1);
4085 while ((field = mono_class_get_fields (klass, &iter))) {
4086 if (field->type->type == MONO_TYPE_GENERICINST)
4087 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4090 if (klass->delegate) {
4091 method = mono_get_delegate_invoke (klass);
4093 method = mono_marshal_get_delegate_invoke (method, NULL);
4095 if (acfg->aot_opts.log_generics)
4096 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4098 add_method (acfg, method);
4101 /* Add superclasses */
4103 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4106 * For ICollection<T>, add instances of the helper methods
4107 * in Array, since a T[] could be cast to ICollection<T>.
4109 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4110 (!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"))) {
4111 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4112 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4116 if (!strcmp (klass->name, "IEnumerator`1"))
4117 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4119 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4121 /* Add the T[]/InternalEnumerator class */
4122 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4126 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4127 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4131 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4132 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4136 while ((method = mono_class_get_methods (array_class, &iter))) {
4137 if (strstr (method->name, name_prefix)) {
4138 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4140 add_extra_method_with_depth (acfg, m, depth);
4144 g_free (name_prefix);
4147 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4148 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4149 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4150 MonoClass *icomparable, *gcomparer;
4151 MonoGenericContext ctx;
4152 MonoType *args [16];
4154 memset (&ctx, 0, sizeof (ctx));
4156 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4157 g_assert (icomparable);
4158 args [0] = &tclass->byval_arg;
4159 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4161 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4162 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4163 g_assert (gcomparer);
4164 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4168 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4169 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4170 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4171 MonoClass *iface, *gcomparer;
4172 MonoGenericContext ctx;
4173 MonoType *args [16];
4175 memset (&ctx, 0, sizeof (ctx));
4177 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4179 args [0] = &tclass->byval_arg;
4180 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4182 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4183 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4184 g_assert (gcomparer);
4185 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4191 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4194 MonoGenericContext ctx;
4195 MonoType *args [16];
4197 if (acfg->aot_opts.no_instances)
4200 memset (&ctx, 0, sizeof (ctx));
4202 for (i = 0; i < ninsts; ++i) {
4203 args [0] = insts [i];
4204 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4205 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4210 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4212 MonoMethodHeader *header;
4213 MonoMethodSignature *sig;
4216 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4218 sig = mono_method_signature (method);
4221 for (j = 0; j < sig->param_count; ++j)
4222 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4223 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4226 header = mono_method_get_header (method);
4229 for (j = 0; j < header->num_locals; ++j)
4230 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4231 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4233 mono_loader_clear_error ();
4238 * add_generic_instances:
4240 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4243 add_generic_instances (MonoAotCompile *acfg)
4248 MonoGenericContext *context;
4250 if (acfg->aot_opts.no_instances)
4253 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4255 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4256 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4259 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4260 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4261 mono_error_cleanup (&error);
4265 if (method->klass->image != acfg->image)
4268 context = mono_method_get_context (method);
4270 if (context && ((context->class_inst && context->class_inst->is_open)))
4274 * For open methods, create an instantiation which can be passed to the JIT.
4275 * FIXME: Handle class_inst as well.
4277 if (context && context->method_inst && context->method_inst->is_open) {
4279 MonoGenericContext shared_context;
4280 MonoGenericInst *inst;
4281 MonoType **type_argv;
4283 MonoMethod *declaring_method;
4284 gboolean supported = TRUE;
4286 /* Check that the context doesn't contain open constructed types */
4287 if (context->class_inst) {
4288 inst = context->class_inst;
4289 for (i = 0; i < inst->type_argc; ++i) {
4290 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)
4292 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4296 if (context->method_inst) {
4297 inst = context->method_inst;
4298 for (i = 0; i < inst->type_argc; ++i) {
4299 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)
4301 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4309 memset (&shared_context, 0, sizeof (MonoGenericContext));
4311 inst = context->class_inst;
4313 type_argv = g_new0 (MonoType*, inst->type_argc);
4314 for (i = 0; i < inst->type_argc; ++i) {
4315 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)
4316 type_argv [i] = &mono_defaults.object_class->byval_arg;
4318 type_argv [i] = inst->type_argv [i];
4321 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4325 inst = context->method_inst;
4327 type_argv = g_new0 (MonoType*, inst->type_argc);
4328 for (i = 0; i < inst->type_argc; ++i) {
4329 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)
4330 type_argv [i] = &mono_defaults.object_class->byval_arg;
4332 type_argv [i] = inst->type_argv [i];
4335 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4339 if (method->is_generic || method->klass->generic_container)
4340 declaring_method = method;
4342 declaring_method = mono_method_get_declaring_generic_method (method);
4344 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4345 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4349 * If the method is fully sharable, it was already added in place of its
4350 * generic definition.
4352 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4356 * FIXME: Partially shared methods are not shared here, so we end up with
4357 * many identical methods.
4359 add_extra_method (acfg, method);
4362 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4366 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4368 klass = mono_class_get_checked (acfg->image, token, &error);
4369 if (!klass || klass->rank) {
4370 mono_error_cleanup (&error);
4374 add_generic_class (acfg, klass, FALSE, "typespec");
4377 /* Add types of args/locals */
4378 for (i = 0; i < acfg->methods->len; ++i) {
4379 method = g_ptr_array_index (acfg->methods, i);
4380 add_types_from_method_header (acfg, method);
4383 if (acfg->image == mono_defaults.corlib) {
4385 MonoType *insts [256];
4388 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4389 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4390 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4391 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4392 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4393 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4394 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4395 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4396 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4397 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4398 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4399 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4401 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4402 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4404 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4405 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4407 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4409 /* Add instances of the array generic interfaces for primitive types */
4410 /* This will add instances of the InternalArray_ helper methods in Array too */
4411 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4413 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4414 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4416 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4417 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4419 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4422 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4423 * used for all instances of GetGenericValueImpl by the AOT runtime.
4426 MonoGenericContext ctx;
4427 MonoType *args [16];
4428 MonoMethod *get_method;
4429 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4431 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4435 memset (&ctx, 0, sizeof (ctx));
4436 args [0] = &mono_defaults.object_class->byval_arg;
4437 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4438 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4439 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4443 /* Same for CompareExchange<T>/Exchange<T> */
4445 MonoGenericContext ctx;
4446 MonoType *args [16];
4448 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4449 gpointer iter = NULL;
4451 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4452 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4454 memset (&ctx, 0, sizeof (ctx));
4455 args [0] = &mono_defaults.object_class->byval_arg;
4456 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4457 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4458 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4463 /* Same for Volatile.Read/Write<T> */
4465 MonoGenericContext ctx;
4466 MonoType *args [16];
4468 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4469 gpointer iter = NULL;
4471 if (volatile_klass) {
4472 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4473 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4475 memset (&ctx, 0, sizeof (ctx));
4476 args [0] = &mono_defaults.object_class->byval_arg;
4477 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4478 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4479 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4488 * is_direct_callable:
4490 * Return whenever the method identified by JI is directly callable without
4491 * going through the PLT.
4494 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4496 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4497 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4499 gboolean direct_callable = TRUE;
4501 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4502 direct_callable = FALSE;
4503 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4504 // FIXME: Maybe call the wrapper directly ?
4505 direct_callable = FALSE;
4507 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4508 /* Disable this so all calls go through load_method (), see the
4509 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4510 * mono_debugger_agent_init ().
4512 direct_callable = FALSE;
4515 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4516 /* sgen does some initialization when the allocator method is created */
4517 direct_callable = FALSE;
4518 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4519 /* we don't know at compile time whether sgen is concurrent or not */
4520 direct_callable = FALSE;
4522 if (direct_callable)
4525 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4526 if (acfg->aot_opts.direct_pinvoke)
4528 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4529 if (acfg->aot_opts.direct_icalls)
4537 #ifdef MONO_ARCH_AOT_SUPPORTED
4539 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4541 MonoImage *image = method->klass->image;
4542 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4543 MonoTableInfo *tables = image->tables;
4544 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4545 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4546 guint32 im_cols [MONO_IMPLMAP_SIZE];
4549 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4553 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4556 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4558 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4561 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4563 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4570 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4572 if (a->native_offset == b->native_offset)
4573 return a->il_offset - b->il_offset;
4575 return a->native_offset - b->native_offset;
4579 * compute_line_numbers:
4581 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4584 static MonoDebugSourceLocation**
4585 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4587 MonoDebugMethodInfo *minfo;
4588 MonoDebugLineNumberEntry *ln_array;
4589 MonoDebugSourceLocation *loc;
4590 int i, prev_line, prev_il_offset;
4591 int *native_to_il_offset = NULL;
4592 MonoDebugSourceLocation **res;
4595 minfo = mono_debug_lookup_method (method);
4598 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4599 if (debug_info->code_size != code_size)
4602 g_assert (code_size);
4604 /* Compute the native->IL offset mapping */
4606 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4607 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4609 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4611 native_to_il_offset = g_new0 (int, code_size + 1);
4613 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4615 MonoDebugLineNumberEntry *lne = &ln_array [i];
4618 for (j = 0; j < lne->native_offset; ++j)
4619 native_to_il_offset [j] = -1;
4622 if (i < debug_info->num_line_numbers - 1) {
4623 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4625 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4626 native_to_il_offset [j] = lne->il_offset;
4628 for (j = lne->native_offset; j < code_size; ++j)
4629 native_to_il_offset [j] = lne->il_offset;
4634 /* Compute the native->line number mapping */
4635 res = g_new0 (MonoDebugSourceLocation*, code_size);
4636 prev_il_offset = -1;
4639 for (i = 0; i < code_size; ++i) {
4640 int il_offset = native_to_il_offset [i];
4642 if (il_offset == -1 || il_offset == prev_il_offset)
4644 prev_il_offset = il_offset;
4645 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4646 if (!(loc && loc->source_file))
4648 if (loc->row == prev_line) {
4649 mono_debug_symfile_free_location (loc);
4652 prev_line = loc->row;
4653 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4655 /* This will cover the prolog too */
4665 get_file_index (MonoAotCompile *acfg, const char *source_file)
4669 // FIXME: Free these
4670 if (!acfg->dwarf_ln_filenames)
4671 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4672 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4674 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4675 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4676 emit_unset_mode (acfg);
4677 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4689 * emit_and_reloc_code:
4691 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4692 * is true, calls are made through the GOT too. This is used for emitting trampolines
4693 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4694 * since trampolines are needed to make PTL work.
4697 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4699 int i, pindex, start_index;
4701 MonoJumpInfo *patch_info;
4702 MonoDebugSourceLocation **locs = NULL;
4704 #ifdef MONO_ARCH_AOT_SUPPORTED
4705 gboolean direct_call, external_call;
4707 const char *direct_call_target = 0;
4708 const char *direct_pinvoke;
4711 if (acfg->gas_line_numbers && method && debug_info) {
4712 locs = compute_line_numbers (method, code_len, debug_info);
4714 int findex = get_file_index (acfg, "<unknown>");
4715 emit_unset_mode (acfg);
4716 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4720 /* Collect and sort relocations */
4721 patches = g_ptr_array_new ();
4722 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4723 g_ptr_array_add (patches, patch_info);
4724 g_ptr_array_sort (patches, compare_patches);
4727 for (i = 0; i < code_len; i += INST_LEN) {
4729 for (pindex = start_index; pindex < patches->len; ++pindex) {
4730 patch_info = g_ptr_array_index (patches, pindex);
4731 if (patch_info->ip.i >= i)
4735 if (locs && locs [i]) {
4736 MonoDebugSourceLocation *loc = locs [i];
4739 findex = get_file_index (acfg, loc->source_file);
4740 emit_unset_mode (acfg);
4741 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4742 mono_debug_symfile_free_location (loc);
4746 #ifdef MONO_ARCH_AOT_SUPPORTED
4747 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4748 start_index = pindex;
4750 switch (patch_info->type) {
4751 case MONO_PATCH_INFO_NONE:
4753 case MONO_PATCH_INFO_GOT_OFFSET: {
4756 arch_emit_got_offset (acfg, code + i, &code_size);
4757 i += code_size - INST_LEN;
4759 patch_info->type = MONO_PATCH_INFO_NONE;
4762 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4763 int code_size, index;
4764 char *selector = (void*)patch_info->data.target;
4766 if (!acfg->objc_selector_to_index)
4767 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4768 if (!acfg->objc_selectors)
4769 acfg->objc_selectors = g_ptr_array_new ();
4770 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4774 index = acfg->objc_selector_index;
4775 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4776 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4777 acfg->objc_selector_index ++;
4780 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4781 i += code_size - INST_LEN;
4783 patch_info->type = MONO_PATCH_INFO_NONE;
4788 * If this patch is a call, try emitting a direct call instead of
4789 * through a PLT entry. This is possible if the called method is in
4790 * the same assembly and requires no initialization.
4792 direct_call = FALSE;
4793 external_call = FALSE;
4794 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4795 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4796 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4797 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4799 direct_call_target = callee_cfg->asm_symbol;
4800 patch_info->type = MONO_PATCH_INFO_NONE;
4801 acfg->stats.direct_calls ++;
4804 acfg->stats.all_calls ++;
4805 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4806 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4807 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4808 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4810 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4811 if (direct_pinvoke) {
4813 g_assert (strlen (direct_pinvoke) < 1000);
4814 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4817 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4818 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4819 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4820 /* Call to a C function implementing a jit icall */
4822 external_call = TRUE;
4823 g_assert (strlen (sym) < 1000);
4824 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4826 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4827 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4828 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4829 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4830 /* Call to a jit icall without a wrapper */
4832 external_call = TRUE;
4833 g_assert (strlen (sym) < 1000);
4834 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4839 patch_info->type = MONO_PATCH_INFO_NONE;
4840 acfg->stats.direct_calls ++;
4843 if (!got_only && !direct_call) {
4844 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4846 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4848 direct_call_target = plt_entry->symbol;
4850 /* Nullify the patch */
4851 patch_info->type = MONO_PATCH_INFO_NONE;
4852 plt_entry->jit_used = TRUE;
4859 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4860 i += call_size - INST_LEN;
4864 got_slot = get_got_offset (acfg, FALSE, patch_info);
4866 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4867 i += code_size - INST_LEN;
4873 #endif /* MONO_ARCH_AOT_SUPPORTED */
4876 /* Find next patch */
4878 for (pindex = start_index; pindex < patches->len; ++pindex) {
4879 patch_info = g_ptr_array_index (patches, pindex);
4880 if (patch_info->ip.i >= i)
4884 /* Try to emit multiple bytes at once */
4885 if (pindex < patches->len && patch_info->ip.i > i) {
4888 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4889 if (locs && locs [limit])
4893 emit_code_bytes (acfg, code + i, limit - i);
4894 i = limit - INST_LEN;
4896 emit_code_bytes (acfg, code + i, INST_LEN);
4907 * Return a modified version of S which only includes characters permissible in symbols.
4910 sanitize_symbol (MonoAotCompile *acfg, char *s)
4912 gboolean process = FALSE;
4921 for (i = 0; i < len; ++i)
4922 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4927 gs = g_string_sized_new (len);
4928 for (i = 0; i < len; ++i) {
4930 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4931 g_string_append_c (gs, c);
4932 } else if (c > 0x7f) {
4933 /* multi-byte utf8 */
4934 g_string_append_printf (gs, "_0x%x", c);
4937 while (c >> 6 == 0x2) {
4938 g_string_append_printf (gs, "%x", c);
4942 g_string_append_printf (gs, "_");
4945 g_string_append_c (gs, '_');
4949 res = mono_mempool_strdup (acfg->mempool, gs->str);
4950 g_string_free (gs, TRUE);
4955 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4957 char *name1, *name2, *cached;
4958 int i, j, len, count;
4959 MonoMethod *cached_method;
4961 name1 = mono_method_full_name (method, TRUE);
4964 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4965 if ((!prefix || !*prefix) && name1 [0] == 'L')
4969 len = strlen (name1);
4970 name2 = malloc (strlen (prefix) + len + 16);
4971 memcpy (name2, prefix, strlen (prefix));
4972 j = strlen (prefix);
4973 for (i = 0; i < len; ++i) {
4974 if (isalnum (name1 [i])) {
4975 name2 [j ++] = name1 [i];
4976 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4978 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4981 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4991 cached_method = g_hash_table_lookup (cache, name2);
4992 if (!(cached_method && cached_method != method))
4994 sprintf (name2 + j, "_%d", count);
4998 cached = g_strdup (name2);
4999 g_hash_table_insert (cache, cached, method);
5005 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5010 char *debug_sym = NULL;
5011 char *symbol = NULL;
5012 int func_alignment = AOT_FUNC_ALIGNMENT;
5015 method = cfg->orig_method;
5016 code = cfg->native_code;
5018 method_index = get_method_index (acfg, method);
5019 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5021 /* Make the labels local */
5022 emit_section_change (acfg, ".text", 0);
5023 emit_alignment_code (acfg, func_alignment);
5025 if (acfg->global_symbols && acfg->need_no_dead_strip)
5026 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5028 emit_label (acfg, cfg->asm_symbol);
5030 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5032 * Write a C style symbol for every method, this has two uses:
5033 * - it works on platforms where the dwarf debugging info is not
5035 * - it allows the setting of breakpoints of aot-ed methods.
5037 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5038 cfg->asm_debug_symbol = g_strdup (debug_sym);
5040 if (acfg->need_no_dead_strip)
5041 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5042 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5043 emit_label (acfg, debug_sym);
5046 export_name = g_hash_table_lookup (acfg->export_names, method);
5048 /* Emit a global symbol for the method */
5049 emit_global_inner (acfg, export_name, TRUE);
5050 emit_label (acfg, export_name);
5053 if (cfg->verbose_level > 0)
5054 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5056 acfg->stats.code_size += cfg->code_len;
5058 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5060 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
5064 if (acfg->aot_opts.write_symbols) {
5066 emit_symbol_size (acfg, debug_sym, ".");
5068 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5072 emit_label (acfg, symbol);
5079 * Encode PATCH_INFO into its disk representation.
5082 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5086 switch (patch_info->type) {
5087 case MONO_PATCH_INFO_NONE:
5089 case MONO_PATCH_INFO_IMAGE:
5090 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5092 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5093 case MONO_PATCH_INFO_JIT_TLS_ID:
5094 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5095 case MONO_PATCH_INFO_GC_NURSERY_START:
5097 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5098 encode_value (patch_info->data.index, p, &p);
5100 case MONO_PATCH_INFO_METHOD_REL:
5101 encode_value ((gint)patch_info->data.offset, p, &p);
5103 case MONO_PATCH_INFO_SWITCH: {
5104 gpointer *table = (gpointer *)patch_info->data.table->table;
5107 encode_value (patch_info->data.table->table_size, p, &p);
5108 for (k = 0; k < patch_info->data.table->table_size; k++)
5109 encode_value ((int)(gssize)table [k], p, &p);
5112 case MONO_PATCH_INFO_METHODCONST:
5113 case MONO_PATCH_INFO_METHOD:
5114 case MONO_PATCH_INFO_METHOD_JUMP:
5115 case MONO_PATCH_INFO_ICALL_ADDR:
5116 case MONO_PATCH_INFO_METHOD_RGCTX:
5117 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5118 encode_method_ref (acfg, patch_info->data.method, p, &p);
5120 case MONO_PATCH_INFO_INTERNAL_METHOD:
5121 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5122 guint32 len = strlen (patch_info->data.name);
5124 encode_value (len, p, &p);
5126 memcpy (p, patch_info->data.name, len);
5131 case MONO_PATCH_INFO_LDSTR: {
5132 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5133 guint32 token = patch_info->data.token->token;
5134 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5135 encode_value (image_index, p, &p);
5136 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5139 case MONO_PATCH_INFO_RVA:
5140 case MONO_PATCH_INFO_DECLSEC:
5141 case MONO_PATCH_INFO_LDTOKEN:
5142 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5143 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5144 encode_value (patch_info->data.token->token, p, &p);
5145 encode_value (patch_info->data.token->has_context, p, &p);
5146 if (patch_info->data.token->has_context)
5147 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5149 case MONO_PATCH_INFO_EXC_NAME: {
5150 MonoClass *ex_class;
5153 mono_class_from_name (mono_defaults.exception_class->image,
5154 "System", patch_info->data.target);
5155 g_assert (ex_class);
5156 encode_klass_ref (acfg, ex_class, p, &p);
5159 case MONO_PATCH_INFO_R4:
5160 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5162 case MONO_PATCH_INFO_R8:
5163 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5164 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5166 case MONO_PATCH_INFO_VTABLE:
5167 case MONO_PATCH_INFO_CLASS:
5168 case MONO_PATCH_INFO_IID:
5169 case MONO_PATCH_INFO_ADJUSTED_IID:
5170 case MONO_PATCH_INFO_CLASS_INIT:
5171 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5173 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5174 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5175 if (patch_info->data.del_tramp->method) {
5176 encode_value (1, p, &p);
5177 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5179 encode_value (0, p, &p);
5181 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5183 case MONO_PATCH_INFO_FIELD:
5184 case MONO_PATCH_INFO_SFLDA:
5185 encode_field_info (acfg, patch_info->data.field, p, &p);
5187 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5189 case MONO_PATCH_INFO_RGCTX_FETCH: {
5190 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5195 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5196 * reference the same method, so encode the method only once.
5198 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5200 buf2 = g_malloc (1024);
5203 encode_method_ref (acfg, entry->method, p2, &p2);
5204 g_assert (p2 - buf2 < 1024);
5206 offset = add_to_blob (acfg, buf2, p2 - buf2);
5209 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5214 encode_value (offset, p, &p);
5215 g_assert ((int)entry->info_type < 256);
5216 g_assert (entry->data->type < 256);
5217 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5218 encode_patch (acfg, entry->data, p, &p);
5221 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5222 case MONO_PATCH_INFO_MONITOR_ENTER:
5223 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5224 case MONO_PATCH_INFO_MONITOR_EXIT:
5225 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5227 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5228 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5229 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5231 case MONO_PATCH_INFO_SIGNATURE:
5232 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5234 case MONO_PATCH_INFO_TLS_OFFSET:
5235 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5237 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5238 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5239 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5241 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5242 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5245 encode_method_ref (acfg, info->method, p, &p);
5246 encode_value (info->num_entries, p, &p);
5247 for (i = 0; i < info->num_entries; ++i) {
5248 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5250 encode_value (template->info_type, p, &p);
5251 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5252 case MONO_PATCH_INFO_CLASS:
5253 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5255 case MONO_PATCH_INFO_FIELD:
5256 encode_field_info (acfg, template->data, p, &p);
5259 g_assert_not_reached ();
5265 case MONO_PATCH_INFO_LDSTR_LIT: {
5266 const char *s = patch_info->data.target;
5267 int len = strlen (s);
5269 encode_value (len, p, &p);
5270 memcpy (p, s, len + 1);
5275 g_warning ("unable to handle jump info %d", patch_info->type);
5276 g_assert_not_reached ();
5283 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5286 guint32 pindex, offset;
5287 MonoJumpInfo *patch_info;
5289 encode_value (n_patches, p, &p);
5291 for (pindex = 0; pindex < patches->len; ++pindex) {
5292 patch_info = g_ptr_array_index (patches, pindex);
5294 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5298 offset = get_got_offset (acfg, llvm, patch_info);
5299 encode_value (offset, p, &p);
5306 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5310 int pindex, buf_size, n_patches;
5312 MonoJumpInfo *patch_info;
5313 guint32 method_index;
5315 guint32 first_got_offset;
5317 method = cfg->orig_method;
5319 method_index = get_method_index (acfg, method);
5321 /* Sort relocations */
5322 patches = g_ptr_array_new ();
5323 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5324 g_ptr_array_add (patches, patch_info);
5325 g_ptr_array_sort (patches, compare_patches);
5327 first_got_offset = acfg->cfgs [method_index]->got_offset;
5329 /**********************/
5330 /* Encode method info */
5331 /**********************/
5333 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5334 p = buf = g_malloc (buf_size);
5336 if (mono_class_get_cctor (method->klass))
5337 encode_klass_ref (acfg, method->klass, p, &p);
5339 /* Not needed when loading the method */
5340 encode_value (0, p, &p);
5343 if (cfg->opt & MONO_OPT_SHARED) {
5344 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5345 for (l = cfg->ldstr_list; l; l = l->next) {
5346 encode_value ((long)l->data, p, &p);
5350 /* Used only in shared mode */
5351 g_assert (!cfg->ldstr_list);
5354 for (pindex = 0; pindex < patches->len; ++pindex) {
5355 patch_info = g_ptr_array_index (patches, pindex);
5357 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5358 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5359 patch_info->type = MONO_PATCH_INFO_NONE;
5364 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5365 /* Stored in a GOT slot initialized at module load time */
5366 patch_info->type = MONO_PATCH_INFO_NONE;
5370 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5371 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START) {
5372 /* Stored in a GOT slot initialized at module load time */
5373 patch_info->type = MONO_PATCH_INFO_NONE;
5377 if (is_plt_patch (patch_info)) {
5378 /* Calls are made through the PLT */
5379 patch_info->type = MONO_PATCH_INFO_NONE;
5387 g_assert (cfg->has_got_slots);
5389 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5391 acfg->stats.info_size += p - buf;
5393 g_assert (p - buf < buf_size);
5395 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5400 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5402 guint32 cache_index;
5405 /* Reuse the unwind module to canonize and store unwind info entries */
5406 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5408 /* Use +/- 1 to distinguish 0s from missing entries */
5409 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5417 * It would be easier to use assembler symbols, but the caller needs an
5420 offset = acfg->unwind_info_offset;
5421 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5422 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5425 encode_value (encoded_len, p, &p);
5427 acfg->unwind_info_offset += encoded_len + (p - buf);
5433 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5436 guint32 debug_info_size, seq_points_size;
5438 MonoMethodHeader *header;
5439 guint8 *p, *buf, *debug_info;
5440 MonoJitInfo *jinfo = cfg->jit_info;
5442 gboolean use_unwind_ops = FALSE;
5443 MonoSeqPointInfo *seq_points;
5445 code = cfg->native_code;
5446 header = cfg->header;
5448 if (!acfg->aot_opts.nodebug) {
5449 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5452 debug_info_size = 0;
5455 seq_points = cfg->seq_point_info;
5456 seq_points_size = (store_seq_points)? seq_point_info_get_write_size (seq_points) : 0;
5458 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5460 p = buf = g_malloc (buf_size);
5462 use_unwind_ops = cfg->unwind_ops != NULL;
5464 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points_size ? 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);
5466 encode_value (flags, p, &p);
5468 if (use_unwind_ops) {
5469 guint32 encoded_len;
5471 guint32 unwind_desc;
5473 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5475 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5476 encode_value (unwind_desc, p, &p);
5478 encode_value (jinfo->unwind_info, p, &p);
5481 /*Encode the number of holes before the number of clauses to make decoding easier*/
5482 if (jinfo->has_try_block_holes) {
5483 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5484 encode_value (table->num_holes, p, &p);
5487 if (jinfo->has_arch_eh_info) {
5489 * In AOT mode, the code length is calculated from the address of the previous method,
5490 * which could include alignment padding, so calculating the start of the epilog as
5491 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5493 encode_value (jinfo->code_size, p, &p);
5496 /* Exception table */
5497 if (cfg->compile_llvm) {
5499 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5500 * since the information is only available to llc. Instead, we let llc save the data
5501 * into the LSDA, and read it from there at runtime.
5503 /* The assembly might be CIL stripped so emit the data ourselves */
5504 if (header->num_clauses)
5505 encode_value (header->num_clauses, p, &p);
5507 for (k = 0; k < header->num_clauses; ++k) {
5508 MonoExceptionClause *clause;
5510 clause = &header->clauses [k];
5512 encode_value (clause->flags, p, &p);
5513 if (clause->data.catch_class) {
5514 encode_value (1, p, &p);
5515 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5517 encode_value (0, p, &p);
5520 /* Emit a list of nesting clauses */
5521 for (i = 0; i < header->num_clauses; ++i) {
5523 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5525 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5527 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5528 encode_value (i, p, &p);
5530 encode_value (-1, p, &p);
5533 if (jinfo->num_clauses)
5534 encode_value (jinfo->num_clauses, p, &p);
5536 for (k = 0; k < jinfo->num_clauses; ++k) {
5537 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5539 encode_value (ei->flags, p, &p);
5540 encode_value (ei->exvar_offset, p, &p);
5542 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5543 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5545 if (ei->data.catch_class) {
5549 buf2 = g_malloc (4096);
5551 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5553 g_assert (len < 4096);
5554 encode_value (len, p, &p);
5555 memcpy (p, buf2, len);
5559 encode_value (0, p, &p);
5563 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5564 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5565 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5569 if (jinfo->has_try_block_holes) {
5570 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5571 for (i = 0; i < table->num_holes; ++i) {
5572 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5573 encode_value (hole->clause, p, &p);
5574 encode_value (hole->length, p, &p);
5575 encode_value (hole->offset, p, &p);
5579 if (jinfo->has_arch_eh_info) {
5580 MonoArchEHJitInfo *eh_info;
5582 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5583 encode_value (eh_info->stack_size, p, &p);
5584 encode_value (eh_info->epilog_size, p, &p);
5587 if (jinfo->has_generic_jit_info) {
5588 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5589 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5593 encode_value (gi->nlocs, p, &p);
5595 for (i = 0; i < gi->nlocs; ++i) {
5596 MonoDwarfLocListEntry *entry = &gi->locations [i];
5598 encode_value (entry->is_reg ? 1 : 0, p, &p);
5599 encode_value (entry->reg, p, &p);
5601 encode_value (entry->offset, p, &p);
5603 g_assert (entry->from == 0);
5605 encode_value (entry->from, p, &p);
5606 encode_value (entry->to, p, &p);
5609 if (!cfg->compile_llvm) {
5610 encode_value (gi->has_this ? 1 : 0, p, &p);
5611 encode_value (gi->this_reg, p, &p);
5612 encode_value (gi->this_offset, p, &p);
5617 * Need to encode jinfo->method too, since it is not equal to 'method'
5618 * when using generic sharing.
5620 buf2 = g_malloc (4096);
5622 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5624 g_assert (len < 4096);
5625 encode_value (len, p, &p);
5626 memcpy (p, buf2, len);
5630 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5631 MonoMethodInflated *inflated;
5632 MonoGenericContext *context;
5633 MonoGenericInst *inst;
5635 g_assert (jinfo->d.method->is_inflated);
5636 inflated = (MonoMethodInflated*)jinfo->d.method;
5637 context = &inflated->context;
5639 encode_value (1, p, &p);
5640 if (context->class_inst) {
5641 inst = context->class_inst;
5643 encode_value (inst->type_argc, p, &p);
5644 for (i = 0; i < inst->type_argc; ++i)
5645 encode_value (gsctx->var_is_vt [i], p, &p);
5647 encode_value (0, p, &p);
5649 if (context->method_inst) {
5650 inst = context->method_inst;
5652 encode_value (inst->type_argc, p, &p);
5653 for (i = 0; i < inst->type_argc; ++i)
5654 encode_value (gsctx->mvar_is_vt [i], p, &p);
5656 encode_value (0, p, &p);
5659 encode_value (0, p, &p);
5663 if (seq_points_size)
5664 p += seq_point_info_write (seq_points, p);
5666 g_assert (debug_info_size < buf_size);
5668 encode_value (debug_info_size, p, &p);
5669 if (debug_info_size) {
5670 memcpy (p, debug_info, debug_info_size);
5671 p += debug_info_size;
5672 g_free (debug_info);
5677 encode_value (cfg->gc_map_size, p, &p);
5678 /* The GC map requires 4 bytes of alignment */
5679 while ((gsize)p % 4)
5681 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5682 p += cfg->gc_map_size;
5685 acfg->stats.ex_info_size += p - buf;
5687 g_assert (p - buf < buf_size);
5690 /* The GC Map requires 4 byte alignment */
5691 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5696 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5699 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5701 int i, buf_size, res;
5702 gboolean no_special_static, cant_encode;
5703 gpointer iter = NULL;
5706 mono_error_cleanup (&error);
5710 p = buf = g_malloc (buf_size);
5712 /* Mark as unusable */
5713 encode_value (-1, p, &p);
5715 res = add_to_blob (acfg, buf, p - buf);
5721 buf_size = 10240 + (klass->vtable_size * 16);
5722 p = buf = g_malloc (buf_size);
5726 mono_class_init (klass);
5728 mono_class_get_nested_types (klass, &iter);
5729 g_assert (klass->nested_classes_inited);
5731 mono_class_setup_vtable (klass);
5734 * Emit all the information which is required for creating vtables so
5735 * the runtime does not need to create the MonoMethod structures which
5736 * take up a lot of space.
5739 no_special_static = !mono_class_has_special_static_fields (klass);
5741 /* Check whenever we have enough info to encode the vtable */
5742 cant_encode = FALSE;
5743 for (i = 0; i < klass->vtable_size; ++i) {
5744 MonoMethod *cm = klass->vtable [i];
5746 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5750 mono_class_has_finalizer (klass);
5752 if (klass->generic_container || cant_encode) {
5753 encode_value (-1, p, &p);
5755 encode_value (klass->vtable_size, p, &p);
5756 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);
5757 if (klass->has_cctor)
5758 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5759 if (klass->has_finalize)
5760 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5762 encode_value (klass->instance_size, p, &p);
5763 encode_value (mono_class_data_size (klass), p, &p);
5764 encode_value (klass->packing_size, p, &p);
5765 encode_value (klass->min_align, p, &p);
5767 for (i = 0; i < klass->vtable_size; ++i) {
5768 MonoMethod *cm = klass->vtable [i];
5771 encode_method_ref (acfg, cm, p, &p);
5773 encode_value (0, p, &p);
5777 acfg->stats.class_info_size += p - buf;
5779 g_assert (p - buf < buf_size);
5780 res = add_to_blob (acfg, buf, p - buf);
5787 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5789 char *debug_sym = NULL;
5793 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5794 /* Need to add a prefix to create unique symbols */
5795 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5797 prefix = g_strdup ("plt_");
5801 case MONO_PATCH_INFO_METHOD:
5802 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5804 case MONO_PATCH_INFO_INTERNAL_METHOD:
5805 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5807 case MONO_PATCH_INFO_CLASS_INIT:
5808 s = mono_type_get_name (&ji->data.klass->byval_arg);
5809 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5812 case MONO_PATCH_INFO_RGCTX_FETCH:
5813 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5815 case MONO_PATCH_INFO_ICALL_ADDR: {
5816 char *s = get_debug_sym (ji->data.method, "", cache);
5818 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5822 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5823 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5825 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5826 debug_sym = g_strdup_printf ("%s_generic_class_init", prefix);
5834 return sanitize_symbol (acfg, debug_sym);
5838 * Calls made from AOTed code are routed through a table of jumps similar to the
5839 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5840 * control to the AOT runtime through a trampoline.
5843 emit_plt (MonoAotCompile *acfg)
5849 sprintf (symbol, "plt");
5851 emit_section_change (acfg, ".text", 0);
5852 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5853 emit_label (acfg, symbol);
5854 emit_label (acfg, acfg->plt_symbol);
5856 for (i = 0; i < acfg->plt_offset; ++i) {
5857 char *debug_sym = NULL;
5858 MonoPltEntry *plt_entry = NULL;
5862 * The first plt entry is unused.
5866 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5868 debug_sym = plt_entry->debug_sym;
5870 if (acfg->thumb_mixed && !plt_entry->jit_used)
5871 /* Emit only a thumb version */
5874 /* Skip plt entries not actually called */
5875 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5878 if (acfg->llvm && !acfg->thumb_mixed) {
5879 emit_label (acfg, plt_entry->llvm_symbol);
5881 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5882 #if defined(TARGET_MACH)
5883 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5889 if (acfg->need_no_dead_strip) {
5890 emit_unset_mode (acfg);
5891 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5893 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5894 emit_label (acfg, debug_sym);
5897 emit_label (acfg, plt_entry->symbol);
5899 arch_emit_plt_entry (acfg, i);
5902 emit_symbol_size (acfg, debug_sym, ".");
5905 if (acfg->thumb_mixed) {
5906 /* Make sure the ARM symbols don't alias the thumb ones */
5907 emit_zero_bytes (acfg, 16);
5910 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5913 for (i = 0; i < acfg->plt_offset; ++i) {
5914 char *debug_sym = NULL;
5915 MonoPltEntry *plt_entry = NULL;
5920 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5922 /* Skip plt entries not actually called by LLVM code */
5923 if (!plt_entry->llvm_used)
5926 if (acfg->aot_opts.write_symbols) {
5927 if (plt_entry->debug_sym)
5928 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5932 #if defined(TARGET_MACH)
5933 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5934 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5936 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5937 emit_label (acfg, debug_sym);
5939 fprintf (acfg->fp, "\n.thumb_func\n");
5941 emit_label (acfg, plt_entry->llvm_symbol);
5944 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5946 arch_emit_llvm_plt_entry (acfg, i);
5949 emit_symbol_size (acfg, debug_sym, ".");
5955 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5957 sprintf (symbol, "plt_end");
5958 emit_label (acfg, symbol);
5962 * emit_trampoline_full:
5964 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5965 * create_jit_info_for_trampoline ().
5967 static G_GNUC_UNUSED void
5968 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5970 char start_symbol [256];
5971 char end_symbol [256];
5973 guint32 buf_size, info_offset;
5974 MonoJumpInfo *patch_info;
5987 code_size = info->code_size;
5989 unwind_ops = info->unwind_ops;
5991 #ifdef __native_client_codegen__
5992 mono_nacl_fix_patches (code, ji);
5997 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5999 emit_section_change (acfg, ".text", 0);
6000 emit_global (acfg, start_symbol, TRUE);
6001 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6002 emit_label (acfg, start_symbol);
6004 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6005 emit_label (acfg, symbol);
6008 * The code should access everything through the GOT, so we pass
6011 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6013 emit_symbol_size (acfg, start_symbol, ".");
6016 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6017 emit_label (acfg, end_symbol);
6022 /* Sort relocations */
6023 patches = g_ptr_array_new ();
6024 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6025 if (patch_info->type != MONO_PATCH_INFO_NONE)
6026 g_ptr_array_add (patches, patch_info);
6027 g_ptr_array_sort (patches, compare_patches);
6029 buf_size = patches->len * 128 + 128;
6030 buf = g_malloc (buf_size);
6033 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6034 g_assert (p - buf < buf_size);
6036 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6038 info_offset = add_to_blob (acfg, buf, p - buf);
6040 emit_section_change (acfg, RODATA_SECT, 0);
6041 emit_global (acfg, symbol, FALSE);
6042 emit_label (acfg, symbol);
6044 emit_int32 (acfg, info_offset);
6048 guint32 encoded_len;
6052 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6054 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6055 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6058 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6059 emit_int32 (acfg, uw_offset);
6062 /* Emit debug info */
6066 sprintf (symbol, "%s", name);
6067 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6070 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6074 static G_GNUC_UNUSED void
6075 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6077 emit_trampoline_full (acfg, got_offset, info, FALSE);
6081 emit_trampolines (MonoAotCompile *acfg)
6084 char end_symbol [256];
6085 int i, tramp_got_offset;
6086 MonoAotTrampoline ntype;
6087 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6091 if (!acfg->aot_opts.full_aot)
6094 g_assert (acfg->image->assembly);
6096 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6097 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6098 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6099 MonoTrampInfo *info;
6102 * Emit the generic trampolines.
6104 * We could save some code by treating the generic trampolines as a wrapper
6105 * method, but that approach has its own complexities, so we choose the simpler
6108 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6109 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6110 #ifdef DISABLE_REMOTING
6111 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6114 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6115 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6118 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6119 emit_trampoline (acfg, acfg->got_offset, info);
6122 mono_arch_get_nullified_class_init_trampoline (&info);
6123 emit_trampoline (acfg, acfg->got_offset, info);
6124 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6125 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6126 emit_trampoline (acfg, acfg->got_offset, info);
6127 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6128 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6129 emit_trampoline (acfg, acfg->got_offset, info);
6131 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6132 emit_trampoline (acfg, acfg->got_offset, info);
6135 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6136 emit_trampoline (acfg, acfg->got_offset, info);
6138 /* Emit the exception related code pieces */
6139 mono_arch_get_restore_context (&info, TRUE);
6140 emit_trampoline (acfg, acfg->got_offset, info);
6141 mono_arch_get_call_filter (&info, TRUE);
6142 emit_trampoline (acfg, acfg->got_offset, info);
6143 mono_arch_get_throw_exception (&info, TRUE);
6144 emit_trampoline (acfg, acfg->got_offset, info);
6145 mono_arch_get_rethrow_exception (&info, TRUE);
6146 emit_trampoline (acfg, acfg->got_offset, info);
6147 mono_arch_get_throw_corlib_exception (&info, TRUE);
6148 emit_trampoline (acfg, acfg->got_offset, info);
6150 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6151 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6152 emit_trampoline (acfg, acfg->got_offset, info);
6153 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6154 emit_trampoline (acfg, acfg->got_offset, info);
6157 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6158 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6160 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6162 /* Create a separate out trampoline for more information in stack traces */
6163 info->name = g_strdup ("gsharedvt_out_trampoline");
6164 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6168 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6170 GSList *l = mono_arch_get_trampolines (TRUE);
6173 MonoTrampInfo *info = l->data;
6175 emit_trampoline (acfg, acfg->got_offset, info);
6181 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6184 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6185 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6186 emit_trampoline (acfg, acfg->got_offset, info);
6188 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6189 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6190 emit_trampoline (acfg, acfg->got_offset, info);
6193 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6194 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6195 emit_trampoline (acfg, acfg->got_offset, info);
6201 /* delegate_invoke_impl trampolines */
6202 l = mono_arch_get_delegate_invoke_impls ();
6204 MonoTrampInfo *info = l->data;
6206 emit_trampoline (acfg, acfg->got_offset, info);
6211 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6213 /* Emit trampolines which are numerous */
6216 * These include the following:
6217 * - specific trampolines
6218 * - static rgctx invoke trampolines
6220 * These trampolines have the same code, they are parameterized by GOT
6222 * They are defined in this file, in the arch_... routines instead of
6223 * in tramp-<ARCH>.c, since it is easier to do it this way.
6227 * When running in aot-only mode, we can't create specific trampolines at
6228 * runtime, so we create a few, and save them in the AOT file.
6229 * Normal trampolines embed their argument as a literal inside the
6230 * trampoline code, we can't do that here, so instead we embed an offset
6231 * which needs to be added to the trampoline address to get the address of
6232 * the GOT slot which contains the argument value.
6233 * The generated trampolines jump to the generic trampolines using another
6234 * GOT slot, which will be setup by the AOT loader to point to the
6235 * generic trampoline code of the given type.
6239 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6243 emit_section_change (acfg, ".text", 0);
6245 tramp_got_offset = acfg->got_offset;
6247 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6249 case MONO_AOT_TRAMP_SPECIFIC:
6250 sprintf (symbol, "specific_trampolines");
6252 case MONO_AOT_TRAMP_STATIC_RGCTX:
6253 sprintf (symbol, "static_rgctx_trampolines");
6255 case MONO_AOT_TRAMP_IMT_THUNK:
6256 sprintf (symbol, "imt_thunks");
6258 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6259 sprintf (symbol, "gsharedvt_arg_trampolines");
6262 g_assert_not_reached ();
6265 sprintf (end_symbol, "%s_e", symbol);
6267 if (acfg->aot_opts.write_symbols)
6268 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6270 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6271 emit_label (acfg, symbol);
6273 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6275 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6279 case MONO_AOT_TRAMP_SPECIFIC:
6280 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6281 tramp_got_offset += 2;
6283 case MONO_AOT_TRAMP_STATIC_RGCTX:
6284 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6285 tramp_got_offset += 2;
6287 case MONO_AOT_TRAMP_IMT_THUNK:
6288 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6289 tramp_got_offset += 1;
6291 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6292 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6293 tramp_got_offset += 2;
6296 g_assert_not_reached ();
6298 #ifdef __native_client_codegen__
6299 /* align to avoid 32-byte boundary crossings */
6300 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6303 if (!acfg->trampoline_size [ntype]) {
6304 g_assert (tramp_size);
6305 acfg->trampoline_size [ntype] = tramp_size;
6309 emit_label (acfg, end_symbol);
6310 emit_int32 (acfg, 0);
6313 arch_emit_specific_trampoline_pages (acfg);
6315 /* Reserve some entries at the end of the GOT for our use */
6316 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6319 acfg->got_offset += acfg->num_trampoline_got_entries;
6323 str_begins_with (const char *str1, const char *str2)
6325 int len = strlen (str2);
6326 return strncmp (str1, str2, len) == 0;
6330 mono_aot_readonly_field_override (MonoClassField *field)
6333 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6334 char *p = rdv->name;
6336 len = strlen (field->parent->name_space);
6337 if (strncmp (p, field->parent->name_space, len))
6342 len = strlen (field->parent->name);
6343 if (strncmp (p, field->parent->name, len))
6348 if (strcmp (p, field->name))
6350 switch (rdv->type) {
6352 return &rdv->value.i1;
6354 return &rdv->value.i2;
6356 return &rdv->value.i4;
6365 add_readonly_value (MonoAotOptions *opts, const char *val)
6370 /* the format of val is:
6371 * namespace.typename.fieldname=type/value
6372 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6374 fval = strrchr (val, '/');
6376 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6379 tval = strrchr (val, '=');
6381 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6384 rdv = g_new0 (ReadOnlyValue, 1);
6385 rdv->name = g_malloc0 (tval - val + 1);
6386 memcpy (rdv->name, val, tval - val);
6389 if (strncmp (tval, "i1", 2) == 0) {
6390 rdv->value.i1 = atoi (fval);
6391 rdv->type = MONO_TYPE_I1;
6392 } else if (strncmp (tval, "i2", 2) == 0) {
6393 rdv->value.i2 = atoi (fval);
6394 rdv->type = MONO_TYPE_I2;
6395 } else if (strncmp (tval, "i4", 2) == 0) {
6396 rdv->value.i4 = atoi (fval);
6397 rdv->type = MONO_TYPE_I4;
6399 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6402 rdv->next = readonly_values;
6403 readonly_values = rdv;
6407 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6409 gchar **args, **ptr;
6411 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6412 for (ptr = args; ptr && *ptr; ptr ++) {
6413 const char *arg = *ptr;
6415 if (str_begins_with (arg, "outfile=")) {
6416 opts->outfile = g_strdup (arg + strlen ("outfile="));
6417 } else if (str_begins_with (arg, "llvm-outfile=")) {
6418 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6419 } else if (str_begins_with (arg, "save-temps")) {
6420 opts->save_temps = TRUE;
6421 } else if (str_begins_with (arg, "keep-temps")) {
6422 opts->save_temps = TRUE;
6423 } else if (str_begins_with (arg, "write-symbols")) {
6424 opts->write_symbols = TRUE;
6425 } else if (str_begins_with (arg, "no-write-symbols")) {
6426 opts->write_symbols = FALSE;
6427 } else if (str_begins_with (arg, "metadata-only")) {
6428 opts->metadata_only = TRUE;
6429 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6430 opts->bind_to_runtime_version = TRUE;
6431 } else if (str_begins_with (arg, "full")) {
6432 opts->full_aot = TRUE;
6433 } else if (str_begins_with (arg, "threads=")) {
6434 opts->nthreads = atoi (arg + strlen ("threads="));
6435 } else if (str_begins_with (arg, "static")) {
6436 opts->static_link = TRUE;
6437 opts->no_dlsym = TRUE;
6438 } else if (str_begins_with (arg, "asmonly")) {
6439 opts->asm_only = TRUE;
6440 } else if (str_begins_with (arg, "asmwriter")) {
6441 opts->asm_writer = TRUE;
6442 } else if (str_begins_with (arg, "nodebug")) {
6443 opts->nodebug = TRUE;
6444 } else if (str_begins_with (arg, "dwarfdebug")) {
6445 opts->dwarf_debug = TRUE;
6446 } else if (str_begins_with (arg, "nopagetrampolines")) {
6447 opts->use_trampolines_page = FALSE;
6448 } else if (str_begins_with (arg, "ntrampolines=")) {
6449 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6450 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6451 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6452 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6453 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6454 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6455 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6456 } else if (str_begins_with (arg, "autoreg")) {
6457 opts->autoreg = TRUE;
6458 } else if (str_begins_with (arg, "tool-prefix=")) {
6459 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6460 } else if (str_begins_with (arg, "ld-flags=")) {
6461 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6462 } else if (str_begins_with (arg, "soft-debug")) {
6463 opts->soft_debug = TRUE;
6464 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6465 opts->gen_seq_points_file = TRUE;
6466 } else if (str_begins_with (arg, "direct-pinvoke")) {
6467 opts->direct_pinvoke = TRUE;
6468 } else if (str_begins_with (arg, "direct-icalls")) {
6469 opts->direct_icalls = TRUE;
6470 } else if (str_begins_with (arg, "no-direct-calls")) {
6471 opts->no_direct_calls = TRUE;
6472 } else if (str_begins_with (arg, "print-skipped")) {
6473 opts->print_skipped_methods = TRUE;
6474 } else if (str_begins_with (arg, "stats")) {
6476 } else if (str_begins_with (arg, "no-instances")) {
6477 opts->no_instances = TRUE;
6478 } else if (str_begins_with (arg, "log-generics")) {
6479 opts->log_generics = TRUE;
6480 } else if (str_begins_with (arg, "log-instances=")) {
6481 opts->log_instances = TRUE;
6482 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6483 } else if (str_begins_with (arg, "log-instances")) {
6484 opts->log_instances = TRUE;
6485 } else if (str_begins_with (arg, "internal-logfile=")) {
6486 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6487 } else if (str_begins_with (arg, "mtriple=")) {
6488 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6489 } else if (str_begins_with (arg, "llvm-path=")) {
6490 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6491 if (!g_str_has_suffix (opts->llvm_path, G_DIR_SEPARATOR_S)) {
6492 gchar *old = opts->llvm_path;
6493 opts->llvm_path = g_strconcat (opts->llvm_path, G_DIR_SEPARATOR_S, NULL);
6496 } else if (!strcmp (arg, "llvm")) {
6498 } else if (str_begins_with (arg, "readonly-value=")) {
6499 add_readonly_value (opts, arg + strlen ("readonly-value="));
6500 } else if (str_begins_with (arg, "info")) {
6501 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6503 } else if (str_begins_with (arg, "gc-maps")) {
6504 mini_gc_enable_gc_maps_for_aot ();
6505 } else if (str_begins_with (arg, "dump")) {
6506 opts->dump_json = TRUE;
6507 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6508 printf ("Supported options for --aot:\n");
6509 printf (" outfile=\n");
6510 printf (" llvm-outfile=\n");
6511 printf (" save-temps\n");
6512 printf (" keep-temps\n");
6513 printf (" write-symbols\n");
6514 printf (" metadata-only\n");
6515 printf (" bind-to-runtime-version\n");
6517 printf (" threads=\n");
6518 printf (" static\n");
6519 printf (" asmonly\n");
6520 printf (" asmwriter\n");
6521 printf (" nodebug\n");
6522 printf (" dwarfdebug\n");
6523 printf (" ntrampolines=\n");
6524 printf (" nrgctx-trampolines=\n");
6525 printf (" nimt-trampolines=\n");
6526 printf (" ngsharedvt-trampolines=\n");
6527 printf (" autoreg\n");
6528 printf (" tool-prefix=\n");
6529 printf (" readonly-value=\n");
6530 printf (" soft-debug\n");
6531 printf (" gen-seq-points-file\n");
6532 printf (" gc-maps\n");
6533 printf (" print-skipped\n");
6534 printf (" no-instances\n");
6535 printf (" stats\n");
6538 printf (" help/?\n");
6541 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6546 if (opts->use_trampolines_page) {
6547 opts->ntrampolines = 0;
6548 opts->nrgctx_trampolines = 0;
6549 opts->nimt_trampolines = 0;
6550 opts->ngsharedvt_arg_trampolines = 0;
6556 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6558 MonoMethod *method = (MonoMethod*)key;
6559 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6560 MonoAotCompile *acfg = user_data;
6561 MonoJumpInfoToken *new_ji;
6563 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6564 new_ji->image = ji->image;
6565 new_ji->token = ji->token;
6566 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6570 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6572 if (klass->type_token)
6574 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6577 return can_encode_class (acfg, klass->element_class);
6582 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6584 if (method->wrapper_type) {
6585 switch (method->wrapper_type) {
6586 case MONO_WRAPPER_NONE:
6587 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6588 case MONO_WRAPPER_XDOMAIN_INVOKE:
6589 case MONO_WRAPPER_STFLD:
6590 case MONO_WRAPPER_LDFLD:
6591 case MONO_WRAPPER_LDFLDA:
6592 case MONO_WRAPPER_LDFLD_REMOTE:
6593 case MONO_WRAPPER_STFLD_REMOTE:
6594 case MONO_WRAPPER_STELEMREF:
6595 case MONO_WRAPPER_ISINST:
6596 case MONO_WRAPPER_PROXY_ISINST:
6597 case MONO_WRAPPER_ALLOC:
6598 case MONO_WRAPPER_REMOTING_INVOKE:
6599 case MONO_WRAPPER_UNKNOWN:
6600 case MONO_WRAPPER_WRITE_BARRIER:
6601 case MONO_WRAPPER_DELEGATE_INVOKE:
6602 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6603 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6604 case MONO_WRAPPER_SYNCHRONIZED:
6606 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6607 case MONO_WRAPPER_CASTCLASS: {
6608 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6617 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6621 if (!method->token) {
6622 /* The method is part of a constructed type like Int[,].Set (). */
6623 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6624 if (method->klass->rank)
6634 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6636 switch (patch_info->type) {
6637 case MONO_PATCH_INFO_METHOD:
6638 case MONO_PATCH_INFO_METHODCONST:
6639 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6640 MonoMethod *method = patch_info->data.method;
6642 return can_encode_method (acfg, method);
6644 case MONO_PATCH_INFO_VTABLE:
6645 case MONO_PATCH_INFO_CLASS_INIT:
6646 case MONO_PATCH_INFO_CLASS:
6647 case MONO_PATCH_INFO_IID:
6648 case MONO_PATCH_INFO_ADJUSTED_IID:
6649 if (!can_encode_class (acfg, patch_info->data.klass)) {
6650 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6654 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6655 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6656 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6661 case MONO_PATCH_INFO_RGCTX_FETCH: {
6662 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6664 if (!can_encode_method (acfg, entry->method))
6666 if (!can_encode_patch (acfg, entry->data))
6680 * AOT compile a given method.
6681 * This function might be called by multiple threads, so it must be thread-safe.
6684 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6687 MonoJumpInfo *patch_info;
6690 MonoMethod *wrapped;
6693 if (acfg->aot_opts.metadata_only)
6696 mono_acfg_lock (acfg);
6697 index = get_method_index (acfg, method);
6698 mono_acfg_unlock (acfg);
6700 /* fixme: maybe we can also precompile wrapper methods */
6701 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6702 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6703 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6704 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6708 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6711 wrapped = mono_marshal_method_from_wrapper (method);
6712 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6713 // FIXME: The wrapper should be generic too, but it is not
6716 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6719 InterlockedIncrement (&acfg->stats.mcount);
6722 if (method->is_generic || method->klass->generic_container) {
6723 InterlockedIncrement (&acfg->stats.genericcount);
6728 //acfg->aot_opts.print_skipped_methods = TRUE;
6731 * Since these methods are the only ones which are compiled with
6732 * AOT support, and they are not used by runtime startup/shutdown code,
6733 * the runtime will not see AOT methods during AOT compilation,so it
6734 * does not need to support them by creating a fake GOT etc.
6736 flags = JIT_FLAG_AOT;
6737 if (acfg->aot_opts.full_aot)
6738 flags |= JIT_FLAG_FULL_AOT;
6740 flags |= JIT_FLAG_LLVM;
6741 if (acfg->aot_opts.no_direct_calls)
6742 flags |= JIT_FLAG_NO_DIRECT_ICALLS;
6743 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6744 mono_loader_clear_error ();
6746 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6747 if (acfg->aot_opts.print_skipped_methods)
6748 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6749 InterlockedIncrement (&acfg->stats.genericcount);
6752 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6753 if (acfg->aot_opts.print_skipped_methods)
6754 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6755 /* Let the exception happen at runtime */
6759 if (cfg->disable_aot) {
6760 if (acfg->aot_opts.print_skipped_methods)
6761 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6762 InterlockedIncrement (&acfg->stats.ocount);
6763 mono_destroy_compile (cfg);
6766 cfg->method_index = index;
6768 /* Nullify patches which need no aot processing */
6769 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6770 switch (patch_info->type) {
6771 case MONO_PATCH_INFO_LABEL:
6772 case MONO_PATCH_INFO_BB:
6773 patch_info->type = MONO_PATCH_INFO_NONE;
6780 /* Collect method->token associations from the cfg */
6781 mono_acfg_lock (acfg);
6782 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6783 mono_acfg_unlock (acfg);
6784 g_hash_table_destroy (cfg->token_info_hash);
6785 cfg->token_info_hash = NULL;
6788 * Check for absolute addresses.
6791 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6792 switch (patch_info->type) {
6793 case MONO_PATCH_INFO_ABS:
6794 /* unable to handle this */
6803 if (acfg->aot_opts.print_skipped_methods)
6804 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6805 InterlockedIncrement (&acfg->stats.abscount);
6806 mono_destroy_compile (cfg);
6810 /* Lock for the rest of the code */
6811 mono_acfg_lock (acfg);
6814 * Check for methods/klasses we can't encode.
6817 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6818 if (!can_encode_patch (acfg, patch_info))
6823 if (acfg->aot_opts.print_skipped_methods)
6824 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6825 acfg->stats.ocount++;
6826 mono_destroy_compile (cfg);
6827 mono_acfg_unlock (acfg);
6831 if (method->is_inflated && acfg->aot_opts.log_instances) {
6832 if (acfg->instances_logfile)
6833 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6835 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6838 /* Adds generic instances referenced by this method */
6840 * The depth is used to avoid infinite loops when generic virtual recursion is
6843 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6844 if (!acfg->aot_opts.no_instances && depth < 32) {
6845 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6846 switch (patch_info->type) {
6847 case MONO_PATCH_INFO_METHOD: {
6848 MonoMethod *m = patch_info->data.method;
6849 if (m->is_inflated) {
6850 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6851 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6852 !method_has_type_vars (m)) {
6853 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6854 if (acfg->aot_opts.full_aot)
6855 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6857 add_extra_method_with_depth (acfg, m, depth + 1);
6858 add_types_from_method_header (acfg, m);
6861 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6863 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
6864 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
6866 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
6867 add_extra_method_with_depth (acfg, m, depth + 1);
6871 case MONO_PATCH_INFO_VTABLE: {
6872 MonoClass *klass = patch_info->data.klass;
6874 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6875 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6878 case MONO_PATCH_INFO_SFLDA: {
6879 MonoClass *klass = patch_info->data.field->parent;
6881 /* The .cctor needs to run at runtime. */
6882 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6883 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6892 /* Determine whenever the method has GOT slots */
6893 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6894 switch (patch_info->type) {
6895 case MONO_PATCH_INFO_GOT_OFFSET:
6896 case MONO_PATCH_INFO_NONE:
6897 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6898 case MONO_PATCH_INFO_GC_NURSERY_START:
6900 case MONO_PATCH_INFO_IMAGE:
6901 /* The assembly is stored in GOT slot 0 */
6902 if (patch_info->data.image != acfg->image)
6903 cfg->has_got_slots = TRUE;
6906 if (!is_plt_patch (patch_info))
6907 cfg->has_got_slots = TRUE;
6912 if (!cfg->has_got_slots)
6913 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6916 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6918 /* Make a copy of the patch info which is in the mempool */
6920 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6922 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6923 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6926 patches = new_patch_info;
6928 patches_end->next = new_patch_info;
6929 patches_end = new_patch_info;
6931 cfg->patch_info = patches;
6933 /* Make a copy of the unwind info */
6935 GSList *l, *unwind_ops;
6939 for (l = cfg->unwind_ops; l; l = l->next) {
6940 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6941 memcpy (op, l->data, sizeof (MonoUnwindOp));
6942 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6944 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6946 /* Make a copy of the argument/local info */
6948 MonoInst **args, **locals;
6949 MonoMethodSignature *sig;
6950 MonoMethodHeader *header;
6953 sig = mono_method_signature (method);
6954 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6955 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6956 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6957 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6961 header = mono_method_get_header (method);
6962 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6963 for (i = 0; i < header->num_locals; ++i) {
6964 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6965 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6967 cfg->locals = locals;
6970 /* Free some fields used by cfg to conserve memory */
6971 mono_mempool_destroy (cfg->mempool);
6972 cfg->mempool = NULL;
6973 g_free (cfg->varinfo);
6974 cfg->varinfo = NULL;
6978 mono_regstate_free (cfg->rs);
6982 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6984 while (index >= acfg->cfgs_size) {
6985 MonoCompile **new_cfgs;
6988 new_size = acfg->cfgs_size * 2;
6989 new_cfgs = g_new0 (MonoCompile*, new_size);
6990 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6991 g_free (acfg->cfgs);
6992 acfg->cfgs = new_cfgs;
6993 acfg->cfgs_size = new_size;
6995 acfg->cfgs [index] = cfg;
6997 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7000 if (cfg->orig_method->wrapper_type)
7001 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7004 mono_acfg_unlock (acfg);
7006 InterlockedIncrement (&acfg->stats.ccount);
7010 compile_thread_main (gpointer *user_data)
7012 MonoDomain *domain = user_data [0];
7013 MonoAotCompile *acfg = user_data [1];
7014 GPtrArray *methods = user_data [2];
7017 mono_thread_attach (domain);
7019 for (i = 0; i < methods->len; ++i)
7020 compile_method (acfg, g_ptr_array_index (methods, i));
7024 load_profile_files (MonoAotCompile *acfg)
7028 int file_index, res, method_index, i;
7031 GList *unordered, *l;
7036 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7038 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7043 infile = fopen (tmp, "r");
7046 printf ("Using profile data file '%s'\n", tmp);
7051 res = fscanf (infile, "%32s\n", ver);
7052 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7053 printf ("Profile file has wrong version or invalid.\n");
7060 MonoMethodDesc *desc;
7063 if (fgets (name, 1023, infile) == NULL)
7066 /* Kill the newline */
7067 if (strlen (name) > 0)
7068 name [strlen (name) - 1] = '\0';
7070 desc = mono_method_desc_new (name, TRUE);
7072 method = mono_method_desc_search_in_image (desc, acfg->image);
7074 if (method && mono_method_get_token (method)) {
7075 token = mono_method_get_token (method);
7076 method_index = mono_metadata_token_index (token) - 1;
7079 for (i = 0; i < acfg->method_order->len; ++i) {
7080 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7086 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7088 //printf ("No method found matching '%s'.\n", name);
7094 /* Add missing methods */
7096 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7098 for (i = 0; i < acfg->method_order->len; ++i) {
7099 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7105 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7107 unordered = g_list_reverse (unordered);
7108 for (l = unordered; l; l = l->next)
7109 g_ptr_array_add (acfg->method_order, l->data);
7112 /* Used by the LLVM backend */
7114 mono_aot_get_got_offset (MonoJumpInfo *ji)
7116 return get_got_offset (llvm_acfg, TRUE, ji);
7120 mono_aot_get_method_name (MonoCompile *cfg)
7122 if (llvm_acfg->aot_opts.static_link)
7123 /* Include the assembly name too to avoid duplicate symbol errors */
7124 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7126 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7130 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7132 return is_direct_callable (llvm_acfg, NULL, patch_info);
7136 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7138 MonoPltEntry *plt_entry;
7140 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7141 plt_entry->llvm_used = FALSE;
7145 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7147 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7148 MonoPltEntry *plt_entry;
7149 const char *sym = NULL;
7152 ji->data.target = data;
7154 if (!can_encode_patch (llvm_acfg, ji))
7157 if (llvm_acfg->aot_opts.direct_icalls) {
7158 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7159 /* Call to a C function implementing a jit icall */
7160 sym = mono_lookup_jit_icall_symbol (data);
7161 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7162 MonoMethod *method = (gpointer)data;
7163 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7164 sym = mono_lookup_icall_symbol (method);
7167 return g_strdup (sym);
7170 plt_entry = get_plt_entry (llvm_acfg, ji);
7171 plt_entry->llvm_used = TRUE;
7173 #if defined(TARGET_MACH)
7174 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7176 return g_strdup_printf (plt_entry->llvm_symbol);
7181 mono_aot_get_method_index (MonoMethod *method)
7183 g_assert (llvm_acfg);
7184 return get_method_index (llvm_acfg, method);
7188 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7192 mono_acfg_lock (llvm_acfg);
7193 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7194 mono_acfg_unlock (llvm_acfg);
7200 execute_system (const char * command)
7205 // We need an extra set of quotes around the whole command to properly handle commands
7206 // with spaces since internally the command is called through "cmd /c.
7207 command = g_strdup_printf ("\"%s\"", command);
7209 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7210 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7211 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7212 status = _wsystem (wstr);
7217 status = system (command);
7228 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7232 emit_llvm_file (MonoAotCompile *acfg)
7234 char *command, *opts, *tempbc, *output_fname;
7236 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7237 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7241 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7242 * a lot of time, and doesn't seem to save much space.
7243 * The following optimizations cannot be enabled:
7245 * - 'jump-threading' changes our blockaddress references to int constants.
7246 * - 'basiccg' fails because it contains:
7247 * if (CS && !isa<IntrinsicInst>(II)) {
7248 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7249 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7250 * The opt list below was produced by taking the output of:
7251 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7252 * then removing tailcallelim + the global opts.
7253 * strip-dead-prototypes deletes unused intrinsics definitions.
7255 opts = g_strdup ("-instcombine -simplifycfg");
7256 //opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -domtree -verify");
7257 /* The dse pass is disabled because of #13734 and #17616 */
7259 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7260 * // If we have no DataLayout information around, then the size of the store
7261 * // is inferrable from the pointee type. If they are the same type, then
7262 * // we know that the store is safe.
7263 * if (AA.getDataLayout() == 0 &&
7264 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7265 * return OverwriteComplete;
7266 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7268 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -inline-cost -inline -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -adce -simplifycfg -instcombine -strip-dead-prototypes -domtree -verify");
7270 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7271 aot_printf (acfg, "Executing opt: %s\n", command);
7272 if (execute_system (command) != 0)
7277 if (!acfg->llc_args)
7278 acfg->llc_args = g_string_new ("");
7280 /* Verbose asm slows down llc greatly */
7281 g_string_append (acfg->llc_args, " -asm-verbose=false");
7283 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7285 if (acfg->aot_opts.mtriple)
7286 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7288 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7290 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7291 /* ios requires PIC code now */
7292 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7294 if (llvm_acfg->aot_opts.static_link)
7295 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7297 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7299 unlink (acfg->tmpfname);
7301 if (acfg->llvm_owriter) {
7302 /* Emit an object file directly */
7303 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7304 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7306 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7308 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7309 g_free (output_fname);
7311 aot_printf (acfg, "Executing llc: %s\n", command);
7313 if (execute_system (command) != 0)
7320 emit_code (MonoAotCompile *acfg)
7322 int oindex, i, prev_index;
7325 #if defined(TARGET_POWERPC64)
7326 sprintf (symbol, ".Lgot_addr");
7327 emit_section_change (acfg, ".text", 0);
7328 emit_alignment (acfg, 8);
7329 emit_label (acfg, symbol);
7330 emit_pointer (acfg, acfg->got_symbol);
7334 * This global symbol is used to compute the address of each method using the
7335 * code_offsets array. It is also used to compute the memory ranges occupied by
7336 * AOT code, so it must be equal to the address of the first emitted method.
7338 emit_section_change (acfg, ".text", 0);
7339 emit_alignment_code (acfg, 8);
7341 for (i = 0; i < acfg->nmethods; ++i) {
7342 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7343 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7348 if (!acfg->methods_symbol) {
7349 sprintf (symbol, "methods");
7350 emit_label (acfg, symbol);
7351 acfg->methods_symbol = g_strdup (symbol);
7353 emit_label (acfg, "jit_code_start");
7356 * Emit some padding so the local symbol for the first method doesn't have the
7357 * same address as 'methods'.
7359 #if defined(__default_codegen__)
7360 emit_padding (acfg, 16);
7361 #elif defined(__native_client_codegen__)
7363 const int kPaddingSize = 16;
7364 guint8 pad_buffer[kPaddingSize];
7365 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7366 emit_bytes (acfg, pad_buffer, kPaddingSize);
7370 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7374 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7376 cfg = acfg->cfgs [i];
7381 method = cfg->orig_method;
7383 /* Emit unbox trampoline */
7384 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7385 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7387 emit_section_change (acfg, ".text", 0);
7388 #ifdef __native_client_codegen__
7389 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7392 if (acfg->thumb_mixed && cfg->compile_llvm) {
7393 emit_set_thumb_mode (acfg);
7394 fprintf (acfg->fp, "\n.thumb_func\n");
7397 emit_label (acfg, symbol);
7399 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7401 if (acfg->thumb_mixed && cfg->compile_llvm)
7402 emit_set_arm_mode (acfg);
7405 if (cfg->compile_llvm)
7406 acfg->stats.llvm_count ++;
7408 emit_method_code (acfg, cfg);
7411 emit_section_change (acfg, ".text", 0);
7412 emit_alignment_code (acfg, 8);
7413 emit_label (acfg, "jit_code_end");
7415 /* To distinguish it from the next symbol */
7416 emit_padding (acfg, 4);
7419 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7420 * from optimizing them away, since it doesn't see that code_offsets references them.
7421 * JITted methods don't need this since they are referenced using assembler local
7423 * FIXME: This is why write-symbols doesn't work on OSX ?
7425 if (acfg->llvm && acfg->need_no_dead_strip) {
7426 fprintf (acfg->fp, "\n");
7427 for (i = 0; i < acfg->nmethods; ++i) {
7428 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7429 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7434 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7435 * This is PIE code, and the linker can update it if needed.
7437 sprintf (symbol, "method_addresses");
7438 emit_section_change (acfg, ".text", 1);
7439 emit_alignment_code (acfg, 8);
7440 emit_label (acfg, symbol);
7441 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7442 emit_unset_mode (acfg);
7443 if (acfg->need_no_dead_strip)
7444 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7446 for (i = 0; i < acfg->nmethods; ++i) {
7447 #ifdef MONO_ARCH_AOT_SUPPORTED
7451 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7453 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7457 sprintf (symbol, "method_addresses_end");
7458 emit_label (acfg, symbol);
7461 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7462 sprintf (symbol, "unbox_trampolines");
7463 emit_section_change (acfg, RODATA_SECT, 0);
7464 emit_alignment (acfg, 8);
7465 emit_label (acfg, symbol);
7468 for (i = 0; i < acfg->nmethods; ++i) {
7473 cfg = acfg->cfgs [i];
7477 method = cfg->orig_method;
7479 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7480 index = get_method_index (acfg, method);
7482 emit_int32 (acfg, index);
7483 /* Make sure the table is sorted by index */
7484 g_assert (index > prev_index);
7488 sprintf (symbol, "unbox_trampolines_end");
7489 emit_label (acfg, symbol);
7490 emit_int32 (acfg, 0);
7492 /* Emit a separate table with the trampoline addresses/offsets */
7493 sprintf (symbol, "unbox_trampoline_addresses");
7494 emit_section_change (acfg, ".text", 0);
7495 emit_alignment_code (acfg, 8);
7496 emit_label (acfg, symbol);
7498 for (i = 0; i < acfg->nmethods; ++i) {
7503 cfg = acfg->cfgs [i];
7507 method = cfg->orig_method;
7509 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7510 #ifdef MONO_ARCH_AOT_SUPPORTED
7513 index = get_method_index (acfg, method);
7514 sprintf (symbol, "ut_%d", index);
7516 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7520 emit_int32 (acfg, 0);
7524 emit_info (MonoAotCompile *acfg)
7530 offsets = g_new0 (gint32, acfg->nmethods);
7532 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7533 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7535 if (acfg->cfgs [i]) {
7536 emit_method_info (acfg, acfg->cfgs [i]);
7537 offsets [i] = acfg->cfgs [i]->method_info_offset;
7543 sprintf (symbol, "method_info_offsets");
7544 emit_section_change (acfg, RODATA_SECT, 1);
7545 emit_alignment (acfg, 8);
7546 emit_label (acfg, symbol);
7548 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7553 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7555 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7556 #define mix(a,b,c) { \
7557 a -= c; a ^= rot(c, 4); c += b; \
7558 b -= a; b ^= rot(a, 6); a += c; \
7559 c -= b; c ^= rot(b, 8); b += a; \
7560 a -= c; a ^= rot(c,16); c += b; \
7561 b -= a; b ^= rot(a,19); a += c; \
7562 c -= b; c ^= rot(b, 4); b += a; \
7564 #define final(a,b,c) { \
7565 c ^= b; c -= rot(b,14); \
7566 a ^= c; a -= rot(c,11); \
7567 b ^= a; b -= rot(a,25); \
7568 c ^= b; c -= rot(b,16); \
7569 a ^= c; a -= rot(c,4); \
7570 b ^= a; b -= rot(a,14); \
7571 c ^= b; c -= rot(b,24); \
7575 mono_aot_type_hash (MonoType *t1)
7577 guint hash = t1->type;
7579 hash |= t1->byref << 6; /* do not collide with t1->type values */
7581 case MONO_TYPE_VALUETYPE:
7582 case MONO_TYPE_CLASS:
7583 case MONO_TYPE_SZARRAY:
7584 /* check if the distribution is good enough */
7585 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7587 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7588 case MONO_TYPE_ARRAY:
7589 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7590 case MONO_TYPE_GENERICINST:
7591 return ((hash << 5) - hash) ^ 0;
7598 * mono_aot_method_hash:
7600 * Return a hash code for methods which only depends on metadata.
7603 mono_aot_method_hash (MonoMethod *method)
7605 MonoMethodSignature *sig;
7609 guint32 *hashes_start, *hashes;
7611 MonoGenericInst *class_ginst = NULL;
7612 MonoGenericInst *ginst = NULL;
7614 /* Similar to the hash in mono_method_get_imt_slot () */
7616 sig = mono_method_signature (method);
7618 if (method->klass->generic_class)
7619 class_ginst = method->klass->generic_class->context.class_inst;
7620 if (method->is_inflated)
7621 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7623 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7624 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7625 hashes = hashes_start;
7627 /* Some wrappers are assigned to random classes */
7628 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7629 klass = method->klass;
7631 klass = mono_defaults.object_class;
7633 if (!method->wrapper_type) {
7636 if (klass->generic_class)
7637 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7639 full_name = mono_type_full_name (&klass->byval_arg);
7641 hashes [0] = mono_metadata_str_hash (full_name);
7645 hashes [0] = mono_metadata_str_hash (klass->name);
7646 hashes [1] = mono_metadata_str_hash (klass->name_space);
7648 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7649 /* The method name includes a stringified pointer */
7652 hashes [2] = mono_metadata_str_hash (method->name);
7653 hashes [3] = method->wrapper_type;
7654 hashes [4] = mono_aot_type_hash (sig->ret);
7656 for (i = 0; i < sig->param_count; i++) {
7657 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7660 for (i = 0; i < class_ginst->type_argc; ++i)
7661 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7664 for (i = 0; i < ginst->type_argc; ++i)
7665 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7667 g_assert (hindex == hashes_count);
7669 /* Setup internal state */
7670 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7672 /* Handle most of the hashes */
7673 while (hashes_count > 3) {
7682 /* Handle the last 3 hashes (all the case statements fall through) */
7683 switch (hashes_count) {
7684 case 3 : c += hashes [2];
7685 case 2 : b += hashes [1];
7686 case 1 : a += hashes [0];
7688 case 0: /* nothing left to add */
7692 free (hashes_start);
7701 * mono_aot_get_array_helper_from_wrapper;
7703 * Get the helper method in Array called by an array wrapper method.
7706 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7710 MonoGenericContext ctx;
7711 MonoType *args [16];
7712 char *mname, *iname, *s, *s2, *helper_name = NULL;
7714 prefix = "System.Collections.Generic";
7715 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7716 s2 = strstr (s, "`1.");
7722 //printf ("X: %s %s\n", iname, mname);
7724 if (!strcmp (iname, "IList"))
7725 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7727 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7728 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7730 g_free (helper_name);
7733 if (m->is_generic) {
7735 memset (&ctx, 0, sizeof (ctx));
7736 args [0] = &method->klass->element_class->byval_arg;
7737 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7738 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7739 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7745 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7747 typedef struct HashEntry {
7748 guint32 key, value, index;
7749 struct HashEntry *next;
7753 * emit_extra_methods:
7755 * Emit methods which are not in the METHOD table, like wrappers.
7758 emit_extra_methods (MonoAotCompile *acfg)
7760 int i, table_size, buf_size;
7763 guint32 *info_offsets;
7766 HashEntry *entry, *new_entry;
7767 int nmethods, max_chain_length;
7770 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7772 /* Emit method info */
7774 for (i = 0; i < acfg->extra_methods->len; ++i) {
7775 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7776 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7782 p = buf = g_malloc (buf_size);
7786 method = cfg->method_to_register;
7788 encode_method_ref (acfg, method, p, &p);
7790 g_assert ((p - buf) < buf_size);
7792 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7797 * Construct a chained hash table for mapping indexes in extra_method_info to
7800 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7801 table = g_ptr_array_sized_new (table_size);
7802 for (i = 0; i < table_size; ++i)
7803 g_ptr_array_add (table, NULL);
7804 chain_lengths = g_new0 (int, table_size);
7805 max_chain_length = 0;
7806 for (i = 0; i < acfg->extra_methods->len; ++i) {
7807 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7808 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7814 key = info_offsets [i];
7815 value = get_method_index (acfg, method);
7817 hash = mono_aot_method_hash (method) % table_size;
7818 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
7820 chain_lengths [hash] ++;
7821 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7823 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7824 new_entry->key = key;
7825 new_entry->value = value;
7827 entry = g_ptr_array_index (table, hash);
7828 if (entry == NULL) {
7829 new_entry->index = hash;
7830 g_ptr_array_index (table, hash) = new_entry;
7833 entry = entry->next;
7835 entry->next = new_entry;
7836 new_entry->index = table->len;
7837 g_ptr_array_add (table, new_entry);
7841 //printf ("MAX: %d\n", max_chain_length);
7843 /* Emit the table */
7844 sprintf (symbol, "extra_method_table");
7845 emit_section_change (acfg, RODATA_SECT, 0);
7846 emit_alignment (acfg, 8);
7847 emit_label (acfg, symbol);
7849 emit_int32 (acfg, table_size);
7850 for (i = 0; i < table->len; ++i) {
7851 HashEntry *entry = g_ptr_array_index (table, i);
7853 if (entry == NULL) {
7854 emit_int32 (acfg, 0);
7855 emit_int32 (acfg, 0);
7856 emit_int32 (acfg, 0);
7858 //g_assert (entry->key > 0);
7859 emit_int32 (acfg, entry->key);
7860 emit_int32 (acfg, entry->value);
7862 emit_int32 (acfg, entry->next->index);
7864 emit_int32 (acfg, 0);
7869 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7870 * This is used by mono_aot_find_jit_info ().
7872 sprintf (symbol, "extra_method_info_offsets");
7873 emit_section_change (acfg, RODATA_SECT, 0);
7874 emit_alignment (acfg, 8);
7875 emit_label (acfg, symbol);
7877 emit_int32 (acfg, acfg->extra_methods->len);
7878 for (i = 0; i < acfg->extra_methods->len; ++i) {
7879 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7881 emit_int32 (acfg, get_method_index (acfg, method));
7882 emit_int32 (acfg, info_offsets [i]);
7887 emit_exception_info (MonoAotCompile *acfg)
7892 SeqPointData sp_data;
7893 gboolean seq_points_to_file = FALSE;
7895 offsets = g_new0 (gint32, acfg->nmethods);
7896 for (i = 0; i < acfg->nmethods; ++i) {
7897 if (acfg->cfgs [i]) {
7898 MonoCompile *cfg = acfg->cfgs [i];
7900 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
7901 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
7902 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
7903 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
7904 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
7906 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
7907 offsets [i] = cfg->ex_info_offset;
7909 if (method_seq_points_to_file) {
7910 if (!seq_points_to_file) {
7911 seq_point_data_init (&sp_data, acfg->nmethods);
7912 seq_points_to_file = TRUE;
7914 seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
7921 if (seq_points_to_file) {
7922 char *seq_points_aot_file;
7923 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
7924 seq_point_data_write (&sp_data, seq_points_aot_file);
7925 seq_point_data_free (&sp_data);
7926 g_free (seq_points_aot_file);
7929 sprintf (symbol, "ex_info_offsets");
7930 emit_section_change (acfg, RODATA_SECT, 1);
7931 emit_alignment (acfg, 8);
7932 emit_label (acfg, symbol);
7934 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7939 emit_unwind_info (MonoAotCompile *acfg)
7945 * The unwind info contains a lot of duplicates so we emit each unique
7946 * entry once, and only store the offset from the start of the table in the
7950 sprintf (symbol, "unwind_info");
7951 emit_section_change (acfg, RODATA_SECT, 1);
7952 emit_alignment (acfg, 8);
7953 emit_label (acfg, symbol);
7955 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7956 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7957 guint8 *unwind_info;
7958 guint32 unwind_info_len;
7962 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7965 encode_value (unwind_info_len, p, &p);
7966 emit_bytes (acfg, buf, p - buf);
7967 emit_bytes (acfg, unwind_info, unwind_info_len);
7969 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7974 emit_class_info (MonoAotCompile *acfg)
7980 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7981 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7982 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7984 sprintf (symbol, "class_info_offsets");
7985 emit_section_change (acfg, RODATA_SECT, 1);
7986 emit_alignment (acfg, 8);
7987 emit_label (acfg, symbol);
7989 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7993 typedef struct ClassNameTableEntry {
7994 guint32 token, index;
7995 struct ClassNameTableEntry *next;
7996 } ClassNameTableEntry;
7999 emit_class_name_table (MonoAotCompile *acfg)
8002 guint32 token, hash;
8007 ClassNameTableEntry *entry, *new_entry;
8010 * Construct a chained hash table for mapping class names to typedef tokens.
8012 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8013 table = g_ptr_array_sized_new (table_size);
8014 for (i = 0; i < table_size; ++i)
8015 g_ptr_array_add (table, NULL);
8016 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8018 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8019 klass = mono_class_get_checked (acfg->image, token, &error);
8021 mono_error_cleanup (&error);
8024 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8025 hash = mono_metadata_str_hash (full_name) % table_size;
8028 /* FIXME: Allocate from the mempool */
8029 new_entry = g_new0 (ClassNameTableEntry, 1);
8030 new_entry->token = token;
8032 entry = g_ptr_array_index (table, hash);
8033 if (entry == NULL) {
8034 new_entry->index = hash;
8035 g_ptr_array_index (table, hash) = new_entry;
8038 entry = entry->next;
8040 entry->next = new_entry;
8041 new_entry->index = table->len;
8042 g_ptr_array_add (table, new_entry);
8046 /* Emit the table */
8047 sprintf (symbol, "class_name_table");
8048 emit_section_change (acfg, RODATA_SECT, 0);
8049 emit_alignment (acfg, 8);
8050 emit_label (acfg, symbol);
8052 /* FIXME: Optimize memory usage */
8053 g_assert (table_size < 65000);
8054 emit_int16 (acfg, table_size);
8055 g_assert (table->len < 65000);
8056 for (i = 0; i < table->len; ++i) {
8057 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8059 if (entry == NULL) {
8060 emit_int16 (acfg, 0);
8061 emit_int16 (acfg, 0);
8063 emit_int16 (acfg, mono_metadata_token_index (entry->token));
8065 emit_int16 (acfg, entry->next->index);
8067 emit_int16 (acfg, 0);
8073 emit_image_table (MonoAotCompile *acfg)
8079 * The image table is small but referenced in a lot of places.
8080 * So we emit it at once, and reference its elements by an index.
8083 sprintf (symbol, "image_table");
8084 emit_section_change (acfg, RODATA_SECT, 1);
8085 emit_alignment (acfg, 8);
8086 emit_label (acfg, symbol);
8088 emit_int32 (acfg, acfg->image_table->len);
8089 for (i = 0; i < acfg->image_table->len; i++) {
8090 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8091 MonoAssemblyName *aname = &image->assembly->aname;
8093 /* FIXME: Support multi-module assemblies */
8094 g_assert (image->assembly->image == image);
8096 emit_string (acfg, image->assembly_name);
8097 emit_string (acfg, image->guid);
8098 emit_string (acfg, aname->culture ? aname->culture : "");
8099 emit_string (acfg, (const char*)aname->public_key_token);
8101 emit_alignment (acfg, 8);
8102 emit_int32 (acfg, aname->flags);
8103 emit_int32 (acfg, aname->major);
8104 emit_int32 (acfg, aname->minor);
8105 emit_int32 (acfg, aname->build);
8106 emit_int32 (acfg, aname->revision);
8111 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8114 int i, first_plt_got_patch = 0, buf_size;
8116 guint32 *got_info_offsets;
8117 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8119 /* Add the patches needed by the PLT to the GOT */
8121 acfg->plt_got_offset_base = acfg->got_offset;
8122 first_plt_got_patch = info->got_patches->len;
8123 for (i = 1; i < acfg->plt_offset; ++i) {
8124 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8126 g_ptr_array_add (info->got_patches, plt_entry->ji);
8128 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8131 acfg->got_offset += acfg->plt_offset;
8136 * - optimize offsets table.
8137 * - reduce number of exported symbols.
8138 * - emit info for a klass only once.
8139 * - determine when a method uses a GOT slot which is guaranteed to be already
8141 * - clean up and document the code.
8142 * - use String.Empty in class libs.
8145 /* Encode info required to decode shared GOT entries */
8146 buf_size = info->got_patches->len * 128;
8147 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8148 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8150 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8152 if (acfg->plt_offset)
8153 acfg->plt_got_info_offsets [0] = 0;
8155 for (i = 0; i < info->got_patches->len; ++i) {
8156 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8161 encode_value (ji->type, p, &p);
8163 encode_patch (acfg, ji, p, &p);
8164 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8165 g_assert (p - buf <= buf_size);
8166 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8168 if (!llvm && i >= first_plt_got_patch)
8169 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8170 acfg->stats.got_info_size += p - buf;
8173 /* Emit got_info_offsets table */
8175 sprintf (symbol, "llvm_got_info_offsets");
8177 sprintf (symbol, "got_info_offsets");
8178 emit_section_change (acfg, RODATA_SECT, 1);
8179 emit_alignment (acfg, 8);
8180 emit_label (acfg, symbol);
8182 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8183 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8187 emit_got (MonoAotCompile *acfg)
8191 /* Don't make GOT global so accesses to it don't need relocations */
8192 sprintf (symbol, "%s", acfg->got_symbol);
8193 emit_section_change (acfg, ".bss", 0);
8194 emit_alignment (acfg, 8);
8195 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8196 emit_label (acfg, symbol);
8197 if (acfg->got_offset > 0)
8198 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8200 sprintf (symbol, "got_end");
8201 emit_label (acfg, symbol);
8204 typedef struct GlobalsTableEntry {
8205 guint32 value, index;
8206 struct GlobalsTableEntry *next;
8207 } GlobalsTableEntry;
8210 emit_globals (MonoAotCompile *acfg)
8216 GlobalsTableEntry *entry, *new_entry;
8218 if (!acfg->aot_opts.static_link)
8222 * When static linking, we emit a table containing our globals.
8226 * Construct a chained hash table for mapping global names to their index in
8227 * the globals table.
8229 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8230 table = g_ptr_array_sized_new (table_size);
8231 for (i = 0; i < table_size; ++i)
8232 g_ptr_array_add (table, NULL);
8233 for (i = 0; i < acfg->globals->len; ++i) {
8234 char *name = g_ptr_array_index (acfg->globals, i);
8236 hash = mono_metadata_str_hash (name) % table_size;
8238 /* FIXME: Allocate from the mempool */
8239 new_entry = g_new0 (GlobalsTableEntry, 1);
8240 new_entry->value = i;
8242 entry = g_ptr_array_index (table, hash);
8243 if (entry == NULL) {
8244 new_entry->index = hash;
8245 g_ptr_array_index (table, hash) = new_entry;
8248 entry = entry->next;
8250 entry->next = new_entry;
8251 new_entry->index = table->len;
8252 g_ptr_array_add (table, new_entry);
8256 /* Emit the table */
8257 sprintf (symbol, ".Lglobals_hash");
8258 emit_section_change (acfg, RODATA_SECT, 0);
8259 emit_alignment (acfg, 8);
8260 emit_label (acfg, symbol);
8262 /* FIXME: Optimize memory usage */
8263 g_assert (table_size < 65000);
8264 emit_int16 (acfg, table_size);
8265 for (i = 0; i < table->len; ++i) {
8266 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8268 if (entry == NULL) {
8269 emit_int16 (acfg, 0);
8270 emit_int16 (acfg, 0);
8272 emit_int16 (acfg, entry->value + 1);
8274 emit_int16 (acfg, entry->next->index);
8276 emit_int16 (acfg, 0);
8280 /* Emit the names */
8281 for (i = 0; i < acfg->globals->len; ++i) {
8282 char *name = g_ptr_array_index (acfg->globals, i);
8284 sprintf (symbol, "name_%d", i);
8285 emit_section_change (acfg, RODATA_SECT, 1);
8287 emit_alignment (acfg, 4);
8289 emit_label (acfg, symbol);
8290 emit_string (acfg, name);
8293 /* Emit the globals table */
8294 sprintf (symbol, "globals");
8295 emit_section_change (acfg, ".data", 0);
8296 /* This is not a global, since it is accessed by the init function */
8297 emit_alignment (acfg, 8);
8298 emit_label (acfg, symbol);
8300 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8301 emit_pointer (acfg, symbol);
8303 for (i = 0; i < acfg->globals->len; ++i) {
8304 char *name = g_ptr_array_index (acfg->globals, i);
8306 sprintf (symbol, "name_%d", i);
8307 emit_pointer (acfg, symbol);
8309 g_assert (strlen (name) < sizeof (symbol));
8310 sprintf (symbol, "%s", name);
8311 emit_pointer (acfg, symbol);
8313 /* Null terminate the table */
8314 emit_int32 (acfg, 0);
8315 emit_int32 (acfg, 0);
8319 emit_autoreg (MonoAotCompile *acfg)
8324 * Emit a function into the .ctor section which will be called by the ELF
8325 * loader to register this module with the runtime.
8327 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8330 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8332 arch_emit_autoreg (acfg, symbol);
8338 emit_mem_end (MonoAotCompile *acfg)
8342 sprintf (symbol, "mem_end");
8343 emit_section_change (acfg, ".text", 1);
8344 emit_alignment_code (acfg, 8);
8345 emit_label (acfg, symbol);
8349 * Emit a structure containing all the information not stored elsewhere.
8352 emit_file_info (MonoAotCompile *acfg)
8357 const char *gc_name;
8360 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8362 if (acfg->aot_opts.bind_to_runtime_version) {
8363 build_info = mono_get_runtime_build_info ();
8364 emit_string_symbol (acfg, "runtime_version", build_info);
8365 g_free (build_info);
8367 emit_string_symbol (acfg, "runtime_version", "");
8370 /* Emit a string holding the assembly name */
8371 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8374 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8377 gc_name = mono_gc_get_gc_name ();
8378 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8380 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8381 emit_section_change (acfg, ".data", 0);
8382 emit_alignment (acfg, 8);
8383 emit_label (acfg, symbol);
8384 if (!acfg->aot_opts.static_link)
8385 emit_global (acfg, symbol, FALSE);
8387 /* The data emitted here must match MonoAotFileInfo. */
8389 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8390 emit_int32 (acfg, 0);
8393 * We emit pointers to our data structures instead of emitting global symbols which
8394 * point to them, to reduce the number of globals, and because using globals leads to
8395 * various problems (i.e. arm/thumb).
8397 emit_pointer (acfg, acfg->got_symbol);
8399 emit_pointer (acfg, acfg->llvm_got_symbol);
8401 emit_pointer (acfg, NULL);
8402 emit_pointer (acfg, acfg->methods_symbol);
8403 emit_pointer (acfg, "jit_code_start");
8404 emit_pointer (acfg, "jit_code_end");
8407 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8409 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8411 emit_pointer (acfg, NULL);
8413 emit_pointer (acfg, "blob");
8414 emit_pointer (acfg, "class_name_table");
8415 emit_pointer (acfg, "class_info_offsets");
8416 emit_pointer (acfg, "method_info_offsets");
8417 emit_pointer (acfg, "ex_info_offsets");
8418 emit_pointer (acfg, "method_addresses");
8419 emit_pointer (acfg, "extra_method_info_offsets");
8420 emit_pointer (acfg, "extra_method_table");
8421 emit_pointer (acfg, "got_info_offsets");
8423 emit_pointer (acfg, "llvm_got_info_offsets");
8425 emit_pointer (acfg, NULL);
8426 emit_pointer (acfg, "unwind_info");
8427 emit_pointer (acfg, "mem_end");
8428 emit_pointer (acfg, "image_table");
8429 emit_pointer (acfg, "plt");
8430 emit_pointer (acfg, "plt_end");
8431 emit_pointer (acfg, "assembly_guid");
8432 emit_pointer (acfg, "runtime_version");
8433 if (acfg->num_trampoline_got_entries) {
8434 emit_pointer (acfg, "specific_trampolines");
8435 emit_pointer (acfg, "static_rgctx_trampolines");
8436 emit_pointer (acfg, "imt_thunks");
8437 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8439 emit_pointer (acfg, NULL);
8440 emit_pointer (acfg, NULL);
8441 emit_pointer (acfg, NULL);
8442 emit_pointer (acfg, NULL);
8444 if (acfg->thumb_mixed) {
8445 emit_pointer (acfg, "thumb_end");
8447 emit_pointer (acfg, NULL);
8449 if (acfg->aot_opts.static_link) {
8450 emit_pointer (acfg, "globals");
8452 emit_pointer (acfg, NULL);
8454 emit_pointer (acfg, "assembly_name");
8455 emit_pointer (acfg, "unbox_trampolines");
8456 emit_pointer (acfg, "unbox_trampolines_end");
8457 emit_pointer (acfg, "unbox_trampoline_addresses");
8459 emit_int32 (acfg, acfg->plt_got_offset_base);
8460 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8461 emit_int32 (acfg, acfg->plt_offset);
8462 emit_int32 (acfg, acfg->nmethods);
8463 emit_int32 (acfg, acfg->flags);
8464 emit_int32 (acfg, acfg->opts);
8465 emit_int32 (acfg, acfg->simd_opts);
8466 emit_int32 (acfg, gc_name_offset);
8468 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8469 emit_int32 (acfg, acfg->num_trampolines [i]);
8470 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8471 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8472 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8473 emit_int32 (acfg, acfg->trampoline_size [i]);
8474 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8476 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8481 memset (&t, 0, sizeof (MonoType));
8482 t.type = MONO_TYPE_R8;
8483 mono_type_size (&t, &align);
8484 emit_int32 (acfg, align);
8486 memset (&t, 0, sizeof (MonoType));
8487 t.type = MONO_TYPE_I8;
8488 mono_type_size (&t, &align);
8490 emit_int32 (acfg, align);
8493 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8494 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8496 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8497 emit_int32 (acfg, acfg->tramp_page_size);
8498 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8499 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8501 if (acfg->aot_opts.static_link) {
8505 * Emit a global symbol which can be passed by an embedding app to
8506 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8509 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8511 /* Get rid of characters which cannot occur in symbols */
8513 for (p = symbol; *p; ++p) {
8514 if (!(isalnum (*p) || *p == '_'))
8517 acfg->static_linking_symbol = g_strdup (symbol);
8518 emit_global_inner (acfg, symbol, FALSE);
8519 emit_alignment (acfg, sizeof (gpointer));
8520 emit_label (acfg, symbol);
8521 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8526 emit_blob (MonoAotCompile *acfg)
8530 sprintf (symbol, "blob");
8531 emit_section_change (acfg, RODATA_SECT, 1);
8532 emit_alignment (acfg, 8);
8533 emit_label (acfg, symbol);
8535 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8539 emit_objc_selectors (MonoAotCompile *acfg)
8543 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8548 * cat > foo.m << EOF
8551 * return @selector(print:);
8556 img_writer_emit_unset_mode (acfg->w);
8557 g_assert (acfg->fp);
8558 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8559 fprintf (acfg->fp, ".align 3\n");
8560 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8561 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8562 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8564 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8565 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8566 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8567 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8570 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8571 fprintf (acfg->fp, ".align 3\n");
8572 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8573 fprintf (acfg->fp, ".long 0\n");
8574 fprintf (acfg->fp, ".long 16\n");
8578 emit_dwarf_info (MonoAotCompile *acfg)
8580 #ifdef EMIT_DWARF_INFO
8584 /* DIEs for methods */
8585 for (i = 0; i < acfg->nmethods; ++i) {
8586 MonoCompile *cfg = acfg->cfgs [i];
8591 // FIXME: LLVM doesn't define .Lme_...
8592 if (cfg->compile_llvm)
8595 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8597 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
8603 collect_methods (MonoAotCompile *acfg)
8606 MonoImage *image = acfg->image;
8608 /* Collect methods */
8609 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8612 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8614 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8617 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8618 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8619 mono_error_cleanup (&error);
8623 /* Load all methods eagerly to skip the slower lazy loading code */
8624 mono_class_setup_methods (method->klass);
8626 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8627 /* Compile the wrapper instead */
8628 /* We do this here instead of add_wrappers () because it is easy to do it here */
8629 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8633 /* FIXME: Some mscorlib methods don't have debug info */
8635 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8636 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8637 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8638 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8639 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8640 if (!mono_debug_lookup_method (method)) {
8641 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8648 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8649 add_method_with_index (acfg, method, i, FALSE);
8650 acfg->method_index ++;
8653 /* gsharedvt methods */
8654 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8657 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8659 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8662 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8663 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8666 if (strcmp (method->name, "gshared2"))
8670 if (!strstr (method->klass->image->name, "mini"))
8673 if (method->is_generic || method->klass->generic_container) {
8674 MonoMethod *gshared;
8676 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8677 add_extra_method (acfg, gshared);
8681 add_generic_instances (acfg);
8683 if (acfg->aot_opts.full_aot)
8684 add_wrappers (acfg);
8689 compile_methods (MonoAotCompile *acfg)
8693 if (acfg->aot_opts.nthreads > 0) {
8698 gpointer *user_data;
8699 MonoMethod **methods;
8701 methods_len = acfg->methods->len;
8703 len = acfg->methods->len / acfg->aot_opts.nthreads;
8706 * Partition the list of methods into fragments, and hand it to threads to
8709 threads = g_ptr_array_new ();
8710 /* Make a copy since acfg->methods is modified by compile_method () */
8711 methods = g_new0 (MonoMethod*, methods_len);
8712 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8713 for (i = 0; i < methods_len; ++i)
8714 methods [i] = g_ptr_array_index (acfg->methods, i);
8716 while (i < methods_len) {
8717 frag = g_ptr_array_new ();
8718 for (j = 0; j < len; ++j) {
8719 if (i < methods_len) {
8720 g_ptr_array_add (frag, methods [i]);
8725 user_data = g_new0 (gpointer, 3);
8726 user_data [0] = mono_domain_get ();
8727 user_data [1] = acfg;
8728 user_data [2] = frag;
8730 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8731 g_ptr_array_add (threads, handle);
8735 for (i = 0; i < threads->len; ++i) {
8736 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8742 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8743 for (i = methods_len; i < acfg->methods->len; ++i) {
8744 /* This can new methods to acfg->methods */
8745 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8750 compile_asm (MonoAotCompile *acfg)
8752 char *command, *objfile;
8753 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8754 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8755 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
8757 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8758 #define AS_OPTIONS "--64"
8759 #elif defined(TARGET_POWERPC64)
8760 #define AS_OPTIONS "-a64 -mppc64"
8761 #define LD_OPTIONS "-m elf64ppc"
8762 #elif defined(sparc) && SIZEOF_VOID_P == 8
8763 #define AS_OPTIONS "-xarch=v9"
8764 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8765 #define AS_OPTIONS "-arch i386"
8767 #define AS_OPTIONS ""
8770 #ifdef __native_client_codegen__
8771 #if defined(TARGET_AMD64)
8772 #define AS_NAME "nacl64-as"
8774 #define AS_NAME "nacl-as"
8776 #elif defined(TARGET_OSX)
8777 #define AS_NAME "clang"
8779 #define AS_NAME "as"
8783 #define LD_OPTIONS ""
8787 #define LD_NAME "ld -shared -G"
8788 #elif defined(__ppc__) && defined(TARGET_MACH)
8789 #define LD_NAME "gcc -dynamiclib"
8790 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8791 #define LD_NAME "clang --shared"
8792 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
8793 #define LD_NAME "gcc -shared --dll"
8794 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8795 #define LD_NAME "clang -m32 -dynamiclib"
8798 if (acfg->aot_opts.asm_only) {
8799 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8800 if (acfg->aot_opts.static_link)
8801 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8803 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8807 if (acfg->aot_opts.static_link) {
8808 if (acfg->aot_opts.outfile)
8809 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8811 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8813 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8817 g_string_append (acfg->as_args, "-c -x assembler");
8820 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);
8821 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8822 if (execute_system (command) != 0) {
8828 if (acfg->llvm && !acfg->llvm_owriter) {
8829 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", acfg->llvm_ofile, acfg->llvm_sfile);
8830 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8831 if (execute_system (command) != 0) {
8840 if (acfg->aot_opts.static_link) {
8841 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8842 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8847 if (acfg->aot_opts.outfile)
8848 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8850 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8852 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8855 llvm_ofile = g_strdup (acfg->llvm_ofile);
8857 llvm_ofile = g_strdup ("");
8860 /* replace the ; flags separators with spaces */
8861 g_strdelimit (ld_flags, ";", ' ');
8864 command = g_strdup_printf ("%s -o %s %s %s.o %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
8866 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
8867 acfg->tmpfname, ld_flags);
8869 aot_printf (acfg, "Executing the native linker: %s\n", command);
8870 if (execute_system (command) != 0) {
8871 g_free (tmp_outfile_name);
8872 g_free (outfile_name);
8881 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8882 printf ("Stripping the binary: %s\n", com);
8883 execute_system (com);
8886 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8888 * gas generates 'mapping symbols' each time code and data is mixed, which
8889 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8891 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8892 aot_printf (acfg, "Stripping the binary: %s\n", command);
8893 if (execute_system (command) != 0) {
8894 g_free (tmp_outfile_name);
8895 g_free (outfile_name);
8902 rename (tmp_outfile_name, outfile_name);
8904 #if defined(TARGET_MACH)
8905 command = g_strdup_printf ("dsymutil %s", outfile_name);
8906 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8907 if (execute_system (command) != 0) {
8912 if (!acfg->aot_opts.save_temps)
8915 g_free (tmp_outfile_name);
8916 g_free (outfile_name);
8919 if (acfg->aot_opts.save_temps)
8920 aot_printf (acfg, "Retained input file.\n");
8922 unlink (acfg->tmpfname);
8927 static void init_got_info (GotInfo *info)
8931 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8932 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8933 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8934 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8935 info->got_patches = g_ptr_array_new ();
8938 static MonoAotCompile*
8939 acfg_create (MonoAssembly *ass, guint32 opts)
8941 MonoImage *image = ass->image;
8942 MonoAotCompile *acfg;
8944 acfg = g_new0 (MonoAotCompile, 1);
8945 acfg->methods = g_ptr_array_new ();
8946 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8947 acfg->method_depth = g_hash_table_new (NULL, NULL);
8948 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8949 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8950 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8951 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
8952 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8953 acfg->image_hash = g_hash_table_new (NULL, NULL);
8954 acfg->image_table = g_ptr_array_new ();
8955 acfg->globals = g_ptr_array_new ();
8956 acfg->image = image;
8958 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8959 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8960 acfg->mempool = mono_mempool_new ();
8961 acfg->extra_methods = g_ptr_array_new ();
8962 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8963 acfg->unwind_ops = g_ptr_array_new ();
8964 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8965 acfg->method_order = g_ptr_array_new ();
8966 acfg->export_names = g_hash_table_new (NULL, NULL);
8967 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8968 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8969 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8970 mono_mutex_init_recursive (&acfg->mutex);
8972 init_got_info (&acfg->got_info);
8973 init_got_info (&acfg->llvm_got_info);
8979 got_info_free (GotInfo *info)
8983 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8984 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
8985 g_free (info->patch_to_got_offset_by_type);
8986 g_hash_table_destroy (info->patch_to_got_offset);
8987 g_ptr_array_free (info->got_patches, TRUE);
8991 acfg_free (MonoAotCompile *acfg)
8995 img_writer_destroy (acfg->w);
8996 for (i = 0; i < acfg->nmethods; ++i)
8998 g_free (acfg->cfgs [i]);
8999 g_free (acfg->cfgs);
9000 g_free (acfg->static_linking_symbol);
9001 g_free (acfg->got_symbol);
9002 g_free (acfg->plt_symbol);
9003 g_ptr_array_free (acfg->methods, TRUE);
9004 g_ptr_array_free (acfg->image_table, TRUE);
9005 g_ptr_array_free (acfg->globals, TRUE);
9006 g_ptr_array_free (acfg->unwind_ops, TRUE);
9007 g_hash_table_destroy (acfg->method_indexes);
9008 g_hash_table_destroy (acfg->method_depth);
9009 g_hash_table_destroy (acfg->plt_offset_to_entry);
9010 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9011 if (acfg->patch_to_plt_entry [i])
9012 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9014 g_free (acfg->patch_to_plt_entry);
9015 g_hash_table_destroy (acfg->method_to_cfg);
9016 g_hash_table_destroy (acfg->token_info_hash);
9017 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9018 g_hash_table_destroy (acfg->image_hash);
9019 g_hash_table_destroy (acfg->unwind_info_offsets);
9020 g_hash_table_destroy (acfg->method_label_hash);
9021 g_hash_table_destroy (acfg->export_names);
9022 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9023 g_hash_table_destroy (acfg->klass_blob_hash);
9024 g_hash_table_destroy (acfg->method_blob_hash);
9025 got_info_free (&acfg->got_info);
9026 got_info_free (&acfg->llvm_got_info);
9027 mono_mempool_destroy (acfg->mempool);
9031 #define WRAPPER(e,n) n,
9032 static const char* const
9033 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9034 #include "mono/metadata/wrapper-types.h"
9038 static G_GNUC_UNUSED const char*
9039 get_wrapper_type_name (int type)
9041 return wrapper_type_names [type];
9047 static void aot_dump (MonoAotCompile *acfg)
9053 json_writer_init (&writer);
9055 json_writer_object_begin(&writer);
9058 json_writer_indent (&writer);
9059 json_writer_object_key(&writer, "methods");
9060 json_writer_array_begin (&writer);
9063 for (i = 0; i < acfg->nmethods; ++i) {
9068 cfg = acfg->cfgs [i];
9072 method = cfg->orig_method;
9074 json_writer_indent (&writer);
9075 json_writer_object_begin(&writer);
9077 json_writer_indent (&writer);
9078 json_writer_object_key(&writer, "name");
9079 json_writer_printf (&writer, "\"%s\",\n", method->name);
9081 json_writer_indent (&writer);
9082 json_writer_object_key(&writer, "signature");
9083 json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9084 /*signature=*/TRUE));
9086 json_writer_indent (&writer);
9087 json_writer_object_key(&writer, "code_size");
9088 json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9090 klass = method->klass;
9092 json_writer_indent (&writer);
9093 json_writer_object_key(&writer, "class");
9094 json_writer_printf (&writer, "\"%s\",\n", klass->name);
9096 json_writer_indent (&writer);
9097 json_writer_object_key(&writer, "namespace");
9098 json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9100 json_writer_indent (&writer);
9101 json_writer_object_key(&writer, "wrapper_type");
9102 json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9104 json_writer_indent_pop (&writer);
9105 json_writer_indent (&writer);
9106 json_writer_object_end (&writer);
9107 json_writer_printf (&writer, ",\n");
9110 json_writer_indent_pop (&writer);
9111 json_writer_indent (&writer);
9112 json_writer_array_end (&writer);
9113 json_writer_printf (&writer, ",\n");
9117 json_writer_indent_push (&writer);
9118 json_writer_indent (&writer);
9119 json_writer_object_key(&writer, "plt");
9120 json_writer_array_begin (&writer);
9122 for (i = 0; i < acfg->plt_offset; ++i) {
9123 MonoPltEntry *plt_entry = NULL;
9128 * The first plt entry is unused.
9132 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9135 json_writer_indent (&writer);
9136 json_writer_printf (&writer, "{ ");
9137 json_writer_object_key(&writer, "symbol");
9138 json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9141 json_writer_indent_pop (&writer);
9142 json_writer_indent (&writer);
9143 json_writer_array_end (&writer);
9144 json_writer_printf (&writer, ",\n");
9149 json_writer_indent_push (&writer);
9150 json_writer_indent (&writer);
9151 json_writer_object_key(&writer, "got");
9152 json_writer_array_begin (&writer);
9154 json_writer_indent_push (&writer);
9155 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9156 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9158 json_writer_indent (&writer);
9159 json_writer_printf (&writer, "{ ");
9160 json_writer_object_key(&writer, "patch_name");
9161 json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9164 json_writer_indent_pop (&writer);
9165 json_writer_indent (&writer);
9166 json_writer_array_end (&writer);
9167 json_writer_printf (&writer, ",\n");
9170 json_writer_indent_pop (&writer);
9171 json_writer_indent (&writer);
9172 json_writer_object_end (&writer);
9174 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9175 dumpfile = fopen (dumpname, "w+");
9178 fprintf (dumpfile, "%s", writer.text->str);
9181 json_writer_destroy (&writer);
9185 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9187 MonoImage *image = ass->image;
9190 MonoAotCompile *acfg;
9191 char *outfile_name, *tmp_outfile_name, *p;
9192 char llvm_stats_msg [256];
9196 acfg = acfg_create (ass, opts);
9198 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9199 acfg->aot_opts.write_symbols = TRUE;
9200 acfg->aot_opts.ntrampolines = 1024;
9201 acfg->aot_opts.nrgctx_trampolines = 1024;
9202 acfg->aot_opts.nimt_trampolines = 128;
9203 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9204 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9205 acfg->aot_opts.llvm_path = g_strdup ("");
9207 acfg->aot_opts.use_trampolines_page = TRUE;
9210 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9212 if (acfg->aot_opts.logfile) {
9213 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9216 if (acfg->aot_opts.static_link)
9217 acfg->aot_opts.autoreg = TRUE;
9219 //acfg->aot_opts.print_skipped_methods = TRUE;
9221 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9222 if (opts & MONO_OPT_GSHAREDVT) {
9223 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9228 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9230 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9231 if (acfg->aot_opts.full_aot) {
9232 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9237 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9238 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9242 if (acfg->aot_opts.static_link)
9243 acfg->aot_opts.asm_writer = TRUE;
9245 if (acfg->aot_opts.soft_debug) {
9246 MonoDebugOptions *opt = mini_get_debug_options ();
9248 opt->mdb_optimizations = TRUE;
9249 opt->gen_sdb_seq_points = TRUE;
9251 if (!mono_debug_enabled ()) {
9252 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9255 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9258 if (mono_use_llvm || acfg->aot_opts.llvm) {
9260 acfg->aot_opts.asm_writer = TRUE;
9261 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9263 if (acfg->aot_opts.soft_debug) {
9264 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9270 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9271 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9276 * Emit all LLVM code into a separate assembly/object file and link with it
9279 if (!acfg->aot_opts.asm_only)
9280 acfg->llvm_owriter = TRUE;
9283 if (acfg->aot_opts.full_aot)
9284 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9286 if (acfg->aot_opts.instances_logfile_path) {
9287 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9288 if (!acfg->instances_logfile) {
9289 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9294 load_profile_files (acfg);
9296 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
9297 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9298 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
9300 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
9301 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9302 if (acfg->opts & MONO_OPT_GSHAREDVT)
9303 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9306 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
9310 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9311 /* Get rid of characters which cannot occur in symbols */
9312 for (p = acfg->assembly_name_sym; *p; ++p) {
9313 if (!(isalnum (*p) || *p == '_'))
9317 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9318 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9319 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9321 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9323 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9324 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9327 acfg->method_index = 1;
9329 if (acfg->aot_opts.full_aot)
9330 mono_set_partial_sharing_supported (TRUE);
9332 res = collect_methods (acfg);
9336 acfg->cfgs_size = acfg->methods->len + 32;
9337 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9339 /* PLT offset 0 is reserved for the PLT trampoline */
9340 acfg->plt_offset = 1;
9345 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, TRUE, TRUE);
9349 /* GOT offset 0 is reserved for the address of the current assembly */
9353 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9354 ji->type = MONO_PATCH_INFO_IMAGE;
9355 ji->data.image = acfg->image;
9357 get_got_offset (acfg, FALSE, ji);
9358 get_got_offset (acfg, TRUE, ji);
9360 /* Slot 1 is reserved for the mscorlib got addr */
9361 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9362 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9363 get_got_offset (acfg, FALSE, ji);
9364 get_got_offset (acfg, TRUE, ji);
9366 /* This is very common */
9367 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9368 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9369 get_got_offset (acfg, FALSE, ji);
9370 get_got_offset (acfg, TRUE, ji);
9372 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9373 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9374 get_got_offset (acfg, FALSE, ji);
9375 get_got_offset (acfg, TRUE, ji);
9377 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9378 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9379 get_got_offset (acfg, FALSE, ji);
9380 get_got_offset (acfg, TRUE, ji);
9385 compile_methods (acfg);
9389 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9397 if (acfg->aot_opts.asm_only) {
9398 if (acfg->aot_opts.outfile) {
9399 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9400 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9402 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9403 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9405 g_assert (acfg->aot_opts.llvm_outfile);
9406 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9408 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
9409 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9410 acfg->llvm_sfile = g_strdup ("temp-llvm.s");
9411 acfg->llvm_ofile = g_strdup ("temp-llvm.o");
9414 res = emit_llvm_file (acfg);
9420 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
9421 if (acfg->aot_opts.outfile)
9422 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9424 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9427 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9428 * it might be in another file system so the rename () won't work.
9430 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9432 acfg->fp = fopen (tmp_outfile_name, "w");
9434 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9438 acfg->w = img_writer_create (acfg->fp, TRUE);
9439 acfg->use_bin_writer = TRUE;
9441 if (acfg->aot_opts.asm_only) {
9442 if (acfg->aot_opts.outfile)
9443 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9445 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9446 acfg->fp = fopen (acfg->tmpfname, "w+");
9448 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9449 acfg->fp = fdopen (i, "w+");
9451 if (acfg->fp == 0) {
9452 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9455 acfg->w = img_writer_create (acfg->fp, FALSE);
9457 tmp_outfile_name = NULL;
9458 outfile_name = NULL;
9461 /* Compute symbols for methods */
9462 for (i = 0; i < acfg->nmethods; ++i) {
9463 if (acfg->cfgs [i]) {
9464 MonoCompile *cfg = acfg->cfgs [i];
9465 int method_index = get_method_index (acfg, cfg->orig_method);
9467 if (COMPILE_LLVM (cfg))
9468 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9469 else if (acfg->global_symbols || acfg->llvm)
9470 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9472 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9473 cfg->asm_debug_symbol = cfg->asm_symbol;
9477 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9479 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9480 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9483 //acfg->gas_line_numbers = TRUE;
9486 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9487 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9488 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9491 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9494 img_writer_emit_start (acfg->w);
9497 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9499 if (acfg->thumb_mixed) {
9502 * This global symbol marks the end of THUMB code, and the beginning of ARM
9503 * code generated by our JIT.
9505 sprintf (symbol, "thumb_end");
9506 emit_section_change (acfg, ".text", 0);
9507 emit_alignment_code (acfg, 8);
9508 emit_label (acfg, symbol);
9509 emit_zero_bytes (acfg, 16);
9511 fprintf (acfg->fp, ".arm\n");
9518 emit_extra_methods (acfg);
9520 emit_trampolines (acfg);
9522 emit_class_name_table (acfg);
9524 emit_got_info (acfg, FALSE);
9526 emit_got_info (acfg, TRUE);
9528 emit_exception_info (acfg);
9530 emit_unwind_info (acfg);
9532 emit_class_info (acfg);
9536 emit_image_table (acfg);
9540 emit_file_info (acfg);
9544 emit_objc_selectors (acfg);
9546 emit_globals (acfg);
9548 emit_autoreg (acfg);
9551 emit_dwarf_info (acfg);
9552 mono_dwarf_writer_close (acfg->dwarf);
9555 emit_mem_end (acfg);
9557 if (acfg->need_pt_gnu_stack) {
9558 /* This is required so the .so doesn't have an executable stack */
9559 /* The bin writer already emits this */
9560 if (!acfg->use_bin_writer)
9561 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9566 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9569 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9571 strcpy (llvm_stats_msg, "");
9573 all_sizes = acfg->stats.code_size + acfg->stats.info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
9575 aot_printf (acfg, "Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d\n",
9576 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9577 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9578 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9579 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9580 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9581 acfg->stats.plt_size ? (int)acfg->stats.plt_size : (int)acfg->plt_offset, acfg->stats.plt_size ? (int)(acfg->stats.plt_size * 100 / all_sizes) : 0,
9582 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9583 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9584 (int)(acfg->got_offset * sizeof (gpointer)));
9585 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9586 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9588 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9589 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9590 if (acfg->stats.genericcount)
9591 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9592 if (acfg->stats.abscount)
9593 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9594 if (acfg->stats.lmfcount)
9595 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9596 if (acfg->stats.ocount)
9597 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9600 res = img_writer_emit_writeout (acfg->w);
9605 if (acfg->use_bin_writer) {
9606 int err = rename (tmp_outfile_name, outfile_name);
9609 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9613 res = compile_asm (acfg);
9620 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9622 if (acfg->aot_opts.stats) {
9625 aot_printf (acfg, "GOT slot distribution:\n");
9626 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9627 if (acfg->stats.got_slot_types [i])
9628 aot_printf (acfg, "\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9631 aot_printf (acfg, "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);
9633 if (acfg->aot_opts.dump_json)
9646 mono_aot_readonly_field_override (MonoClassField *field)
9652 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)