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 mono_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 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
373 emit_label (MonoAotCompile *acfg, const char *name)
375 mono_img_writer_emit_label (acfg->w, name);
379 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
381 mono_img_writer_emit_bytes (acfg->w, buf, size);
385 emit_string (MonoAotCompile *acfg, const char *value)
387 mono_img_writer_emit_string (acfg->w, value);
391 emit_line (MonoAotCompile *acfg)
393 mono_img_writer_emit_line (acfg->w);
397 emit_alignment (MonoAotCompile *acfg, int size)
399 mono_img_writer_emit_alignment (acfg->w, size);
403 emit_alignment_code (MonoAotCompile *acfg, int size)
405 if (acfg->align_pad_value)
406 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
408 mono_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 mono_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 mono_img_writer_emit_pointer (acfg->w, s);
446 mono_img_writer_emit_pointer (acfg->w, target);
451 emit_int16 (MonoAotCompile *acfg, int value)
453 mono_img_writer_emit_int16 (acfg->w, value);
457 emit_int32 (MonoAotCompile *acfg, int value)
459 mono_img_writer_emit_int32 (acfg->w, value);
463 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
465 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
469 emit_zero_bytes (MonoAotCompile *acfg, int num)
471 mono_img_writer_emit_zero_bytes (acfg->w, num);
475 emit_byte (MonoAotCompile *acfg, guint8 val)
477 mono_img_writer_emit_byte (acfg->w, val);
480 #ifdef __native_client_codegen__
482 emit_nacl_call_alignment (MonoAotCompile *acfg)
484 mono_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 mono_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 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
501 mono_img_writer_emit_global (acfg->w, name, func);
506 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
508 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
512 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
514 mono_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 mono_img_writer_emit_label (acfg->w, name);
520 mono_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 mono_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 mono_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 (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
882 * between code and 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 (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
924 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
927 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
930 /* mov reg, got+offset(%rip) */
932 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
936 /* Decode reg, see amd64_mov_reg_membase () */
937 rex_r = code [0] & AMD64_REX_R;
938 g_assert (code [0] == 0x49 + rex_r);
939 g_assert (code [1] == 0x8b);
940 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
942 emit_unset_mode (acfg);
943 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
946 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
947 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
948 *code_size = mono_arch_get_patch_offset (code) + 4;
950 #elif defined(TARGET_X86)
951 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
952 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
953 *code_size = mono_arch_get_patch_offset (code) + 4;
954 #elif defined(TARGET_ARM)
955 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
956 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
957 *code_size = mono_arch_get_patch_offset (code) + 4;
958 #elif defined(TARGET_ARM64)
959 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
960 arm64_emit_got_access (acfg, code, got_slot, code_size);
961 #elif defined(TARGET_POWERPC)
966 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
968 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
969 g_assert (code - buf == 8);
970 emit_bytes (acfg, buf, code - buf);
971 *code_size = code - buf;
974 g_assert_not_reached ();
980 #ifdef MONO_ARCH_AOT_SUPPORTED
982 * arch_emit_objc_selector_ref:
984 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
987 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
989 #if defined(TARGET_ARM)
992 int lindex = acfg->objc_selector_index_2 ++;
995 emit_bytes (acfg, code, 8);
997 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
998 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1000 emit_label (acfg, symbol1);
1001 mono_img_writer_emit_unset_mode (acfg->w);
1002 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1005 #elif defined(TARGET_ARM64)
1006 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1008 g_assert_not_reached ();
1014 * arch_emit_plt_entry:
1016 * Emit code for the PLT entry.
1017 * The plt entry should look like this:
1018 * <indirect jump to GOT_SYMBOL + OFFSET>
1019 * <INFO_OFFSET embedded into the instruction stream>
1022 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1024 #if defined(TARGET_X86)
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, info_offset);
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, info_offset);
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, got_symbol, ".", offset - 4);
1052 emit_unset_mode (acfg);
1053 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1055 /* Used by mono_aot_get_plt_info_offset */
1056 emit_int32 (acfg, info_offset);
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, got_symbol, ".", offset - 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, info_offset);
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, got_symbol, ".", offset - 4);
1088 /* Used by mono_aot_get_plt_info_offset */
1089 emit_int32 (acfg, info_offset);
1090 #elif defined(TARGET_ARM64)
1091 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1092 #elif defined(TARGET_POWERPC)
1093 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1094 g_assert (!acfg->use_bin_writer);
1095 emit_unset_mode (acfg);
1096 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1097 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1098 fprintf (acfg->fp, "add 11, 11, 30\n");
1099 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1100 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1101 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1102 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1104 fprintf (acfg->fp, "mtctr 11\n");
1105 fprintf (acfg->fp, "bctr\n");
1106 emit_int32 (acfg, info_offset);
1108 g_assert_not_reached ();
1113 * arch_emit_llvm_plt_entry:
1115 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1116 * This is only needed on arm to handle thumb interop.
1119 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1121 #if defined(TARGET_ARM)
1122 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1123 /* The caller already transitioned to thumb */
1124 /* The code below should be 12 bytes long */
1125 /* clang has trouble encoding these instructions, so emit the binary */
1127 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1128 /* thumb can't encode ld pc, [pc, ip] */
1129 fprintf (acfg->fp, "add ip, pc, ip\n");
1130 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1131 fprintf (acfg->fp, "bx ip\n");
1133 emit_set_thumb_mode (acfg);
1134 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1135 fprintf (acfg->fp, ".2byte 0x44fc\n");
1136 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1137 fprintf (acfg->fp, ".2byte 0x4760\n");
1138 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1139 emit_int32 (acfg, info_offset);
1140 emit_unset_mode (acfg);
1141 emit_set_arm_mode (acfg);
1143 g_assert_not_reached ();
1148 * arch_emit_specific_trampoline_pages:
1150 * Emits a page full of trampolines: each trampoline uses its own address to
1151 * lookup both the generic trampoline code and the data argument.
1152 * This page can be remapped in process multiple times so we can get an
1153 * unlimited number of trampolines.
1154 * Specifically this implementation uses the following trick: two memory pages
1155 * are allocated, with the first containing the data and the second containing the trampolines.
1156 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1157 * implementation does all the lifting.
1158 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1159 * on the arm 32 bit system.
1162 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1164 #if defined(TARGET_ARM)
1167 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1169 #define COMMON_TRAMP_SIZE 16
1170 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1171 int imm8, rot_amount;
1174 if (!acfg->aot_opts.use_trampolines_page)
1177 acfg->tramp_page_size = mono_pagesize ();
1179 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1180 emit_alignment (acfg, mono_pagesize ());
1181 emit_global (acfg, symbol, TRUE);
1182 emit_label (acfg, symbol);
1184 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1186 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1187 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1188 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1189 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1191 g_assert (code - buf == COMMON_TRAMP_SIZE);
1194 emit_bytes (acfg, buf, code - buf);
1196 for (i = 0; i < count; ++i) {
1198 ARM_PUSH (code, 0x5fff);
1200 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1201 g_assert (code - buf == 8);
1202 emit_bytes (acfg, buf, code - buf);
1205 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1206 * the instruction pointer address, so the generic trampoline at the start of the page
1207 * subtracts 4096 to get to the data page and loads the values
1208 * We again fit the generic trampiline in 16 bytes.
1210 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1211 emit_global (acfg, symbol, TRUE);
1212 emit_label (acfg, symbol);
1214 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1215 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1216 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1217 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1219 g_assert (code - buf == COMMON_TRAMP_SIZE);
1222 emit_bytes (acfg, buf, code - buf);
1224 for (i = 0; i < count; ++i) {
1226 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1228 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1229 g_assert (code - buf == 8);
1230 emit_bytes (acfg, buf, code - buf);
1234 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1236 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1237 emit_global (acfg, symbol, TRUE);
1238 emit_label (acfg, symbol);
1240 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1241 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1242 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1243 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1244 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1245 g_assert (code - buf == COMMON_TRAMP_SIZE);
1247 emit_bytes (acfg, buf, code - buf);
1249 for (i = 0; i < count; ++i) {
1251 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1253 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1254 g_assert (code - buf == 8);
1255 emit_bytes (acfg, buf, code - buf);
1258 /* now the imt trampolines: each specific trampolines puts in the ip register
1259 * the instruction pointer address, so the generic trampoline at the start of the page
1260 * subtracts 4096 to get to the data page and loads the values
1261 * We again fit the generic trampiline in 16 bytes.
1263 #define IMT_TRAMP_SIZE 72
1264 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1265 emit_global (acfg, symbol, TRUE);
1266 emit_label (acfg, symbol);
1268 /* Need at least two free registers, plus a slot for storing the pc */
1269 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1271 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1272 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1273 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1275 /* The IMT method is in v5, r0 has the imt array address */
1278 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1279 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1280 imt_found_check = code;
1281 ARM_B_COND (code, ARMCOND_EQ, 0);
1283 /* End-of-loop check */
1284 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1285 loop_end_check = code;
1286 ARM_B_COND (code, ARMCOND_EQ, 0);
1289 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1290 loop_branch_back = code;
1292 arm_patch (loop_branch_back, loop_start);
1295 arm_patch (imt_found_check, code);
1296 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1297 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1298 /* Save it to the third stack slot */
1299 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1300 /* Restore the registers and branch */
1301 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1304 arm_patch (loop_end_check, code);
1305 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1306 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1307 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1311 g_assert (code - buf == IMT_TRAMP_SIZE);
1312 emit_bytes (acfg, buf, code - buf);
1314 for (i = 0; i < count; ++i) {
1316 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1318 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1319 g_assert (code - buf == 8);
1320 emit_bytes (acfg, buf, code - buf);
1323 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1324 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1325 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1326 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1327 #elif defined(TARGET_ARM64)
1328 arm64_emit_specific_trampoline_pages (acfg);
1333 * arch_emit_specific_trampoline:
1335 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1336 * two GOT slots which contain the generic trampoline address and the trampoline
1337 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1340 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1343 * The trampolines created here are variations of the specific
1344 * trampolines created in mono_arch_create_specific_trampoline (). The
1346 * - the generic trampoline address is taken from a got slot.
1347 * - the offset of the got slot where the trampoline argument is stored
1348 * is embedded in the instruction stream, and the generic trampoline
1349 * can load the argument by loading the offset, adding it to the
1350 * address of the trampoline to get the address of the got slot, and
1351 * loading the argument from there.
1352 * - all the trampolines should be of the same length.
1354 #if defined(TARGET_AMD64)
1355 #if defined(__default_codegen__)
1356 /* This should be exactly 8 bytes long */
1358 /* call *<offset>(%rip) */
1360 emit_unset_mode (acfg);
1361 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1362 emit_zero_bytes (acfg, 2);
1364 emit_byte (acfg, '\x41');
1365 emit_byte (acfg, '\xff');
1366 emit_byte (acfg, '\x15');
1367 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1368 emit_zero_bytes (acfg, 1);
1370 #elif defined(__native_client_codegen__)
1372 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1373 guint8 *code = buf_aligned;
1378 /* Emit this call in 'code' so we can find out how long it is. */
1379 amd64_call_reg (code, AMD64_R11);
1380 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1381 call_len = code - call_start;
1383 /* The tramp_size is twice the NaCl alignment because it starts with */
1384 /* a call which needs to be aligned to the end of the boundary. */
1385 *tramp_size = kNaClAlignment*2;
1387 /* Emit nops to align call site below which is 7 bytes plus */
1388 /* the length of the call sequence emitted above. */
1389 /* Note: this requires the specific trampoline starts on a */
1390 /* kNaclAlignedment aligned address, which it does because */
1391 /* it's its own function that is aligned. */
1392 guint8 nop_buf[256];
1393 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1394 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1395 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1397 /* The trampoline is stored at the offset'th pointer, the -4 is */
1398 /* present because RIP relative addressing starts at the end of */
1399 /* the current instruction, while the label "." is relative to */
1400 /* the beginning of the current asm location, which in this case */
1401 /* is not the mov instruction, but the offset itself, due to the */
1402 /* way the bytes and ints are emitted here. */
1403 got_offset = (offset * sizeof(gpointer)) - 4;
1405 /* mov <OFFSET>(%rip), %r11d */
1406 emit_byte (acfg, '\x45');
1407 emit_byte (acfg, '\x8b');
1408 emit_byte (acfg, '\x1d');
1409 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1412 emit_bytes (acfg, call_start, call_len);
1414 /* The arg is stored at the offset+1 pointer, relative to beginning */
1415 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1416 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1418 /* We can't emit this data directly, hide in a "push imm32" */
1419 emit_byte (acfg, '\x68'); /* push */
1420 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1421 emit_alignment (acfg, kNaClAlignment);
1422 #endif /*__native_client_codegen__*/
1423 #elif defined(TARGET_ARM)
1427 /* This should be exactly 20 bytes long */
1430 ARM_PUSH (code, 0x5fff);
1431 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1432 /* Load the value from the GOT */
1433 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1435 ARM_BLX_REG (code, ARMREG_R1);
1437 g_assert (code - buf == 16);
1440 emit_bytes (acfg, buf, code - buf);
1442 * Only one offset is needed, since the second one would be equal to the
1445 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1446 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1447 #elif defined(TARGET_ARM64)
1448 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1449 #elif defined(TARGET_POWERPC)
1456 g_assert (!acfg->use_bin_writer);
1459 * PPC has no ip relative addressing, so we need to compute the address
1460 * of the mscorlib got. That is slow and complex, so instead, we store it
1461 * in the second got slot of every aot image. The caller already computed
1462 * the address of its got and placed it into r30.
1464 emit_unset_mode (acfg);
1465 /* Load mscorlib got address */
1466 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1467 /* Load generic trampoline address */
1468 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1469 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1470 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1471 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1472 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1474 fprintf (acfg->fp, "mtctr 11\n");
1475 /* Load trampoline argument */
1476 /* On ppc, we pass it normally to the generic trampoline */
1477 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1478 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1479 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1480 /* Branch to generic trampoline */
1481 fprintf (acfg->fp, "bctr\n");
1483 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1484 *tramp_size = 10 * 4;
1486 *tramp_size = 9 * 4;
1488 #elif defined(TARGET_X86)
1492 /* Similar to the PPC code above */
1494 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1496 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1497 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1498 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1499 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1500 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1505 /* Load mscorlib got address */
1506 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1507 /* Push trampoline argument */
1508 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1509 /* Load generic trampoline address */
1510 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1511 /* Branch to generic trampoline */
1512 x86_jump_reg (code, X86_ECX);
1514 #ifdef __native_client_codegen__
1516 /* emit nops to next 32 byte alignment */
1517 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1518 while (code < (buf + a)) x86_nop(code);
1521 emit_bytes (acfg, buf, code - buf);
1523 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1524 g_assert (code - buf == *tramp_size);
1526 g_assert_not_reached ();
1531 * arch_emit_unbox_trampoline:
1533 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1534 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1537 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1539 #if defined(TARGET_AMD64)
1544 this_reg = mono_arch_get_this_arg_reg (NULL);
1546 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1548 emit_bytes (acfg, buf, code - buf);
1551 emit_unset_mode (acfg);
1552 fprintf (acfg->fp, "jmp %s\n", call_target);
1554 emit_byte (acfg, '\xe9');
1555 emit_symbol_diff (acfg, call_target, ".", -4);
1557 #elif defined(TARGET_X86)
1564 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1566 emit_bytes (acfg, buf, code - buf);
1569 emit_byte (acfg, '\xe9');
1570 emit_symbol_diff (acfg, call_target, ".", -4);
1571 #elif defined(TARGET_ARM)
1575 if (acfg->thumb_mixed && cfg->compile_llvm) {
1576 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1577 fprintf (acfg->fp, "b %s\n", call_target);
1578 fprintf (acfg->fp, ".arm\n");
1579 fprintf (acfg->fp, ".align 2\n");
1585 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1587 emit_bytes (acfg, buf, code - buf);
1588 /* jump to method */
1589 if (acfg->use_bin_writer) {
1596 mono_img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1597 emit_bytes (acfg, buf, 4);
1599 if (acfg->thumb_mixed && cfg->compile_llvm)
1600 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1602 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1604 #elif defined(TARGET_ARM64)
1605 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1606 #elif defined(TARGET_POWERPC)
1609 g_assert (!acfg->use_bin_writer);
1611 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1612 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1614 g_assert_not_reached ();
1619 * arch_emit_static_rgctx_trampoline:
1621 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1622 * two GOT slots which contain the rgctx argument, and the method to jump to.
1623 * TRAMP_SIZE is set to the size of the emitted trampoline.
1624 * These kinds of trampolines cannot be enumerated statically, since there could
1625 * be one trampoline per method instantiation, so we emit the same code for all
1626 * trampolines, and parameterize them using two GOT slots.
1629 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1631 #if defined(TARGET_AMD64)
1632 #if defined(__default_codegen__)
1633 /* This should be exactly 13 bytes long */
1637 emit_unset_mode (acfg);
1638 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1639 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1641 /* mov <OFFSET>(%rip), %r10 */
1642 emit_byte (acfg, '\x4d');
1643 emit_byte (acfg, '\x8b');
1644 emit_byte (acfg, '\x15');
1645 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1647 /* jmp *<offset>(%rip) */
1648 emit_byte (acfg, '\xff');
1649 emit_byte (acfg, '\x25');
1650 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1652 #elif defined(__native_client_codegen__)
1654 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1655 guint8 *code = buf_aligned;
1657 /* mov <OFFSET>(%rip), %r10d */
1658 emit_byte (acfg, '\x45');
1659 emit_byte (acfg, '\x8b');
1660 emit_byte (acfg, '\x15');
1661 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1663 /* mov <OFFSET>(%rip), %r11d */
1664 emit_byte (acfg, '\x45');
1665 emit_byte (acfg, '\x8b');
1666 emit_byte (acfg, '\x1d');
1667 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1670 amd64_jump_reg (code, AMD64_R11);
1671 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1673 emit_alignment (acfg, kNaClAlignment);
1674 *tramp_size = kNaClAlignment;
1675 #endif /*__native_client_codegen__*/
1677 #elif defined(TARGET_ARM)
1681 /* This should be exactly 24 bytes long */
1684 /* Load rgctx value */
1685 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1686 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1687 /* Load branch addr + branch */
1688 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1689 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1691 g_assert (code - buf == 16);
1694 emit_bytes (acfg, buf, code - buf);
1695 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1696 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1697 #elif defined(TARGET_ARM64)
1698 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1699 #elif defined(TARGET_POWERPC)
1706 g_assert (!acfg->use_bin_writer);
1709 * PPC has no ip relative addressing, so we need to compute the address
1710 * of the mscorlib got. That is slow and complex, so instead, we store it
1711 * in the second got slot of every aot image. The caller already computed
1712 * the address of its got and placed it into r30.
1714 emit_unset_mode (acfg);
1715 /* Load mscorlib got address */
1716 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1718 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1719 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1720 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1721 /* Load target address */
1722 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1723 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1724 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1725 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1726 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1727 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1729 fprintf (acfg->fp, "mtctr 11\n");
1730 /* Branch to the target address */
1731 fprintf (acfg->fp, "bctr\n");
1733 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1734 *tramp_size = 11 * 4;
1736 *tramp_size = 9 * 4;
1739 #elif defined(TARGET_X86)
1743 /* Similar to the PPC code above */
1745 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1748 /* Load mscorlib got address */
1749 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1751 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1752 /* Branch to the target address */
1753 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1755 #ifdef __native_client_codegen__
1757 /* emit nops to next 32 byte alignment */
1758 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1759 while (code < (buf + a)) x86_nop(code);
1763 emit_bytes (acfg, buf, code - buf);
1765 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1766 g_assert (code - buf == *tramp_size);
1768 g_assert_not_reached ();
1773 * arch_emit_imt_thunk:
1775 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1776 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1777 * key is the IMT key, and ptr holds the address of a memory location holding
1778 * the address to branch to if the IMT arg matches the key. The array is
1779 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1781 * TRAMP_SIZE is set to the size of the emitted trampoline.
1784 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1786 #if defined(TARGET_AMD64)
1788 #if defined(__native_client_codegen__)
1791 guint8 *labels [16];
1793 guint8 *mov_buf_ptr = mov_buf;
1795 const int kSizeOfMove = 7;
1796 #if defined(__default_codegen__)
1797 code = buf = g_malloc (256);
1798 #elif defined(__native_client_codegen__)
1799 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1800 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1801 /* The RIP relative move below is emitted first */
1806 /* FIXME: Optimize this, i.e. use binary search etc. */
1807 /* Maybe move the body into a separate function (slower, but much smaller) */
1809 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1812 emit_unset_mode (acfg);
1813 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1817 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1819 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1822 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1824 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1827 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1828 amd64_jump_code (code, labels [0]);
1831 mono_amd64_patch (labels [2], code);
1832 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1833 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1836 mono_amd64_patch (labels [1], code);
1837 /* Load fail tramp */
1838 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1839 /* Check if there is a fail tramp */
1840 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1842 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1843 /* Jump to fail tramp */
1844 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1847 mono_amd64_patch (labels [3], code);
1848 x86_breakpoint (code);
1851 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1852 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1853 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1854 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1855 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1856 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1858 emit_bytes (acfg, buf, code - buf);
1860 *tramp_size = code - buf + kSizeOfMove;
1861 #if defined(__native_client_codegen__)
1862 /* The tramp will be padded to the next kNaClAlignment bundle. */
1863 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1866 #if defined(__default_codegen__)
1868 #elif defined(__native_client_codegen__)
1872 #elif defined(TARGET_X86)
1874 #ifdef __native_client_codegen__
1877 guint8 *labels [16];
1879 #if defined(__default_codegen__)
1880 code = buf = g_malloc (256);
1881 #elif defined(__native_client_codegen__)
1882 buf_alloc = g_malloc (256 + kNaClAlignment);
1883 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1886 /* Allocate a temporary stack slot */
1887 x86_push_reg (code, X86_EAX);
1889 x86_push_reg (code, X86_EAX);
1891 /* Load mscorlib got address */
1892 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1894 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1897 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1899 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1902 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1904 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1907 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1908 x86_jump_code (code, labels [0]);
1911 mono_x86_patch (labels [2], code);
1912 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1913 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1914 /* Save the target address to the temporary stack location */
1915 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1917 x86_pop_reg (code, X86_EAX);
1918 /* Jump to the target address */
1922 mono_x86_patch (labels [1], code);
1923 /* Load fail tramp */
1924 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1925 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1927 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1928 /* Jump to fail tramp */
1929 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1930 x86_pop_reg (code, X86_EAX);
1934 mono_x86_patch (labels [3], code);
1935 x86_breakpoint (code);
1937 #ifdef __native_client_codegen__
1939 /* emit nops to next 32 byte alignment */
1940 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1941 while (code < (buf + a)) x86_nop(code);
1944 emit_bytes (acfg, buf, code - buf);
1946 *tramp_size = code - buf;
1948 #if defined(__default_codegen__)
1950 #elif defined(__native_client_codegen__)
1954 #elif defined(TARGET_ARM)
1956 guint8 *code, *code2, *labels [16];
1960 /* The IMT method is in v5 */
1962 /* Need at least two free registers, plus a slot for storing the pc */
1963 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1965 /* Load the parameter from the GOT */
1966 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1967 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1970 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1971 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1973 ARM_B_COND (code, ARMCOND_EQ, 0);
1975 /* End-of-loop check */
1976 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1978 ARM_B_COND (code, ARMCOND_EQ, 0);
1981 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1984 arm_patch (labels [4], labels [1]);
1987 arm_patch (labels [2], code);
1988 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1989 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1990 /* Save it to the third stack slot */
1991 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1992 /* Restore the registers and branch */
1993 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1996 arm_patch (labels [3], code);
1997 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1998 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1999 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2003 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2005 emit_bytes (acfg, buf, code - buf);
2006 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2008 *tramp_size = code - buf + 4;
2009 #elif defined(TARGET_ARM64)
2010 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2011 #elif defined(TARGET_POWERPC)
2013 guint8 *code, *labels [16];
2017 /* Load the mscorlib got address */
2018 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2019 /* Load the parameter from the GOT */
2020 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2021 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2023 /* Load and check key */
2025 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2026 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2028 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2030 /* End-of-loop check */
2031 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2033 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2036 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2039 mono_ppc_patch (labels [4], labels [1]);
2042 mono_ppc_patch (labels [2], code);
2043 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2044 /* r12 now contains the value of the vtable slot */
2045 /* this is not a function descriptor on ppc64 */
2046 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2047 ppc_mtctr (code, ppc_r12);
2048 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2051 mono_ppc_patch (labels [3], code);
2055 *tramp_size = code - buf;
2057 emit_bytes (acfg, buf, code - buf);
2059 g_assert_not_reached ();
2064 * arch_emit_gsharedvt_arg_trampoline:
2066 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2067 * two GOT slots which contain the argument, and the code to jump to.
2068 * TRAMP_SIZE is set to the size of the emitted trampoline.
2069 * These kinds of trampolines cannot be enumerated statically, since there could
2070 * be one trampoline per method instantiation, so we emit the same code for all
2071 * trampolines, and parameterize them using two GOT slots.
2074 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2076 #if defined(TARGET_X86)
2080 /* Similar to the PPC code above */
2082 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2085 /* Load mscorlib got address */
2086 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2088 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2089 /* Branch to the target address */
2090 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2092 #ifdef __native_client_codegen__
2094 /* emit nops to next 32 byte alignment */
2095 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2096 while (code < (buf + a)) x86_nop(code);
2100 emit_bytes (acfg, buf, code - buf);
2102 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2103 g_assert (code - buf == *tramp_size);
2104 #elif defined(TARGET_ARM)
2108 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2109 /* Similar to arch_emit_specific_trampoline () */
2112 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2113 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2114 /* Load the arg value from the GOT */
2115 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2116 /* Load the addr from the GOT */
2117 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2119 ARM_BX (code, ARMREG_R1);
2121 g_assert (code - buf == 20);
2124 emit_bytes (acfg, buf, code - buf);
2125 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2126 #elif defined(TARGET_ARM64)
2127 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2129 g_assert_not_reached ();
2134 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2136 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2137 /* Based on code generated by gcc */
2138 emit_unset_mode (acfg);
2141 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2142 ".section .ctors,\"aw\",@progbits\n"
2146 ".section .opd,\"aw\"\n"
2149 ".long .%s,.TOC.@tocbase32\n"
2152 ".type .%s,@function\n"
2154 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2156 ".section .ctors,\"aw\",@progbits\n"
2160 ".section .opd,\"aw\"\n"
2163 ".long .%1$s,.TOC.@tocbase32\n"
2164 ".size %1$s,.-%1$s\n"
2166 ".type .%1$s,@function\n"
2168 ".%1$s:\n", symbol);
2179 "lis 3, .Lglobals@h\n"
2180 "ori 3, 3, .Lglobals@l\n"
2181 "bl .mono_aot_register_module\n"
2189 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2191 ".size .%s,.-.%s\n", symbol, symbol);
2194 ".size .%1$s,.-.%1$s\n", symbol);
2200 /* END OF ARCH SPECIFIC CODE */
2203 mono_get_field_token (MonoClassField *field)
2205 MonoClass *klass = field->parent;
2208 for (i = 0; i < klass->field.count; ++i) {
2209 if (field == &klass->fields [i])
2210 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2213 g_assert_not_reached ();
2218 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2222 //printf ("ENCODE: %d 0x%x.\n", value, value);
2225 * Same encoding as the one used in the metadata, extended to handle values
2226 * greater than 0x1fffffff.
2228 if ((value >= 0) && (value <= 127))
2230 else if ((value >= 0) && (value <= 16383)) {
2231 p [0] = 0x80 | (value >> 8);
2232 p [1] = value & 0xff;
2234 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2235 p [0] = (value >> 24) | 0xc0;
2236 p [1] = (value >> 16) & 0xff;
2237 p [2] = (value >> 8) & 0xff;
2238 p [3] = value & 0xff;
2243 p [1] = (value >> 24) & 0xff;
2244 p [2] = (value >> 16) & 0xff;
2245 p [3] = (value >> 8) & 0xff;
2246 p [4] = value & 0xff;
2254 stream_init (MonoDynamicStream *sh)
2257 sh->alloc_size = 4096;
2258 sh->data = g_malloc (4096);
2260 /* So offsets are > 0 */
2266 make_room_in_stream (MonoDynamicStream *stream, int size)
2268 if (size <= stream->alloc_size)
2271 while (stream->alloc_size <= size) {
2272 if (stream->alloc_size < 4096)
2273 stream->alloc_size = 4096;
2275 stream->alloc_size *= 2;
2278 stream->data = g_realloc (stream->data, stream->alloc_size);
2282 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2286 make_room_in_stream (stream, stream->index + len);
2287 memcpy (stream->data + stream->index, data, len);
2288 idx = stream->index;
2289 stream->index += len;
2296 * Add data to the binary blob inside the aot image. Returns the offset inside the
2297 * blob where the data was stored.
2300 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2302 if (acfg->blob.alloc_size == 0)
2303 stream_init (&acfg->blob);
2305 return add_stream_data (&acfg->blob, (char*)data, data_len);
2309 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2314 if (acfg->blob.alloc_size == 0)
2315 stream_init (&acfg->blob);
2317 count = acfg->blob.index % align;
2319 /* we assume the stream data will be aligned */
2321 add_stream_data (&acfg->blob, buf, 4 - count);
2323 return add_stream_data (&acfg->blob, (char*)data, data_len);
2327 * emit_offset_table:
2329 * Emit a table of increasing offsets in a compact form using differential encoding.
2330 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2331 * group size, the more compact the table becomes, but the slower it becomes to compute
2332 * a given entry. Returns the size of the table.
2335 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2337 gint32 current_offset;
2338 int i, buf_size, ngroups, index_entry_size;
2340 guint32 *index_offsets;
2342 ngroups = (noffsets + (group_size - 1)) / group_size;
2344 index_offsets = g_new0 (guint32, ngroups);
2346 buf_size = noffsets * 4;
2347 p = buf = g_malloc0 (buf_size);
2350 for (i = 0; i < noffsets; ++i) {
2351 //printf ("D: %d -> %d\n", i, offsets [i]);
2352 if ((i % group_size) == 0) {
2353 index_offsets [i / group_size] = p - buf;
2354 /* Emit the full value for these entries */
2355 encode_value (offsets [i], p, &p);
2357 /* The offsets are allowed to be non-increasing */
2358 //g_assert (offsets [i] >= current_offset);
2359 encode_value (offsets [i] - current_offset, p, &p);
2361 current_offset = offsets [i];
2364 if (ngroups && index_offsets [ngroups - 1] < 65000)
2365 index_entry_size = 2;
2367 index_entry_size = 4;
2369 /* Emit the header */
2370 emit_int32 (acfg, noffsets);
2371 emit_int32 (acfg, group_size);
2372 emit_int32 (acfg, ngroups);
2373 emit_int32 (acfg, index_entry_size);
2375 /* Emit the index */
2376 for (i = 0; i < ngroups; ++i) {
2377 if (index_entry_size == 2)
2378 emit_int16 (acfg, index_offsets [i]);
2380 emit_int32 (acfg, index_offsets [i]);
2384 emit_bytes (acfg, buf, p - buf);
2386 return (int)(p - buf) + (ngroups * 4);
2390 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2394 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2398 index = g_hash_table_size (cfg->image_hash);
2399 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2400 g_ptr_array_add (cfg->image_table, image);
2406 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2409 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2411 /* FIXME: Search referenced images as well */
2412 if (!acfg->typespec_classes) {
2413 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2414 for (i = 0; i < len; ++i) {
2416 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2417 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2420 for (i = 0; i < len; ++i) {
2421 if (acfg->typespec_classes [i] == klass)
2426 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2432 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2435 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2438 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2441 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2444 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2449 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2453 if (klass->generic_class) {
2455 g_assert (klass->type_token);
2457 /* Find a typespec for a class if possible */
2458 token = find_typespec_for_class (acfg, klass);
2460 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2461 encode_value (token, p, &p);
2463 MonoClass *gclass = klass->generic_class->container_class;
2464 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2465 static int count = 0;
2468 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2469 encode_klass_ref (acfg, gclass, p, &p);
2470 encode_ginst (acfg, inst, p, &p);
2474 } else if (klass->type_token) {
2475 int iindex = get_image_index (acfg, klass->image);
2477 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2479 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2480 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2482 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2483 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2484 encode_value (get_image_index (acfg, klass->image), p, &p);
2486 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2487 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2488 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2490 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2491 encode_value (klass->byval_arg.type, p, &p);
2492 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2494 encode_value (container ? 1 : 0, p, &p);
2496 encode_value (container->is_method, p, &p);
2497 g_assert (!par->gshared_constraint);
2498 if (container->is_method)
2499 encode_method_ref (acfg, container->owner.method, p, &p);
2501 encode_klass_ref (acfg, container->owner.klass, p, &p);
2503 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2504 if (par->gshared_constraint) {
2507 encode_type (acfg, par->gshared_constraint, p, &p);
2509 name = mono_generic_param_name (par);
2511 int len = strlen (name);
2513 encode_value (len, p, &p);
2514 memcpy (p, name, len);
2517 encode_value (0, p, &p);
2521 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2522 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2523 encode_type (acfg, &klass->byval_arg, p, &p);
2526 g_assert (klass->rank > 0);
2527 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2528 encode_value (klass->rank, p, &p);
2529 encode_klass_ref (acfg, klass->element_class, p, &p);
2537 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2538 * standard metadata encoding.
2541 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2543 gboolean shared = FALSE;
2546 * The encoding of generic instances is large so emit them only once.
2548 if (klass->generic_class) {
2550 g_assert (klass->type_token);
2552 /* Find a typespec for a class if possible */
2553 token = find_typespec_for_class (acfg, klass);
2556 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2561 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2565 buf2 = g_malloc (1024);
2568 encode_klass_ref_inner (acfg, klass, p, &p);
2569 g_assert (p - buf2 < 1024);
2571 offset = add_to_blob (acfg, buf2, p - buf2);
2574 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2580 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2581 encode_value (offset, p, &p);
2586 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2590 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2592 guint32 token = mono_get_field_token (field);
2595 encode_klass_ref (cfg, field->parent, p, &p);
2596 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2597 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2602 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2607 encode_value (inst->type_argc, p, &p);
2608 for (i = 0; i < inst->type_argc; ++i)
2609 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2614 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2617 MonoGenericInst *inst;
2619 inst = context->class_inst;
2621 g_assert (inst->type_argc);
2622 encode_ginst (acfg, inst, p, &p);
2624 encode_value (0, p, &p);
2626 inst = context->method_inst;
2628 g_assert (inst->type_argc);
2629 encode_ginst (acfg, inst, p, &p);
2631 encode_value (0, p, &p);
2637 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2641 g_assert (t->num_mods == 0);
2642 /* t->attrs can be ignored */
2643 //g_assert (t->attrs == 0);
2646 *p = MONO_TYPE_PINNED;
2650 *p = MONO_TYPE_BYREF;
2658 case MONO_TYPE_VOID:
2659 case MONO_TYPE_BOOLEAN:
2660 case MONO_TYPE_CHAR:
2673 case MONO_TYPE_STRING:
2674 case MONO_TYPE_OBJECT:
2675 case MONO_TYPE_TYPEDBYREF:
2677 case MONO_TYPE_VALUETYPE:
2678 case MONO_TYPE_CLASS:
2679 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2681 case MONO_TYPE_SZARRAY:
2682 encode_klass_ref (acfg, t->data.klass, p, &p);
2685 encode_type (acfg, t->data.type, p, &p);
2687 case MONO_TYPE_GENERICINST: {
2688 MonoClass *gclass = t->data.generic_class->container_class;
2689 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2691 encode_klass_ref (acfg, gclass, p, &p);
2692 encode_ginst (acfg, inst, p, &p);
2695 case MONO_TYPE_ARRAY: {
2696 MonoArrayType *array = t->data.array;
2699 encode_klass_ref (acfg, array->eklass, p, &p);
2700 encode_value (array->rank, p, &p);
2701 encode_value (array->numsizes, p, &p);
2702 for (i = 0; i < array->numsizes; ++i)
2703 encode_value (array->sizes [i], p, &p);
2704 encode_value (array->numlobounds, p, &p);
2705 for (i = 0; i < array->numlobounds; ++i)
2706 encode_value (array->lobounds [i], p, &p);
2710 case MONO_TYPE_MVAR:
2711 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2714 g_assert_not_reached ();
2721 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2727 /* Similar to the metadata encoding */
2728 if (sig->generic_param_count)
2732 if (sig->explicit_this)
2734 flags |= (sig->call_convention & 0x0F);
2738 if (sig->generic_param_count)
2739 encode_value (sig->generic_param_count, p, &p);
2740 encode_value (sig->param_count, p, &p);
2742 encode_type (acfg, sig->ret, p, &p);
2743 for (i = 0; i < sig->param_count; ++i) {
2744 if (sig->sentinelpos == i) {
2745 *p = MONO_TYPE_SENTINEL;
2748 encode_type (acfg, sig->params [i], p, &p);
2754 #define MAX_IMAGE_INDEX 250
2757 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2759 guint32 image_index = get_image_index (acfg, method->klass->image);
2760 guint32 token = method->token;
2761 MonoJumpInfoToken *ji;
2765 * The encoding for most methods is as follows:
2766 * - image index encoded as a leb128
2767 * - token index encoded as a leb128
2768 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2769 * types of method encodings.
2772 /* Mark methods which can't use aot trampolines because they need the further
2773 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2775 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2776 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2777 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2779 if (method->wrapper_type) {
2780 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2782 encode_value (method->wrapper_type, p, &p);
2784 switch (method->wrapper_type) {
2785 case MONO_WRAPPER_REMOTING_INVOKE:
2786 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2787 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2790 m = mono_marshal_method_from_wrapper (method);
2792 encode_method_ref (acfg, m, p, &p);
2795 case MONO_WRAPPER_PROXY_ISINST:
2796 case MONO_WRAPPER_LDFLD:
2797 case MONO_WRAPPER_LDFLDA:
2798 case MONO_WRAPPER_STFLD:
2799 case MONO_WRAPPER_ISINST: {
2800 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2803 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2806 case MONO_WRAPPER_LDFLD_REMOTE:
2807 case MONO_WRAPPER_STFLD_REMOTE:
2809 case MONO_WRAPPER_ALLOC: {
2810 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2812 /* The GC name is saved once in MonoAotFileInfo */
2813 g_assert (info->alloc_type != -1);
2814 encode_value (info->alloc_type, p, &p);
2817 case MONO_WRAPPER_WRITE_BARRIER:
2819 case MONO_WRAPPER_STELEMREF: {
2820 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2823 encode_value (info->subtype, p, &p);
2824 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2825 encode_value (info->d.virtual_stelemref.kind, p, &p);
2828 case MONO_WRAPPER_UNKNOWN: {
2829 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2832 encode_value (info->subtype, p, &p);
2833 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2834 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2835 encode_klass_ref (acfg, method->klass, p, &p);
2836 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2837 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2838 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2839 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2842 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2843 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2846 encode_value (info->subtype, p, &p);
2847 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2848 strcpy ((char*)p, method->name);
2849 p += strlen (method->name) + 1;
2850 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2851 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2853 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2854 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2858 case MONO_WRAPPER_SYNCHRONIZED: {
2861 m = mono_marshal_method_from_wrapper (method);
2863 g_assert (m != method);
2864 encode_method_ref (acfg, m, p, &p);
2867 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2868 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2871 encode_value (info->subtype, p, &p);
2873 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2874 encode_value (info->d.element_addr.rank, p, &p);
2875 encode_value (info->d.element_addr.elem_size, p, &p);
2876 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2877 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2879 g_assert_not_reached ();
2883 case MONO_WRAPPER_CASTCLASS: {
2884 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2887 encode_value (info->subtype, p, &p);
2890 case MONO_WRAPPER_RUNTIME_INVOKE: {
2891 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2894 encode_value (info->subtype, p, &p);
2895 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2896 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2897 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2898 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2901 case MONO_WRAPPER_DELEGATE_INVOKE:
2902 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2903 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2904 if (method->is_inflated) {
2905 /* These wrappers are identified by their class */
2906 encode_value (1, p, &p);
2907 encode_klass_ref (acfg, method->klass, p, &p);
2909 MonoMethodSignature *sig = mono_method_signature (method);
2910 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2912 encode_value (0, p, &p);
2913 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2914 encode_value (info ? info->subtype : 0, p, &p);
2915 encode_signature (acfg, sig, p, &p);
2919 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2920 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2923 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2924 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2928 g_assert_not_reached ();
2930 } else if (mono_method_signature (method)->is_inflated) {
2932 * This is a generic method, find the original token which referenced it and
2934 * Obtain the token from information recorded by the JIT.
2936 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2938 image_index = get_image_index (acfg, ji->image);
2939 g_assert (image_index < MAX_IMAGE_INDEX);
2942 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2943 encode_value (image_index, p, &p);
2944 encode_value (token, p, &p);
2946 MonoMethod *declaring;
2947 MonoGenericContext *context = mono_method_get_context (method);
2949 g_assert (method->is_inflated);
2950 declaring = ((MonoMethodInflated*)method)->declaring;
2953 * This might be a non-generic method of a generic instance, which
2954 * doesn't have a token since the reference is generated by the JIT
2955 * like Nullable:Box/Unbox, or by generic sharing.
2957 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2958 /* Encode the klass */
2959 encode_klass_ref (acfg, method->klass, p, &p);
2960 /* Encode the method */
2961 image_index = get_image_index (acfg, method->klass->image);
2962 g_assert (image_index < MAX_IMAGE_INDEX);
2963 g_assert (declaring->token);
2964 token = declaring->token;
2965 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2966 encode_value (image_index, p, &p);
2967 encode_value (token, p, &p);
2968 encode_generic_context (acfg, context, p, &p);
2970 } else if (token == 0) {
2971 /* This might be a method of a constructed type like int[,].Set */
2972 /* Obtain the token from information recorded by the JIT */
2973 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2975 image_index = get_image_index (acfg, ji->image);
2976 g_assert (image_index < MAX_IMAGE_INDEX);
2979 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2980 encode_value (image_index, p, &p);
2981 encode_value (token, p, &p);
2984 g_assert (method->klass->rank);
2986 /* Encode directly */
2987 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2988 encode_klass_ref (acfg, method->klass, p, &p);
2989 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2990 encode_value (0, p, &p);
2991 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2992 encode_value (1, p, &p);
2993 else if (!strcmp (method->name, "Get"))
2994 encode_value (2, p, &p);
2995 else if (!strcmp (method->name, "Address"))
2996 encode_value (3, p, &p);
2997 else if (!strcmp (method->name, "Set"))
2998 encode_value (4, p, &p);
3000 g_assert_not_reached ();
3003 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3005 if (image_index >= MONO_AOT_METHODREF_MIN) {
3006 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3007 encode_value (image_index, p, &p);
3008 encode_value (mono_metadata_token_index (token), p, &p);
3010 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3017 compare_patches (gconstpointer a, gconstpointer b)
3021 i = (*(MonoJumpInfo**)a)->ip.i;
3022 j = (*(MonoJumpInfo**)b)->ip.i;
3033 static G_GNUC_UNUSED char*
3034 patch_to_string (MonoJumpInfo *patch_info)
3038 str = g_string_new ("");
3040 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3042 switch (patch_info->type) {
3043 case MONO_PATCH_INFO_VTABLE:
3044 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3049 g_string_append_printf (str, ")");
3050 return g_string_free (str, FALSE);
3056 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3059 static inline gboolean
3060 is_plt_patch (MonoJumpInfo *patch_info)
3062 switch (patch_info->type) {
3063 case MONO_PATCH_INFO_METHOD:
3064 case MONO_PATCH_INFO_INTERNAL_METHOD:
3065 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3066 case MONO_PATCH_INFO_ICALL_ADDR:
3067 case MONO_PATCH_INFO_CLASS_INIT:
3068 case MONO_PATCH_INFO_RGCTX_FETCH:
3069 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3070 case MONO_PATCH_INFO_MONITOR_ENTER:
3071 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3072 case MONO_PATCH_INFO_MONITOR_EXIT:
3073 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3083 * Return the symbol identifying the plt entry PLT_OFFSET.
3086 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3090 * The Apple linker reorganizes object files, so it doesn't like branches to local
3091 * labels, since those have no relocations.
3093 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3095 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3102 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3104 static MonoPltEntry*
3105 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3108 gboolean synchronized = FALSE;
3109 static int synchronized_symbol_idx;
3111 if (!is_plt_patch (patch_info))
3114 if (!acfg->patch_to_plt_entry [patch_info->type])
3115 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3116 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3118 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3120 * Allocate a separate PLT slot for each such patch, since some plt
3121 * entries will refer to the method itself, and some will refer to the
3125 synchronized = TRUE;
3129 MonoJumpInfo *new_ji;
3131 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3133 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3134 res->plt_offset = acfg->plt_offset;
3136 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3137 if (acfg->aot_opts.write_symbols)
3138 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3140 /* Avoid duplicate symbols because we don't cache */
3141 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3143 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3144 synchronized_symbol_idx ++;
3147 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3149 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3151 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3153 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3155 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3156 //mono_print_ji (patch_info); printf ("\n");
3157 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3159 acfg->plt_offset ++;
3168 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3169 * JI could be found if it exists, otherwise allocates a new one.
3172 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3175 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3177 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3179 return got_offset - 1;
3182 got_offset = acfg->llvm_got_offset;
3183 acfg->llvm_got_offset ++;
3185 got_offset = acfg->got_offset;
3186 acfg->got_offset ++;
3189 acfg->stats.got_slots ++;
3190 acfg->stats.got_slot_types [ji->type] ++;
3192 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3193 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3194 g_ptr_array_add (info->got_patches, ji);
3199 /* Add a method to the list of methods which need to be emitted */
3201 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3204 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3205 g_ptr_array_add (acfg->methods, method);
3206 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3207 acfg->nmethods = acfg->methods->len + 1;
3210 if (method->wrapper_type || extra)
3211 g_ptr_array_add (acfg->extra_methods, method);
3215 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3217 /* One instantiation with valuetypes is generated for each async method */
3218 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3225 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3227 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3235 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3239 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3243 index = acfg->method_index;
3244 add_method_with_index (acfg, method, index, extra);
3246 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3248 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3250 acfg->method_index ++;
3256 add_method (MonoAotCompile *acfg, MonoMethod *method)
3258 return add_method_full (acfg, method, FALSE, 0);
3262 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3264 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3265 method = mini_get_shared_method (method);
3266 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3267 /* Use the gsharedvt version */
3270 if (acfg->aot_opts.log_generics)
3271 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3273 add_method_full (acfg, method, TRUE, depth);
3277 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3279 add_extra_method_with_depth (acfg, method, 0);
3283 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3285 MonoAotCompile *acfg = user_data;
3286 MonoJitICallInfo *callinfo = value;
3287 MonoMethod *wrapper;
3293 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3294 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3297 add_method (acfg, wrapper);
3301 get_runtime_invoke_sig (MonoMethodSignature *sig)
3303 MonoMethodBuilder *mb;
3306 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3307 m = mono_mb_create_method (mb, sig, 16);
3308 return mono_marshal_get_runtime_invoke (m, FALSE);
3312 can_marshal_struct (MonoClass *klass)
3314 MonoClassField *field;
3315 gboolean can_marshal = TRUE;
3316 gpointer iter = NULL;
3317 MonoMarshalType *info;
3320 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3323 info = mono_marshal_load_type_info (klass);
3325 /* Only allow a few field types to avoid asserts in the marshalling code */
3326 while ((field = mono_class_get_fields (klass, &iter))) {
3327 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3330 switch (field->type->type) {
3335 case MONO_TYPE_BOOLEAN:
3338 case MONO_TYPE_CHAR:
3346 case MONO_TYPE_STRING:
3348 case MONO_TYPE_VALUETYPE:
3349 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3350 can_marshal = FALSE;
3352 case MONO_TYPE_SZARRAY: {
3353 gboolean has_mspec = FALSE;
3356 for (i = 0; i < info->num_fields; ++i) {
3357 if (info->fields [i].field == field && info->fields [i].mspec)
3362 can_marshal = FALSE;
3366 can_marshal = FALSE;
3372 /* Its hard to compute whenever these can be marshalled or not */
3373 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3380 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3382 /* Create a vtype instantiation */
3383 MonoGenericContext shared_context;
3385 MonoGenericInst *inst;
3386 MonoGenericContainer *container;
3387 MonoClass **constraints;
3390 memset (ctx, 0, sizeof (MonoGenericContext));
3392 if (method->klass->generic_container) {
3393 shared_context = method->klass->generic_container->context;
3394 inst = shared_context.class_inst;
3396 args = g_new0 (MonoType*, inst->type_argc);
3397 for (i = 0; i < inst->type_argc; ++i) {
3398 args [i] = &mono_defaults.int_class->byval_arg;
3400 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3402 if (method->is_generic) {
3403 container = mono_method_get_generic_container (method);
3404 shared_context = container->context;
3405 inst = shared_context.method_inst;
3407 args = g_new0 (MonoType*, inst->type_argc);
3408 for (i = 0; i < container->type_argc; ++i) {
3409 MonoGenericParamInfo *info = &container->type_params [i].info;
3410 gboolean ref_only = FALSE;
3412 if (info && info->constraints) {
3413 constraints = info->constraints;
3415 while (*constraints) {
3416 MonoClass *cklass = *constraints;
3417 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3418 /* Inflaring the method with our vtype would not be valid */
3425 args [i] = &mono_defaults.object_class->byval_arg;
3427 args [i] = &mono_defaults.int_class->byval_arg;
3429 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3434 add_wrappers (MonoAotCompile *acfg)
3436 MonoMethod *method, *m;
3438 MonoMethodSignature *sig, *csig;
3442 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3443 * so there is only one wrapper of a given type, or inlining their contents into their
3446 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3449 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3450 gboolean skip = FALSE;
3452 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3453 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3455 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3456 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3457 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3460 /* Skip methods which can not be handled by get_runtime_invoke () */
3461 sig = mono_method_signature (method);
3464 if ((sig->ret->type == MONO_TYPE_PTR) ||
3465 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3467 if (mono_class_is_open_constructed_type (sig->ret))
3470 for (j = 0; j < sig->param_count; j++) {
3471 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3473 if (mono_class_is_open_constructed_type (sig->params [j]))
3477 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3478 if (!mono_class_is_contextbound (method->klass)) {
3479 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3480 gboolean has_nullable = FALSE;
3482 for (j = 0; j < sig->param_count; j++) {
3483 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3484 has_nullable = TRUE;
3487 if (info && !has_nullable) {
3488 /* Supported by the dynamic runtime-invoke wrapper */
3492 mono_arch_dyn_call_free (info);
3497 //printf ("%s\n", mono_method_full_name (method, TRUE));
3498 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3502 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3505 /* Runtime invoke wrappers */
3507 /* void runtime-invoke () [.cctor] */
3508 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3509 csig->ret = &mono_defaults.void_class->byval_arg;
3510 add_method (acfg, get_runtime_invoke_sig (csig));
3512 /* void runtime-invoke () [Finalize] */
3513 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3515 csig->ret = &mono_defaults.void_class->byval_arg;
3516 add_method (acfg, get_runtime_invoke_sig (csig));
3518 /* void runtime-invoke (string) [exception ctor] */
3519 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3521 csig->ret = &mono_defaults.void_class->byval_arg;
3522 csig->params [0] = &mono_defaults.string_class->byval_arg;
3523 add_method (acfg, get_runtime_invoke_sig (csig));
3525 /* void runtime-invoke (string, string) [exception ctor] */
3526 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3528 csig->ret = &mono_defaults.void_class->byval_arg;
3529 csig->params [0] = &mono_defaults.string_class->byval_arg;
3530 csig->params [1] = &mono_defaults.string_class->byval_arg;
3531 add_method (acfg, get_runtime_invoke_sig (csig));
3533 /* string runtime-invoke () [Exception.ToString ()] */
3534 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3536 csig->ret = &mono_defaults.string_class->byval_arg;
3537 add_method (acfg, get_runtime_invoke_sig (csig));
3539 /* void runtime-invoke (string, Exception) [exception ctor] */
3540 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3542 csig->ret = &mono_defaults.void_class->byval_arg;
3543 csig->params [0] = &mono_defaults.string_class->byval_arg;
3544 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3545 add_method (acfg, get_runtime_invoke_sig (csig));
3547 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3548 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3550 csig->ret = &(mono_class_from_name (
3551 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3552 csig->params [0] = &mono_defaults.string_class->byval_arg;
3553 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3554 add_method (acfg, get_runtime_invoke_sig (csig));
3556 /* runtime-invoke used by finalizers */
3557 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3559 /* This is used by mono_runtime_capture_context () */
3560 method = mono_get_context_capture_method ();
3562 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3564 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3565 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3569 add_method (acfg, mono_marshal_get_stelemref ());
3571 if (MONO_ARCH_HAVE_TLS_GET) {
3572 /* Managed Allocators */
3573 nallocators = mono_gc_get_managed_allocator_types ();
3574 for (i = 0; i < nallocators; ++i) {
3575 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3577 add_method (acfg, m);
3579 for (i = 0; i < nallocators; ++i) {
3580 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3582 add_method (acfg, m);
3586 /* write barriers */
3587 if (mono_gc_is_moving ()) {
3588 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3589 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3592 /* Stelemref wrappers */
3594 MonoMethod **wrappers;
3597 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3598 for (i = 0; i < nwrappers; ++i)
3599 add_method (acfg, wrappers [i]);
3603 /* castclass_with_check wrapper */
3604 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3605 /* isinst_with_check wrapper */
3606 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3608 /* JIT icall wrappers */
3609 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3610 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3614 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3615 * we use the original method instead at runtime.
3616 * Since full-aot doesn't support remoting, this is not a problem.
3619 /* remoting-invoke wrappers */
3620 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3621 MonoMethodSignature *sig;
3623 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3624 method = mono_get_method (acfg->image, token, NULL);
3626 sig = mono_method_signature (method);
3628 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3629 m = mono_marshal_get_remoting_invoke_with_check (method);
3631 add_method (acfg, m);
3636 /* delegate-invoke wrappers */
3637 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3640 MonoCustomAttrInfo *cattr;
3642 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3643 klass = mono_class_get_checked (acfg->image, token, &error);
3646 mono_error_cleanup (&error);
3650 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3653 if (!klass->generic_container) {
3654 method = mono_get_delegate_invoke (klass);
3656 m = mono_marshal_get_delegate_invoke (method, NULL);
3658 add_method (acfg, m);
3660 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3662 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3664 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3666 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3668 cattr = mono_custom_attrs_from_class (klass);
3673 for (j = 0; j < cattr->num_attrs; ++j)
3674 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3676 if (j < cattr->num_attrs) {
3678 MonoMethod *wrapper;
3679 MonoMethod *del_invoke;
3681 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3682 invoke = mono_get_delegate_invoke (klass);
3683 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3684 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3685 add_method (acfg, wrapper);
3686 add_method (acfg, del_invoke);
3689 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3691 MonoGenericContext ctx;
3692 MonoMethod *inst, *gshared;
3695 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3698 method = mono_get_delegate_invoke (klass);
3699 create_gsharedvt_inst (acfg, method, &ctx);
3701 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3702 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3704 m = mono_marshal_get_delegate_invoke (inst, NULL);
3705 g_assert (m->is_inflated);
3707 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3708 add_extra_method (acfg, gshared);
3711 method = mono_get_delegate_begin_invoke (klass);
3712 create_gsharedvt_inst (acfg, method, &ctx);
3714 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3715 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3717 m = mono_marshal_get_delegate_begin_invoke (inst);
3718 g_assert (m->is_inflated);
3720 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3721 add_extra_method (acfg, gshared);
3724 method = mono_get_delegate_end_invoke (klass);
3725 create_gsharedvt_inst (acfg, method, &ctx);
3727 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3728 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3730 m = mono_marshal_get_delegate_end_invoke (inst);
3731 g_assert (m->is_inflated);
3733 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3734 add_extra_method (acfg, gshared);
3739 /* array access wrappers */
3740 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3744 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3745 klass = mono_class_get_checked (acfg->image, token, &error);
3748 mono_error_cleanup (&error);
3752 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3753 MonoMethod *m, *wrapper;
3755 /* Add runtime-invoke wrappers too */
3757 m = mono_class_get_method_from_name (klass, "Get", -1);
3759 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3760 add_extra_method (acfg, wrapper);
3761 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3763 m = mono_class_get_method_from_name (klass, "Set", -1);
3765 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3766 add_extra_method (acfg, wrapper);
3767 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3771 /* Synchronized wrappers */
3772 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3774 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3775 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3776 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3778 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3779 if (method->is_generic) {
3781 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3783 MonoGenericContext ctx;
3784 MonoMethod *inst, *gshared, *m;
3787 * Create a generic wrapper for a generic instance, and AOT that.
3789 create_gsharedvt_inst (acfg, method, &ctx);
3790 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3791 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3792 m = mono_marshal_get_synchronized_wrapper (inst);
3793 g_assert (m->is_inflated);
3794 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3795 add_method (acfg, gshared);
3797 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3802 /* pinvoke wrappers */
3803 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3806 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3808 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3809 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3811 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3812 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3813 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3817 /* native-to-managed wrappers */
3818 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3821 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3822 MonoCustomAttrInfo *cattr;
3825 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3826 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3829 * Only generate native-to-managed wrappers for methods which have an
3830 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3831 * name to avoid defining a new assembly to contain it.
3833 cattr = mono_custom_attrs_from_method (method);
3836 for (j = 0; j < cattr->num_attrs; ++j)
3837 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3839 if (j < cattr->num_attrs) {
3840 MonoCustomAttrEntry *e = &cattr->attrs [j];
3841 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3842 const char *p = (const char*)e->data;
3844 int slen, num_named, named_type;
3848 char *export_name = NULL;
3849 MonoMethod *wrapper;
3851 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3852 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3853 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3854 mono_method_full_name (method, TRUE));
3858 g_assert (sig->param_count == 1);
3859 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3862 * Decode the cattr manually since we can't create objects
3863 * during aot compilation.
3869 /* From load_cattr_value () in reflection.c */
3870 slen = mono_metadata_decode_value (p, &p);
3871 n = g_memdup (p, slen + 1);
3873 t = mono_reflection_type_from_name (n, acfg->image);
3877 klass = mono_class_from_mono_type (t);
3878 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3882 num_named = read16 (p);
3885 g_assert (num_named < 2);
3886 if (num_named == 1) {
3890 /* parse ExportSymbol attribute */
3892 named_type = *named;
3894 /* data_type = *named; */
3897 name_len = mono_metadata_decode_blob_size (named, &named);
3898 name = g_malloc (name_len + 1);
3899 memcpy (name, named, name_len);
3900 name [name_len] = 0;
3903 g_assert (named_type == 0x54);
3904 g_assert (!strcmp (name, "ExportSymbol"));
3906 /* load_cattr_value (), string case */
3907 g_assert (*named != (char)0xff);
3908 slen = mono_metadata_decode_value (named, &named);
3909 export_name = g_malloc (slen + 1);
3910 memcpy (export_name, named, slen);
3911 export_name [slen] = 0;
3915 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3916 add_method (acfg, wrapper);
3918 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3922 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3923 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3924 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3928 /* StructureToPtr/PtrToStructure wrappers */
3929 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3933 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3934 klass = mono_class_get_checked (acfg->image, token, &error);
3937 mono_error_cleanup (&error);
3941 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3942 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3943 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3944 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3950 has_type_vars (MonoClass *klass)
3952 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3955 return has_type_vars (klass->element_class);
3956 if (klass->generic_class) {
3957 MonoGenericContext *context = &klass->generic_class->context;
3958 if (context->class_inst) {
3961 for (i = 0; i < context->class_inst->type_argc; ++i)
3962 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3966 if (klass->generic_container)
3972 is_vt_inst (MonoGenericInst *inst)
3976 for (i = 0; i < inst->type_argc; ++i) {
3977 MonoType *t = inst->type_argv [i];
3978 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3985 method_has_type_vars (MonoMethod *method)
3987 if (has_type_vars (method->klass))
3990 if (method->is_inflated) {
3991 MonoGenericContext *context = mono_method_get_context (method);
3992 if (context->method_inst) {
3995 for (i = 0; i < context->method_inst->type_argc; ++i)
3996 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4004 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4006 return opts->mode == MONO_AOT_MODE_FULL;
4009 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4012 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4014 /* This might lead to a huge code blowup so only do it if neccesary */
4015 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4018 add_generic_class_with_depth (acfg, klass, 0, ref);
4022 check_type_depth (MonoType *t, int depth)
4030 case MONO_TYPE_GENERICINST: {
4031 MonoGenericClass *gklass = t->data.generic_class;
4032 MonoGenericInst *ginst = gklass->context.class_inst;
4035 for (i = 0; i < ginst->type_argc; ++i) {
4036 if (check_type_depth (ginst->type_argv [i], depth + 1))
4050 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4053 * add_generic_class:
4055 * Add all methods of a generic class.
4058 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4061 MonoClassField *field;
4063 gboolean use_gsharedvt = FALSE;
4065 if (!acfg->ginst_hash)
4066 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4068 mono_class_init (klass);
4070 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4073 if (has_type_vars (klass))
4076 if (!klass->generic_class && !klass->rank)
4079 if (klass->exception_type)
4082 if (!acfg->ginst_hash)
4083 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4085 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4088 if (check_type_depth (&klass->byval_arg, 0))
4091 if (acfg->aot_opts.log_generics)
4092 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4094 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4097 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4098 * Enable this only for some classes since gsharedvt might not support all methods.
4100 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) &&
4101 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4102 use_gsharedvt = TRUE;
4105 while ((method = mono_class_get_methods (klass, &iter))) {
4106 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4108 * This is partial sharing, and we can't handle it yet
4113 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4115 add_types_from_method_header (acfg, method);
4119 if (method->is_generic)
4124 * FIXME: Instances which are referenced by these methods are not added,
4125 * for example Array.Resize<int> for List<int>.Add ().
4127 add_extra_method_with_depth (acfg, method, depth + 1);
4131 while ((field = mono_class_get_fields (klass, &iter))) {
4132 if (field->type->type == MONO_TYPE_GENERICINST)
4133 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4136 if (klass->delegate) {
4137 method = mono_get_delegate_invoke (klass);
4139 method = mono_marshal_get_delegate_invoke (method, NULL);
4141 if (acfg->aot_opts.log_generics)
4142 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4144 add_method (acfg, method);
4147 /* Add superclasses */
4149 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4152 * For ICollection<T>, add instances of the helper methods
4153 * in Array, since a T[] could be cast to ICollection<T>.
4155 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4156 (!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"))) {
4157 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4158 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4162 if (!strcmp (klass->name, "IEnumerator`1"))
4163 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4165 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4167 /* Add the T[]/InternalEnumerator class */
4168 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4172 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4173 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4177 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4178 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4182 while ((method = mono_class_get_methods (array_class, &iter))) {
4183 if (strstr (method->name, name_prefix)) {
4184 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4186 add_extra_method_with_depth (acfg, m, depth);
4190 g_free (name_prefix);
4193 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4194 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4195 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4196 MonoClass *icomparable, *gcomparer;
4197 MonoGenericContext ctx;
4198 MonoType *args [16];
4200 memset (&ctx, 0, sizeof (ctx));
4202 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4203 g_assert (icomparable);
4204 args [0] = &tclass->byval_arg;
4205 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4207 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4208 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4209 g_assert (gcomparer);
4210 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4214 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4215 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4216 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4217 MonoClass *iface, *gcomparer;
4218 MonoGenericContext ctx;
4219 MonoType *args [16];
4221 memset (&ctx, 0, sizeof (ctx));
4223 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4225 args [0] = &tclass->byval_arg;
4226 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4228 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4229 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4230 g_assert (gcomparer);
4231 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4237 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4240 MonoGenericContext ctx;
4241 MonoType *args [16];
4243 if (acfg->aot_opts.no_instances)
4246 memset (&ctx, 0, sizeof (ctx));
4248 for (i = 0; i < ninsts; ++i) {
4249 args [0] = insts [i];
4250 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4251 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4256 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4258 MonoMethodHeader *header;
4259 MonoMethodSignature *sig;
4262 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4264 sig = mono_method_signature (method);
4267 for (j = 0; j < sig->param_count; ++j)
4268 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4269 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4272 header = mono_method_get_header (method);
4275 for (j = 0; j < header->num_locals; ++j)
4276 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4277 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4279 mono_loader_clear_error ();
4284 * add_generic_instances:
4286 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4289 add_generic_instances (MonoAotCompile *acfg)
4294 MonoGenericContext *context;
4296 if (acfg->aot_opts.no_instances)
4299 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4301 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4302 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4305 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4306 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4307 mono_error_cleanup (&error);
4311 if (method->klass->image != acfg->image)
4314 context = mono_method_get_context (method);
4316 if (context && ((context->class_inst && context->class_inst->is_open)))
4320 * For open methods, create an instantiation which can be passed to the JIT.
4321 * FIXME: Handle class_inst as well.
4323 if (context && context->method_inst && context->method_inst->is_open) {
4325 MonoGenericContext shared_context;
4326 MonoGenericInst *inst;
4327 MonoType **type_argv;
4329 MonoMethod *declaring_method;
4330 gboolean supported = TRUE;
4332 /* Check that the context doesn't contain open constructed types */
4333 if (context->class_inst) {
4334 inst = context->class_inst;
4335 for (i = 0; i < inst->type_argc; ++i) {
4336 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)
4338 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4342 if (context->method_inst) {
4343 inst = context->method_inst;
4344 for (i = 0; i < inst->type_argc; ++i) {
4345 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)
4347 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4355 memset (&shared_context, 0, sizeof (MonoGenericContext));
4357 inst = context->class_inst;
4359 type_argv = g_new0 (MonoType*, inst->type_argc);
4360 for (i = 0; i < inst->type_argc; ++i) {
4361 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)
4362 type_argv [i] = &mono_defaults.object_class->byval_arg;
4364 type_argv [i] = inst->type_argv [i];
4367 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4371 inst = context->method_inst;
4373 type_argv = g_new0 (MonoType*, inst->type_argc);
4374 for (i = 0; i < inst->type_argc; ++i) {
4375 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)
4376 type_argv [i] = &mono_defaults.object_class->byval_arg;
4378 type_argv [i] = inst->type_argv [i];
4381 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4385 if (method->is_generic || method->klass->generic_container)
4386 declaring_method = method;
4388 declaring_method = mono_method_get_declaring_generic_method (method);
4390 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4391 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4395 * If the method is fully sharable, it was already added in place of its
4396 * generic definition.
4398 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4402 * FIXME: Partially shared methods are not shared here, so we end up with
4403 * many identical methods.
4405 add_extra_method (acfg, method);
4408 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4412 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4414 klass = mono_class_get_checked (acfg->image, token, &error);
4415 if (!klass || klass->rank) {
4416 mono_error_cleanup (&error);
4420 add_generic_class (acfg, klass, FALSE, "typespec");
4423 /* Add types of args/locals */
4424 for (i = 0; i < acfg->methods->len; ++i) {
4425 method = g_ptr_array_index (acfg->methods, i);
4426 add_types_from_method_header (acfg, method);
4429 if (acfg->image == mono_defaults.corlib) {
4431 MonoType *insts [256];
4434 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4435 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4436 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4437 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4438 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4439 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4440 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4441 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4442 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4443 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4444 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4445 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4447 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4448 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4450 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4451 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4453 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4455 /* Add instances of the array generic interfaces for primitive types */
4456 /* This will add instances of the InternalArray_ helper methods in Array too */
4457 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4459 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4460 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4462 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4463 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4465 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4468 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4469 * used for all instances of GetGenericValueImpl by the AOT runtime.
4472 MonoGenericContext ctx;
4473 MonoType *args [16];
4474 MonoMethod *get_method;
4475 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4477 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4481 memset (&ctx, 0, sizeof (ctx));
4482 args [0] = &mono_defaults.object_class->byval_arg;
4483 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4484 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4485 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4489 /* Same for CompareExchange<T>/Exchange<T> */
4491 MonoGenericContext ctx;
4492 MonoType *args [16];
4494 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4495 gpointer iter = NULL;
4497 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4498 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4500 memset (&ctx, 0, sizeof (ctx));
4501 args [0] = &mono_defaults.object_class->byval_arg;
4502 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4503 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4504 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4509 /* Same for Volatile.Read/Write<T> */
4511 MonoGenericContext ctx;
4512 MonoType *args [16];
4514 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4515 gpointer iter = NULL;
4517 if (volatile_klass) {
4518 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4519 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4521 memset (&ctx, 0, sizeof (ctx));
4522 args [0] = &mono_defaults.object_class->byval_arg;
4523 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4524 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4525 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4534 * is_direct_callable:
4536 * Return whenever the method identified by JI is directly callable without
4537 * going through the PLT.
4540 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4542 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4543 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4545 gboolean direct_callable = TRUE;
4547 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4548 direct_callable = FALSE;
4549 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4550 // FIXME: Maybe call the wrapper directly ?
4551 direct_callable = FALSE;
4553 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4554 /* Disable this so all calls go through load_method (), see the
4555 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4556 * mono_debugger_agent_init ().
4558 direct_callable = FALSE;
4561 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4562 /* sgen does some initialization when the allocator method is created */
4563 direct_callable = FALSE;
4564 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4565 /* we don't know at compile time whether sgen is concurrent or not */
4566 direct_callable = FALSE;
4568 if (direct_callable)
4571 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4572 if (acfg->aot_opts.direct_pinvoke)
4574 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4575 if (acfg->aot_opts.direct_icalls)
4583 #ifdef MONO_ARCH_AOT_SUPPORTED
4585 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4587 MonoImage *image = method->klass->image;
4588 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4589 MonoTableInfo *tables = image->tables;
4590 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4591 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4592 guint32 im_cols [MONO_IMPLMAP_SIZE];
4595 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4599 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4602 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4604 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4607 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4609 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4616 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4618 if (a->native_offset == b->native_offset)
4619 return a->il_offset - b->il_offset;
4621 return a->native_offset - b->native_offset;
4625 * compute_line_numbers:
4627 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4630 static MonoDebugSourceLocation**
4631 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4633 MonoDebugMethodInfo *minfo;
4634 MonoDebugLineNumberEntry *ln_array;
4635 MonoDebugSourceLocation *loc;
4636 int i, prev_line, prev_il_offset;
4637 int *native_to_il_offset = NULL;
4638 MonoDebugSourceLocation **res;
4641 minfo = mono_debug_lookup_method (method);
4644 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4645 if (debug_info->code_size != code_size)
4648 g_assert (code_size);
4650 /* Compute the native->IL offset mapping */
4652 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4653 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4655 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4657 native_to_il_offset = g_new0 (int, code_size + 1);
4659 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4661 MonoDebugLineNumberEntry *lne = &ln_array [i];
4664 for (j = 0; j < lne->native_offset; ++j)
4665 native_to_il_offset [j] = -1;
4668 if (i < debug_info->num_line_numbers - 1) {
4669 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4671 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4672 native_to_il_offset [j] = lne->il_offset;
4674 for (j = lne->native_offset; j < code_size; ++j)
4675 native_to_il_offset [j] = lne->il_offset;
4680 /* Compute the native->line number mapping */
4681 res = g_new0 (MonoDebugSourceLocation*, code_size);
4682 prev_il_offset = -1;
4685 for (i = 0; i < code_size; ++i) {
4686 int il_offset = native_to_il_offset [i];
4688 if (il_offset == -1 || il_offset == prev_il_offset)
4690 prev_il_offset = il_offset;
4691 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4692 if (!(loc && loc->source_file))
4694 if (loc->row == prev_line) {
4695 mono_debug_symfile_free_location (loc);
4698 prev_line = loc->row;
4699 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4701 /* This will cover the prolog too */
4711 get_file_index (MonoAotCompile *acfg, const char *source_file)
4715 // FIXME: Free these
4716 if (!acfg->dwarf_ln_filenames)
4717 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4718 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4720 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4721 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4722 emit_unset_mode (acfg);
4723 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4735 * emit_and_reloc_code:
4737 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4738 * is true, calls are made through the GOT too. This is used for emitting trampolines
4739 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4740 * since trampolines are needed to make PTL work.
4743 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4745 int i, pindex, start_index;
4747 MonoJumpInfo *patch_info;
4748 MonoDebugSourceLocation **locs = NULL;
4750 #ifdef MONO_ARCH_AOT_SUPPORTED
4751 gboolean direct_call, external_call;
4753 const char *direct_call_target = 0;
4754 const char *direct_pinvoke;
4757 if (acfg->gas_line_numbers && method && debug_info) {
4758 locs = compute_line_numbers (method, code_len, debug_info);
4760 int findex = get_file_index (acfg, "<unknown>");
4761 emit_unset_mode (acfg);
4762 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4766 /* Collect and sort relocations */
4767 patches = g_ptr_array_new ();
4768 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4769 g_ptr_array_add (patches, patch_info);
4770 g_ptr_array_sort (patches, compare_patches);
4773 for (i = 0; i < code_len; i += INST_LEN) {
4775 for (pindex = start_index; pindex < patches->len; ++pindex) {
4776 patch_info = g_ptr_array_index (patches, pindex);
4777 if (patch_info->ip.i >= i)
4781 if (locs && locs [i]) {
4782 MonoDebugSourceLocation *loc = locs [i];
4785 findex = get_file_index (acfg, loc->source_file);
4786 emit_unset_mode (acfg);
4787 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4788 mono_debug_symfile_free_location (loc);
4792 #ifdef MONO_ARCH_AOT_SUPPORTED
4793 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4794 start_index = pindex;
4796 switch (patch_info->type) {
4797 case MONO_PATCH_INFO_NONE:
4799 case MONO_PATCH_INFO_GOT_OFFSET: {
4802 arch_emit_got_offset (acfg, code + i, &code_size);
4803 i += code_size - INST_LEN;
4805 patch_info->type = MONO_PATCH_INFO_NONE;
4808 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4809 int code_size, index;
4810 char *selector = (void*)patch_info->data.target;
4812 if (!acfg->objc_selector_to_index)
4813 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4814 if (!acfg->objc_selectors)
4815 acfg->objc_selectors = g_ptr_array_new ();
4816 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4820 index = acfg->objc_selector_index;
4821 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4822 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4823 acfg->objc_selector_index ++;
4826 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4827 i += code_size - INST_LEN;
4829 patch_info->type = MONO_PATCH_INFO_NONE;
4834 * If this patch is a call, try emitting a direct call instead of
4835 * through a PLT entry. This is possible if the called method is in
4836 * the same assembly and requires no initialization.
4838 direct_call = FALSE;
4839 external_call = FALSE;
4840 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4841 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4842 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4843 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4845 direct_call_target = callee_cfg->asm_symbol;
4846 patch_info->type = MONO_PATCH_INFO_NONE;
4847 acfg->stats.direct_calls ++;
4850 acfg->stats.all_calls ++;
4851 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4852 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4853 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4854 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4856 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4857 if (direct_pinvoke) {
4859 g_assert (strlen (direct_pinvoke) < 1000);
4860 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4863 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4864 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4865 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4866 /* Call to a C function implementing a jit icall */
4868 external_call = TRUE;
4869 g_assert (strlen (sym) < 1000);
4870 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4872 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4873 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4874 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4875 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4876 /* Call to a jit icall without a wrapper */
4878 external_call = TRUE;
4879 g_assert (strlen (sym) < 1000);
4880 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4885 patch_info->type = MONO_PATCH_INFO_NONE;
4886 acfg->stats.direct_calls ++;
4889 if (!got_only && !direct_call) {
4890 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4892 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4894 direct_call_target = plt_entry->symbol;
4896 /* Nullify the patch */
4897 patch_info->type = MONO_PATCH_INFO_NONE;
4898 plt_entry->jit_used = TRUE;
4905 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4906 i += call_size - INST_LEN;
4910 got_slot = get_got_offset (acfg, FALSE, patch_info);
4912 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
4913 i += code_size - INST_LEN;
4919 #endif /* MONO_ARCH_AOT_SUPPORTED */
4922 /* Find next patch */
4924 for (pindex = start_index; pindex < patches->len; ++pindex) {
4925 patch_info = g_ptr_array_index (patches, pindex);
4926 if (patch_info->ip.i >= i)
4930 /* Try to emit multiple bytes at once */
4931 if (pindex < patches->len && patch_info->ip.i > i) {
4934 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4935 if (locs && locs [limit])
4939 emit_code_bytes (acfg, code + i, limit - i);
4940 i = limit - INST_LEN;
4942 emit_code_bytes (acfg, code + i, INST_LEN);
4953 * Return a modified version of S which only includes characters permissible in symbols.
4956 sanitize_symbol (MonoAotCompile *acfg, char *s)
4958 gboolean process = FALSE;
4967 for (i = 0; i < len; ++i)
4968 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4973 gs = g_string_sized_new (len);
4974 for (i = 0; i < len; ++i) {
4976 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4977 g_string_append_c (gs, c);
4978 } else if (c > 0x7f) {
4979 /* multi-byte utf8 */
4980 g_string_append_printf (gs, "_0x%x", c);
4983 while (c >> 6 == 0x2) {
4984 g_string_append_printf (gs, "%x", c);
4988 g_string_append_printf (gs, "_");
4991 g_string_append_c (gs, '_');
4995 res = mono_mempool_strdup (acfg->mempool, gs->str);
4996 g_string_free (gs, TRUE);
5001 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5003 char *name1, *name2, *cached;
5004 int i, j, len, count;
5005 MonoMethod *cached_method;
5007 name1 = mono_method_full_name (method, TRUE);
5010 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5011 if ((!prefix || !*prefix) && name1 [0] == 'L')
5015 len = strlen (name1);
5016 name2 = malloc (strlen (prefix) + len + 16);
5017 memcpy (name2, prefix, strlen (prefix));
5018 j = strlen (prefix);
5019 for (i = 0; i < len; ++i) {
5020 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5022 } else if (isalnum (name1 [i])) {
5023 name2 [j ++] = name1 [i];
5024 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5026 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5029 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5039 cached_method = g_hash_table_lookup (cache, name2);
5040 if (!(cached_method && cached_method != method))
5042 sprintf (name2 + j, "_%d", count);
5046 cached = g_strdup (name2);
5047 g_hash_table_insert (cache, cached, method);
5053 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5058 char *debug_sym = NULL;
5059 char *symbol = NULL;
5060 int func_alignment = AOT_FUNC_ALIGNMENT;
5063 method = cfg->orig_method;
5064 code = cfg->native_code;
5066 method_index = get_method_index (acfg, method);
5067 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5069 /* Make the labels local */
5070 emit_section_change (acfg, ".text", 0);
5071 emit_alignment_code (acfg, func_alignment);
5073 if (acfg->global_symbols && acfg->need_no_dead_strip)
5074 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5076 emit_label (acfg, cfg->asm_symbol);
5078 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5080 * Write a C style symbol for every method, this has two uses:
5081 * - it works on platforms where the dwarf debugging info is not
5083 * - it allows the setting of breakpoints of aot-ed methods.
5085 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5086 cfg->asm_debug_symbol = g_strdup (debug_sym);
5088 if (acfg->need_no_dead_strip)
5089 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5090 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5091 emit_label (acfg, debug_sym);
5094 export_name = g_hash_table_lookup (acfg->export_names, method);
5096 /* Emit a global symbol for the method */
5097 emit_global_inner (acfg, export_name, TRUE);
5098 emit_label (acfg, export_name);
5101 if (cfg->verbose_level > 0)
5102 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5104 acfg->stats.code_size += cfg->code_len;
5106 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5108 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 ()));
5112 if (acfg->aot_opts.write_symbols) {
5114 emit_symbol_size (acfg, debug_sym, ".");
5116 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5120 emit_label (acfg, symbol);
5127 * Encode PATCH_INFO into its disk representation.
5130 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5134 switch (patch_info->type) {
5135 case MONO_PATCH_INFO_NONE:
5137 case MONO_PATCH_INFO_IMAGE:
5138 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5140 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5141 case MONO_PATCH_INFO_JIT_TLS_ID:
5142 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5143 case MONO_PATCH_INFO_GC_NURSERY_START:
5145 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5146 encode_value (patch_info->data.index, p, &p);
5148 case MONO_PATCH_INFO_METHOD_REL:
5149 encode_value ((gint)patch_info->data.offset, p, &p);
5151 case MONO_PATCH_INFO_SWITCH: {
5152 gpointer *table = (gpointer *)patch_info->data.table->table;
5155 encode_value (patch_info->data.table->table_size, p, &p);
5156 for (k = 0; k < patch_info->data.table->table_size; k++)
5157 encode_value ((int)(gssize)table [k], p, &p);
5160 case MONO_PATCH_INFO_METHODCONST:
5161 case MONO_PATCH_INFO_METHOD:
5162 case MONO_PATCH_INFO_METHOD_JUMP:
5163 case MONO_PATCH_INFO_ICALL_ADDR:
5164 case MONO_PATCH_INFO_METHOD_RGCTX:
5165 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5166 encode_method_ref (acfg, patch_info->data.method, p, &p);
5168 case MONO_PATCH_INFO_INTERNAL_METHOD:
5169 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5170 guint32 len = strlen (patch_info->data.name);
5172 encode_value (len, p, &p);
5174 memcpy (p, patch_info->data.name, len);
5179 case MONO_PATCH_INFO_LDSTR: {
5180 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5181 guint32 token = patch_info->data.token->token;
5182 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5183 encode_value (image_index, p, &p);
5184 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5187 case MONO_PATCH_INFO_RVA:
5188 case MONO_PATCH_INFO_DECLSEC:
5189 case MONO_PATCH_INFO_LDTOKEN:
5190 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5191 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5192 encode_value (patch_info->data.token->token, p, &p);
5193 encode_value (patch_info->data.token->has_context, p, &p);
5194 if (patch_info->data.token->has_context)
5195 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5197 case MONO_PATCH_INFO_EXC_NAME: {
5198 MonoClass *ex_class;
5201 mono_class_from_name (mono_defaults.exception_class->image,
5202 "System", patch_info->data.target);
5203 g_assert (ex_class);
5204 encode_klass_ref (acfg, ex_class, p, &p);
5207 case MONO_PATCH_INFO_R4:
5208 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5210 case MONO_PATCH_INFO_R8:
5211 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5212 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5214 case MONO_PATCH_INFO_VTABLE:
5215 case MONO_PATCH_INFO_CLASS:
5216 case MONO_PATCH_INFO_IID:
5217 case MONO_PATCH_INFO_ADJUSTED_IID:
5218 case MONO_PATCH_INFO_CLASS_INIT:
5219 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5221 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5222 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5223 if (patch_info->data.del_tramp->method) {
5224 encode_value (1, p, &p);
5225 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5227 encode_value (0, p, &p);
5229 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5231 case MONO_PATCH_INFO_FIELD:
5232 case MONO_PATCH_INFO_SFLDA:
5233 encode_field_info (acfg, patch_info->data.field, p, &p);
5235 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5237 case MONO_PATCH_INFO_RGCTX_FETCH: {
5238 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5243 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5244 * reference the same method, so encode the method only once.
5246 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5248 buf2 = g_malloc (1024);
5251 encode_method_ref (acfg, entry->method, p2, &p2);
5252 g_assert (p2 - buf2 < 1024);
5254 offset = add_to_blob (acfg, buf2, p2 - buf2);
5257 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5262 encode_value (offset, p, &p);
5263 g_assert ((int)entry->info_type < 256);
5264 g_assert (entry->data->type < 256);
5265 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5266 encode_patch (acfg, entry->data, p, &p);
5269 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5270 case MONO_PATCH_INFO_MONITOR_ENTER:
5271 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5272 case MONO_PATCH_INFO_MONITOR_EXIT:
5273 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5275 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5276 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5277 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5279 case MONO_PATCH_INFO_SIGNATURE:
5280 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5282 case MONO_PATCH_INFO_TLS_OFFSET:
5283 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5285 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5286 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5287 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5289 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5290 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5293 encode_method_ref (acfg, info->method, p, &p);
5294 encode_value (info->num_entries, p, &p);
5295 for (i = 0; i < info->num_entries; ++i) {
5296 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5298 encode_value (template->info_type, p, &p);
5299 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5300 case MONO_PATCH_INFO_CLASS:
5301 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5303 case MONO_PATCH_INFO_FIELD:
5304 encode_field_info (acfg, template->data, p, &p);
5307 g_assert_not_reached ();
5313 case MONO_PATCH_INFO_LDSTR_LIT: {
5314 const char *s = patch_info->data.target;
5315 int len = strlen (s);
5317 encode_value (len, p, &p);
5318 memcpy (p, s, len + 1);
5322 case MONO_PATCH_INFO_VIRT_METHOD:
5323 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5324 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5326 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5329 g_warning ("unable to handle jump info %d", patch_info->type);
5330 g_assert_not_reached ();
5337 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5340 guint32 pindex, offset;
5341 MonoJumpInfo *patch_info;
5343 encode_value (n_patches, p, &p);
5345 for (pindex = 0; pindex < patches->len; ++pindex) {
5346 patch_info = g_ptr_array_index (patches, pindex);
5348 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5352 offset = get_got_offset (acfg, llvm, patch_info);
5353 encode_value (offset, p, &p);
5360 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5364 int pindex, buf_size, n_patches;
5366 MonoJumpInfo *patch_info;
5367 guint32 method_index;
5369 guint32 first_got_offset;
5371 method = cfg->orig_method;
5373 method_index = get_method_index (acfg, method);
5375 /* Sort relocations */
5376 patches = g_ptr_array_new ();
5377 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5378 g_ptr_array_add (patches, patch_info);
5379 g_ptr_array_sort (patches, compare_patches);
5381 first_got_offset = acfg->cfgs [method_index]->got_offset;
5383 /**********************/
5384 /* Encode method info */
5385 /**********************/
5387 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5388 p = buf = g_malloc (buf_size);
5390 if (mono_class_get_cctor (method->klass))
5391 encode_klass_ref (acfg, method->klass, p, &p);
5393 /* Not needed when loading the method */
5394 encode_value (0, p, &p);
5397 if (cfg->opt & MONO_OPT_SHARED) {
5398 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5399 for (l = cfg->ldstr_list; l; l = l->next) {
5400 encode_value ((long)l->data, p, &p);
5404 /* Used only in shared mode */
5405 g_assert (!cfg->ldstr_list);
5408 for (pindex = 0; pindex < patches->len; ++pindex) {
5409 patch_info = g_ptr_array_index (patches, pindex);
5411 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5412 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5413 patch_info->type = MONO_PATCH_INFO_NONE;
5418 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5419 /* Stored in a GOT slot initialized at module load time */
5420 patch_info->type = MONO_PATCH_INFO_NONE;
5424 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5425 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START) {
5426 /* Stored in a GOT slot initialized at module load time */
5427 patch_info->type = MONO_PATCH_INFO_NONE;
5431 if (is_plt_patch (patch_info)) {
5432 /* Calls are made through the PLT */
5433 patch_info->type = MONO_PATCH_INFO_NONE;
5441 g_assert (cfg->has_got_slots);
5443 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5445 acfg->stats.info_size += p - buf;
5447 g_assert (p - buf < buf_size);
5449 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5454 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5456 guint32 cache_index;
5459 /* Reuse the unwind module to canonize and store unwind info entries */
5460 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5462 /* Use +/- 1 to distinguish 0s from missing entries */
5463 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5471 * It would be easier to use assembler symbols, but the caller needs an
5474 offset = acfg->unwind_info_offset;
5475 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5476 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5479 encode_value (encoded_len, p, &p);
5481 acfg->unwind_info_offset += encoded_len + (p - buf);
5487 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5490 guint32 debug_info_size, seq_points_size;
5492 MonoMethodHeader *header;
5493 guint8 *p, *buf, *debug_info;
5494 MonoJitInfo *jinfo = cfg->jit_info;
5496 gboolean use_unwind_ops = FALSE;
5497 MonoSeqPointInfo *seq_points;
5499 code = cfg->native_code;
5500 header = cfg->header;
5502 if (!acfg->aot_opts.nodebug) {
5503 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5506 debug_info_size = 0;
5509 seq_points = cfg->seq_point_info;
5510 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5512 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5514 p = buf = g_malloc (buf_size);
5516 use_unwind_ops = cfg->unwind_ops != NULL;
5518 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);
5520 encode_value (flags, p, &p);
5522 if (use_unwind_ops) {
5523 guint32 encoded_len;
5525 guint32 unwind_desc;
5527 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5529 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5530 encode_value (unwind_desc, p, &p);
5532 encode_value (jinfo->unwind_info, p, &p);
5535 /*Encode the number of holes before the number of clauses to make decoding easier*/
5536 if (jinfo->has_try_block_holes) {
5537 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5538 encode_value (table->num_holes, p, &p);
5541 if (jinfo->has_arch_eh_info) {
5543 * In AOT mode, the code length is calculated from the address of the previous method,
5544 * which could include alignment padding, so calculating the start of the epilog as
5545 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5547 encode_value (jinfo->code_size, p, &p);
5550 /* Exception table */
5551 if (cfg->compile_llvm) {
5553 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5554 * since the information is only available to llc. Instead, we let llc save the data
5555 * into the LSDA, and read it from there at runtime.
5557 /* The assembly might be CIL stripped so emit the data ourselves */
5558 if (header->num_clauses)
5559 encode_value (header->num_clauses, p, &p);
5561 for (k = 0; k < header->num_clauses; ++k) {
5562 MonoExceptionClause *clause;
5564 clause = &header->clauses [k];
5566 encode_value (clause->flags, p, &p);
5567 if (clause->data.catch_class) {
5568 encode_value (1, p, &p);
5569 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5571 encode_value (0, p, &p);
5574 /* Emit a list of nesting clauses */
5575 for (i = 0; i < header->num_clauses; ++i) {
5577 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5579 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5581 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5582 encode_value (i, p, &p);
5584 encode_value (-1, p, &p);
5587 if (jinfo->num_clauses)
5588 encode_value (jinfo->num_clauses, p, &p);
5590 for (k = 0; k < jinfo->num_clauses; ++k) {
5591 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5593 encode_value (ei->flags, p, &p);
5594 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5595 /* Not used for catch clauses */
5596 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5597 encode_value (ei->exvar_offset, p, &p);
5599 encode_value (ei->exvar_offset, p, &p);
5602 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5603 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5605 if (ei->data.catch_class) {
5609 buf2 = g_malloc (4096);
5611 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5613 g_assert (len < 4096);
5614 encode_value (len, p, &p);
5615 memcpy (p, buf2, len);
5619 encode_value (0, p, &p);
5623 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5624 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5625 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5629 if (jinfo->has_try_block_holes) {
5630 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5631 for (i = 0; i < table->num_holes; ++i) {
5632 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5633 encode_value (hole->clause, p, &p);
5634 encode_value (hole->length, p, &p);
5635 encode_value (hole->offset, p, &p);
5639 if (jinfo->has_arch_eh_info) {
5640 MonoArchEHJitInfo *eh_info;
5642 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5643 encode_value (eh_info->stack_size, p, &p);
5644 encode_value (eh_info->epilog_size, p, &p);
5647 if (jinfo->has_generic_jit_info) {
5648 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5649 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5653 encode_value (gi->nlocs, p, &p);
5655 for (i = 0; i < gi->nlocs; ++i) {
5656 MonoDwarfLocListEntry *entry = &gi->locations [i];
5658 encode_value (entry->is_reg ? 1 : 0, p, &p);
5659 encode_value (entry->reg, p, &p);
5661 encode_value (entry->offset, p, &p);
5663 g_assert (entry->from == 0);
5665 encode_value (entry->from, p, &p);
5666 encode_value (entry->to, p, &p);
5669 if (!cfg->compile_llvm) {
5670 encode_value (gi->has_this ? 1 : 0, p, &p);
5671 encode_value (gi->this_reg, p, &p);
5672 encode_value (gi->this_offset, p, &p);
5677 * Need to encode jinfo->method too, since it is not equal to 'method'
5678 * when using generic sharing.
5680 buf2 = g_malloc (4096);
5682 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5684 g_assert (len < 4096);
5685 encode_value (len, p, &p);
5686 memcpy (p, buf2, len);
5690 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5691 MonoMethodInflated *inflated;
5692 MonoGenericContext *context;
5693 MonoGenericInst *inst;
5695 g_assert (jinfo->d.method->is_inflated);
5696 inflated = (MonoMethodInflated*)jinfo->d.method;
5697 context = &inflated->context;
5699 encode_value (1, p, &p);
5700 if (context->class_inst) {
5701 inst = context->class_inst;
5703 encode_value (inst->type_argc, p, &p);
5704 for (i = 0; i < inst->type_argc; ++i)
5705 encode_value (gsctx->var_is_vt [i], p, &p);
5707 encode_value (0, p, &p);
5709 if (context->method_inst) {
5710 inst = context->method_inst;
5712 encode_value (inst->type_argc, p, &p);
5713 for (i = 0; i < inst->type_argc; ++i)
5714 encode_value (gsctx->mvar_is_vt [i], p, &p);
5716 encode_value (0, p, &p);
5719 encode_value (0, p, &p);
5723 if (seq_points_size)
5724 p += mono_seq_point_info_write (seq_points, p);
5726 g_assert (debug_info_size < buf_size);
5728 encode_value (debug_info_size, p, &p);
5729 if (debug_info_size) {
5730 memcpy (p, debug_info, debug_info_size);
5731 p += debug_info_size;
5732 g_free (debug_info);
5737 encode_value (cfg->gc_map_size, p, &p);
5738 /* The GC map requires 4 bytes of alignment */
5739 while ((gsize)p % 4)
5741 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5742 p += cfg->gc_map_size;
5745 acfg->stats.ex_info_size += p - buf;
5747 g_assert (p - buf < buf_size);
5750 /* The GC Map requires 4 byte alignment */
5751 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5756 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5759 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5761 int i, buf_size, res;
5762 gboolean no_special_static, cant_encode;
5763 gpointer iter = NULL;
5766 mono_error_cleanup (&error);
5770 p = buf = g_malloc (buf_size);
5772 /* Mark as unusable */
5773 encode_value (-1, p, &p);
5775 res = add_to_blob (acfg, buf, p - buf);
5781 buf_size = 10240 + (klass->vtable_size * 16);
5782 p = buf = g_malloc (buf_size);
5786 mono_class_init (klass);
5788 mono_class_get_nested_types (klass, &iter);
5789 g_assert (klass->nested_classes_inited);
5791 mono_class_setup_vtable (klass);
5794 * Emit all the information which is required for creating vtables so
5795 * the runtime does not need to create the MonoMethod structures which
5796 * take up a lot of space.
5799 no_special_static = !mono_class_has_special_static_fields (klass);
5801 /* Check whenever we have enough info to encode the vtable */
5802 cant_encode = FALSE;
5803 for (i = 0; i < klass->vtable_size; ++i) {
5804 MonoMethod *cm = klass->vtable [i];
5806 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5810 mono_class_has_finalizer (klass);
5812 if (klass->generic_container || cant_encode) {
5813 encode_value (-1, p, &p);
5815 encode_value (klass->vtable_size, p, &p);
5816 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);
5817 if (klass->has_cctor)
5818 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5819 if (klass->has_finalize)
5820 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5822 encode_value (klass->instance_size, p, &p);
5823 encode_value (mono_class_data_size (klass), p, &p);
5824 encode_value (klass->packing_size, p, &p);
5825 encode_value (klass->min_align, p, &p);
5827 for (i = 0; i < klass->vtable_size; ++i) {
5828 MonoMethod *cm = klass->vtable [i];
5831 encode_method_ref (acfg, cm, p, &p);
5833 encode_value (0, p, &p);
5837 acfg->stats.class_info_size += p - buf;
5839 g_assert (p - buf < buf_size);
5840 res = add_to_blob (acfg, buf, p - buf);
5847 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5849 char *debug_sym = NULL;
5853 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5854 /* Need to add a prefix to create unique symbols */
5855 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5857 prefix = g_strdup ("plt_");
5861 case MONO_PATCH_INFO_METHOD:
5862 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5864 case MONO_PATCH_INFO_INTERNAL_METHOD:
5865 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5867 case MONO_PATCH_INFO_CLASS_INIT:
5868 s = mono_type_get_name (&ji->data.klass->byval_arg);
5869 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5872 case MONO_PATCH_INFO_RGCTX_FETCH:
5873 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5875 case MONO_PATCH_INFO_ICALL_ADDR: {
5876 char *s = get_debug_sym (ji->data.method, "", cache);
5878 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5882 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5883 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5885 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5886 debug_sym = g_strdup_printf ("%s_generic_class_init", prefix);
5894 return sanitize_symbol (acfg, debug_sym);
5898 * Calls made from AOTed code are routed through a table of jumps similar to the
5899 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5900 * control to the AOT runtime through a trampoline.
5903 emit_plt (MonoAotCompile *acfg)
5909 sprintf (symbol, "plt");
5911 emit_section_change (acfg, ".text", 0);
5912 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5913 emit_label (acfg, symbol);
5914 emit_label (acfg, acfg->plt_symbol);
5916 for (i = 0; i < acfg->plt_offset; ++i) {
5917 char *debug_sym = NULL;
5918 MonoPltEntry *plt_entry = NULL;
5922 * The first plt entry is unused.
5926 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5928 debug_sym = plt_entry->debug_sym;
5930 if (acfg->thumb_mixed && !plt_entry->jit_used)
5931 /* Emit only a thumb version */
5934 /* Skip plt entries not actually called */
5935 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5938 if (acfg->llvm && !acfg->thumb_mixed) {
5939 emit_label (acfg, plt_entry->llvm_symbol);
5941 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5942 #if defined(TARGET_MACH)
5943 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5949 if (acfg->need_no_dead_strip) {
5950 emit_unset_mode (acfg);
5951 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5953 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5954 emit_label (acfg, debug_sym);
5957 emit_label (acfg, plt_entry->symbol);
5959 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
5962 emit_symbol_size (acfg, debug_sym, ".");
5965 if (acfg->thumb_mixed) {
5966 /* Make sure the ARM symbols don't alias the thumb ones */
5967 emit_zero_bytes (acfg, 16);
5970 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5973 for (i = 0; i < acfg->plt_offset; ++i) {
5974 char *debug_sym = NULL;
5975 MonoPltEntry *plt_entry = NULL;
5980 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5982 /* Skip plt entries not actually called by LLVM code */
5983 if (!plt_entry->llvm_used)
5986 if (acfg->aot_opts.write_symbols) {
5987 if (plt_entry->debug_sym)
5988 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5992 #if defined(TARGET_MACH)
5993 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5994 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5996 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5997 emit_label (acfg, debug_sym);
5999 fprintf (acfg->fp, "\n.thumb_func\n");
6001 emit_label (acfg, plt_entry->llvm_symbol);
6004 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6006 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6009 emit_symbol_size (acfg, debug_sym, ".");
6015 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6017 sprintf (symbol, "plt_end");
6018 emit_label (acfg, symbol);
6022 * emit_trampoline_full:
6024 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6025 * create_jit_info_for_trampoline ().
6027 static G_GNUC_UNUSED void
6028 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6030 char start_symbol [256];
6031 char end_symbol [256];
6033 guint32 buf_size, info_offset;
6034 MonoJumpInfo *patch_info;
6047 code_size = info->code_size;
6049 unwind_ops = info->unwind_ops;
6051 #ifdef __native_client_codegen__
6052 mono_nacl_fix_patches (code, ji);
6057 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6059 emit_section_change (acfg, ".text", 0);
6060 emit_global (acfg, start_symbol, TRUE);
6061 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6062 emit_label (acfg, start_symbol);
6064 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6065 emit_label (acfg, symbol);
6068 * The code should access everything through the GOT, so we pass
6071 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6073 emit_symbol_size (acfg, start_symbol, ".");
6076 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6077 emit_label (acfg, end_symbol);
6082 /* Sort relocations */
6083 patches = g_ptr_array_new ();
6084 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6085 if (patch_info->type != MONO_PATCH_INFO_NONE)
6086 g_ptr_array_add (patches, patch_info);
6087 g_ptr_array_sort (patches, compare_patches);
6089 buf_size = patches->len * 128 + 128;
6090 buf = g_malloc (buf_size);
6093 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6094 g_assert (p - buf < buf_size);
6096 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6098 info_offset = add_to_blob (acfg, buf, p - buf);
6100 emit_section_change (acfg, RODATA_SECT, 0);
6101 emit_global (acfg, symbol, FALSE);
6102 emit_label (acfg, symbol);
6104 emit_int32 (acfg, info_offset);
6108 guint32 encoded_len;
6112 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6114 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6115 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6118 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6119 emit_int32 (acfg, uw_offset);
6122 /* Emit debug info */
6126 sprintf (symbol, "%s", name);
6127 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6130 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6134 static G_GNUC_UNUSED void
6135 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6137 emit_trampoline_full (acfg, got_offset, info, FALSE);
6141 emit_trampolines (MonoAotCompile *acfg)
6144 char end_symbol [256];
6145 int i, tramp_got_offset;
6146 MonoAotTrampoline ntype;
6147 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6151 if (!mono_aot_mode_is_full (&acfg->aot_opts))
6154 g_assert (acfg->image->assembly);
6156 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6157 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6158 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6159 MonoTrampInfo *info;
6162 * Emit the generic trampolines.
6164 * We could save some code by treating the generic trampolines as a wrapper
6165 * method, but that approach has its own complexities, so we choose the simpler
6168 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6169 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6170 #ifdef DISABLE_REMOTING
6171 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6174 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6175 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6178 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6179 emit_trampoline (acfg, acfg->got_offset, info);
6182 mono_arch_get_nullified_class_init_trampoline (&info);
6183 emit_trampoline (acfg, acfg->got_offset, info);
6184 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6185 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6186 emit_trampoline (acfg, acfg->got_offset, info);
6187 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6188 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6189 emit_trampoline (acfg, acfg->got_offset, info);
6191 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6192 emit_trampoline (acfg, acfg->got_offset, info);
6195 #ifndef MONO_ARCH_HAVE_OP_GENERIC_CLASS_INIT
6196 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6197 emit_trampoline (acfg, acfg->got_offset, info);
6200 /* Emit the exception related code pieces */
6201 mono_arch_get_restore_context (&info, TRUE);
6202 emit_trampoline (acfg, acfg->got_offset, info);
6203 mono_arch_get_call_filter (&info, TRUE);
6204 emit_trampoline (acfg, acfg->got_offset, info);
6205 mono_arch_get_throw_exception (&info, TRUE);
6206 emit_trampoline (acfg, acfg->got_offset, info);
6207 mono_arch_get_rethrow_exception (&info, TRUE);
6208 emit_trampoline (acfg, acfg->got_offset, info);
6209 mono_arch_get_throw_corlib_exception (&info, TRUE);
6210 emit_trampoline (acfg, acfg->got_offset, info);
6212 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6213 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6214 emit_trampoline (acfg, acfg->got_offset, info);
6215 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6216 emit_trampoline (acfg, acfg->got_offset, info);
6219 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6220 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6222 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6224 /* Create a separate out trampoline for more information in stack traces */
6225 info->name = g_strdup ("gsharedvt_out_trampoline");
6226 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6230 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6232 GSList *l = mono_arch_get_trampolines (TRUE);
6235 MonoTrampInfo *info = l->data;
6237 emit_trampoline (acfg, acfg->got_offset, info);
6243 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6246 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6247 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6248 emit_trampoline (acfg, acfg->got_offset, info);
6250 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6251 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6252 emit_trampoline (acfg, acfg->got_offset, info);
6255 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6256 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6257 emit_trampoline (acfg, acfg->got_offset, info);
6263 /* delegate_invoke_impl trampolines */
6264 l = mono_arch_get_delegate_invoke_impls ();
6266 MonoTrampInfo *info = l->data;
6268 emit_trampoline (acfg, acfg->got_offset, info);
6273 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6275 /* Emit trampolines which are numerous */
6278 * These include the following:
6279 * - specific trampolines
6280 * - static rgctx invoke trampolines
6282 * These trampolines have the same code, they are parameterized by GOT
6284 * They are defined in this file, in the arch_... routines instead of
6285 * in tramp-<ARCH>.c, since it is easier to do it this way.
6289 * When running in aot-only mode, we can't create specific trampolines at
6290 * runtime, so we create a few, and save them in the AOT file.
6291 * Normal trampolines embed their argument as a literal inside the
6292 * trampoline code, we can't do that here, so instead we embed an offset
6293 * which needs to be added to the trampoline address to get the address of
6294 * the GOT slot which contains the argument value.
6295 * The generated trampolines jump to the generic trampolines using another
6296 * GOT slot, which will be setup by the AOT loader to point to the
6297 * generic trampoline code of the given type.
6301 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6305 emit_section_change (acfg, ".text", 0);
6307 tramp_got_offset = acfg->got_offset;
6309 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6311 case MONO_AOT_TRAMP_SPECIFIC:
6312 sprintf (symbol, "specific_trampolines");
6314 case MONO_AOT_TRAMP_STATIC_RGCTX:
6315 sprintf (symbol, "static_rgctx_trampolines");
6317 case MONO_AOT_TRAMP_IMT_THUNK:
6318 sprintf (symbol, "imt_thunks");
6320 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6321 sprintf (symbol, "gsharedvt_arg_trampolines");
6324 g_assert_not_reached ();
6327 sprintf (end_symbol, "%s_e", symbol);
6329 if (acfg->aot_opts.write_symbols)
6330 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6332 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6333 emit_label (acfg, symbol);
6335 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6337 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6341 case MONO_AOT_TRAMP_SPECIFIC:
6342 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6343 tramp_got_offset += 2;
6345 case MONO_AOT_TRAMP_STATIC_RGCTX:
6346 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6347 tramp_got_offset += 2;
6349 case MONO_AOT_TRAMP_IMT_THUNK:
6350 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6351 tramp_got_offset += 1;
6353 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6354 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6355 tramp_got_offset += 2;
6358 g_assert_not_reached ();
6360 #ifdef __native_client_codegen__
6361 /* align to avoid 32-byte boundary crossings */
6362 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6365 if (!acfg->trampoline_size [ntype]) {
6366 g_assert (tramp_size);
6367 acfg->trampoline_size [ntype] = tramp_size;
6371 emit_label (acfg, end_symbol);
6372 emit_int32 (acfg, 0);
6375 arch_emit_specific_trampoline_pages (acfg);
6377 /* Reserve some entries at the end of the GOT for our use */
6378 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6381 acfg->got_offset += acfg->num_trampoline_got_entries;
6385 str_begins_with (const char *str1, const char *str2)
6387 int len = strlen (str2);
6388 return strncmp (str1, str2, len) == 0;
6392 mono_aot_readonly_field_override (MonoClassField *field)
6395 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6396 char *p = rdv->name;
6398 len = strlen (field->parent->name_space);
6399 if (strncmp (p, field->parent->name_space, len))
6404 len = strlen (field->parent->name);
6405 if (strncmp (p, field->parent->name, len))
6410 if (strcmp (p, field->name))
6412 switch (rdv->type) {
6414 return &rdv->value.i1;
6416 return &rdv->value.i2;
6418 return &rdv->value.i4;
6427 add_readonly_value (MonoAotOptions *opts, const char *val)
6432 /* the format of val is:
6433 * namespace.typename.fieldname=type/value
6434 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6436 fval = strrchr (val, '/');
6438 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6441 tval = strrchr (val, '=');
6443 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6446 rdv = g_new0 (ReadOnlyValue, 1);
6447 rdv->name = g_malloc0 (tval - val + 1);
6448 memcpy (rdv->name, val, tval - val);
6451 if (strncmp (tval, "i1", 2) == 0) {
6452 rdv->value.i1 = atoi (fval);
6453 rdv->type = MONO_TYPE_I1;
6454 } else if (strncmp (tval, "i2", 2) == 0) {
6455 rdv->value.i2 = atoi (fval);
6456 rdv->type = MONO_TYPE_I2;
6457 } else if (strncmp (tval, "i4", 2) == 0) {
6458 rdv->value.i4 = atoi (fval);
6459 rdv->type = MONO_TYPE_I4;
6461 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6464 rdv->next = readonly_values;
6465 readonly_values = rdv;
6469 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6471 gchar **args, **ptr;
6473 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6474 for (ptr = args; ptr && *ptr; ptr ++) {
6475 const char *arg = *ptr;
6477 if (str_begins_with (arg, "outfile=")) {
6478 opts->outfile = g_strdup (arg + strlen ("outfile="));
6479 } else if (str_begins_with (arg, "llvm-outfile=")) {
6480 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6481 } else if (str_begins_with (arg, "save-temps")) {
6482 opts->save_temps = TRUE;
6483 } else if (str_begins_with (arg, "keep-temps")) {
6484 opts->save_temps = TRUE;
6485 } else if (str_begins_with (arg, "write-symbols")) {
6486 opts->write_symbols = TRUE;
6487 } else if (str_begins_with (arg, "no-write-symbols")) {
6488 opts->write_symbols = FALSE;
6489 } else if (str_begins_with (arg, "metadata-only")) {
6490 opts->metadata_only = TRUE;
6491 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6492 opts->bind_to_runtime_version = TRUE;
6493 } else if (str_begins_with (arg, "full")) {
6494 opts->mode = MONO_AOT_MODE_FULL;
6495 } else if (str_begins_with (arg, "hybrid")) {
6496 opts->mode = MONO_AOT_MODE_HYBRID;
6497 } else if (str_begins_with (arg, "threads=")) {
6498 opts->nthreads = atoi (arg + strlen ("threads="));
6499 } else if (str_begins_with (arg, "static")) {
6500 opts->static_link = TRUE;
6501 opts->no_dlsym = TRUE;
6502 } else if (str_begins_with (arg, "asmonly")) {
6503 opts->asm_only = TRUE;
6504 } else if (str_begins_with (arg, "asmwriter")) {
6505 opts->asm_writer = TRUE;
6506 } else if (str_begins_with (arg, "nodebug")) {
6507 opts->nodebug = TRUE;
6508 } else if (str_begins_with (arg, "dwarfdebug")) {
6509 opts->dwarf_debug = TRUE;
6510 } else if (str_begins_with (arg, "nopagetrampolines")) {
6511 opts->use_trampolines_page = FALSE;
6512 } else if (str_begins_with (arg, "ntrampolines=")) {
6513 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6514 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6515 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6516 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6517 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6518 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6519 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6520 } else if (str_begins_with (arg, "autoreg")) {
6521 opts->autoreg = TRUE;
6522 } else if (str_begins_with (arg, "tool-prefix=")) {
6523 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6524 } else if (str_begins_with (arg, "ld-flags=")) {
6525 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6526 } else if (str_begins_with (arg, "soft-debug")) {
6527 opts->soft_debug = TRUE;
6528 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6529 opts->gen_seq_points_file = TRUE;
6530 } else if (str_begins_with (arg, "direct-pinvoke")) {
6531 opts->direct_pinvoke = TRUE;
6532 } else if (str_begins_with (arg, "direct-icalls")) {
6533 opts->direct_icalls = TRUE;
6534 } else if (str_begins_with (arg, "no-direct-calls")) {
6535 opts->no_direct_calls = TRUE;
6536 } else if (str_begins_with (arg, "print-skipped")) {
6537 opts->print_skipped_methods = TRUE;
6538 } else if (str_begins_with (arg, "stats")) {
6540 } else if (str_begins_with (arg, "no-instances")) {
6541 opts->no_instances = TRUE;
6542 } else if (str_begins_with (arg, "log-generics")) {
6543 opts->log_generics = TRUE;
6544 } else if (str_begins_with (arg, "log-instances=")) {
6545 opts->log_instances = TRUE;
6546 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6547 } else if (str_begins_with (arg, "log-instances")) {
6548 opts->log_instances = TRUE;
6549 } else if (str_begins_with (arg, "internal-logfile=")) {
6550 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6551 } else if (str_begins_with (arg, "mtriple=")) {
6552 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6553 } else if (str_begins_with (arg, "llvm-path=")) {
6554 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6555 if (!g_str_has_suffix (opts->llvm_path, G_DIR_SEPARATOR_S)) {
6556 gchar *old = opts->llvm_path;
6557 opts->llvm_path = g_strconcat (opts->llvm_path, G_DIR_SEPARATOR_S, NULL);
6560 } else if (!strcmp (arg, "llvm")) {
6562 } else if (str_begins_with (arg, "readonly-value=")) {
6563 add_readonly_value (opts, arg + strlen ("readonly-value="));
6564 } else if (str_begins_with (arg, "info")) {
6565 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6567 } else if (str_begins_with (arg, "gc-maps")) {
6568 mini_gc_enable_gc_maps_for_aot ();
6569 } else if (str_begins_with (arg, "dump")) {
6570 opts->dump_json = TRUE;
6571 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6572 printf ("Supported options for --aot:\n");
6573 printf (" outfile=\n");
6574 printf (" llvm-outfile=\n");
6575 printf (" save-temps\n");
6576 printf (" keep-temps\n");
6577 printf (" write-symbols\n");
6578 printf (" metadata-only\n");
6579 printf (" bind-to-runtime-version\n");
6581 printf (" threads=\n");
6582 printf (" static\n");
6583 printf (" asmonly\n");
6584 printf (" asmwriter\n");
6585 printf (" nodebug\n");
6586 printf (" dwarfdebug\n");
6587 printf (" ntrampolines=\n");
6588 printf (" nrgctx-trampolines=\n");
6589 printf (" nimt-trampolines=\n");
6590 printf (" ngsharedvt-trampolines=\n");
6591 printf (" autoreg\n");
6592 printf (" tool-prefix=\n");
6593 printf (" readonly-value=\n");
6594 printf (" soft-debug\n");
6595 printf (" gen-seq-points-file\n");
6596 printf (" gc-maps\n");
6597 printf (" print-skipped\n");
6598 printf (" no-instances\n");
6599 printf (" stats\n");
6602 printf (" help/?\n");
6605 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6610 if (opts->use_trampolines_page) {
6611 opts->ntrampolines = 0;
6612 opts->nrgctx_trampolines = 0;
6613 opts->nimt_trampolines = 0;
6614 opts->ngsharedvt_arg_trampolines = 0;
6620 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6622 MonoMethod *method = (MonoMethod*)key;
6623 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6624 MonoAotCompile *acfg = user_data;
6625 MonoJumpInfoToken *new_ji;
6627 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6628 new_ji->image = ji->image;
6629 new_ji->token = ji->token;
6630 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6634 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6636 if (klass->type_token)
6638 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6641 return can_encode_class (acfg, klass->element_class);
6646 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6648 if (method->wrapper_type) {
6649 switch (method->wrapper_type) {
6650 case MONO_WRAPPER_NONE:
6651 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6652 case MONO_WRAPPER_XDOMAIN_INVOKE:
6653 case MONO_WRAPPER_STFLD:
6654 case MONO_WRAPPER_LDFLD:
6655 case MONO_WRAPPER_LDFLDA:
6656 case MONO_WRAPPER_LDFLD_REMOTE:
6657 case MONO_WRAPPER_STFLD_REMOTE:
6658 case MONO_WRAPPER_STELEMREF:
6659 case MONO_WRAPPER_ISINST:
6660 case MONO_WRAPPER_PROXY_ISINST:
6661 case MONO_WRAPPER_ALLOC:
6662 case MONO_WRAPPER_REMOTING_INVOKE:
6663 case MONO_WRAPPER_UNKNOWN:
6664 case MONO_WRAPPER_WRITE_BARRIER:
6665 case MONO_WRAPPER_DELEGATE_INVOKE:
6666 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6667 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6668 case MONO_WRAPPER_SYNCHRONIZED:
6670 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6671 case MONO_WRAPPER_CASTCLASS: {
6672 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6681 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6685 if (!method->token) {
6686 /* The method is part of a constructed type like Int[,].Set (). */
6687 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6688 if (method->klass->rank)
6698 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6700 switch (patch_info->type) {
6701 case MONO_PATCH_INFO_METHOD:
6702 case MONO_PATCH_INFO_METHODCONST:
6703 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6704 MonoMethod *method = patch_info->data.method;
6706 return can_encode_method (acfg, method);
6708 case MONO_PATCH_INFO_VTABLE:
6709 case MONO_PATCH_INFO_CLASS_INIT:
6710 case MONO_PATCH_INFO_CLASS:
6711 case MONO_PATCH_INFO_IID:
6712 case MONO_PATCH_INFO_ADJUSTED_IID:
6713 if (!can_encode_class (acfg, patch_info->data.klass)) {
6714 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6718 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6719 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6720 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6725 case MONO_PATCH_INFO_RGCTX_FETCH: {
6726 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6728 if (!can_encode_method (acfg, entry->method))
6730 if (!can_encode_patch (acfg, entry->data))
6744 * AOT compile a given method.
6745 * This function might be called by multiple threads, so it must be thread-safe.
6748 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6751 MonoJumpInfo *patch_info;
6754 MonoMethod *wrapped;
6757 if (acfg->aot_opts.metadata_only)
6760 mono_acfg_lock (acfg);
6761 index = get_method_index (acfg, method);
6762 mono_acfg_unlock (acfg);
6764 /* fixme: maybe we can also precompile wrapper methods */
6765 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6766 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6767 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6768 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6772 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6775 wrapped = mono_marshal_method_from_wrapper (method);
6776 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6777 // FIXME: The wrapper should be generic too, but it is not
6780 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6783 InterlockedIncrement (&acfg->stats.mcount);
6786 if (method->is_generic || method->klass->generic_container) {
6787 InterlockedIncrement (&acfg->stats.genericcount);
6792 //acfg->aot_opts.print_skipped_methods = TRUE;
6795 * Since these methods are the only ones which are compiled with
6796 * AOT support, and they are not used by runtime startup/shutdown code,
6797 * the runtime will not see AOT methods during AOT compilation,so it
6798 * does not need to support them by creating a fake GOT etc.
6800 flags = JIT_FLAG_AOT;
6801 if (mono_aot_mode_is_full (&acfg->aot_opts))
6802 flags |= JIT_FLAG_FULL_AOT;
6804 flags |= JIT_FLAG_LLVM;
6805 if (acfg->aot_opts.no_direct_calls)
6806 flags |= JIT_FLAG_NO_DIRECT_ICALLS;
6807 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6808 mono_loader_clear_error ();
6810 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6811 if (acfg->aot_opts.print_skipped_methods)
6812 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6813 InterlockedIncrement (&acfg->stats.genericcount);
6816 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6817 if (acfg->aot_opts.print_skipped_methods)
6818 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6819 /* Let the exception happen at runtime */
6823 if (cfg->disable_aot) {
6824 if (acfg->aot_opts.print_skipped_methods)
6825 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6826 InterlockedIncrement (&acfg->stats.ocount);
6827 mono_destroy_compile (cfg);
6830 cfg->method_index = index;
6832 /* Nullify patches which need no aot processing */
6833 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6834 switch (patch_info->type) {
6835 case MONO_PATCH_INFO_LABEL:
6836 case MONO_PATCH_INFO_BB:
6837 patch_info->type = MONO_PATCH_INFO_NONE;
6844 /* Collect method->token associations from the cfg */
6845 mono_acfg_lock (acfg);
6846 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6847 mono_acfg_unlock (acfg);
6848 g_hash_table_destroy (cfg->token_info_hash);
6849 cfg->token_info_hash = NULL;
6852 * Check for absolute addresses.
6855 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6856 switch (patch_info->type) {
6857 case MONO_PATCH_INFO_ABS:
6858 /* unable to handle this */
6867 if (acfg->aot_opts.print_skipped_methods)
6868 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6869 InterlockedIncrement (&acfg->stats.abscount);
6870 mono_destroy_compile (cfg);
6874 /* Lock for the rest of the code */
6875 mono_acfg_lock (acfg);
6878 * Check for methods/klasses we can't encode.
6881 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6882 if (!can_encode_patch (acfg, patch_info))
6887 if (acfg->aot_opts.print_skipped_methods)
6888 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6889 acfg->stats.ocount++;
6890 mono_destroy_compile (cfg);
6891 mono_acfg_unlock (acfg);
6895 if (method->is_inflated && acfg->aot_opts.log_instances) {
6896 if (acfg->instances_logfile)
6897 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6899 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6902 /* Adds generic instances referenced by this method */
6904 * The depth is used to avoid infinite loops when generic virtual recursion is
6907 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6908 if (!acfg->aot_opts.no_instances && depth < 32) {
6909 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6910 switch (patch_info->type) {
6911 case MONO_PATCH_INFO_METHOD: {
6912 MonoMethod *m = patch_info->data.method;
6913 if (m->is_inflated) {
6914 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6915 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6916 !method_has_type_vars (m)) {
6917 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6918 if (mono_aot_mode_is_full (&acfg->aot_opts))
6919 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6921 add_extra_method_with_depth (acfg, m, depth + 1);
6922 add_types_from_method_header (acfg, m);
6925 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6927 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
6928 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
6930 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
6931 add_extra_method_with_depth (acfg, m, depth + 1);
6935 case MONO_PATCH_INFO_VTABLE: {
6936 MonoClass *klass = patch_info->data.klass;
6938 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6939 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6942 case MONO_PATCH_INFO_SFLDA: {
6943 MonoClass *klass = patch_info->data.field->parent;
6945 /* The .cctor needs to run at runtime. */
6946 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6947 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6956 /* Determine whenever the method has GOT slots */
6957 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6958 switch (patch_info->type) {
6959 case MONO_PATCH_INFO_GOT_OFFSET:
6960 case MONO_PATCH_INFO_NONE:
6961 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6962 case MONO_PATCH_INFO_GC_NURSERY_START:
6964 case MONO_PATCH_INFO_IMAGE:
6965 /* The assembly is stored in GOT slot 0 */
6966 if (patch_info->data.image != acfg->image)
6967 cfg->has_got_slots = TRUE;
6970 if (!is_plt_patch (patch_info))
6971 cfg->has_got_slots = TRUE;
6976 if (!cfg->has_got_slots)
6977 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6980 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6982 /* Make a copy of the patch info which is in the mempool */
6984 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6986 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6987 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6990 patches = new_patch_info;
6992 patches_end->next = new_patch_info;
6993 patches_end = new_patch_info;
6995 cfg->patch_info = patches;
6997 /* Make a copy of the unwind info */
6999 GSList *l, *unwind_ops;
7003 for (l = cfg->unwind_ops; l; l = l->next) {
7004 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7005 memcpy (op, l->data, sizeof (MonoUnwindOp));
7006 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7008 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7010 /* Make a copy of the argument/local info */
7012 MonoInst **args, **locals;
7013 MonoMethodSignature *sig;
7014 MonoMethodHeader *header;
7017 sig = mono_method_signature (method);
7018 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7019 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7020 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7021 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7025 header = mono_method_get_header (method);
7026 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7027 for (i = 0; i < header->num_locals; ++i) {
7028 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7029 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7031 cfg->locals = locals;
7034 /* Free some fields used by cfg to conserve memory */
7035 mono_mempool_destroy (cfg->mempool);
7036 cfg->mempool = NULL;
7037 g_free (cfg->varinfo);
7038 cfg->varinfo = NULL;
7042 mono_regstate_free (cfg->rs);
7046 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7048 while (index >= acfg->cfgs_size) {
7049 MonoCompile **new_cfgs;
7052 new_size = acfg->cfgs_size * 2;
7053 new_cfgs = g_new0 (MonoCompile*, new_size);
7054 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7055 g_free (acfg->cfgs);
7056 acfg->cfgs = new_cfgs;
7057 acfg->cfgs_size = new_size;
7059 acfg->cfgs [index] = cfg;
7061 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7064 if (cfg->orig_method->wrapper_type)
7065 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7068 mono_acfg_unlock (acfg);
7070 InterlockedIncrement (&acfg->stats.ccount);
7074 compile_thread_main (gpointer *user_data)
7076 MonoDomain *domain = user_data [0];
7077 MonoAotCompile *acfg = user_data [1];
7078 GPtrArray *methods = user_data [2];
7081 mono_thread_attach (domain);
7083 for (i = 0; i < methods->len; ++i)
7084 compile_method (acfg, g_ptr_array_index (methods, i));
7088 load_profile_files (MonoAotCompile *acfg)
7092 int file_index, res, method_index, i;
7095 GList *unordered, *l;
7100 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7102 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7107 infile = fopen (tmp, "r");
7110 printf ("Using profile data file '%s'\n", tmp);
7115 res = fscanf (infile, "%32s\n", ver);
7116 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7117 printf ("Profile file has wrong version or invalid.\n");
7124 MonoMethodDesc *desc;
7127 if (fgets (name, 1023, infile) == NULL)
7130 /* Kill the newline */
7131 if (strlen (name) > 0)
7132 name [strlen (name) - 1] = '\0';
7134 desc = mono_method_desc_new (name, TRUE);
7136 method = mono_method_desc_search_in_image (desc, acfg->image);
7138 if (method && mono_method_get_token (method)) {
7139 token = mono_method_get_token (method);
7140 method_index = mono_metadata_token_index (token) - 1;
7143 for (i = 0; i < acfg->method_order->len; ++i) {
7144 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7150 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7152 //printf ("No method found matching '%s'.\n", name);
7158 /* Add missing methods */
7160 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7162 for (i = 0; i < acfg->method_order->len; ++i) {
7163 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7169 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7171 unordered = g_list_reverse (unordered);
7172 for (l = unordered; l; l = l->next)
7173 g_ptr_array_add (acfg->method_order, l->data);
7176 /* Used by the LLVM backend */
7178 mono_aot_get_got_offset (MonoJumpInfo *ji)
7180 return get_got_offset (llvm_acfg, TRUE, ji);
7184 mono_aot_get_method_name (MonoCompile *cfg)
7186 if (llvm_acfg->aot_opts.static_link)
7187 /* Include the assembly name too to avoid duplicate symbol errors */
7188 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7190 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7194 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7196 return is_direct_callable (llvm_acfg, NULL, patch_info);
7200 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7202 MonoPltEntry *plt_entry;
7204 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7205 plt_entry->llvm_used = FALSE;
7209 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7211 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7212 MonoPltEntry *plt_entry;
7213 const char *sym = NULL;
7216 ji->data.target = data;
7218 if (!can_encode_patch (llvm_acfg, ji))
7221 if (llvm_acfg->aot_opts.direct_icalls) {
7222 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7223 /* Call to a C function implementing a jit icall */
7224 sym = mono_lookup_jit_icall_symbol (data);
7225 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7226 MonoMethod *method = (gpointer)data;
7227 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7228 sym = mono_lookup_icall_symbol (method);
7231 return g_strdup (sym);
7234 plt_entry = get_plt_entry (llvm_acfg, ji);
7235 plt_entry->llvm_used = TRUE;
7237 #if defined(TARGET_MACH)
7238 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7240 return g_strdup_printf (plt_entry->llvm_symbol);
7245 mono_aot_get_method_index (MonoMethod *method)
7247 g_assert (llvm_acfg);
7248 return get_method_index (llvm_acfg, method);
7252 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7256 mono_acfg_lock (llvm_acfg);
7257 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7258 mono_acfg_unlock (llvm_acfg);
7264 execute_system (const char * command)
7269 // We need an extra set of quotes around the whole command to properly handle commands
7270 // with spaces since internally the command is called through "cmd /c.
7271 command = g_strdup_printf ("\"%s\"", command);
7273 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7274 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7275 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7276 status = _wsystem (wstr);
7281 status = system (command);
7292 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7296 emit_llvm_file (MonoAotCompile *acfg)
7298 char *command, *opts, *tempbc, *output_fname;
7300 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7301 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7305 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7306 * a lot of time, and doesn't seem to save much space.
7307 * The following optimizations cannot be enabled:
7309 * - 'jump-threading' changes our blockaddress references to int constants.
7310 * - 'basiccg' fails because it contains:
7311 * if (CS && !isa<IntrinsicInst>(II)) {
7312 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7313 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7314 * The opt list below was produced by taking the output of:
7315 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7316 * then removing tailcallelim + the global opts.
7317 * strip-dead-prototypes deletes unused intrinsics definitions.
7319 opts = g_strdup ("-instcombine -simplifycfg");
7320 //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");
7321 /* The dse pass is disabled because of #13734 and #17616 */
7323 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7324 * // If we have no DataLayout information around, then the size of the store
7325 * // is inferrable from the pointee type. If they are the same type, then
7326 * // we know that the store is safe.
7327 * if (AA.getDataLayout() == 0 &&
7328 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7329 * return OverwriteComplete;
7330 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7332 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");
7334 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7335 aot_printf (acfg, "Executing opt: %s\n", command);
7336 if (execute_system (command) != 0)
7341 if (!acfg->llc_args)
7342 acfg->llc_args = g_string_new ("");
7344 /* Verbose asm slows down llc greatly */
7345 g_string_append (acfg->llc_args, " -asm-verbose=false");
7347 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7349 if (acfg->aot_opts.mtriple)
7350 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7352 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7354 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7355 /* ios requires PIC code now */
7356 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7358 if (llvm_acfg->aot_opts.static_link)
7359 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7361 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7363 unlink (acfg->tmpfname);
7365 if (acfg->llvm_owriter) {
7366 /* Emit an object file directly */
7367 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7368 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7370 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7372 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7373 g_free (output_fname);
7375 aot_printf (acfg, "Executing llc: %s\n", command);
7377 if (execute_system (command) != 0)
7384 emit_code (MonoAotCompile *acfg)
7386 int oindex, i, prev_index;
7389 #if defined(TARGET_POWERPC64)
7390 sprintf (symbol, ".Lgot_addr");
7391 emit_section_change (acfg, ".text", 0);
7392 emit_alignment (acfg, 8);
7393 emit_label (acfg, symbol);
7394 emit_pointer (acfg, acfg->got_symbol);
7398 * This global symbol is used to compute the address of each method using the
7399 * code_offsets array. It is also used to compute the memory ranges occupied by
7400 * AOT code, so it must be equal to the address of the first emitted method.
7402 emit_section_change (acfg, ".text", 0);
7403 emit_alignment_code (acfg, 8);
7405 for (i = 0; i < acfg->nmethods; ++i) {
7406 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7407 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7412 if (!acfg->methods_symbol) {
7413 sprintf (symbol, "methods");
7414 emit_label (acfg, symbol);
7415 acfg->methods_symbol = g_strdup (symbol);
7417 emit_label (acfg, "jit_code_start");
7420 * Emit some padding so the local symbol for the first method doesn't have the
7421 * same address as 'methods'.
7423 #if defined(__default_codegen__)
7424 emit_padding (acfg, 16);
7425 #elif defined(__native_client_codegen__)
7427 const int kPaddingSize = 16;
7428 guint8 pad_buffer[kPaddingSize];
7429 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7430 emit_bytes (acfg, pad_buffer, kPaddingSize);
7434 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7438 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7440 cfg = acfg->cfgs [i];
7445 method = cfg->orig_method;
7447 /* Emit unbox trampoline */
7448 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7449 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7451 emit_section_change (acfg, ".text", 0);
7452 #ifdef __native_client_codegen__
7453 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7456 if (acfg->thumb_mixed && cfg->compile_llvm) {
7457 emit_set_thumb_mode (acfg);
7458 fprintf (acfg->fp, "\n.thumb_func\n");
7461 emit_label (acfg, symbol);
7463 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7465 if (acfg->thumb_mixed && cfg->compile_llvm)
7466 emit_set_arm_mode (acfg);
7469 if (cfg->compile_llvm)
7470 acfg->stats.llvm_count ++;
7472 emit_method_code (acfg, cfg);
7475 emit_section_change (acfg, ".text", 0);
7476 emit_alignment_code (acfg, 8);
7477 emit_label (acfg, "jit_code_end");
7479 /* To distinguish it from the next symbol */
7480 emit_padding (acfg, 4);
7483 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7484 * from optimizing them away, since it doesn't see that code_offsets references them.
7485 * JITted methods don't need this since they are referenced using assembler local
7487 * FIXME: This is why write-symbols doesn't work on OSX ?
7489 if (acfg->llvm && acfg->need_no_dead_strip) {
7490 fprintf (acfg->fp, "\n");
7491 for (i = 0; i < acfg->nmethods; ++i) {
7492 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7493 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7498 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7499 * This is PIE code, and the linker can update it if needed.
7501 sprintf (symbol, "method_addresses");
7502 emit_section_change (acfg, ".text", 1);
7503 emit_alignment_code (acfg, 8);
7504 emit_label (acfg, symbol);
7505 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7506 emit_unset_mode (acfg);
7507 if (acfg->need_no_dead_strip)
7508 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7510 for (i = 0; i < acfg->nmethods; ++i) {
7511 #ifdef MONO_ARCH_AOT_SUPPORTED
7515 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7517 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7521 sprintf (symbol, "method_addresses_end");
7522 emit_label (acfg, symbol);
7525 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7526 sprintf (symbol, "unbox_trampolines");
7527 emit_section_change (acfg, RODATA_SECT, 0);
7528 emit_alignment (acfg, 8);
7529 emit_label (acfg, symbol);
7532 for (i = 0; i < acfg->nmethods; ++i) {
7537 cfg = acfg->cfgs [i];
7541 method = cfg->orig_method;
7543 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7544 index = get_method_index (acfg, method);
7546 emit_int32 (acfg, index);
7547 /* Make sure the table is sorted by index */
7548 g_assert (index > prev_index);
7552 sprintf (symbol, "unbox_trampolines_end");
7553 emit_label (acfg, symbol);
7554 emit_int32 (acfg, 0);
7556 /* Emit a separate table with the trampoline addresses/offsets */
7557 sprintf (symbol, "unbox_trampoline_addresses");
7558 emit_section_change (acfg, ".text", 0);
7559 emit_alignment_code (acfg, 8);
7560 emit_label (acfg, symbol);
7562 for (i = 0; i < acfg->nmethods; ++i) {
7567 cfg = acfg->cfgs [i];
7571 method = cfg->orig_method;
7573 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7574 #ifdef MONO_ARCH_AOT_SUPPORTED
7577 index = get_method_index (acfg, method);
7578 sprintf (symbol, "ut_%d", index);
7580 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7584 emit_int32 (acfg, 0);
7588 emit_info (MonoAotCompile *acfg)
7594 offsets = g_new0 (gint32, acfg->nmethods);
7596 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7597 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7599 if (acfg->cfgs [i]) {
7600 emit_method_info (acfg, acfg->cfgs [i]);
7601 offsets [i] = acfg->cfgs [i]->method_info_offset;
7607 sprintf (symbol, "method_info_offsets");
7608 emit_section_change (acfg, RODATA_SECT, 1);
7609 emit_alignment (acfg, 8);
7610 emit_label (acfg, symbol);
7612 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7617 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7619 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7620 #define mix(a,b,c) { \
7621 a -= c; a ^= rot(c, 4); c += b; \
7622 b -= a; b ^= rot(a, 6); a += c; \
7623 c -= b; c ^= rot(b, 8); b += a; \
7624 a -= c; a ^= rot(c,16); c += b; \
7625 b -= a; b ^= rot(a,19); a += c; \
7626 c -= b; c ^= rot(b, 4); b += a; \
7628 #define final(a,b,c) { \
7629 c ^= b; c -= rot(b,14); \
7630 a ^= c; a -= rot(c,11); \
7631 b ^= a; b -= rot(a,25); \
7632 c ^= b; c -= rot(b,16); \
7633 a ^= c; a -= rot(c,4); \
7634 b ^= a; b -= rot(a,14); \
7635 c ^= b; c -= rot(b,24); \
7639 mono_aot_type_hash (MonoType *t1)
7641 guint hash = t1->type;
7643 hash |= t1->byref << 6; /* do not collide with t1->type values */
7645 case MONO_TYPE_VALUETYPE:
7646 case MONO_TYPE_CLASS:
7647 case MONO_TYPE_SZARRAY:
7648 /* check if the distribution is good enough */
7649 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7651 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7652 case MONO_TYPE_ARRAY:
7653 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7654 case MONO_TYPE_GENERICINST:
7655 return ((hash << 5) - hash) ^ 0;
7662 * mono_aot_method_hash:
7664 * Return a hash code for methods which only depends on metadata.
7667 mono_aot_method_hash (MonoMethod *method)
7669 MonoMethodSignature *sig;
7673 guint32 *hashes_start, *hashes;
7675 MonoGenericInst *class_ginst = NULL;
7676 MonoGenericInst *ginst = NULL;
7678 /* Similar to the hash in mono_method_get_imt_slot () */
7680 sig = mono_method_signature (method);
7682 if (method->klass->generic_class)
7683 class_ginst = method->klass->generic_class->context.class_inst;
7684 if (method->is_inflated)
7685 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7687 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7688 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7689 hashes = hashes_start;
7691 /* Some wrappers are assigned to random classes */
7692 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7693 klass = method->klass;
7695 klass = mono_defaults.object_class;
7697 if (!method->wrapper_type) {
7700 if (klass->generic_class)
7701 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7703 full_name = mono_type_full_name (&klass->byval_arg);
7705 hashes [0] = mono_metadata_str_hash (full_name);
7709 hashes [0] = mono_metadata_str_hash (klass->name);
7710 hashes [1] = mono_metadata_str_hash (klass->name_space);
7712 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7713 /* The method name includes a stringified pointer */
7716 hashes [2] = mono_metadata_str_hash (method->name);
7717 hashes [3] = method->wrapper_type;
7718 hashes [4] = mono_aot_type_hash (sig->ret);
7720 for (i = 0; i < sig->param_count; i++) {
7721 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7724 for (i = 0; i < class_ginst->type_argc; ++i)
7725 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7728 for (i = 0; i < ginst->type_argc; ++i)
7729 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7731 g_assert (hindex == hashes_count);
7733 /* Setup internal state */
7734 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7736 /* Handle most of the hashes */
7737 while (hashes_count > 3) {
7746 /* Handle the last 3 hashes (all the case statements fall through) */
7747 switch (hashes_count) {
7748 case 3 : c += hashes [2];
7749 case 2 : b += hashes [1];
7750 case 1 : a += hashes [0];
7752 case 0: /* nothing left to add */
7756 free (hashes_start);
7765 * mono_aot_get_array_helper_from_wrapper;
7767 * Get the helper method in Array called by an array wrapper method.
7770 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7774 MonoGenericContext ctx;
7775 MonoType *args [16];
7776 char *mname, *iname, *s, *s2, *helper_name = NULL;
7778 prefix = "System.Collections.Generic";
7779 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7780 s2 = strstr (s, "`1.");
7786 //printf ("X: %s %s\n", iname, mname);
7788 if (!strcmp (iname, "IList"))
7789 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7791 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7792 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7794 g_free (helper_name);
7797 if (m->is_generic) {
7799 memset (&ctx, 0, sizeof (ctx));
7800 args [0] = &method->klass->element_class->byval_arg;
7801 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7802 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7803 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7809 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7811 typedef struct HashEntry {
7812 guint32 key, value, index;
7813 struct HashEntry *next;
7817 * emit_extra_methods:
7819 * Emit methods which are not in the METHOD table, like wrappers.
7822 emit_extra_methods (MonoAotCompile *acfg)
7824 int i, table_size, buf_size;
7827 guint32 *info_offsets;
7830 HashEntry *entry, *new_entry;
7831 int nmethods, max_chain_length;
7834 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7836 /* Emit method info */
7838 for (i = 0; i < acfg->extra_methods->len; ++i) {
7839 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7840 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7846 p = buf = g_malloc (buf_size);
7850 method = cfg->method_to_register;
7852 encode_method_ref (acfg, method, p, &p);
7854 g_assert ((p - buf) < buf_size);
7856 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7861 * Construct a chained hash table for mapping indexes in extra_method_info to
7864 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7865 table = g_ptr_array_sized_new (table_size);
7866 for (i = 0; i < table_size; ++i)
7867 g_ptr_array_add (table, NULL);
7868 chain_lengths = g_new0 (int, table_size);
7869 max_chain_length = 0;
7870 for (i = 0; i < acfg->extra_methods->len; ++i) {
7871 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7872 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7878 key = info_offsets [i];
7879 value = get_method_index (acfg, method);
7881 hash = mono_aot_method_hash (method) % table_size;
7882 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
7884 chain_lengths [hash] ++;
7885 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7887 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7888 new_entry->key = key;
7889 new_entry->value = value;
7891 entry = g_ptr_array_index (table, hash);
7892 if (entry == NULL) {
7893 new_entry->index = hash;
7894 g_ptr_array_index (table, hash) = new_entry;
7897 entry = entry->next;
7899 entry->next = new_entry;
7900 new_entry->index = table->len;
7901 g_ptr_array_add (table, new_entry);
7905 //printf ("MAX: %d\n", max_chain_length);
7907 /* Emit the table */
7908 sprintf (symbol, "extra_method_table");
7909 emit_section_change (acfg, RODATA_SECT, 0);
7910 emit_alignment (acfg, 8);
7911 emit_label (acfg, symbol);
7913 emit_int32 (acfg, table_size);
7914 for (i = 0; i < table->len; ++i) {
7915 HashEntry *entry = g_ptr_array_index (table, i);
7917 if (entry == NULL) {
7918 emit_int32 (acfg, 0);
7919 emit_int32 (acfg, 0);
7920 emit_int32 (acfg, 0);
7922 //g_assert (entry->key > 0);
7923 emit_int32 (acfg, entry->key);
7924 emit_int32 (acfg, entry->value);
7926 emit_int32 (acfg, entry->next->index);
7928 emit_int32 (acfg, 0);
7933 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7934 * This is used by mono_aot_find_jit_info ().
7936 sprintf (symbol, "extra_method_info_offsets");
7937 emit_section_change (acfg, RODATA_SECT, 0);
7938 emit_alignment (acfg, 8);
7939 emit_label (acfg, symbol);
7941 emit_int32 (acfg, acfg->extra_methods->len);
7942 for (i = 0; i < acfg->extra_methods->len; ++i) {
7943 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7945 emit_int32 (acfg, get_method_index (acfg, method));
7946 emit_int32 (acfg, info_offsets [i]);
7951 emit_exception_info (MonoAotCompile *acfg)
7956 SeqPointData sp_data;
7957 gboolean seq_points_to_file = FALSE;
7959 offsets = g_new0 (gint32, acfg->nmethods);
7960 for (i = 0; i < acfg->nmethods; ++i) {
7961 if (acfg->cfgs [i]) {
7962 MonoCompile *cfg = acfg->cfgs [i];
7964 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
7965 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
7966 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
7967 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
7968 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
7970 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
7971 offsets [i] = cfg->ex_info_offset;
7973 if (method_seq_points_to_file) {
7974 if (!seq_points_to_file) {
7975 mono_seq_point_data_init (&sp_data, acfg->nmethods);
7976 seq_points_to_file = TRUE;
7978 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
7985 if (seq_points_to_file) {
7986 char *seq_points_aot_file;
7987 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
7988 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
7989 mono_seq_point_data_free (&sp_data);
7990 g_free (seq_points_aot_file);
7993 sprintf (symbol, "ex_info_offsets");
7994 emit_section_change (acfg, RODATA_SECT, 1);
7995 emit_alignment (acfg, 8);
7996 emit_label (acfg, symbol);
7998 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
8003 emit_unwind_info (MonoAotCompile *acfg)
8009 * The unwind info contains a lot of duplicates so we emit each unique
8010 * entry once, and only store the offset from the start of the table in the
8014 sprintf (symbol, "unwind_info");
8015 emit_section_change (acfg, RODATA_SECT, 1);
8016 emit_alignment (acfg, 8);
8017 emit_label (acfg, symbol);
8019 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8020 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8021 guint8 *unwind_info;
8022 guint32 unwind_info_len;
8026 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8029 encode_value (unwind_info_len, p, &p);
8030 emit_bytes (acfg, buf, p - buf);
8031 emit_bytes (acfg, unwind_info, unwind_info_len);
8033 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8038 emit_class_info (MonoAotCompile *acfg)
8044 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8045 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8046 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8048 sprintf (symbol, "class_info_offsets");
8049 emit_section_change (acfg, RODATA_SECT, 1);
8050 emit_alignment (acfg, 8);
8051 emit_label (acfg, symbol);
8053 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8057 typedef struct ClassNameTableEntry {
8058 guint32 token, index;
8059 struct ClassNameTableEntry *next;
8060 } ClassNameTableEntry;
8063 emit_class_name_table (MonoAotCompile *acfg)
8066 guint32 token, hash;
8071 ClassNameTableEntry *entry, *new_entry;
8074 * Construct a chained hash table for mapping class names to typedef tokens.
8076 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8077 table = g_ptr_array_sized_new (table_size);
8078 for (i = 0; i < table_size; ++i)
8079 g_ptr_array_add (table, NULL);
8080 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8082 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8083 klass = mono_class_get_checked (acfg->image, token, &error);
8085 mono_error_cleanup (&error);
8088 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8089 hash = mono_metadata_str_hash (full_name) % table_size;
8092 /* FIXME: Allocate from the mempool */
8093 new_entry = g_new0 (ClassNameTableEntry, 1);
8094 new_entry->token = token;
8096 entry = g_ptr_array_index (table, hash);
8097 if (entry == NULL) {
8098 new_entry->index = hash;
8099 g_ptr_array_index (table, hash) = new_entry;
8102 entry = entry->next;
8104 entry->next = new_entry;
8105 new_entry->index = table->len;
8106 g_ptr_array_add (table, new_entry);
8110 /* Emit the table */
8111 sprintf (symbol, "class_name_table");
8112 emit_section_change (acfg, RODATA_SECT, 0);
8113 emit_alignment (acfg, 8);
8114 emit_label (acfg, symbol);
8116 /* FIXME: Optimize memory usage */
8117 g_assert (table_size < 65000);
8118 emit_int16 (acfg, table_size);
8119 g_assert (table->len < 65000);
8120 for (i = 0; i < table->len; ++i) {
8121 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8123 if (entry == NULL) {
8124 emit_int16 (acfg, 0);
8125 emit_int16 (acfg, 0);
8127 emit_int16 (acfg, mono_metadata_token_index (entry->token));
8129 emit_int16 (acfg, entry->next->index);
8131 emit_int16 (acfg, 0);
8137 emit_image_table (MonoAotCompile *acfg)
8143 * The image table is small but referenced in a lot of places.
8144 * So we emit it at once, and reference its elements by an index.
8147 sprintf (symbol, "image_table");
8148 emit_section_change (acfg, RODATA_SECT, 1);
8149 emit_alignment (acfg, 8);
8150 emit_label (acfg, symbol);
8152 emit_int32 (acfg, acfg->image_table->len);
8153 for (i = 0; i < acfg->image_table->len; i++) {
8154 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8155 MonoAssemblyName *aname = &image->assembly->aname;
8157 /* FIXME: Support multi-module assemblies */
8158 g_assert (image->assembly->image == image);
8160 emit_string (acfg, image->assembly_name);
8161 emit_string (acfg, image->guid);
8162 emit_string (acfg, aname->culture ? aname->culture : "");
8163 emit_string (acfg, (const char*)aname->public_key_token);
8165 emit_alignment (acfg, 8);
8166 emit_int32 (acfg, aname->flags);
8167 emit_int32 (acfg, aname->major);
8168 emit_int32 (acfg, aname->minor);
8169 emit_int32 (acfg, aname->build);
8170 emit_int32 (acfg, aname->revision);
8175 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8178 int i, first_plt_got_patch = 0, buf_size;
8180 guint32 *got_info_offsets;
8181 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8183 /* Add the patches needed by the PLT to the GOT */
8185 acfg->plt_got_offset_base = acfg->got_offset;
8186 first_plt_got_patch = info->got_patches->len;
8187 for (i = 1; i < acfg->plt_offset; ++i) {
8188 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8190 g_ptr_array_add (info->got_patches, plt_entry->ji);
8192 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8195 acfg->got_offset += acfg->plt_offset;
8200 * - optimize offsets table.
8201 * - reduce number of exported symbols.
8202 * - emit info for a klass only once.
8203 * - determine when a method uses a GOT slot which is guaranteed to be already
8205 * - clean up and document the code.
8206 * - use String.Empty in class libs.
8209 /* Encode info required to decode shared GOT entries */
8210 buf_size = info->got_patches->len * 128;
8211 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8212 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8214 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8216 if (acfg->plt_offset)
8217 acfg->plt_got_info_offsets [0] = 0;
8219 for (i = 0; i < info->got_patches->len; ++i) {
8220 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8225 encode_value (ji->type, p, &p);
8227 encode_patch (acfg, ji, p, &p);
8228 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8229 g_assert (p - buf <= buf_size);
8230 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8232 if (!llvm && i >= first_plt_got_patch)
8233 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8234 acfg->stats.got_info_size += p - buf;
8237 /* Emit got_info_offsets table */
8239 sprintf (symbol, "llvm_got_info_offsets");
8241 sprintf (symbol, "got_info_offsets");
8242 emit_section_change (acfg, RODATA_SECT, 1);
8243 emit_alignment (acfg, 8);
8244 emit_label (acfg, symbol);
8246 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8247 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8251 emit_got (MonoAotCompile *acfg)
8255 /* Don't make GOT global so accesses to it don't need relocations */
8256 sprintf (symbol, "%s", acfg->got_symbol);
8257 emit_section_change (acfg, ".bss", 0);
8258 emit_alignment (acfg, 8);
8259 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8260 emit_label (acfg, symbol);
8261 if (acfg->got_offset > 0)
8262 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8264 sprintf (symbol, "got_end");
8265 emit_label (acfg, symbol);
8268 typedef struct GlobalsTableEntry {
8269 guint32 value, index;
8270 struct GlobalsTableEntry *next;
8271 } GlobalsTableEntry;
8274 emit_globals (MonoAotCompile *acfg)
8280 GlobalsTableEntry *entry, *new_entry;
8282 if (!acfg->aot_opts.static_link)
8286 * When static linking, we emit a table containing our globals.
8290 * Construct a chained hash table for mapping global names to their index in
8291 * the globals table.
8293 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8294 table = g_ptr_array_sized_new (table_size);
8295 for (i = 0; i < table_size; ++i)
8296 g_ptr_array_add (table, NULL);
8297 for (i = 0; i < acfg->globals->len; ++i) {
8298 char *name = g_ptr_array_index (acfg->globals, i);
8300 hash = mono_metadata_str_hash (name) % table_size;
8302 /* FIXME: Allocate from the mempool */
8303 new_entry = g_new0 (GlobalsTableEntry, 1);
8304 new_entry->value = i;
8306 entry = g_ptr_array_index (table, hash);
8307 if (entry == NULL) {
8308 new_entry->index = hash;
8309 g_ptr_array_index (table, hash) = new_entry;
8312 entry = entry->next;
8314 entry->next = new_entry;
8315 new_entry->index = table->len;
8316 g_ptr_array_add (table, new_entry);
8320 /* Emit the table */
8321 sprintf (symbol, ".Lglobals_hash");
8322 emit_section_change (acfg, RODATA_SECT, 0);
8323 emit_alignment (acfg, 8);
8324 emit_label (acfg, symbol);
8326 /* FIXME: Optimize memory usage */
8327 g_assert (table_size < 65000);
8328 emit_int16 (acfg, table_size);
8329 for (i = 0; i < table->len; ++i) {
8330 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8332 if (entry == NULL) {
8333 emit_int16 (acfg, 0);
8334 emit_int16 (acfg, 0);
8336 emit_int16 (acfg, entry->value + 1);
8338 emit_int16 (acfg, entry->next->index);
8340 emit_int16 (acfg, 0);
8344 /* Emit the names */
8345 for (i = 0; i < acfg->globals->len; ++i) {
8346 char *name = g_ptr_array_index (acfg->globals, i);
8348 sprintf (symbol, "name_%d", i);
8349 emit_section_change (acfg, RODATA_SECT, 1);
8351 emit_alignment (acfg, 4);
8353 emit_label (acfg, symbol);
8354 emit_string (acfg, name);
8357 /* Emit the globals table */
8358 sprintf (symbol, "globals");
8359 emit_section_change (acfg, ".data", 0);
8360 /* This is not a global, since it is accessed by the init function */
8361 emit_alignment (acfg, 8);
8362 emit_label (acfg, symbol);
8364 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8365 emit_pointer (acfg, symbol);
8367 for (i = 0; i < acfg->globals->len; ++i) {
8368 char *name = g_ptr_array_index (acfg->globals, i);
8370 sprintf (symbol, "name_%d", i);
8371 emit_pointer (acfg, symbol);
8373 g_assert (strlen (name) < sizeof (symbol));
8374 sprintf (symbol, "%s", name);
8375 emit_pointer (acfg, symbol);
8377 /* Null terminate the table */
8378 emit_int32 (acfg, 0);
8379 emit_int32 (acfg, 0);
8383 emit_autoreg (MonoAotCompile *acfg)
8388 * Emit a function into the .ctor section which will be called by the ELF
8389 * loader to register this module with the runtime.
8391 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8394 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8396 arch_emit_autoreg (acfg, symbol);
8402 emit_mem_end (MonoAotCompile *acfg)
8406 sprintf (symbol, "mem_end");
8407 emit_section_change (acfg, ".text", 1);
8408 emit_alignment_code (acfg, 8);
8409 emit_label (acfg, symbol);
8413 * Emit a structure containing all the information not stored elsewhere.
8416 emit_file_info (MonoAotCompile *acfg)
8421 const char *gc_name;
8424 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8426 if (acfg->aot_opts.bind_to_runtime_version) {
8427 build_info = mono_get_runtime_build_info ();
8428 emit_string_symbol (acfg, "runtime_version", build_info);
8429 g_free (build_info);
8431 emit_string_symbol (acfg, "runtime_version", "");
8434 /* Emit a string holding the assembly name */
8435 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8438 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8441 gc_name = mono_gc_get_gc_name ();
8442 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8444 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8445 emit_section_change (acfg, ".data", 0);
8446 emit_alignment (acfg, 8);
8447 emit_label (acfg, symbol);
8448 if (!acfg->aot_opts.static_link)
8449 emit_global (acfg, symbol, FALSE);
8451 /* The data emitted here must match MonoAotFileInfo. */
8453 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8454 emit_int32 (acfg, 0);
8457 * We emit pointers to our data structures instead of emitting global symbols which
8458 * point to them, to reduce the number of globals, and because using globals leads to
8459 * various problems (i.e. arm/thumb).
8461 emit_pointer (acfg, acfg->got_symbol);
8463 emit_pointer (acfg, acfg->llvm_got_symbol);
8465 emit_pointer (acfg, NULL);
8466 emit_pointer (acfg, acfg->methods_symbol);
8467 emit_pointer (acfg, "jit_code_start");
8468 emit_pointer (acfg, "jit_code_end");
8471 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8473 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8475 emit_pointer (acfg, NULL);
8477 emit_pointer (acfg, "blob");
8478 emit_pointer (acfg, "class_name_table");
8479 emit_pointer (acfg, "class_info_offsets");
8480 emit_pointer (acfg, "method_info_offsets");
8481 emit_pointer (acfg, "ex_info_offsets");
8482 emit_pointer (acfg, "method_addresses");
8483 emit_pointer (acfg, "extra_method_info_offsets");
8484 emit_pointer (acfg, "extra_method_table");
8485 emit_pointer (acfg, "got_info_offsets");
8487 emit_pointer (acfg, "llvm_got_info_offsets");
8489 emit_pointer (acfg, NULL);
8490 emit_pointer (acfg, "unwind_info");
8491 emit_pointer (acfg, "mem_end");
8492 emit_pointer (acfg, "image_table");
8493 emit_pointer (acfg, "plt");
8494 emit_pointer (acfg, "plt_end");
8495 emit_pointer (acfg, "assembly_guid");
8496 emit_pointer (acfg, "runtime_version");
8497 if (acfg->num_trampoline_got_entries) {
8498 emit_pointer (acfg, "specific_trampolines");
8499 emit_pointer (acfg, "static_rgctx_trampolines");
8500 emit_pointer (acfg, "imt_thunks");
8501 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8503 emit_pointer (acfg, NULL);
8504 emit_pointer (acfg, NULL);
8505 emit_pointer (acfg, NULL);
8506 emit_pointer (acfg, NULL);
8508 if (acfg->thumb_mixed) {
8509 emit_pointer (acfg, "thumb_end");
8511 emit_pointer (acfg, NULL);
8513 if (acfg->aot_opts.static_link) {
8514 emit_pointer (acfg, "globals");
8516 emit_pointer (acfg, NULL);
8518 emit_pointer (acfg, "assembly_name");
8519 emit_pointer (acfg, "unbox_trampolines");
8520 emit_pointer (acfg, "unbox_trampolines_end");
8521 emit_pointer (acfg, "unbox_trampoline_addresses");
8523 emit_int32 (acfg, acfg->plt_got_offset_base);
8524 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8525 emit_int32 (acfg, acfg->plt_offset);
8526 emit_int32 (acfg, acfg->nmethods);
8527 emit_int32 (acfg, acfg->flags);
8528 emit_int32 (acfg, acfg->opts);
8529 emit_int32 (acfg, acfg->simd_opts);
8530 emit_int32 (acfg, gc_name_offset);
8532 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8533 emit_int32 (acfg, acfg->num_trampolines [i]);
8534 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8535 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8536 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8537 emit_int32 (acfg, acfg->trampoline_size [i]);
8538 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8540 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8545 memset (&t, 0, sizeof (MonoType));
8546 t.type = MONO_TYPE_R8;
8547 mono_type_size (&t, &align);
8548 emit_int32 (acfg, align);
8550 memset (&t, 0, sizeof (MonoType));
8551 t.type = MONO_TYPE_I8;
8552 mono_type_size (&t, &align);
8554 emit_int32 (acfg, align);
8557 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8558 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8560 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8561 emit_int32 (acfg, acfg->tramp_page_size);
8562 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8563 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8565 if (acfg->aot_opts.static_link) {
8569 * Emit a global symbol which can be passed by an embedding app to
8570 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8573 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8575 /* Get rid of characters which cannot occur in symbols */
8577 for (p = symbol; *p; ++p) {
8578 if (!(isalnum (*p) || *p == '_'))
8581 acfg->static_linking_symbol = g_strdup (symbol);
8582 emit_global_inner (acfg, symbol, FALSE);
8583 emit_alignment (acfg, sizeof (gpointer));
8584 emit_label (acfg, symbol);
8585 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8590 emit_blob (MonoAotCompile *acfg)
8594 sprintf (symbol, "blob");
8595 emit_section_change (acfg, RODATA_SECT, 1);
8596 emit_alignment (acfg, 8);
8597 emit_label (acfg, symbol);
8599 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8603 emit_objc_selectors (MonoAotCompile *acfg)
8608 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8613 * cat > foo.m << EOF
8616 * return @selector(print:);
8621 mono_img_writer_emit_unset_mode (acfg->w);
8622 g_assert (acfg->fp);
8623 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8624 fprintf (acfg->fp, ".align 3\n");
8625 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8626 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8627 emit_label (acfg, symbol);
8628 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8629 emit_pointer (acfg, symbol);
8632 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8633 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8634 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8635 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8638 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8639 fprintf (acfg->fp, ".align 3\n");
8640 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8641 fprintf (acfg->fp, ".long 0\n");
8642 fprintf (acfg->fp, ".long 16\n");
8646 emit_dwarf_info (MonoAotCompile *acfg)
8648 #ifdef EMIT_DWARF_INFO
8652 /* DIEs for methods */
8653 for (i = 0; i < acfg->nmethods; ++i) {
8654 MonoCompile *cfg = acfg->cfgs [i];
8659 // FIXME: LLVM doesn't define .Lme_...
8660 if (cfg->compile_llvm)
8663 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8665 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 ()));
8671 collect_methods (MonoAotCompile *acfg)
8674 MonoImage *image = acfg->image;
8676 /* Collect methods */
8677 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8680 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8682 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8685 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8686 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8687 mono_error_cleanup (&error);
8691 /* Load all methods eagerly to skip the slower lazy loading code */
8692 mono_class_setup_methods (method->klass);
8694 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8695 /* Compile the wrapper instead */
8696 /* We do this here instead of add_wrappers () because it is easy to do it here */
8697 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8701 /* FIXME: Some mscorlib methods don't have debug info */
8703 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8704 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8705 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8706 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8707 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8708 if (!mono_debug_lookup_method (method)) {
8709 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8716 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8717 add_method_with_index (acfg, method, i, FALSE);
8718 acfg->method_index ++;
8721 /* gsharedvt methods */
8722 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8725 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8727 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8730 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8731 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8734 if (strcmp (method->name, "gshared2"))
8738 if (!strstr (method->klass->image->name, "mini"))
8741 if (method->is_generic || method->klass->generic_container) {
8742 MonoMethod *gshared;
8744 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8745 add_extra_method (acfg, gshared);
8749 add_generic_instances (acfg);
8751 if (mono_aot_mode_is_full (&acfg->aot_opts))
8752 add_wrappers (acfg);
8757 compile_methods (MonoAotCompile *acfg)
8761 if (acfg->aot_opts.nthreads > 0) {
8766 gpointer *user_data;
8767 MonoMethod **methods;
8769 methods_len = acfg->methods->len;
8771 len = acfg->methods->len / acfg->aot_opts.nthreads;
8774 * Partition the list of methods into fragments, and hand it to threads to
8777 threads = g_ptr_array_new ();
8778 /* Make a copy since acfg->methods is modified by compile_method () */
8779 methods = g_new0 (MonoMethod*, methods_len);
8780 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8781 for (i = 0; i < methods_len; ++i)
8782 methods [i] = g_ptr_array_index (acfg->methods, i);
8784 while (i < methods_len) {
8785 frag = g_ptr_array_new ();
8786 for (j = 0; j < len; ++j) {
8787 if (i < methods_len) {
8788 g_ptr_array_add (frag, methods [i]);
8793 user_data = g_new0 (gpointer, 3);
8794 user_data [0] = mono_domain_get ();
8795 user_data [1] = acfg;
8796 user_data [2] = frag;
8798 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8799 g_ptr_array_add (threads, handle);
8803 for (i = 0; i < threads->len; ++i) {
8804 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8810 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8811 for (i = methods_len; i < acfg->methods->len; ++i) {
8812 /* This can new methods to acfg->methods */
8813 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8818 compile_asm (MonoAotCompile *acfg)
8820 char *command, *objfile;
8821 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8822 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8823 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
8825 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8826 #define AS_OPTIONS "--64"
8827 #elif defined(TARGET_POWERPC64)
8828 #define AS_OPTIONS "-a64 -mppc64"
8829 #define LD_OPTIONS "-m elf64ppc"
8830 #elif defined(sparc) && SIZEOF_VOID_P == 8
8831 #define AS_OPTIONS "-xarch=v9"
8832 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8833 #define AS_OPTIONS "-arch i386"
8835 #define AS_OPTIONS ""
8838 #ifdef __native_client_codegen__
8839 #if defined(TARGET_AMD64)
8840 #define AS_NAME "nacl64-as"
8842 #define AS_NAME "nacl-as"
8844 #elif defined(TARGET_OSX)
8845 #define AS_NAME "clang"
8847 #define AS_NAME "as"
8851 #define LD_OPTIONS ""
8855 #define LD_NAME "ld -shared -G"
8856 #elif defined(__ppc__) && defined(TARGET_MACH)
8857 #define LD_NAME "gcc -dynamiclib"
8858 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8859 #define LD_NAME "clang --shared"
8860 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
8861 #define LD_NAME "gcc -shared --dll"
8862 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8863 #define LD_NAME "clang -m32 -dynamiclib"
8864 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
8865 #define LD_NAME "gcc --shared"
8868 if (acfg->aot_opts.asm_only) {
8869 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8870 if (acfg->aot_opts.static_link)
8871 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8873 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8877 if (acfg->aot_opts.static_link) {
8878 if (acfg->aot_opts.outfile)
8879 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8881 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8883 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8887 g_string_append (acfg->as_args, "-c -x assembler");
8890 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);
8891 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8892 if (execute_system (command) != 0) {
8898 if (acfg->llvm && !acfg->llvm_owriter) {
8899 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);
8900 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8901 if (execute_system (command) != 0) {
8910 if (acfg->aot_opts.static_link) {
8911 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8912 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8917 if (acfg->aot_opts.outfile)
8918 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8920 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8922 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8925 llvm_ofile = g_strdup (acfg->llvm_ofile);
8927 llvm_ofile = g_strdup ("");
8930 /* replace the ; flags separators with spaces */
8931 g_strdelimit (ld_flags, ";", ' ');
8934 command = g_strdup_printf ("%s -o %s %s %s.o %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
8936 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
8937 acfg->tmpfname, ld_flags);
8939 aot_printf (acfg, "Executing the native linker: %s\n", command);
8940 if (execute_system (command) != 0) {
8941 g_free (tmp_outfile_name);
8942 g_free (outfile_name);
8951 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8952 printf ("Stripping the binary: %s\n", com);
8953 execute_system (com);
8956 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8958 * gas generates 'mapping symbols' each time code and data is mixed, which
8959 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8961 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8962 aot_printf (acfg, "Stripping the binary: %s\n", command);
8963 if (execute_system (command) != 0) {
8964 g_free (tmp_outfile_name);
8965 g_free (outfile_name);
8972 rename (tmp_outfile_name, outfile_name);
8974 #if defined(TARGET_MACH)
8975 command = g_strdup_printf ("dsymutil %s", outfile_name);
8976 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8977 if (execute_system (command) != 0) {
8982 if (!acfg->aot_opts.save_temps)
8985 g_free (tmp_outfile_name);
8986 g_free (outfile_name);
8989 if (acfg->aot_opts.save_temps)
8990 aot_printf (acfg, "Retained input file.\n");
8992 unlink (acfg->tmpfname);
8997 static void init_got_info (GotInfo *info)
9001 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9002 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9003 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9004 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9005 info->got_patches = g_ptr_array_new ();
9008 static MonoAotCompile*
9009 acfg_create (MonoAssembly *ass, guint32 opts)
9011 MonoImage *image = ass->image;
9012 MonoAotCompile *acfg;
9014 acfg = g_new0 (MonoAotCompile, 1);
9015 acfg->methods = g_ptr_array_new ();
9016 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9017 acfg->method_depth = g_hash_table_new (NULL, NULL);
9018 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9019 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9020 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9021 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9022 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9023 acfg->image_hash = g_hash_table_new (NULL, NULL);
9024 acfg->image_table = g_ptr_array_new ();
9025 acfg->globals = g_ptr_array_new ();
9026 acfg->image = image;
9028 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9029 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9030 acfg->mempool = mono_mempool_new ();
9031 acfg->extra_methods = g_ptr_array_new ();
9032 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9033 acfg->unwind_ops = g_ptr_array_new ();
9034 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9035 acfg->method_order = g_ptr_array_new ();
9036 acfg->export_names = g_hash_table_new (NULL, NULL);
9037 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9038 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9039 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9040 mono_mutex_init_recursive (&acfg->mutex);
9042 init_got_info (&acfg->got_info);
9043 init_got_info (&acfg->llvm_got_info);
9049 got_info_free (GotInfo *info)
9053 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9054 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9055 g_free (info->patch_to_got_offset_by_type);
9056 g_hash_table_destroy (info->patch_to_got_offset);
9057 g_ptr_array_free (info->got_patches, TRUE);
9061 acfg_free (MonoAotCompile *acfg)
9065 mono_img_writer_destroy (acfg->w);
9066 for (i = 0; i < acfg->nmethods; ++i)
9068 g_free (acfg->cfgs [i]);
9069 g_free (acfg->cfgs);
9070 g_free (acfg->static_linking_symbol);
9071 g_free (acfg->got_symbol);
9072 g_free (acfg->plt_symbol);
9073 g_ptr_array_free (acfg->methods, TRUE);
9074 g_ptr_array_free (acfg->image_table, TRUE);
9075 g_ptr_array_free (acfg->globals, TRUE);
9076 g_ptr_array_free (acfg->unwind_ops, TRUE);
9077 g_hash_table_destroy (acfg->method_indexes);
9078 g_hash_table_destroy (acfg->method_depth);
9079 g_hash_table_destroy (acfg->plt_offset_to_entry);
9080 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9081 if (acfg->patch_to_plt_entry [i])
9082 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9084 g_free (acfg->patch_to_plt_entry);
9085 g_hash_table_destroy (acfg->method_to_cfg);
9086 g_hash_table_destroy (acfg->token_info_hash);
9087 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9088 g_hash_table_destroy (acfg->image_hash);
9089 g_hash_table_destroy (acfg->unwind_info_offsets);
9090 g_hash_table_destroy (acfg->method_label_hash);
9091 g_hash_table_destroy (acfg->export_names);
9092 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9093 g_hash_table_destroy (acfg->klass_blob_hash);
9094 g_hash_table_destroy (acfg->method_blob_hash);
9095 got_info_free (&acfg->got_info);
9096 got_info_free (&acfg->llvm_got_info);
9097 mono_mempool_destroy (acfg->mempool);
9101 #define WRAPPER(e,n) n,
9102 static const char* const
9103 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9104 #include "mono/metadata/wrapper-types.h"
9108 static G_GNUC_UNUSED const char*
9109 get_wrapper_type_name (int type)
9111 return wrapper_type_names [type];
9117 static void aot_dump (MonoAotCompile *acfg)
9123 mono_json_writer_init (&writer);
9125 mono_json_writer_object_begin(&writer);
9128 mono_json_writer_indent (&writer);
9129 mono_json_writer_object_key(&writer, "methods");
9130 mono_json_writer_array_begin (&writer);
9133 for (i = 0; i < acfg->nmethods; ++i) {
9138 cfg = acfg->cfgs [i];
9142 method = cfg->orig_method;
9144 mono_json_writer_indent (&writer);
9145 mono_json_writer_object_begin(&writer);
9147 mono_json_writer_indent (&writer);
9148 mono_json_writer_object_key(&writer, "name");
9149 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9151 mono_json_writer_indent (&writer);
9152 mono_json_writer_object_key(&writer, "signature");
9153 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9154 /*signature=*/TRUE));
9156 mono_json_writer_indent (&writer);
9157 mono_json_writer_object_key(&writer, "code_size");
9158 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9160 klass = method->klass;
9162 mono_json_writer_indent (&writer);
9163 mono_json_writer_object_key(&writer, "class");
9164 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9166 mono_json_writer_indent (&writer);
9167 mono_json_writer_object_key(&writer, "namespace");
9168 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9170 mono_json_writer_indent (&writer);
9171 mono_json_writer_object_key(&writer, "wrapper_type");
9172 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9174 mono_json_writer_indent_pop (&writer);
9175 mono_json_writer_indent (&writer);
9176 mono_json_writer_object_end (&writer);
9177 mono_json_writer_printf (&writer, ",\n");
9180 mono_json_writer_indent_pop (&writer);
9181 mono_json_writer_indent (&writer);
9182 mono_json_writer_array_end (&writer);
9183 mono_json_writer_printf (&writer, ",\n");
9187 mono_json_writer_indent_push (&writer);
9188 mono_json_writer_indent (&writer);
9189 mono_json_writer_object_key(&writer, "plt");
9190 mono_json_writer_array_begin (&writer);
9192 for (i = 0; i < acfg->plt_offset; ++i) {
9193 MonoPltEntry *plt_entry = NULL;
9198 * The first plt entry is unused.
9202 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9205 mono_json_writer_indent (&writer);
9206 mono_json_writer_printf (&writer, "{ ");
9207 mono_json_writer_object_key(&writer, "symbol");
9208 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9211 mono_json_writer_indent_pop (&writer);
9212 mono_json_writer_indent (&writer);
9213 mono_json_writer_array_end (&writer);
9214 mono_json_writer_printf (&writer, ",\n");
9219 mono_json_writer_indent_push (&writer);
9220 mono_json_writer_indent (&writer);
9221 mono_json_writer_object_key(&writer, "got");
9222 mono_json_writer_array_begin (&writer);
9224 mono_json_writer_indent_push (&writer);
9225 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9226 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9228 mono_json_writer_indent (&writer);
9229 mono_json_writer_printf (&writer, "{ ");
9230 mono_json_writer_object_key(&writer, "patch_name");
9231 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9234 mono_json_writer_indent_pop (&writer);
9235 mono_json_writer_indent (&writer);
9236 mono_json_writer_array_end (&writer);
9237 mono_json_writer_printf (&writer, ",\n");
9240 mono_json_writer_indent_pop (&writer);
9241 mono_json_writer_indent (&writer);
9242 mono_json_writer_object_end (&writer);
9244 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9245 dumpfile = fopen (dumpname, "w+");
9248 fprintf (dumpfile, "%s", writer.text->str);
9251 mono_json_writer_destroy (&writer);
9255 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9257 MonoImage *image = ass->image;
9260 MonoAotCompile *acfg;
9261 char *outfile_name, *tmp_outfile_name, *p;
9262 char llvm_stats_msg [256];
9266 acfg = acfg_create (ass, opts);
9268 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9269 acfg->aot_opts.write_symbols = TRUE;
9270 acfg->aot_opts.ntrampolines = 1024;
9271 acfg->aot_opts.nrgctx_trampolines = 1024;
9272 acfg->aot_opts.nimt_trampolines = 128;
9273 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9274 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9275 acfg->aot_opts.llvm_path = g_strdup ("");
9277 acfg->aot_opts.use_trampolines_page = TRUE;
9280 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9282 if (acfg->aot_opts.logfile) {
9283 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9286 if (acfg->aot_opts.static_link)
9287 acfg->aot_opts.autoreg = TRUE;
9289 //acfg->aot_opts.print_skipped_methods = TRUE;
9291 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9292 if (opts & MONO_OPT_GSHAREDVT) {
9293 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9298 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9300 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9301 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9302 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9307 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9308 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9312 if (acfg->aot_opts.static_link)
9313 acfg->aot_opts.asm_writer = TRUE;
9315 if (acfg->aot_opts.soft_debug) {
9316 MonoDebugOptions *opt = mini_get_debug_options ();
9318 opt->mdb_optimizations = TRUE;
9319 opt->gen_sdb_seq_points = TRUE;
9321 if (!mono_debug_enabled ()) {
9322 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9325 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9328 if (mono_use_llvm || acfg->aot_opts.llvm) {
9330 acfg->aot_opts.asm_writer = TRUE;
9331 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9333 if (acfg->aot_opts.soft_debug) {
9334 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9340 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9341 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9346 * Emit all LLVM code into a separate assembly/object file and link with it
9349 if (!acfg->aot_opts.asm_only)
9350 acfg->llvm_owriter = TRUE;
9353 if (mono_aot_mode_is_full (&acfg->aot_opts))
9354 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9356 if (acfg->aot_opts.instances_logfile_path) {
9357 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9358 if (!acfg->instances_logfile) {
9359 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9364 load_profile_files (acfg);
9366 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9367 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9368 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9370 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9371 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9372 if (acfg->opts & MONO_OPT_GSHAREDVT)
9373 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9376 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9380 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9381 /* Get rid of characters which cannot occur in symbols */
9382 for (p = acfg->assembly_name_sym; *p; ++p) {
9383 if (!(isalnum (*p) || *p == '_'))
9387 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9388 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9389 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9391 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9393 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9394 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9397 acfg->method_index = 1;
9399 if (mono_aot_mode_is_full (&acfg->aot_opts))
9400 mono_set_partial_sharing_supported (TRUE);
9402 res = collect_methods (acfg);
9406 acfg->cfgs_size = acfg->methods->len + 32;
9407 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9409 /* PLT offset 0 is reserved for the PLT trampoline */
9410 acfg->plt_offset = 1;
9415 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, TRUE, TRUE);
9419 /* GOT offset 0 is reserved for the address of the current assembly */
9423 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9424 ji->type = MONO_PATCH_INFO_IMAGE;
9425 ji->data.image = acfg->image;
9427 get_got_offset (acfg, FALSE, ji);
9428 get_got_offset (acfg, TRUE, ji);
9430 /* Slot 1 is reserved for the mscorlib got addr */
9431 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9432 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9433 get_got_offset (acfg, FALSE, ji);
9434 get_got_offset (acfg, TRUE, ji);
9436 /* This is very common */
9437 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9438 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9439 get_got_offset (acfg, FALSE, ji);
9440 get_got_offset (acfg, TRUE, ji);
9442 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9443 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9444 get_got_offset (acfg, FALSE, ji);
9445 get_got_offset (acfg, TRUE, ji);
9447 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9448 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9449 get_got_offset (acfg, FALSE, ji);
9450 get_got_offset (acfg, TRUE, ji);
9455 compile_methods (acfg);
9459 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9467 if (acfg->aot_opts.asm_only) {
9468 if (acfg->aot_opts.outfile) {
9469 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9470 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9472 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9473 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9475 g_assert (acfg->aot_opts.llvm_outfile);
9476 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9478 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
9479 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9480 acfg->llvm_sfile = g_strdup ("temp-llvm.s");
9481 acfg->llvm_ofile = g_strdup ("temp-llvm.o");
9484 res = emit_llvm_file (acfg);
9490 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && mono_bin_writer_supported ()) {
9491 if (acfg->aot_opts.outfile)
9492 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9494 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9497 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9498 * it might be in another file system so the rename () won't work.
9500 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9502 acfg->fp = fopen (tmp_outfile_name, "w");
9504 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9508 acfg->w = mono_img_writer_create (acfg->fp, TRUE);
9509 acfg->use_bin_writer = TRUE;
9511 if (acfg->aot_opts.asm_only) {
9512 if (acfg->aot_opts.outfile)
9513 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9515 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9516 acfg->fp = fopen (acfg->tmpfname, "w+");
9518 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9519 acfg->fp = fdopen (i, "w+");
9521 if (acfg->fp == 0) {
9522 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9525 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9527 tmp_outfile_name = NULL;
9528 outfile_name = NULL;
9531 /* Compute symbols for methods */
9532 for (i = 0; i < acfg->nmethods; ++i) {
9533 if (acfg->cfgs [i]) {
9534 MonoCompile *cfg = acfg->cfgs [i];
9535 int method_index = get_method_index (acfg, cfg->orig_method);
9537 if (COMPILE_LLVM (cfg))
9538 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9539 else if (acfg->global_symbols || acfg->llvm)
9540 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9542 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9543 cfg->asm_debug_symbol = cfg->asm_symbol;
9547 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9549 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9550 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9553 //acfg->gas_line_numbers = TRUE;
9556 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9557 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9558 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9561 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9564 mono_img_writer_emit_start (acfg->w);
9567 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9569 if (acfg->thumb_mixed) {
9572 * This global symbol marks the end of THUMB code, and the beginning of ARM
9573 * code generated by our JIT.
9575 sprintf (symbol, "thumb_end");
9576 emit_section_change (acfg, ".text", 0);
9577 emit_alignment_code (acfg, 8);
9578 emit_label (acfg, symbol);
9579 emit_zero_bytes (acfg, 16);
9581 fprintf (acfg->fp, ".arm\n");
9588 emit_extra_methods (acfg);
9590 emit_trampolines (acfg);
9592 emit_class_name_table (acfg);
9594 emit_got_info (acfg, FALSE);
9596 emit_got_info (acfg, TRUE);
9598 emit_exception_info (acfg);
9600 emit_unwind_info (acfg);
9602 emit_class_info (acfg);
9606 emit_image_table (acfg);
9610 emit_file_info (acfg);
9614 emit_objc_selectors (acfg);
9616 emit_globals (acfg);
9618 emit_autoreg (acfg);
9621 emit_dwarf_info (acfg);
9622 mono_dwarf_writer_close (acfg->dwarf);
9625 emit_mem_end (acfg);
9627 if (acfg->need_pt_gnu_stack) {
9628 /* This is required so the .so doesn't have an executable stack */
9629 /* The bin writer already emits this */
9630 if (!acfg->use_bin_writer)
9631 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9636 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9639 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9641 strcpy (llvm_stats_msg, "");
9643 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;
9645 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",
9646 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9647 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9648 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9649 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9650 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9651 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,
9652 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9653 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9654 (int)(acfg->got_offset * sizeof (gpointer)));
9655 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9656 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9658 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9659 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9660 if (acfg->stats.genericcount)
9661 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9662 if (acfg->stats.abscount)
9663 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9664 if (acfg->stats.lmfcount)
9665 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9666 if (acfg->stats.ocount)
9667 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9670 res = mono_img_writer_emit_writeout (acfg->w);
9675 if (acfg->use_bin_writer) {
9676 int err = rename (tmp_outfile_name, outfile_name);
9679 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9683 res = compile_asm (acfg);
9690 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9692 if (acfg->aot_opts.stats) {
9695 aot_printf (acfg, "GOT slot distribution:\n");
9696 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9697 if (acfg->stats.got_slot_types [i])
9698 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]);
9701 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);
9703 if (acfg->aot_opts.dump_json)
9716 mono_aot_readonly_field_override (MonoClassField *field)
9722 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)