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;
134 char *instances_logfile_path;
139 typedef struct MonoAotStats {
140 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
141 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
142 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
143 int got_slots, offsets_size;
144 int got_slot_types [MONO_PATCH_INFO_NONE];
145 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
146 int jit_time, gen_time, link_time;
149 typedef struct GotInfo {
150 GHashTable *patch_to_got_offset;
151 GHashTable **patch_to_got_offset_by_type;
152 GPtrArray *got_patches;
155 typedef struct MonoAotCompile {
158 GHashTable *method_indexes;
159 GHashTable *method_depth;
162 GHashTable **patch_to_plt_entry;
163 GHashTable *plt_offset_to_entry;
164 //GHashTable *patch_to_got_offset;
165 //GHashTable **patch_to_got_offset_by_type;
166 //GPtrArray *got_patches;
167 GotInfo got_info, llvm_got_info;
168 GHashTable *image_hash;
169 GHashTable *method_to_cfg;
170 GHashTable *token_info_hash;
171 GHashTable *method_to_pinvoke_import;
172 GPtrArray *extra_methods;
173 GPtrArray *image_table;
175 GPtrArray *method_order;
176 GHashTable *export_names;
177 /* Maps MonoClass* -> blob offset */
178 GHashTable *klass_blob_hash;
179 /* Maps MonoMethod* -> blob offset */
180 GHashTable *method_blob_hash;
181 guint32 *plt_got_info_offsets;
182 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base;
183 /* Number of GOT entries reserved for trampolines */
184 guint32 num_trampoline_got_entries;
185 guint32 tramp_page_size;
187 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
188 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
189 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
190 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
192 MonoAotOptions aot_opts;
196 MonoMemPool *mempool;
199 char *static_linking_symbol;
201 gboolean use_bin_writer;
202 gboolean gas_line_numbers;
203 /* Whenever to emit an object file directly from llc */
204 gboolean llvm_owriter;
206 MonoDwarfWriter *dwarf;
213 GHashTable *unwind_info_offsets;
214 GPtrArray *unwind_ops;
215 guint32 unwind_info_offset;
216 char *got_symbol_base;
217 char *llvm_got_symbol_base;
219 char *llvm_got_symbol;
221 char *methods_symbol;
222 char *llvm_eh_frame_symbol;
223 GHashTable *method_label_hash;
224 const char *temp_prefix;
225 const char *user_symbol_prefix;
226 const char *llvm_label_prefix;
227 const char *inst_directive;
229 guint32 label_generator;
231 MonoAotFileFlags flags;
232 MonoDynamicStream blob;
233 MonoClass **typespec_classes;
236 char *assembly_name_sym;
237 GHashTable *plt_entry_debug_sym_cache;
238 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
239 GHashTable *ginst_hash;
240 GHashTable *dwarf_ln_filenames;
241 gboolean global_symbols;
242 int objc_selector_index, objc_selector_index_2;
243 GPtrArray *objc_selectors;
244 GHashTable *objc_selector_to_index;
246 FILE *instances_logfile;
251 char *symbol, *llvm_symbol, *debug_sym;
253 gboolean jit_used, llvm_used;
256 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
257 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
259 /* This points to the current acfg in LLVM mode */
260 static MonoAotCompile *llvm_acfg;
262 #ifdef HAVE_ARRAY_ELEM_INIT
263 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
264 #define MSGSTRFIELD1(line) str##line
265 static const struct msgstr_t {
266 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
267 #include "patch-info.h"
270 #define PATCH_INFO(a,b) b,
271 #include "patch-info.h"
274 static const gint16 opidx [] = {
275 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
276 #include "patch-info.h"
280 static G_GNUC_UNUSED const char*
281 get_patch_name (int info)
283 return (const char*)&opstr + opidx [info];
287 #define PATCH_INFO(a,b) b,
288 static const char* const
289 patch_types [MONO_PATCH_INFO_NUM + 1] = {
290 #include "patch-info.h"
294 static G_GNUC_UNUSED const char*
295 get_patch_name (int info)
297 return patch_types [info];
303 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
306 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
312 output = acfg->logfile;
316 va_start (args, format);
317 vfprintf (output, format, args);
322 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
328 output = acfg->logfile;
332 va_start (args, format);
333 vfprintf (output, format, args);
338 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
343 if (mono_error_ok (error))
347 output = acfg->logfile;
351 va_start (args, format);
352 vfprintf (output, format, args);
354 mono_error_cleanup (error);
356 g_error ("FullAOT cannot continue if there are loader errors");
359 /* Wrappers around the image writer functions */
362 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
364 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
368 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
370 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
374 emit_label (MonoAotCompile *acfg, const char *name)
376 mono_img_writer_emit_label (acfg->w, name);
380 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
382 mono_img_writer_emit_bytes (acfg->w, buf, size);
386 emit_string (MonoAotCompile *acfg, const char *value)
388 mono_img_writer_emit_string (acfg->w, value);
392 emit_line (MonoAotCompile *acfg)
394 mono_img_writer_emit_line (acfg->w);
398 emit_alignment (MonoAotCompile *acfg, int size)
400 mono_img_writer_emit_alignment (acfg->w, size);
404 emit_alignment_code (MonoAotCompile *acfg, int size)
406 if (acfg->align_pad_value)
407 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
409 mono_img_writer_emit_alignment (acfg->w, size);
413 emit_padding (MonoAotCompile *acfg, int size)
418 if (acfg->align_pad_value) {
419 for (i = 0; i < 16; ++i)
420 buf [i] = acfg->align_pad_value;
422 memset (buf, 0, sizeof (buf));
425 for (i = 0; i < size; i += 16) {
427 emit_bytes (acfg, buf, size - i);
429 emit_bytes (acfg, buf, 16);
434 emit_pointer (MonoAotCompile *acfg, const char *target)
436 mono_img_writer_emit_pointer (acfg->w, target);
440 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
442 if (prefix [0] != '\0') {
443 char *s = g_strdup_printf ("%s%s", prefix, target);
444 mono_img_writer_emit_pointer (acfg->w, s);
447 mono_img_writer_emit_pointer (acfg->w, target);
452 emit_int16 (MonoAotCompile *acfg, int value)
454 mono_img_writer_emit_int16 (acfg->w, value);
458 emit_int32 (MonoAotCompile *acfg, int value)
460 mono_img_writer_emit_int32 (acfg->w, value);
464 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
466 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
470 emit_zero_bytes (MonoAotCompile *acfg, int num)
472 mono_img_writer_emit_zero_bytes (acfg->w, num);
476 emit_byte (MonoAotCompile *acfg, guint8 val)
478 mono_img_writer_emit_byte (acfg->w, val);
481 #ifdef __native_client_codegen__
483 emit_nacl_call_alignment (MonoAotCompile *acfg)
485 mono_img_writer_emit_nacl_call_alignment (acfg->w);
489 static G_GNUC_UNUSED void
490 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
492 mono_img_writer_emit_global (acfg->w, name, func);
496 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
498 if (acfg->aot_opts.no_dlsym) {
499 g_ptr_array_add (acfg->globals, g_strdup (name));
500 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
502 mono_img_writer_emit_global (acfg->w, name, func);
507 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
509 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
513 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
515 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
517 /* On apple, all symbols need to be aligned to avoid warnings from ld */
518 emit_alignment (acfg, 4);
520 mono_img_writer_emit_label (acfg->w, name);
521 mono_img_writer_emit_string (acfg->w, value);
524 static G_GNUC_UNUSED void
525 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
528 guint8 b = value & 0x7f;
530 if (value != 0) /* more bytes to come */
536 static G_GNUC_UNUSED void
537 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
540 gboolean negative = (value < 0);
547 /* the following is unnecessary if the
548 * implementation of >>= uses an arithmetic rather
549 * than logical shift for a signed left operand
553 value |= - ((gint64)1 <<(size - 7));
554 /* sign bit of byte is second high order bit (0x40) */
555 if ((value == 0 && !(byte & 0x40)) ||
556 (value == -1 && (byte & 0x40)))
560 emit_byte (acfg, byte);
564 static G_GNUC_UNUSED void
565 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
570 guint8 b = value & 0x7f;
572 if (value != 0) /* more bytes to come */
580 static G_GNUC_UNUSED void
581 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
584 gboolean negative = (value < 0);
592 /* the following is unnecessary if the
593 * implementation of >>= uses an arithmetic rather
594 * than logical shift for a signed left operand
598 value |= - (1 <<(size - 7));
599 /* sign bit of byte is second high order bit (0x40) */
600 if ((value == 0 && !(byte & 0x40)) ||
601 (value == -1 && (byte & 0x40)))
612 emit_unset_mode (MonoAotCompile *acfg)
614 mono_img_writer_emit_unset_mode (acfg->w);
617 static G_GNUC_UNUSED void
618 emit_set_thumb_mode (MonoAotCompile *acfg)
620 emit_unset_mode (acfg);
621 fprintf (acfg->fp, ".code 16\n");
624 static G_GNUC_UNUSED void
625 emit_set_arm_mode (MonoAotCompile *acfg)
627 emit_unset_mode (acfg);
628 fprintf (acfg->fp, ".code 32\n");
632 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
637 g_assert (size % 4 == 0);
638 emit_unset_mode (acfg);
639 for (i = 0; i < size; i += 4)
640 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
642 emit_bytes (acfg, buf, size);
646 /* ARCHITECTURE SPECIFIC CODE */
648 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
649 #define EMIT_DWARF_INFO 1
652 #if defined(TARGET_ARM)
653 #define AOT_FUNC_ALIGNMENT 4
655 #define AOT_FUNC_ALIGNMENT 16
657 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
658 #undef AOT_FUNC_ALIGNMENT
659 #define AOT_FUNC_ALIGNMENT 32
662 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
663 #define PPC_LD_OP "ld"
664 #define PPC_LDX_OP "ldx"
666 #define PPC_LD_OP "lwz"
667 #define PPC_LDX_OP "lwzx"
671 #define AOT_TARGET_STR "AMD64"
676 #define AOT_TARGET_STR "ARM (MACH)"
678 #define AOT_TARGET_STR "ARM (!MACH)"
684 #define AOT_TARGET_STR "ARM64 (MACH)"
686 #define AOT_TARGET_STR "ARM64 (!MACH)"
690 #ifdef TARGET_POWERPC64
691 #ifdef __mono_ilp32__
692 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
694 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
697 #ifdef TARGET_POWERPC
698 #ifdef __mono_ilp32__
699 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
701 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
708 #define AOT_TARGET_STR "X86 (WIN32)"
709 #elif defined(__native_client_codegen__)
710 #define AOT_TARGET_STR "X86 (native client codegen)"
712 #define AOT_TARGET_STR "X86 (!native client codegen)"
716 #ifndef AOT_TARGET_STR
717 #define AOT_TARGET_STR ""
721 arch_init (MonoAotCompile *acfg)
723 acfg->llc_args = g_string_new ("");
724 acfg->as_args = g_string_new ("");
727 * The prefix LLVM likes to put in front of symbol names on darwin.
728 * The mach-os specs require this for globals, but LLVM puts them in front of all
729 * symbols. We need to handle this, since we need to refer to LLVM generated
732 acfg->llvm_label_prefix = "";
733 acfg->user_symbol_prefix = "";
735 #if defined(TARGET_X86)
736 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
739 #if defined(TARGET_AMD64)
740 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
742 acfg->align_pad_value = 0x90;
746 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
747 g_string_append (acfg->llc_args, "-mattr=+v6");
750 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
751 g_string_append (acfg->as_args, " -mfpu=vfp3");
753 g_string_append (acfg->llc_args, " -soft-float");
756 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
757 acfg->thumb_mixed = TRUE;
759 if (acfg->aot_opts.mtriple)
760 mono_arch_set_target (acfg->aot_opts.mtriple);
764 acfg->inst_directive = ".inst";
765 if (acfg->aot_opts.mtriple)
766 mono_arch_set_target (acfg->aot_opts.mtriple);
770 acfg->user_symbol_prefix = "_";
771 acfg->llvm_label_prefix = "_";
772 acfg->inst_directive = ".word";
773 acfg->need_no_dead_strip = TRUE;
774 acfg->aot_opts.gnu_asm = TRUE;
777 #if defined(__linux__) && !defined(TARGET_ARM)
778 acfg->need_pt_gnu_stack = TRUE;
782 acfg->global_symbols = TRUE;
788 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
792 #ifdef MONO_ARCH_AOT_SUPPORTED
794 * arch_emit_direct_call:
796 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
800 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
802 #if defined(TARGET_X86) || defined(TARGET_AMD64)
803 /* Need to make sure this is exactly 5 bytes long */
804 if (!acfg->use_bin_writer) {
805 emit_unset_mode (acfg);
806 fprintf (acfg->fp, "call %s\n", target);
808 emit_byte (acfg, '\xe8');
809 emit_symbol_diff (acfg, target, ".", -4);
812 #elif defined(TARGET_ARM)
813 if (acfg->use_bin_writer) {
820 mono_img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
821 emit_bytes (acfg, buf, 4);
823 emit_unset_mode (acfg);
825 fprintf (acfg->fp, "blx %s\n", target);
827 fprintf (acfg->fp, "bl %s\n", target);
830 #elif defined(TARGET_ARM64)
831 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
832 #elif defined(TARGET_POWERPC)
833 if (acfg->use_bin_writer) {
834 g_assert_not_reached ();
836 emit_unset_mode (acfg);
837 fprintf (acfg->fp, "bl %s\n", target);
841 g_assert_not_reached ();
848 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
850 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
851 * in in the 2. slot of every GOT, and require every method to place the GOT
852 * address in r30, even when it doesn't access the GOT otherwise. This way,
853 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
858 * PPC64 uses function descriptors which greatly complicate all code, since
859 * these are used very inconsistently in the runtime. Some functions like
860 * mono_compile_method () return ftn descriptors, while others like the
861 * trampoline creation functions do not.
862 * We assume that all GOT slots contain function descriptors, and create
863 * descriptors in aot-runtime.c when needed.
864 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
865 * from function descriptors, we could do the same, but it would require
866 * rewriting all the ppc/aot code to handle function descriptors properly.
867 * So instead, we use the same approach as on PPC32.
868 * This is a horrible mess, but fixing it would probably lead to an even bigger
874 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
877 #ifdef MONO_ARCH_AOT_SUPPORTED
879 * arch_emit_got_offset:
881 * The memory pointed to by CODE should hold native code for computing the GOT
882 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
883 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
886 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
888 #if defined(TARGET_POWERPC64)
889 g_assert (!acfg->use_bin_writer);
890 emit_unset_mode (acfg);
892 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
893 * unsupported relocations. So we store the got address into the .Lgot_addr
894 * symbol which is in the text segment, compute its address, and load it.
896 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
897 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
898 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
899 fprintf (acfg->fp, "add 30, 30, 0\n");
900 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
901 acfg->label_generator ++;
903 #elif defined(TARGET_POWERPC)
904 g_assert (!acfg->use_bin_writer);
905 emit_unset_mode (acfg);
906 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
907 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
908 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
909 acfg->label_generator ++;
912 guint32 offset = mono_arch_get_patch_offset (code);
913 emit_bytes (acfg, code, offset);
914 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
916 *code_size = offset + 4;
921 * arch_emit_got_access:
923 * The memory pointed to by CODE should hold native code for loading a GOT
924 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
925 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
928 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
931 /* mov reg, got+offset(%rip) */
933 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
937 /* Decode reg, see amd64_mov_reg_membase () */
938 rex_r = code [0] & AMD64_REX_R;
939 g_assert (code [0] == 0x49 + rex_r);
940 g_assert (code [1] == 0x8b);
941 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
943 emit_unset_mode (acfg);
944 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
947 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
948 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
949 *code_size = mono_arch_get_patch_offset (code) + 4;
951 #elif defined(TARGET_X86)
952 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
953 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
954 *code_size = mono_arch_get_patch_offset (code) + 4;
955 #elif defined(TARGET_ARM)
956 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
957 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
958 *code_size = mono_arch_get_patch_offset (code) + 4;
959 #elif defined(TARGET_ARM64)
960 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
961 arm64_emit_got_access (acfg, code, got_slot, code_size);
962 #elif defined(TARGET_POWERPC)
967 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
969 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
970 g_assert (code - buf == 8);
971 emit_bytes (acfg, buf, code - buf);
972 *code_size = code - buf;
975 g_assert_not_reached ();
981 #ifdef MONO_ARCH_AOT_SUPPORTED
983 * arch_emit_objc_selector_ref:
985 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
988 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
990 #if defined(TARGET_ARM)
993 int lindex = acfg->objc_selector_index_2 ++;
996 emit_bytes (acfg, code, 8);
998 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
999 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1001 emit_label (acfg, symbol1);
1002 mono_img_writer_emit_unset_mode (acfg->w);
1003 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1006 #elif defined(TARGET_ARM64)
1007 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1009 g_assert_not_reached ();
1015 * arch_emit_plt_entry:
1017 * Emit code for the PLT entry.
1018 * The plt entry should look like this:
1019 * <indirect jump to GOT_SYMBOL + OFFSET>
1020 * <INFO_OFFSET embedded into the instruction stream>
1023 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1025 #if defined(TARGET_X86)
1026 #if defined(__default_codegen__)
1027 /* jmp *<offset>(%ebx) */
1028 emit_byte (acfg, 0xff);
1029 emit_byte (acfg, 0xa3);
1030 emit_int32 (acfg, offset);
1031 /* Used by mono_aot_get_plt_info_offset */
1032 emit_int32 (acfg, info_offset);
1033 #elif defined(__native_client_codegen__)
1034 const guint8 kSizeOfNaClJmp = 11;
1035 guint8 bytes[kSizeOfNaClJmp];
1036 guint8 *pbytes = &bytes[0];
1038 x86_jump_membase32 (pbytes, X86_EBX, offset);
1039 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1040 /* four bytes of data, used by mono_arch_patch_plt_entry */
1041 /* For Native Client, make this work with data embedded in push. */
1042 emit_byte (acfg, 0x68); /* hide data in a push */
1043 emit_int32 (acfg, info_offset);
1044 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1045 #endif /*__native_client_codegen__*/
1046 #elif defined(TARGET_AMD64)
1047 #if defined(__default_codegen__)
1048 if (acfg->use_bin_writer) {
1049 emit_byte (acfg, '\xff');
1050 emit_byte (acfg, '\x25');
1051 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1053 emit_unset_mode (acfg);
1054 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1056 /* Used by mono_aot_get_plt_info_offset */
1057 emit_int32 (acfg, info_offset);
1058 acfg->stats.plt_size += 10;
1059 #elif defined(__native_client_codegen__)
1061 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1062 guint8 *code = buf_aligned;
1064 /* mov <OFFSET>(%rip), %r11d */
1065 emit_byte (acfg, '\x45');
1066 emit_byte (acfg, '\x8b');
1067 emit_byte (acfg, '\x1d');
1068 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1070 amd64_jump_reg (code, AMD64_R11);
1071 /* This should be constant for the plt patch */
1072 g_assert ((size_t)(code-buf_aligned) == 10);
1073 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1075 /* Hide data in a push imm32 so it passes validation */
1076 emit_byte (acfg, 0x68); /* push */
1077 emit_int32 (acfg, info_offset);
1078 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1079 #endif /*__native_client_codegen__*/
1080 #elif defined(TARGET_ARM)
1085 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1086 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1087 emit_bytes (acfg, buf, code - buf);
1088 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1089 /* Used by mono_aot_get_plt_info_offset */
1090 emit_int32 (acfg, info_offset);
1091 #elif defined(TARGET_ARM64)
1092 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1093 #elif defined(TARGET_POWERPC)
1094 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1095 g_assert (!acfg->use_bin_writer);
1096 emit_unset_mode (acfg);
1097 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1098 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1099 fprintf (acfg->fp, "add 11, 11, 30\n");
1100 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1101 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1102 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1103 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1105 fprintf (acfg->fp, "mtctr 11\n");
1106 fprintf (acfg->fp, "bctr\n");
1107 emit_int32 (acfg, info_offset);
1109 g_assert_not_reached ();
1114 * arch_emit_llvm_plt_entry:
1116 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1117 * This is only needed on arm to handle thumb interop.
1120 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1122 #if defined(TARGET_ARM)
1123 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1124 /* The caller already transitioned to thumb */
1125 /* The code below should be 12 bytes long */
1126 /* clang has trouble encoding these instructions, so emit the binary */
1128 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1129 /* thumb can't encode ld pc, [pc, ip] */
1130 fprintf (acfg->fp, "add ip, pc, ip\n");
1131 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1132 fprintf (acfg->fp, "bx ip\n");
1134 emit_set_thumb_mode (acfg);
1135 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1136 fprintf (acfg->fp, ".2byte 0x44fc\n");
1137 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1138 fprintf (acfg->fp, ".2byte 0x4760\n");
1139 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1140 emit_int32 (acfg, info_offset);
1141 emit_unset_mode (acfg);
1142 emit_set_arm_mode (acfg);
1144 g_assert_not_reached ();
1149 * arch_emit_specific_trampoline_pages:
1151 * Emits a page full of trampolines: each trampoline uses its own address to
1152 * lookup both the generic trampoline code and the data argument.
1153 * This page can be remapped in process multiple times so we can get an
1154 * unlimited number of trampolines.
1155 * Specifically this implementation uses the following trick: two memory pages
1156 * are allocated, with the first containing the data and the second containing the trampolines.
1157 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1158 * implementation does all the lifting.
1159 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1160 * on the arm 32 bit system.
1163 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1165 #if defined(TARGET_ARM)
1168 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1170 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1171 #define COMMON_TRAMP_SIZE 16
1172 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1173 int imm8, rot_amount;
1176 if (!acfg->aot_opts.use_trampolines_page)
1179 acfg->tramp_page_size = pagesize;
1181 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1182 emit_alignment (acfg, pagesize);
1183 emit_global (acfg, symbol, TRUE);
1184 emit_label (acfg, symbol);
1186 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1188 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1189 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1190 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1191 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1193 g_assert (code - buf == COMMON_TRAMP_SIZE);
1196 emit_bytes (acfg, buf, code - buf);
1198 for (i = 0; i < count; ++i) {
1200 ARM_PUSH (code, 0x5fff);
1202 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1203 g_assert (code - buf == 8);
1204 emit_bytes (acfg, buf, code - buf);
1207 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1208 * the instruction pointer address, so the generic trampoline at the start of the page
1209 * subtracts 4096 to get to the data page and loads the values
1210 * We again fit the generic trampiline in 16 bytes.
1212 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1213 emit_global (acfg, symbol, TRUE);
1214 emit_label (acfg, symbol);
1216 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1217 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1218 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1219 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1221 g_assert (code - buf == COMMON_TRAMP_SIZE);
1224 emit_bytes (acfg, buf, code - buf);
1226 for (i = 0; i < count; ++i) {
1228 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1230 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1231 g_assert (code - buf == 8);
1232 emit_bytes (acfg, buf, code - buf);
1236 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1238 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1239 emit_global (acfg, symbol, TRUE);
1240 emit_label (acfg, symbol);
1242 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1243 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1244 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1245 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1246 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1247 g_assert (code - buf == COMMON_TRAMP_SIZE);
1249 emit_bytes (acfg, buf, code - buf);
1251 for (i = 0; i < count; ++i) {
1253 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1255 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1256 g_assert (code - buf == 8);
1257 emit_bytes (acfg, buf, code - buf);
1260 /* now the imt trampolines: each specific trampolines puts in the ip register
1261 * the instruction pointer address, so the generic trampoline at the start of the page
1262 * subtracts 4096 to get to the data page and loads the values
1263 * We again fit the generic trampiline in 16 bytes.
1265 #define IMT_TRAMP_SIZE 72
1266 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1267 emit_global (acfg, symbol, TRUE);
1268 emit_label (acfg, symbol);
1270 /* Need at least two free registers, plus a slot for storing the pc */
1271 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1273 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1274 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1275 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1277 /* The IMT method is in v5, r0 has the imt array address */
1280 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1281 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1282 imt_found_check = code;
1283 ARM_B_COND (code, ARMCOND_EQ, 0);
1285 /* End-of-loop check */
1286 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1287 loop_end_check = code;
1288 ARM_B_COND (code, ARMCOND_EQ, 0);
1291 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1292 loop_branch_back = code;
1294 arm_patch (loop_branch_back, loop_start);
1297 arm_patch (imt_found_check, code);
1298 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1299 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1300 /* Save it to the third stack slot */
1301 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1302 /* Restore the registers and branch */
1303 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1306 arm_patch (loop_end_check, code);
1307 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1308 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1309 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1313 g_assert (code - buf == IMT_TRAMP_SIZE);
1314 emit_bytes (acfg, buf, code - buf);
1316 for (i = 0; i < count; ++i) {
1318 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1320 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1321 g_assert (code - buf == 8);
1322 emit_bytes (acfg, buf, code - buf);
1325 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1326 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1327 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1328 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1329 #elif defined(TARGET_ARM64)
1330 arm64_emit_specific_trampoline_pages (acfg);
1335 * arch_emit_specific_trampoline:
1337 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1338 * two GOT slots which contain the generic trampoline address and the trampoline
1339 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1342 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1345 * The trampolines created here are variations of the specific
1346 * trampolines created in mono_arch_create_specific_trampoline (). The
1348 * - the generic trampoline address is taken from a got slot.
1349 * - the offset of the got slot where the trampoline argument is stored
1350 * is embedded in the instruction stream, and the generic trampoline
1351 * can load the argument by loading the offset, adding it to the
1352 * address of the trampoline to get the address of the got slot, and
1353 * loading the argument from there.
1354 * - all the trampolines should be of the same length.
1356 #if defined(TARGET_AMD64)
1357 #if defined(__default_codegen__)
1358 /* This should be exactly 8 bytes long */
1360 /* call *<offset>(%rip) */
1362 emit_unset_mode (acfg);
1363 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1364 emit_zero_bytes (acfg, 2);
1366 emit_byte (acfg, '\x41');
1367 emit_byte (acfg, '\xff');
1368 emit_byte (acfg, '\x15');
1369 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1370 emit_zero_bytes (acfg, 1);
1372 #elif defined(__native_client_codegen__)
1374 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1375 guint8 *code = buf_aligned;
1380 /* Emit this call in 'code' so we can find out how long it is. */
1381 amd64_call_reg (code, AMD64_R11);
1382 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1383 call_len = code - call_start;
1385 /* The tramp_size is twice the NaCl alignment because it starts with */
1386 /* a call which needs to be aligned to the end of the boundary. */
1387 *tramp_size = kNaClAlignment*2;
1389 /* Emit nops to align call site below which is 7 bytes plus */
1390 /* the length of the call sequence emitted above. */
1391 /* Note: this requires the specific trampoline starts on a */
1392 /* kNaclAlignedment aligned address, which it does because */
1393 /* it's its own function that is aligned. */
1394 guint8 nop_buf[256];
1395 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1396 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1397 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1399 /* The trampoline is stored at the offset'th pointer, the -4 is */
1400 /* present because RIP relative addressing starts at the end of */
1401 /* the current instruction, while the label "." is relative to */
1402 /* the beginning of the current asm location, which in this case */
1403 /* is not the mov instruction, but the offset itself, due to the */
1404 /* way the bytes and ints are emitted here. */
1405 got_offset = (offset * sizeof(gpointer)) - 4;
1407 /* mov <OFFSET>(%rip), %r11d */
1408 emit_byte (acfg, '\x45');
1409 emit_byte (acfg, '\x8b');
1410 emit_byte (acfg, '\x1d');
1411 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1414 emit_bytes (acfg, call_start, call_len);
1416 /* The arg is stored at the offset+1 pointer, relative to beginning */
1417 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1418 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1420 /* We can't emit this data directly, hide in a "push imm32" */
1421 emit_byte (acfg, '\x68'); /* push */
1422 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1423 emit_alignment (acfg, kNaClAlignment);
1424 #endif /*__native_client_codegen__*/
1425 #elif defined(TARGET_ARM)
1429 /* This should be exactly 20 bytes long */
1432 ARM_PUSH (code, 0x5fff);
1433 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1434 /* Load the value from the GOT */
1435 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1437 ARM_BLX_REG (code, ARMREG_R1);
1439 g_assert (code - buf == 16);
1442 emit_bytes (acfg, buf, code - buf);
1444 * Only one offset is needed, since the second one would be equal to the
1447 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1448 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1449 #elif defined(TARGET_ARM64)
1450 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1451 #elif defined(TARGET_POWERPC)
1458 g_assert (!acfg->use_bin_writer);
1461 * PPC has no ip relative addressing, so we need to compute the address
1462 * of the mscorlib got. That is slow and complex, so instead, we store it
1463 * in the second got slot of every aot image. The caller already computed
1464 * the address of its got and placed it into r30.
1466 emit_unset_mode (acfg);
1467 /* Load mscorlib got address */
1468 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1469 /* Load generic trampoline address */
1470 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1471 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1472 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1473 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1474 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1476 fprintf (acfg->fp, "mtctr 11\n");
1477 /* Load trampoline argument */
1478 /* On ppc, we pass it normally to the generic trampoline */
1479 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1480 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1481 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1482 /* Branch to generic trampoline */
1483 fprintf (acfg->fp, "bctr\n");
1485 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1486 *tramp_size = 10 * 4;
1488 *tramp_size = 9 * 4;
1490 #elif defined(TARGET_X86)
1494 /* Similar to the PPC code above */
1496 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1498 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1499 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1500 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1501 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1502 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1507 /* Load mscorlib got address */
1508 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1509 /* Push trampoline argument */
1510 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1511 /* Load generic trampoline address */
1512 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1513 /* Branch to generic trampoline */
1514 x86_jump_reg (code, X86_ECX);
1516 #ifdef __native_client_codegen__
1518 /* emit nops to next 32 byte alignment */
1519 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1520 while (code < (buf + a)) x86_nop(code);
1523 emit_bytes (acfg, buf, code - buf);
1525 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1526 g_assert (code - buf == *tramp_size);
1528 g_assert_not_reached ();
1533 * arch_emit_unbox_trampoline:
1535 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1536 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1539 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1541 #if defined(TARGET_AMD64)
1546 this_reg = mono_arch_get_this_arg_reg (NULL);
1548 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1550 emit_bytes (acfg, buf, code - buf);
1553 emit_unset_mode (acfg);
1554 fprintf (acfg->fp, "jmp %s\n", call_target);
1556 emit_byte (acfg, '\xe9');
1557 emit_symbol_diff (acfg, call_target, ".", -4);
1559 #elif defined(TARGET_X86)
1566 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1568 emit_bytes (acfg, buf, code - buf);
1571 emit_byte (acfg, '\xe9');
1572 emit_symbol_diff (acfg, call_target, ".", -4);
1573 #elif defined(TARGET_ARM)
1577 if (acfg->thumb_mixed && cfg->compile_llvm) {
1578 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1579 fprintf (acfg->fp, "b %s\n", call_target);
1580 fprintf (acfg->fp, ".arm\n");
1581 fprintf (acfg->fp, ".align 2\n");
1587 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1589 emit_bytes (acfg, buf, code - buf);
1590 /* jump to method */
1591 if (acfg->use_bin_writer) {
1598 mono_img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1599 emit_bytes (acfg, buf, 4);
1601 if (acfg->thumb_mixed && cfg->compile_llvm)
1602 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1604 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1606 #elif defined(TARGET_ARM64)
1607 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1608 #elif defined(TARGET_POWERPC)
1611 g_assert (!acfg->use_bin_writer);
1613 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1614 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1616 g_assert_not_reached ();
1621 * arch_emit_static_rgctx_trampoline:
1623 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1624 * two GOT slots which contain the rgctx argument, and the method to jump to.
1625 * TRAMP_SIZE is set to the size of the emitted trampoline.
1626 * These kinds of trampolines cannot be enumerated statically, since there could
1627 * be one trampoline per method instantiation, so we emit the same code for all
1628 * trampolines, and parameterize them using two GOT slots.
1631 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1633 #if defined(TARGET_AMD64)
1634 #if defined(__default_codegen__)
1635 /* This should be exactly 13 bytes long */
1639 emit_unset_mode (acfg);
1640 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1641 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1643 /* mov <OFFSET>(%rip), %r10 */
1644 emit_byte (acfg, '\x4d');
1645 emit_byte (acfg, '\x8b');
1646 emit_byte (acfg, '\x15');
1647 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1649 /* jmp *<offset>(%rip) */
1650 emit_byte (acfg, '\xff');
1651 emit_byte (acfg, '\x25');
1652 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1654 #elif defined(__native_client_codegen__)
1656 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1657 guint8 *code = buf_aligned;
1659 /* mov <OFFSET>(%rip), %r10d */
1660 emit_byte (acfg, '\x45');
1661 emit_byte (acfg, '\x8b');
1662 emit_byte (acfg, '\x15');
1663 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1665 /* mov <OFFSET>(%rip), %r11d */
1666 emit_byte (acfg, '\x45');
1667 emit_byte (acfg, '\x8b');
1668 emit_byte (acfg, '\x1d');
1669 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1672 amd64_jump_reg (code, AMD64_R11);
1673 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1675 emit_alignment (acfg, kNaClAlignment);
1676 *tramp_size = kNaClAlignment;
1677 #endif /*__native_client_codegen__*/
1679 #elif defined(TARGET_ARM)
1683 /* This should be exactly 24 bytes long */
1686 /* Load rgctx value */
1687 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1688 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1689 /* Load branch addr + branch */
1690 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1691 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1693 g_assert (code - buf == 16);
1696 emit_bytes (acfg, buf, code - buf);
1697 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1698 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1699 #elif defined(TARGET_ARM64)
1700 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1701 #elif defined(TARGET_POWERPC)
1708 g_assert (!acfg->use_bin_writer);
1711 * PPC has no ip relative addressing, so we need to compute the address
1712 * of the mscorlib got. That is slow and complex, so instead, we store it
1713 * in the second got slot of every aot image. The caller already computed
1714 * the address of its got and placed it into r30.
1716 emit_unset_mode (acfg);
1717 /* Load mscorlib got address */
1718 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1720 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1721 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1722 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1723 /* Load target address */
1724 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1725 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1726 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1727 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1728 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1729 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1731 fprintf (acfg->fp, "mtctr 11\n");
1732 /* Branch to the target address */
1733 fprintf (acfg->fp, "bctr\n");
1735 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1736 *tramp_size = 11 * 4;
1738 *tramp_size = 9 * 4;
1741 #elif defined(TARGET_X86)
1745 /* Similar to the PPC code above */
1747 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1750 /* Load mscorlib got address */
1751 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1753 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1754 /* Branch to the target address */
1755 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1757 #ifdef __native_client_codegen__
1759 /* emit nops to next 32 byte alignment */
1760 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1761 while (code < (buf + a)) x86_nop(code);
1765 emit_bytes (acfg, buf, code - buf);
1767 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1768 g_assert (code - buf == *tramp_size);
1770 g_assert_not_reached ();
1775 * arch_emit_imt_thunk:
1777 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1778 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1779 * key is the IMT key, and ptr holds the address of a memory location holding
1780 * the address to branch to if the IMT arg matches the key. The array is
1781 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1783 * TRAMP_SIZE is set to the size of the emitted trampoline.
1786 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1788 #if defined(TARGET_AMD64)
1790 #if defined(__native_client_codegen__)
1793 guint8 *labels [16];
1795 guint8 *mov_buf_ptr = mov_buf;
1797 const int kSizeOfMove = 7;
1798 #if defined(__default_codegen__)
1799 code = buf = g_malloc (256);
1800 #elif defined(__native_client_codegen__)
1801 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1802 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1803 /* The RIP relative move below is emitted first */
1808 /* FIXME: Optimize this, i.e. use binary search etc. */
1809 /* Maybe move the body into a separate function (slower, but much smaller) */
1811 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1814 emit_unset_mode (acfg);
1815 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1819 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1821 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1824 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1826 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1829 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1830 amd64_jump_code (code, labels [0]);
1833 mono_amd64_patch (labels [2], code);
1834 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1835 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1838 mono_amd64_patch (labels [1], code);
1839 /* Load fail tramp */
1840 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1841 /* Check if there is a fail tramp */
1842 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1844 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1845 /* Jump to fail tramp */
1846 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1849 mono_amd64_patch (labels [3], code);
1850 x86_breakpoint (code);
1853 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1854 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1855 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1856 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1857 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1858 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1860 emit_bytes (acfg, buf, code - buf);
1862 *tramp_size = code - buf + kSizeOfMove;
1863 #if defined(__native_client_codegen__)
1864 /* The tramp will be padded to the next kNaClAlignment bundle. */
1865 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1868 #if defined(__default_codegen__)
1870 #elif defined(__native_client_codegen__)
1874 #elif defined(TARGET_X86)
1876 #ifdef __native_client_codegen__
1879 guint8 *labels [16];
1881 #if defined(__default_codegen__)
1882 code = buf = g_malloc (256);
1883 #elif defined(__native_client_codegen__)
1884 buf_alloc = g_malloc (256 + kNaClAlignment);
1885 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1888 /* Allocate a temporary stack slot */
1889 x86_push_reg (code, X86_EAX);
1891 x86_push_reg (code, X86_EAX);
1893 /* Load mscorlib got address */
1894 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1896 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1899 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1901 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1904 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1906 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1909 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1910 x86_jump_code (code, labels [0]);
1913 mono_x86_patch (labels [2], code);
1914 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1915 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1916 /* Save the target address to the temporary stack location */
1917 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1919 x86_pop_reg (code, X86_EAX);
1920 /* Jump to the target address */
1924 mono_x86_patch (labels [1], code);
1925 /* Load fail tramp */
1926 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1927 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1929 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1930 /* Jump to fail tramp */
1931 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1932 x86_pop_reg (code, X86_EAX);
1936 mono_x86_patch (labels [3], code);
1937 x86_breakpoint (code);
1939 #ifdef __native_client_codegen__
1941 /* emit nops to next 32 byte alignment */
1942 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1943 while (code < (buf + a)) x86_nop(code);
1946 emit_bytes (acfg, buf, code - buf);
1948 *tramp_size = code - buf;
1950 #if defined(__default_codegen__)
1952 #elif defined(__native_client_codegen__)
1956 #elif defined(TARGET_ARM)
1958 guint8 *code, *code2, *labels [16];
1962 /* The IMT method is in v5 */
1964 /* Need at least two free registers, plus a slot for storing the pc */
1965 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1967 /* Load the parameter from the GOT */
1968 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1969 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1972 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1973 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1975 ARM_B_COND (code, ARMCOND_EQ, 0);
1977 /* End-of-loop check */
1978 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1980 ARM_B_COND (code, ARMCOND_EQ, 0);
1983 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1986 arm_patch (labels [4], labels [1]);
1989 arm_patch (labels [2], code);
1990 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1991 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1992 /* Save it to the third stack slot */
1993 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1994 /* Restore the registers and branch */
1995 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1998 arm_patch (labels [3], code);
1999 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2000 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2001 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2005 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2007 emit_bytes (acfg, buf, code - buf);
2008 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2010 *tramp_size = code - buf + 4;
2011 #elif defined(TARGET_ARM64)
2012 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2013 #elif defined(TARGET_POWERPC)
2015 guint8 *code, *labels [16];
2019 /* Load the mscorlib got address */
2020 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2021 /* Load the parameter from the GOT */
2022 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2023 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2025 /* Load and check key */
2027 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2028 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2030 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2032 /* End-of-loop check */
2033 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2035 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2038 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2041 mono_ppc_patch (labels [4], labels [1]);
2044 mono_ppc_patch (labels [2], code);
2045 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2046 /* r12 now contains the value of the vtable slot */
2047 /* this is not a function descriptor on ppc64 */
2048 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2049 ppc_mtctr (code, ppc_r12);
2050 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2053 mono_ppc_patch (labels [3], code);
2057 *tramp_size = code - buf;
2059 emit_bytes (acfg, buf, code - buf);
2061 g_assert_not_reached ();
2066 * arch_emit_gsharedvt_arg_trampoline:
2068 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2069 * two GOT slots which contain the argument, and the code to jump to.
2070 * TRAMP_SIZE is set to the size of the emitted trampoline.
2071 * These kinds of trampolines cannot be enumerated statically, since there could
2072 * be one trampoline per method instantiation, so we emit the same code for all
2073 * trampolines, and parameterize them using two GOT slots.
2076 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2078 #if defined(TARGET_X86)
2082 /* Similar to the PPC code above */
2084 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2087 /* Load mscorlib got address */
2088 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2090 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2091 /* Branch to the target address */
2092 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2094 #ifdef __native_client_codegen__
2096 /* emit nops to next 32 byte alignment */
2097 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2098 while (code < (buf + a)) x86_nop(code);
2102 emit_bytes (acfg, buf, code - buf);
2104 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2105 g_assert (code - buf == *tramp_size);
2106 #elif defined(TARGET_ARM)
2110 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2111 /* Similar to arch_emit_specific_trampoline () */
2114 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2115 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2116 /* Load the arg value from the GOT */
2117 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2118 /* Load the addr from the GOT */
2119 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2121 ARM_BX (code, ARMREG_R1);
2123 g_assert (code - buf == 20);
2126 emit_bytes (acfg, buf, code - buf);
2127 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2128 #elif defined(TARGET_ARM64)
2129 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2131 g_assert_not_reached ();
2136 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2138 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2139 /* Based on code generated by gcc */
2140 emit_unset_mode (acfg);
2143 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2144 ".section .ctors,\"aw\",@progbits\n"
2148 ".section .opd,\"aw\"\n"
2151 ".long .%s,.TOC.@tocbase32\n"
2154 ".type .%s,@function\n"
2156 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2158 ".section .ctors,\"aw\",@progbits\n"
2162 ".section .opd,\"aw\"\n"
2165 ".long .%1$s,.TOC.@tocbase32\n"
2166 ".size %1$s,.-%1$s\n"
2168 ".type .%1$s,@function\n"
2170 ".%1$s:\n", symbol);
2181 "lis 3, .Lglobals@h\n"
2182 "ori 3, 3, .Lglobals@l\n"
2183 "bl .mono_aot_register_module\n"
2191 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2193 ".size .%s,.-.%s\n", symbol, symbol);
2196 ".size .%1$s,.-.%1$s\n", symbol);
2202 /* END OF ARCH SPECIFIC CODE */
2205 mono_get_field_token (MonoClassField *field)
2207 MonoClass *klass = field->parent;
2210 for (i = 0; i < klass->field.count; ++i) {
2211 if (field == &klass->fields [i])
2212 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2215 g_assert_not_reached ();
2220 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2224 //printf ("ENCODE: %d 0x%x.\n", value, value);
2227 * Same encoding as the one used in the metadata, extended to handle values
2228 * greater than 0x1fffffff.
2230 if ((value >= 0) && (value <= 127))
2232 else if ((value >= 0) && (value <= 16383)) {
2233 p [0] = 0x80 | (value >> 8);
2234 p [1] = value & 0xff;
2236 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2237 p [0] = (value >> 24) | 0xc0;
2238 p [1] = (value >> 16) & 0xff;
2239 p [2] = (value >> 8) & 0xff;
2240 p [3] = value & 0xff;
2245 p [1] = (value >> 24) & 0xff;
2246 p [2] = (value >> 16) & 0xff;
2247 p [3] = (value >> 8) & 0xff;
2248 p [4] = value & 0xff;
2256 stream_init (MonoDynamicStream *sh)
2259 sh->alloc_size = 4096;
2260 sh->data = g_malloc (4096);
2262 /* So offsets are > 0 */
2268 make_room_in_stream (MonoDynamicStream *stream, int size)
2270 if (size <= stream->alloc_size)
2273 while (stream->alloc_size <= size) {
2274 if (stream->alloc_size < 4096)
2275 stream->alloc_size = 4096;
2277 stream->alloc_size *= 2;
2280 stream->data = g_realloc (stream->data, stream->alloc_size);
2284 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2288 make_room_in_stream (stream, stream->index + len);
2289 memcpy (stream->data + stream->index, data, len);
2290 idx = stream->index;
2291 stream->index += len;
2298 * Add data to the binary blob inside the aot image. Returns the offset inside the
2299 * blob where the data was stored.
2302 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2304 if (acfg->blob.alloc_size == 0)
2305 stream_init (&acfg->blob);
2307 return add_stream_data (&acfg->blob, (char*)data, data_len);
2311 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2316 if (acfg->blob.alloc_size == 0)
2317 stream_init (&acfg->blob);
2319 count = acfg->blob.index % align;
2321 /* we assume the stream data will be aligned */
2323 add_stream_data (&acfg->blob, buf, 4 - count);
2325 return add_stream_data (&acfg->blob, (char*)data, data_len);
2329 * emit_offset_table:
2331 * Emit a table of increasing offsets in a compact form using differential encoding.
2332 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2333 * group size, the more compact the table becomes, but the slower it becomes to compute
2334 * a given entry. Returns the size of the table.
2337 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2339 gint32 current_offset;
2340 int i, buf_size, ngroups, index_entry_size;
2342 guint32 *index_offsets;
2344 ngroups = (noffsets + (group_size - 1)) / group_size;
2346 index_offsets = g_new0 (guint32, ngroups);
2348 buf_size = noffsets * 4;
2349 p = buf = g_malloc0 (buf_size);
2352 for (i = 0; i < noffsets; ++i) {
2353 //printf ("D: %d -> %d\n", i, offsets [i]);
2354 if ((i % group_size) == 0) {
2355 index_offsets [i / group_size] = p - buf;
2356 /* Emit the full value for these entries */
2357 encode_value (offsets [i], p, &p);
2359 /* The offsets are allowed to be non-increasing */
2360 //g_assert (offsets [i] >= current_offset);
2361 encode_value (offsets [i] - current_offset, p, &p);
2363 current_offset = offsets [i];
2366 if (ngroups && index_offsets [ngroups - 1] < 65000)
2367 index_entry_size = 2;
2369 index_entry_size = 4;
2371 /* Emit the header */
2372 emit_int32 (acfg, noffsets);
2373 emit_int32 (acfg, group_size);
2374 emit_int32 (acfg, ngroups);
2375 emit_int32 (acfg, index_entry_size);
2377 /* Emit the index */
2378 for (i = 0; i < ngroups; ++i) {
2379 if (index_entry_size == 2)
2380 emit_int16 (acfg, index_offsets [i]);
2382 emit_int32 (acfg, index_offsets [i]);
2386 emit_bytes (acfg, buf, p - buf);
2388 return (int)(p - buf) + (ngroups * 4);
2392 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2396 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2400 index = g_hash_table_size (cfg->image_hash);
2401 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2402 g_ptr_array_add (cfg->image_table, image);
2408 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2411 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2413 /* FIXME: Search referenced images as well */
2414 if (!acfg->typespec_classes) {
2415 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2416 for (i = 0; i < len; ++i) {
2418 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2419 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2422 for (i = 0; i < len; ++i) {
2423 if (acfg->typespec_classes [i] == klass)
2428 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2434 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2437 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2440 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2443 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2446 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2451 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2455 if (klass->generic_class) {
2457 g_assert (klass->type_token);
2459 /* Find a typespec for a class if possible */
2460 token = find_typespec_for_class (acfg, klass);
2462 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2463 encode_value (token, p, &p);
2465 MonoClass *gclass = klass->generic_class->container_class;
2466 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2467 static int count = 0;
2470 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2471 encode_klass_ref (acfg, gclass, p, &p);
2472 encode_ginst (acfg, inst, p, &p);
2476 } else if (klass->type_token) {
2477 int iindex = get_image_index (acfg, klass->image);
2479 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2481 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2482 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2484 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2485 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2486 encode_value (get_image_index (acfg, klass->image), p, &p);
2488 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2489 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2490 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2492 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2493 encode_value (klass->byval_arg.type, p, &p);
2494 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2496 encode_value (container ? 1 : 0, p, &p);
2498 encode_value (container->is_method, p, &p);
2499 g_assert (!par->gshared_constraint);
2500 if (container->is_method)
2501 encode_method_ref (acfg, container->owner.method, p, &p);
2503 encode_klass_ref (acfg, container->owner.klass, p, &p);
2505 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2506 if (par->gshared_constraint) {
2509 encode_type (acfg, par->gshared_constraint, p, &p);
2511 name = mono_generic_param_name (par);
2513 int len = strlen (name);
2515 encode_value (len, p, &p);
2516 memcpy (p, name, len);
2519 encode_value (0, p, &p);
2523 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2524 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2525 encode_type (acfg, &klass->byval_arg, p, &p);
2528 g_assert (klass->rank > 0);
2529 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2530 encode_value (klass->rank, p, &p);
2531 encode_klass_ref (acfg, klass->element_class, p, &p);
2539 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2540 * standard metadata encoding.
2543 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2545 gboolean shared = FALSE;
2548 * The encoding of generic instances is large so emit them only once.
2550 if (klass->generic_class) {
2552 g_assert (klass->type_token);
2554 /* Find a typespec for a class if possible */
2555 token = find_typespec_for_class (acfg, klass);
2558 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2563 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2567 buf2 = g_malloc (1024);
2570 encode_klass_ref_inner (acfg, klass, p, &p);
2571 g_assert (p - buf2 < 1024);
2573 offset = add_to_blob (acfg, buf2, p - buf2);
2576 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2582 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2583 encode_value (offset, p, &p);
2588 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2592 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2594 guint32 token = mono_get_field_token (field);
2597 encode_klass_ref (cfg, field->parent, p, &p);
2598 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2599 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2604 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2609 encode_value (inst->type_argc, p, &p);
2610 for (i = 0; i < inst->type_argc; ++i)
2611 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2616 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2619 MonoGenericInst *inst;
2621 inst = context->class_inst;
2623 g_assert (inst->type_argc);
2624 encode_ginst (acfg, inst, p, &p);
2626 encode_value (0, p, &p);
2628 inst = context->method_inst;
2630 g_assert (inst->type_argc);
2631 encode_ginst (acfg, inst, p, &p);
2633 encode_value (0, p, &p);
2639 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2643 g_assert (t->num_mods == 0);
2644 /* t->attrs can be ignored */
2645 //g_assert (t->attrs == 0);
2648 *p = MONO_TYPE_PINNED;
2652 *p = MONO_TYPE_BYREF;
2660 case MONO_TYPE_VOID:
2661 case MONO_TYPE_BOOLEAN:
2662 case MONO_TYPE_CHAR:
2675 case MONO_TYPE_STRING:
2676 case MONO_TYPE_OBJECT:
2677 case MONO_TYPE_TYPEDBYREF:
2679 case MONO_TYPE_VALUETYPE:
2680 case MONO_TYPE_CLASS:
2681 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2683 case MONO_TYPE_SZARRAY:
2684 encode_klass_ref (acfg, t->data.klass, p, &p);
2687 encode_type (acfg, t->data.type, p, &p);
2689 case MONO_TYPE_GENERICINST: {
2690 MonoClass *gclass = t->data.generic_class->container_class;
2691 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2693 encode_klass_ref (acfg, gclass, p, &p);
2694 encode_ginst (acfg, inst, p, &p);
2697 case MONO_TYPE_ARRAY: {
2698 MonoArrayType *array = t->data.array;
2701 encode_klass_ref (acfg, array->eklass, p, &p);
2702 encode_value (array->rank, p, &p);
2703 encode_value (array->numsizes, p, &p);
2704 for (i = 0; i < array->numsizes; ++i)
2705 encode_value (array->sizes [i], p, &p);
2706 encode_value (array->numlobounds, p, &p);
2707 for (i = 0; i < array->numlobounds; ++i)
2708 encode_value (array->lobounds [i], p, &p);
2712 case MONO_TYPE_MVAR:
2713 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2716 g_assert_not_reached ();
2723 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2729 /* Similar to the metadata encoding */
2730 if (sig->generic_param_count)
2734 if (sig->explicit_this)
2736 flags |= (sig->call_convention & 0x0F);
2740 if (sig->generic_param_count)
2741 encode_value (sig->generic_param_count, p, &p);
2742 encode_value (sig->param_count, p, &p);
2744 encode_type (acfg, sig->ret, p, &p);
2745 for (i = 0; i < sig->param_count; ++i) {
2746 if (sig->sentinelpos == i) {
2747 *p = MONO_TYPE_SENTINEL;
2750 encode_type (acfg, sig->params [i], p, &p);
2756 #define MAX_IMAGE_INDEX 250
2759 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2761 guint32 image_index = get_image_index (acfg, method->klass->image);
2762 guint32 token = method->token;
2763 MonoJumpInfoToken *ji;
2767 * The encoding for most methods is as follows:
2768 * - image index encoded as a leb128
2769 * - token index encoded as a leb128
2770 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2771 * types of method encodings.
2774 /* Mark methods which can't use aot trampolines because they need the further
2775 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2777 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2778 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2779 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2781 if (method->wrapper_type) {
2782 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2784 encode_value (method->wrapper_type, p, &p);
2786 switch (method->wrapper_type) {
2787 case MONO_WRAPPER_REMOTING_INVOKE:
2788 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2789 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2792 m = mono_marshal_method_from_wrapper (method);
2794 encode_method_ref (acfg, m, p, &p);
2797 case MONO_WRAPPER_PROXY_ISINST:
2798 case MONO_WRAPPER_LDFLD:
2799 case MONO_WRAPPER_LDFLDA:
2800 case MONO_WRAPPER_STFLD:
2801 case MONO_WRAPPER_ISINST: {
2802 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2805 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2808 case MONO_WRAPPER_LDFLD_REMOTE:
2809 case MONO_WRAPPER_STFLD_REMOTE:
2811 case MONO_WRAPPER_ALLOC: {
2812 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2814 /* The GC name is saved once in MonoAotFileInfo */
2815 g_assert (info->alloc_type != -1);
2816 encode_value (info->alloc_type, p, &p);
2819 case MONO_WRAPPER_WRITE_BARRIER:
2821 case MONO_WRAPPER_STELEMREF: {
2822 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2825 encode_value (info->subtype, p, &p);
2826 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2827 encode_value (info->d.virtual_stelemref.kind, p, &p);
2830 case MONO_WRAPPER_UNKNOWN: {
2831 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2834 encode_value (info->subtype, p, &p);
2835 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2836 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2837 encode_klass_ref (acfg, method->klass, p, &p);
2838 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2839 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2840 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2841 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2844 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2845 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2848 encode_value (info->subtype, p, &p);
2849 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2850 strcpy ((char*)p, method->name);
2851 p += strlen (method->name) + 1;
2852 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2853 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2855 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2856 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2860 case MONO_WRAPPER_SYNCHRONIZED: {
2863 m = mono_marshal_method_from_wrapper (method);
2865 g_assert (m != method);
2866 encode_method_ref (acfg, m, p, &p);
2869 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2870 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2873 encode_value (info->subtype, p, &p);
2875 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2876 encode_value (info->d.element_addr.rank, p, &p);
2877 encode_value (info->d.element_addr.elem_size, p, &p);
2878 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2879 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2881 g_assert_not_reached ();
2885 case MONO_WRAPPER_CASTCLASS: {
2886 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2889 encode_value (info->subtype, p, &p);
2892 case MONO_WRAPPER_RUNTIME_INVOKE: {
2893 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2896 encode_value (info->subtype, p, &p);
2897 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2898 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2899 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2900 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2903 case MONO_WRAPPER_DELEGATE_INVOKE:
2904 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2905 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2906 if (method->is_inflated) {
2907 /* These wrappers are identified by their class */
2908 encode_value (1, p, &p);
2909 encode_klass_ref (acfg, method->klass, p, &p);
2911 MonoMethodSignature *sig = mono_method_signature (method);
2912 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2914 encode_value (0, p, &p);
2915 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2916 encode_value (info ? info->subtype : 0, p, &p);
2917 encode_signature (acfg, sig, p, &p);
2921 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2922 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2925 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2926 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2930 g_assert_not_reached ();
2932 } else if (mono_method_signature (method)->is_inflated) {
2934 * This is a generic method, find the original token which referenced it and
2936 * Obtain the token from information recorded by the JIT.
2938 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2940 image_index = get_image_index (acfg, ji->image);
2941 g_assert (image_index < MAX_IMAGE_INDEX);
2944 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2945 encode_value (image_index, p, &p);
2946 encode_value (token, p, &p);
2948 MonoMethod *declaring;
2949 MonoGenericContext *context = mono_method_get_context (method);
2951 g_assert (method->is_inflated);
2952 declaring = ((MonoMethodInflated*)method)->declaring;
2955 * This might be a non-generic method of a generic instance, which
2956 * doesn't have a token since the reference is generated by the JIT
2957 * like Nullable:Box/Unbox, or by generic sharing.
2959 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2960 /* Encode the klass */
2961 encode_klass_ref (acfg, method->klass, p, &p);
2962 /* Encode the method */
2963 image_index = get_image_index (acfg, method->klass->image);
2964 g_assert (image_index < MAX_IMAGE_INDEX);
2965 g_assert (declaring->token);
2966 token = declaring->token;
2967 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2968 encode_value (image_index, p, &p);
2969 encode_value (token, p, &p);
2970 encode_generic_context (acfg, context, p, &p);
2972 } else if (token == 0) {
2973 /* This might be a method of a constructed type like int[,].Set */
2974 /* Obtain the token from information recorded by the JIT */
2975 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2977 image_index = get_image_index (acfg, ji->image);
2978 g_assert (image_index < MAX_IMAGE_INDEX);
2981 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2982 encode_value (image_index, p, &p);
2983 encode_value (token, p, &p);
2986 g_assert (method->klass->rank);
2988 /* Encode directly */
2989 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2990 encode_klass_ref (acfg, method->klass, p, &p);
2991 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2992 encode_value (0, p, &p);
2993 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2994 encode_value (1, p, &p);
2995 else if (!strcmp (method->name, "Get"))
2996 encode_value (2, p, &p);
2997 else if (!strcmp (method->name, "Address"))
2998 encode_value (3, p, &p);
2999 else if (!strcmp (method->name, "Set"))
3000 encode_value (4, p, &p);
3002 g_assert_not_reached ();
3005 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3007 if (image_index >= MONO_AOT_METHODREF_MIN) {
3008 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3009 encode_value (image_index, p, &p);
3010 encode_value (mono_metadata_token_index (token), p, &p);
3012 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3019 compare_patches (gconstpointer a, gconstpointer b)
3023 i = (*(MonoJumpInfo**)a)->ip.i;
3024 j = (*(MonoJumpInfo**)b)->ip.i;
3035 static G_GNUC_UNUSED char*
3036 patch_to_string (MonoJumpInfo *patch_info)
3040 str = g_string_new ("");
3042 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3044 switch (patch_info->type) {
3045 case MONO_PATCH_INFO_VTABLE:
3046 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3051 g_string_append_printf (str, ")");
3052 return g_string_free (str, FALSE);
3058 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3061 static inline gboolean
3062 is_plt_patch (MonoJumpInfo *patch_info)
3064 switch (patch_info->type) {
3065 case MONO_PATCH_INFO_METHOD:
3066 case MONO_PATCH_INFO_INTERNAL_METHOD:
3067 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3068 case MONO_PATCH_INFO_ICALL_ADDR:
3069 case MONO_PATCH_INFO_CLASS_INIT:
3070 case MONO_PATCH_INFO_RGCTX_FETCH:
3071 case MONO_PATCH_INFO_MONITOR_ENTER:
3072 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3073 case MONO_PATCH_INFO_MONITOR_EXIT:
3074 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3084 * Return the symbol identifying the plt entry PLT_OFFSET.
3087 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3091 * The Apple linker reorganizes object files, so it doesn't like branches to local
3092 * labels, since those have no relocations.
3094 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3096 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3103 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3105 static MonoPltEntry*
3106 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3109 gboolean synchronized = FALSE;
3110 static int synchronized_symbol_idx;
3112 if (!is_plt_patch (patch_info))
3115 if (!acfg->patch_to_plt_entry [patch_info->type])
3116 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3117 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3119 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3121 * Allocate a separate PLT slot for each such patch, since some plt
3122 * entries will refer to the method itself, and some will refer to the
3126 synchronized = TRUE;
3130 MonoJumpInfo *new_ji;
3132 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3134 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3135 res->plt_offset = acfg->plt_offset;
3137 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3138 if (acfg->aot_opts.write_symbols)
3139 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3141 /* Avoid duplicate symbols because we don't cache */
3142 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3144 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3145 synchronized_symbol_idx ++;
3148 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3150 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3152 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3154 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3156 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3157 //mono_print_ji (patch_info); printf ("\n");
3158 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3160 acfg->plt_offset ++;
3169 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3170 * JI could be found if it exists, otherwise allocates a new one.
3173 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3176 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3178 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3180 return got_offset - 1;
3183 got_offset = acfg->llvm_got_offset;
3184 acfg->llvm_got_offset ++;
3186 got_offset = acfg->got_offset;
3187 acfg->got_offset ++;
3190 acfg->stats.got_slots ++;
3191 acfg->stats.got_slot_types [ji->type] ++;
3193 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3194 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3195 g_ptr_array_add (info->got_patches, ji);
3200 /* Add a method to the list of methods which need to be emitted */
3202 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3205 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3206 g_ptr_array_add (acfg->methods, method);
3207 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3208 acfg->nmethods = acfg->methods->len + 1;
3211 if (method->wrapper_type || extra)
3212 g_ptr_array_add (acfg->extra_methods, method);
3216 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3218 /* One instantiation with valuetypes is generated for each async method */
3219 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3226 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3228 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3236 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3240 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3244 index = acfg->method_index;
3245 add_method_with_index (acfg, method, index, extra);
3247 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3249 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3251 acfg->method_index ++;
3257 add_method (MonoAotCompile *acfg, MonoMethod *method)
3259 return add_method_full (acfg, method, FALSE, 0);
3263 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3265 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3266 method = mini_get_shared_method (method);
3267 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3268 /* Use the gsharedvt version */
3271 if (acfg->aot_opts.log_generics)
3272 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3274 add_method_full (acfg, method, TRUE, depth);
3278 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3280 add_extra_method_with_depth (acfg, method, 0);
3284 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3286 MonoAotCompile *acfg = user_data;
3287 MonoJitICallInfo *callinfo = value;
3288 MonoMethod *wrapper;
3294 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3295 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3298 add_method (acfg, wrapper);
3302 get_runtime_invoke_sig (MonoMethodSignature *sig)
3304 MonoMethodBuilder *mb;
3307 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3308 m = mono_mb_create_method (mb, sig, 16);
3309 return mono_marshal_get_runtime_invoke (m, FALSE);
3313 can_marshal_struct (MonoClass *klass)
3315 MonoClassField *field;
3316 gboolean can_marshal = TRUE;
3317 gpointer iter = NULL;
3318 MonoMarshalType *info;
3321 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3324 info = mono_marshal_load_type_info (klass);
3326 /* Only allow a few field types to avoid asserts in the marshalling code */
3327 while ((field = mono_class_get_fields (klass, &iter))) {
3328 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3331 switch (field->type->type) {
3336 case MONO_TYPE_BOOLEAN:
3339 case MONO_TYPE_CHAR:
3347 case MONO_TYPE_STRING:
3349 case MONO_TYPE_VALUETYPE:
3350 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3351 can_marshal = FALSE;
3353 case MONO_TYPE_SZARRAY: {
3354 gboolean has_mspec = FALSE;
3357 for (i = 0; i < info->num_fields; ++i) {
3358 if (info->fields [i].field == field && info->fields [i].mspec)
3363 can_marshal = FALSE;
3367 can_marshal = FALSE;
3373 /* Its hard to compute whenever these can be marshalled or not */
3374 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3381 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3383 /* Create a vtype instantiation */
3384 MonoGenericContext shared_context;
3386 MonoGenericInst *inst;
3387 MonoGenericContainer *container;
3388 MonoClass **constraints;
3391 memset (ctx, 0, sizeof (MonoGenericContext));
3393 if (method->klass->generic_container) {
3394 shared_context = method->klass->generic_container->context;
3395 inst = shared_context.class_inst;
3397 args = g_new0 (MonoType*, inst->type_argc);
3398 for (i = 0; i < inst->type_argc; ++i) {
3399 args [i] = &mono_defaults.int_class->byval_arg;
3401 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3403 if (method->is_generic) {
3404 container = mono_method_get_generic_container (method);
3405 shared_context = container->context;
3406 inst = shared_context.method_inst;
3408 args = g_new0 (MonoType*, inst->type_argc);
3409 for (i = 0; i < container->type_argc; ++i) {
3410 MonoGenericParamInfo *info = &container->type_params [i].info;
3411 gboolean ref_only = FALSE;
3413 if (info && info->constraints) {
3414 constraints = info->constraints;
3416 while (*constraints) {
3417 MonoClass *cklass = *constraints;
3418 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3419 /* Inflaring the method with our vtype would not be valid */
3426 args [i] = &mono_defaults.object_class->byval_arg;
3428 args [i] = &mono_defaults.int_class->byval_arg;
3430 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3435 add_wrappers (MonoAotCompile *acfg)
3437 MonoMethod *method, *m;
3439 MonoMethodSignature *sig, *csig;
3443 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3444 * so there is only one wrapper of a given type, or inlining their contents into their
3447 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3450 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3451 gboolean skip = FALSE;
3453 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3454 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3456 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3457 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3458 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3461 /* Skip methods which can not be handled by get_runtime_invoke () */
3462 sig = mono_method_signature (method);
3465 if ((sig->ret->type == MONO_TYPE_PTR) ||
3466 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3468 if (mono_class_is_open_constructed_type (sig->ret))
3471 for (j = 0; j < sig->param_count; j++) {
3472 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3474 if (mono_class_is_open_constructed_type (sig->params [j]))
3478 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3479 if (!mono_class_is_contextbound (method->klass)) {
3480 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3481 gboolean has_nullable = FALSE;
3483 for (j = 0; j < sig->param_count; j++) {
3484 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3485 has_nullable = TRUE;
3488 if (info && !has_nullable) {
3489 /* Supported by the dynamic runtime-invoke wrapper */
3493 mono_arch_dyn_call_free (info);
3498 //printf ("%s\n", mono_method_full_name (method, TRUE));
3499 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3503 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3506 /* Runtime invoke wrappers */
3508 /* void runtime-invoke () [.cctor] */
3509 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3510 csig->ret = &mono_defaults.void_class->byval_arg;
3511 add_method (acfg, get_runtime_invoke_sig (csig));
3513 /* void runtime-invoke () [Finalize] */
3514 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3516 csig->ret = &mono_defaults.void_class->byval_arg;
3517 add_method (acfg, get_runtime_invoke_sig (csig));
3519 /* void runtime-invoke (string) [exception ctor] */
3520 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3522 csig->ret = &mono_defaults.void_class->byval_arg;
3523 csig->params [0] = &mono_defaults.string_class->byval_arg;
3524 add_method (acfg, get_runtime_invoke_sig (csig));
3526 /* void runtime-invoke (string, string) [exception ctor] */
3527 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3529 csig->ret = &mono_defaults.void_class->byval_arg;
3530 csig->params [0] = &mono_defaults.string_class->byval_arg;
3531 csig->params [1] = &mono_defaults.string_class->byval_arg;
3532 add_method (acfg, get_runtime_invoke_sig (csig));
3534 /* string runtime-invoke () [Exception.ToString ()] */
3535 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3537 csig->ret = &mono_defaults.string_class->byval_arg;
3538 add_method (acfg, get_runtime_invoke_sig (csig));
3540 /* void runtime-invoke (string, Exception) [exception ctor] */
3541 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3543 csig->ret = &mono_defaults.void_class->byval_arg;
3544 csig->params [0] = &mono_defaults.string_class->byval_arg;
3545 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3546 add_method (acfg, get_runtime_invoke_sig (csig));
3548 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3549 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3551 csig->ret = &(mono_class_from_name (
3552 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3553 csig->params [0] = &mono_defaults.string_class->byval_arg;
3554 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3555 add_method (acfg, get_runtime_invoke_sig (csig));
3557 /* runtime-invoke used by finalizers */
3558 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3560 /* This is used by mono_runtime_capture_context () */
3561 method = mono_get_context_capture_method ();
3563 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3565 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3566 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3570 add_method (acfg, mono_marshal_get_stelemref ());
3572 if (MONO_ARCH_HAVE_TLS_GET) {
3573 /* Managed Allocators */
3574 nallocators = mono_gc_get_managed_allocator_types ();
3575 for (i = 0; i < nallocators; ++i) {
3576 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3578 add_method (acfg, m);
3580 for (i = 0; i < nallocators; ++i) {
3581 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3583 add_method (acfg, m);
3587 /* write barriers */
3588 if (mono_gc_is_moving ()) {
3589 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3590 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3593 /* Stelemref wrappers */
3595 MonoMethod **wrappers;
3598 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3599 for (i = 0; i < nwrappers; ++i)
3600 add_method (acfg, wrappers [i]);
3604 /* castclass_with_check wrapper */
3605 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3606 /* isinst_with_check wrapper */
3607 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3609 /* JIT icall wrappers */
3610 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3611 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3615 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3616 * we use the original method instead at runtime.
3617 * Since full-aot doesn't support remoting, this is not a problem.
3620 /* remoting-invoke wrappers */
3621 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3622 MonoMethodSignature *sig;
3624 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3625 method = mono_get_method (acfg->image, token, NULL);
3627 sig = mono_method_signature (method);
3629 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3630 m = mono_marshal_get_remoting_invoke_with_check (method);
3632 add_method (acfg, m);
3637 /* delegate-invoke wrappers */
3638 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3641 MonoCustomAttrInfo *cattr;
3643 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3644 klass = mono_class_get_checked (acfg->image, token, &error);
3647 mono_error_cleanup (&error);
3651 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3654 if (!klass->generic_container) {
3655 method = mono_get_delegate_invoke (klass);
3657 m = mono_marshal_get_delegate_invoke (method, NULL);
3659 add_method (acfg, m);
3661 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3663 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3665 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3667 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3669 cattr = mono_custom_attrs_from_class (klass);
3674 for (j = 0; j < cattr->num_attrs; ++j)
3675 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3677 if (j < cattr->num_attrs) {
3679 MonoMethod *wrapper;
3680 MonoMethod *del_invoke;
3682 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3683 invoke = mono_get_delegate_invoke (klass);
3684 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3685 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3686 add_method (acfg, wrapper);
3687 add_method (acfg, del_invoke);
3690 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3692 MonoGenericContext ctx;
3693 MonoMethod *inst, *gshared;
3696 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3699 method = mono_get_delegate_invoke (klass);
3700 create_gsharedvt_inst (acfg, method, &ctx);
3702 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3703 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3705 m = mono_marshal_get_delegate_invoke (inst, NULL);
3706 g_assert (m->is_inflated);
3708 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3709 add_extra_method (acfg, gshared);
3712 method = mono_get_delegate_begin_invoke (klass);
3713 create_gsharedvt_inst (acfg, method, &ctx);
3715 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3716 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3718 m = mono_marshal_get_delegate_begin_invoke (inst);
3719 g_assert (m->is_inflated);
3721 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3722 add_extra_method (acfg, gshared);
3725 method = mono_get_delegate_end_invoke (klass);
3726 create_gsharedvt_inst (acfg, method, &ctx);
3728 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3729 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3731 m = mono_marshal_get_delegate_end_invoke (inst);
3732 g_assert (m->is_inflated);
3734 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3735 add_extra_method (acfg, gshared);
3740 /* array access wrappers */
3741 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3745 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3746 klass = mono_class_get_checked (acfg->image, token, &error);
3749 mono_error_cleanup (&error);
3753 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3754 MonoMethod *m, *wrapper;
3756 /* Add runtime-invoke wrappers too */
3758 m = mono_class_get_method_from_name (klass, "Get", -1);
3760 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3761 add_extra_method (acfg, wrapper);
3762 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3764 m = mono_class_get_method_from_name (klass, "Set", -1);
3766 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3767 add_extra_method (acfg, wrapper);
3768 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3772 /* Synchronized wrappers */
3773 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3775 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3776 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3777 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3779 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3780 if (method->is_generic) {
3782 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3784 MonoGenericContext ctx;
3785 MonoMethod *inst, *gshared, *m;
3788 * Create a generic wrapper for a generic instance, and AOT that.
3790 create_gsharedvt_inst (acfg, method, &ctx);
3791 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3792 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3793 m = mono_marshal_get_synchronized_wrapper (inst);
3794 g_assert (m->is_inflated);
3795 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3796 add_method (acfg, gshared);
3798 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3803 /* pinvoke wrappers */
3804 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3807 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3809 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3810 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3812 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3813 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3814 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3818 /* native-to-managed wrappers */
3819 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3822 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3823 MonoCustomAttrInfo *cattr;
3826 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3827 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3830 * Only generate native-to-managed wrappers for methods which have an
3831 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3832 * name to avoid defining a new assembly to contain it.
3834 cattr = mono_custom_attrs_from_method (method);
3837 for (j = 0; j < cattr->num_attrs; ++j)
3838 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3840 if (j < cattr->num_attrs) {
3841 MonoCustomAttrEntry *e = &cattr->attrs [j];
3842 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3843 const char *p = (const char*)e->data;
3845 int slen, num_named, named_type;
3849 char *export_name = NULL;
3850 MonoMethod *wrapper;
3852 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3853 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3854 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3855 mono_method_full_name (method, TRUE));
3859 g_assert (sig->param_count == 1);
3860 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3863 * Decode the cattr manually since we can't create objects
3864 * during aot compilation.
3870 /* From load_cattr_value () in reflection.c */
3871 slen = mono_metadata_decode_value (p, &p);
3872 n = g_memdup (p, slen + 1);
3874 t = mono_reflection_type_from_name (n, acfg->image);
3878 klass = mono_class_from_mono_type (t);
3879 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3883 num_named = read16 (p);
3886 g_assert (num_named < 2);
3887 if (num_named == 1) {
3891 /* parse ExportSymbol attribute */
3893 named_type = *named;
3895 /* data_type = *named; */
3898 name_len = mono_metadata_decode_blob_size (named, &named);
3899 name = g_malloc (name_len + 1);
3900 memcpy (name, named, name_len);
3901 name [name_len] = 0;
3904 g_assert (named_type == 0x54);
3905 g_assert (!strcmp (name, "ExportSymbol"));
3907 /* load_cattr_value (), string case */
3908 g_assert (*named != (char)0xff);
3909 slen = mono_metadata_decode_value (named, &named);
3910 export_name = g_malloc (slen + 1);
3911 memcpy (export_name, named, slen);
3912 export_name [slen] = 0;
3916 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3917 add_method (acfg, wrapper);
3919 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3923 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3924 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3925 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3929 /* StructureToPtr/PtrToStructure wrappers */
3930 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3934 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3935 klass = mono_class_get_checked (acfg->image, token, &error);
3938 mono_error_cleanup (&error);
3942 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3943 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3944 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3945 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3951 has_type_vars (MonoClass *klass)
3953 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3956 return has_type_vars (klass->element_class);
3957 if (klass->generic_class) {
3958 MonoGenericContext *context = &klass->generic_class->context;
3959 if (context->class_inst) {
3962 for (i = 0; i < context->class_inst->type_argc; ++i)
3963 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3967 if (klass->generic_container)
3973 is_vt_inst (MonoGenericInst *inst)
3977 for (i = 0; i < inst->type_argc; ++i) {
3978 MonoType *t = inst->type_argv [i];
3979 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3986 method_has_type_vars (MonoMethod *method)
3988 if (has_type_vars (method->klass))
3991 if (method->is_inflated) {
3992 MonoGenericContext *context = mono_method_get_context (method);
3993 if (context->method_inst) {
3996 for (i = 0; i < context->method_inst->type_argc; ++i)
3997 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4005 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4007 return opts->mode == MONO_AOT_MODE_FULL;
4010 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4013 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4015 /* This might lead to a huge code blowup so only do it if neccesary */
4016 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4019 add_generic_class_with_depth (acfg, klass, 0, ref);
4023 check_type_depth (MonoType *t, int depth)
4031 case MONO_TYPE_GENERICINST: {
4032 MonoGenericClass *gklass = t->data.generic_class;
4033 MonoGenericInst *ginst = gklass->context.class_inst;
4036 for (i = 0; i < ginst->type_argc; ++i) {
4037 if (check_type_depth (ginst->type_argv [i], depth + 1))
4051 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4054 * add_generic_class:
4056 * Add all methods of a generic class.
4059 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4062 MonoClassField *field;
4064 gboolean use_gsharedvt = FALSE;
4066 if (!acfg->ginst_hash)
4067 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4069 mono_class_init (klass);
4071 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4074 if (has_type_vars (klass))
4077 if (!klass->generic_class && !klass->rank)
4080 if (klass->exception_type)
4083 if (!acfg->ginst_hash)
4084 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4086 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4089 if (check_type_depth (&klass->byval_arg, 0))
4092 if (acfg->aot_opts.log_generics)
4093 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4095 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4098 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4099 * Enable this only for some classes since gsharedvt might not support all methods.
4101 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) &&
4102 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4103 use_gsharedvt = TRUE;
4106 while ((method = mono_class_get_methods (klass, &iter))) {
4107 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4109 * This is partial sharing, and we can't handle it yet
4114 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4116 add_types_from_method_header (acfg, method);
4120 if (method->is_generic)
4125 * FIXME: Instances which are referenced by these methods are not added,
4126 * for example Array.Resize<int> for List<int>.Add ().
4128 add_extra_method_with_depth (acfg, method, depth + 1);
4132 while ((field = mono_class_get_fields (klass, &iter))) {
4133 if (field->type->type == MONO_TYPE_GENERICINST)
4134 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4137 if (klass->delegate) {
4138 method = mono_get_delegate_invoke (klass);
4140 method = mono_marshal_get_delegate_invoke (method, NULL);
4142 if (acfg->aot_opts.log_generics)
4143 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4145 add_method (acfg, method);
4148 /* Add superclasses */
4150 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4153 * For ICollection<T>, add instances of the helper methods
4154 * in Array, since a T[] could be cast to ICollection<T>.
4156 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4157 (!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"))) {
4158 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4159 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4163 if (!strcmp (klass->name, "IEnumerator`1"))
4164 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4166 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4168 /* Add the T[]/InternalEnumerator class */
4169 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4173 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4174 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4178 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4179 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4183 while ((method = mono_class_get_methods (array_class, &iter))) {
4184 if (strstr (method->name, name_prefix)) {
4185 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4187 add_extra_method_with_depth (acfg, m, depth);
4191 g_free (name_prefix);
4194 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4195 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4196 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4197 MonoClass *icomparable, *gcomparer;
4198 MonoGenericContext ctx;
4199 MonoType *args [16];
4201 memset (&ctx, 0, sizeof (ctx));
4203 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4204 g_assert (icomparable);
4205 args [0] = &tclass->byval_arg;
4206 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4208 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4209 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4210 g_assert (gcomparer);
4211 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4215 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4216 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4217 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4218 MonoClass *iface, *gcomparer;
4219 MonoGenericContext ctx;
4220 MonoType *args [16];
4222 memset (&ctx, 0, sizeof (ctx));
4224 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4226 args [0] = &tclass->byval_arg;
4227 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4229 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4230 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4231 g_assert (gcomparer);
4232 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4236 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4237 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4238 MonoClass *enum_comparer;
4239 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4240 MonoGenericContext ctx;
4241 MonoType *args [16];
4243 if (mono_class_is_enum (tclass)) {
4244 memset (&ctx, 0, sizeof (ctx));
4245 args [0] = &tclass->byval_arg;
4246 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4248 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4249 g_assert (enum_comparer);
4250 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4254 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4255 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4256 MonoClass *comparer;
4257 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4258 MonoGenericContext ctx;
4259 MonoType *args [16];
4261 if (mono_class_is_enum (tclass)) {
4262 memset (&ctx, 0, sizeof (ctx));
4263 args [0] = &tclass->byval_arg;
4264 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4266 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4267 g_assert (comparer);
4268 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4274 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4277 MonoGenericContext ctx;
4278 MonoType *args [16];
4280 if (acfg->aot_opts.no_instances)
4283 memset (&ctx, 0, sizeof (ctx));
4285 for (i = 0; i < ninsts; ++i) {
4286 args [0] = insts [i];
4287 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4288 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4293 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4295 MonoMethodHeader *header;
4296 MonoMethodSignature *sig;
4299 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4301 sig = mono_method_signature (method);
4304 for (j = 0; j < sig->param_count; ++j)
4305 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4306 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4309 header = mono_method_get_header (method);
4312 for (j = 0; j < header->num_locals; ++j)
4313 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4314 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4316 mono_loader_clear_error ();
4321 * add_generic_instances:
4323 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4326 add_generic_instances (MonoAotCompile *acfg)
4331 MonoGenericContext *context;
4333 if (acfg->aot_opts.no_instances)
4336 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4338 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4339 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4342 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4343 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4344 mono_error_cleanup (&error);
4348 if (method->klass->image != acfg->image)
4351 context = mono_method_get_context (method);
4353 if (context && ((context->class_inst && context->class_inst->is_open)))
4357 * For open methods, create an instantiation which can be passed to the JIT.
4358 * FIXME: Handle class_inst as well.
4360 if (context && context->method_inst && context->method_inst->is_open) {
4362 MonoGenericContext shared_context;
4363 MonoGenericInst *inst;
4364 MonoType **type_argv;
4366 MonoMethod *declaring_method;
4367 gboolean supported = TRUE;
4369 /* Check that the context doesn't contain open constructed types */
4370 if (context->class_inst) {
4371 inst = context->class_inst;
4372 for (i = 0; i < inst->type_argc; ++i) {
4373 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)
4375 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4379 if (context->method_inst) {
4380 inst = context->method_inst;
4381 for (i = 0; i < inst->type_argc; ++i) {
4382 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)
4384 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4392 memset (&shared_context, 0, sizeof (MonoGenericContext));
4394 inst = context->class_inst;
4396 type_argv = g_new0 (MonoType*, inst->type_argc);
4397 for (i = 0; i < inst->type_argc; ++i) {
4398 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)
4399 type_argv [i] = &mono_defaults.object_class->byval_arg;
4401 type_argv [i] = inst->type_argv [i];
4404 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4408 inst = context->method_inst;
4410 type_argv = g_new0 (MonoType*, inst->type_argc);
4411 for (i = 0; i < inst->type_argc; ++i) {
4412 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)
4413 type_argv [i] = &mono_defaults.object_class->byval_arg;
4415 type_argv [i] = inst->type_argv [i];
4418 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4422 if (method->is_generic || method->klass->generic_container)
4423 declaring_method = method;
4425 declaring_method = mono_method_get_declaring_generic_method (method);
4427 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4428 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4432 * If the method is fully sharable, it was already added in place of its
4433 * generic definition.
4435 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4439 * FIXME: Partially shared methods are not shared here, so we end up with
4440 * many identical methods.
4442 add_extra_method (acfg, method);
4445 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4449 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4451 klass = mono_class_get_checked (acfg->image, token, &error);
4452 if (!klass || klass->rank) {
4453 mono_error_cleanup (&error);
4457 add_generic_class (acfg, klass, FALSE, "typespec");
4460 /* Add types of args/locals */
4461 for (i = 0; i < acfg->methods->len; ++i) {
4462 method = g_ptr_array_index (acfg->methods, i);
4463 add_types_from_method_header (acfg, method);
4466 if (acfg->image == mono_defaults.corlib) {
4468 MonoType *insts [256];
4471 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4472 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4473 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4474 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4475 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4476 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4477 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4478 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4479 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4480 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4481 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4482 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4484 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4485 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4487 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4488 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4490 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4492 /* Add instances of the array generic interfaces for primitive types */
4493 /* This will add instances of the InternalArray_ helper methods in Array too */
4494 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4496 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4497 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4499 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4500 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4502 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4505 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4506 * used for all instances of GetGenericValueImpl by the AOT runtime.
4509 MonoGenericContext ctx;
4510 MonoType *args [16];
4511 MonoMethod *get_method;
4512 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4514 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4518 memset (&ctx, 0, sizeof (ctx));
4519 args [0] = &mono_defaults.object_class->byval_arg;
4520 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4521 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4522 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4526 /* Same for CompareExchange<T>/Exchange<T> */
4528 MonoGenericContext ctx;
4529 MonoType *args [16];
4531 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4532 gpointer iter = NULL;
4534 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4535 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4537 memset (&ctx, 0, sizeof (ctx));
4538 args [0] = &mono_defaults.object_class->byval_arg;
4539 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4540 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4541 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4546 /* Same for Volatile.Read/Write<T> */
4548 MonoGenericContext ctx;
4549 MonoType *args [16];
4551 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4552 gpointer iter = NULL;
4554 if (volatile_klass) {
4555 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4556 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4558 memset (&ctx, 0, sizeof (ctx));
4559 args [0] = &mono_defaults.object_class->byval_arg;
4560 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4561 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4562 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4571 * is_direct_callable:
4573 * Return whenever the method identified by JI is directly callable without
4574 * going through the PLT.
4577 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4579 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4580 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4582 gboolean direct_callable = TRUE;
4584 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4585 direct_callable = FALSE;
4586 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4587 // FIXME: Maybe call the wrapper directly ?
4588 direct_callable = FALSE;
4590 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4591 /* Disable this so all calls go through load_method (), see the
4592 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4593 * mono_debugger_agent_init ().
4595 direct_callable = FALSE;
4598 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4599 /* sgen does some initialization when the allocator method is created */
4600 direct_callable = FALSE;
4601 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4602 /* we don't know at compile time whether sgen is concurrent or not */
4603 direct_callable = FALSE;
4605 if (direct_callable)
4608 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4609 if (acfg->aot_opts.direct_pinvoke)
4611 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4612 if (acfg->aot_opts.direct_icalls)
4620 #ifdef MONO_ARCH_AOT_SUPPORTED
4622 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4624 MonoImage *image = method->klass->image;
4625 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4626 MonoTableInfo *tables = image->tables;
4627 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4628 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4629 guint32 im_cols [MONO_IMPLMAP_SIZE];
4632 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4636 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4639 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4641 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4644 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4646 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4653 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4655 if (a->native_offset == b->native_offset)
4656 return a->il_offset - b->il_offset;
4658 return a->native_offset - b->native_offset;
4662 * compute_line_numbers:
4664 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4667 static MonoDebugSourceLocation**
4668 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4670 MonoDebugMethodInfo *minfo;
4671 MonoDebugLineNumberEntry *ln_array;
4672 MonoDebugSourceLocation *loc;
4673 int i, prev_line, prev_il_offset;
4674 int *native_to_il_offset = NULL;
4675 MonoDebugSourceLocation **res;
4678 minfo = mono_debug_lookup_method (method);
4681 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4682 if (debug_info->code_size != code_size)
4685 g_assert (code_size);
4687 /* Compute the native->IL offset mapping */
4689 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4690 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4692 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4694 native_to_il_offset = g_new0 (int, code_size + 1);
4696 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4698 MonoDebugLineNumberEntry *lne = &ln_array [i];
4701 for (j = 0; j < lne->native_offset; ++j)
4702 native_to_il_offset [j] = -1;
4705 if (i < debug_info->num_line_numbers - 1) {
4706 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4708 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4709 native_to_il_offset [j] = lne->il_offset;
4711 for (j = lne->native_offset; j < code_size; ++j)
4712 native_to_il_offset [j] = lne->il_offset;
4717 /* Compute the native->line number mapping */
4718 res = g_new0 (MonoDebugSourceLocation*, code_size);
4719 prev_il_offset = -1;
4722 for (i = 0; i < code_size; ++i) {
4723 int il_offset = native_to_il_offset [i];
4725 if (il_offset == -1 || il_offset == prev_il_offset)
4727 prev_il_offset = il_offset;
4728 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4729 if (!(loc && loc->source_file))
4731 if (loc->row == prev_line) {
4732 mono_debug_symfile_free_location (loc);
4735 prev_line = loc->row;
4736 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4738 /* This will cover the prolog too */
4748 get_file_index (MonoAotCompile *acfg, const char *source_file)
4752 // FIXME: Free these
4753 if (!acfg->dwarf_ln_filenames)
4754 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4755 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4757 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4758 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4759 emit_unset_mode (acfg);
4760 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4772 * emit_and_reloc_code:
4774 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4775 * is true, calls are made through the GOT too. This is used for emitting trampolines
4776 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4777 * since trampolines are needed to make PTL work.
4780 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4782 int i, pindex, start_index;
4784 MonoJumpInfo *patch_info;
4785 MonoDebugSourceLocation **locs = NULL;
4787 #ifdef MONO_ARCH_AOT_SUPPORTED
4788 gboolean direct_call, external_call;
4790 const char *direct_call_target = 0;
4791 const char *direct_pinvoke;
4794 if (acfg->gas_line_numbers && method && debug_info) {
4795 locs = compute_line_numbers (method, code_len, debug_info);
4797 int findex = get_file_index (acfg, "<unknown>");
4798 emit_unset_mode (acfg);
4799 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4803 /* Collect and sort relocations */
4804 patches = g_ptr_array_new ();
4805 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4806 g_ptr_array_add (patches, patch_info);
4807 g_ptr_array_sort (patches, compare_patches);
4810 for (i = 0; i < code_len; i += INST_LEN) {
4812 for (pindex = start_index; pindex < patches->len; ++pindex) {
4813 patch_info = g_ptr_array_index (patches, pindex);
4814 if (patch_info->ip.i >= i)
4818 if (locs && locs [i]) {
4819 MonoDebugSourceLocation *loc = locs [i];
4822 findex = get_file_index (acfg, loc->source_file);
4823 emit_unset_mode (acfg);
4824 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4825 mono_debug_symfile_free_location (loc);
4829 #ifdef MONO_ARCH_AOT_SUPPORTED
4830 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4831 start_index = pindex;
4833 switch (patch_info->type) {
4834 case MONO_PATCH_INFO_NONE:
4836 case MONO_PATCH_INFO_GOT_OFFSET: {
4839 arch_emit_got_offset (acfg, code + i, &code_size);
4840 i += code_size - INST_LEN;
4842 patch_info->type = MONO_PATCH_INFO_NONE;
4845 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4846 int code_size, index;
4847 char *selector = (void*)patch_info->data.target;
4849 if (!acfg->objc_selector_to_index)
4850 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4851 if (!acfg->objc_selectors)
4852 acfg->objc_selectors = g_ptr_array_new ();
4853 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4857 index = acfg->objc_selector_index;
4858 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4859 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4860 acfg->objc_selector_index ++;
4863 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4864 i += code_size - INST_LEN;
4866 patch_info->type = MONO_PATCH_INFO_NONE;
4871 * If this patch is a call, try emitting a direct call instead of
4872 * through a PLT entry. This is possible if the called method is in
4873 * the same assembly and requires no initialization.
4875 direct_call = FALSE;
4876 external_call = FALSE;
4877 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4878 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4879 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4880 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4882 direct_call_target = callee_cfg->asm_symbol;
4883 patch_info->type = MONO_PATCH_INFO_NONE;
4884 acfg->stats.direct_calls ++;
4887 acfg->stats.all_calls ++;
4888 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4889 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4890 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4891 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4893 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4894 if (direct_pinvoke) {
4896 g_assert (strlen (direct_pinvoke) < 1000);
4897 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4900 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4901 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4902 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4903 /* Call to a C function implementing a jit icall */
4905 external_call = TRUE;
4906 g_assert (strlen (sym) < 1000);
4907 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4909 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4910 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4911 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4912 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4913 /* Call to a jit icall without a wrapper */
4915 external_call = TRUE;
4916 g_assert (strlen (sym) < 1000);
4917 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4922 patch_info->type = MONO_PATCH_INFO_NONE;
4923 acfg->stats.direct_calls ++;
4926 if (!got_only && !direct_call) {
4927 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4929 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4931 direct_call_target = plt_entry->symbol;
4933 /* Nullify the patch */
4934 patch_info->type = MONO_PATCH_INFO_NONE;
4935 plt_entry->jit_used = TRUE;
4942 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4943 i += call_size - INST_LEN;
4947 got_slot = get_got_offset (acfg, FALSE, patch_info);
4949 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
4950 i += code_size - INST_LEN;
4956 #endif /* MONO_ARCH_AOT_SUPPORTED */
4959 /* Find next patch */
4961 for (pindex = start_index; pindex < patches->len; ++pindex) {
4962 patch_info = g_ptr_array_index (patches, pindex);
4963 if (patch_info->ip.i >= i)
4967 /* Try to emit multiple bytes at once */
4968 if (pindex < patches->len && patch_info->ip.i > i) {
4971 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4972 if (locs && locs [limit])
4976 emit_code_bytes (acfg, code + i, limit - i);
4977 i = limit - INST_LEN;
4979 emit_code_bytes (acfg, code + i, INST_LEN);
4990 * Return a modified version of S which only includes characters permissible in symbols.
4993 sanitize_symbol (MonoAotCompile *acfg, char *s)
4995 gboolean process = FALSE;
5004 for (i = 0; i < len; ++i)
5005 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5010 gs = g_string_sized_new (len);
5011 for (i = 0; i < len; ++i) {
5013 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5014 g_string_append_c (gs, c);
5015 } else if (c > 0x7f) {
5016 /* multi-byte utf8 */
5017 g_string_append_printf (gs, "_0x%x", c);
5020 while (c >> 6 == 0x2) {
5021 g_string_append_printf (gs, "%x", c);
5025 g_string_append_printf (gs, "_");
5028 g_string_append_c (gs, '_');
5032 res = mono_mempool_strdup (acfg->mempool, gs->str);
5033 g_string_free (gs, TRUE);
5038 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5040 char *name1, *name2, *cached;
5041 int i, j, len, count;
5042 MonoMethod *cached_method;
5044 name1 = mono_method_full_name (method, TRUE);
5047 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5048 if ((!prefix || !*prefix) && name1 [0] == 'L')
5052 len = strlen (name1);
5053 name2 = malloc (strlen (prefix) + len + 16);
5054 memcpy (name2, prefix, strlen (prefix));
5055 j = strlen (prefix);
5056 for (i = 0; i < len; ++i) {
5057 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5059 } else if (isalnum (name1 [i])) {
5060 name2 [j ++] = name1 [i];
5061 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5063 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5066 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5076 cached_method = g_hash_table_lookup (cache, name2);
5077 if (!(cached_method && cached_method != method))
5079 sprintf (name2 + j, "_%d", count);
5083 cached = g_strdup (name2);
5084 g_hash_table_insert (cache, cached, method);
5090 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5095 char *debug_sym = NULL;
5096 char *symbol = NULL;
5097 int func_alignment = AOT_FUNC_ALIGNMENT;
5100 method = cfg->orig_method;
5101 code = cfg->native_code;
5103 method_index = get_method_index (acfg, method);
5104 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5106 /* Make the labels local */
5107 emit_section_change (acfg, ".text", 0);
5108 emit_alignment_code (acfg, func_alignment);
5110 if (acfg->global_symbols && acfg->need_no_dead_strip)
5111 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5113 emit_label (acfg, cfg->asm_symbol);
5115 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5117 * Write a C style symbol for every method, this has two uses:
5118 * - it works on platforms where the dwarf debugging info is not
5120 * - it allows the setting of breakpoints of aot-ed methods.
5122 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5123 cfg->asm_debug_symbol = g_strdup (debug_sym);
5125 if (acfg->need_no_dead_strip)
5126 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5127 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5128 emit_label (acfg, debug_sym);
5131 export_name = g_hash_table_lookup (acfg->export_names, method);
5133 /* Emit a global symbol for the method */
5134 emit_global_inner (acfg, export_name, TRUE);
5135 emit_label (acfg, export_name);
5138 if (cfg->verbose_level > 0)
5139 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5141 acfg->stats.code_size += cfg->code_len;
5143 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5145 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 ()));
5149 if (acfg->aot_opts.write_symbols) {
5151 emit_symbol_size (acfg, debug_sym, ".");
5153 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5157 emit_label (acfg, symbol);
5164 * Encode PATCH_INFO into its disk representation.
5167 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5171 switch (patch_info->type) {
5172 case MONO_PATCH_INFO_NONE:
5174 case MONO_PATCH_INFO_IMAGE:
5175 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5177 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5178 case MONO_PATCH_INFO_JIT_TLS_ID:
5179 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5180 case MONO_PATCH_INFO_GC_NURSERY_START:
5182 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5183 encode_value (patch_info->data.index, p, &p);
5185 case MONO_PATCH_INFO_METHOD_REL:
5186 encode_value ((gint)patch_info->data.offset, p, &p);
5188 case MONO_PATCH_INFO_SWITCH: {
5189 gpointer *table = (gpointer *)patch_info->data.table->table;
5192 encode_value (patch_info->data.table->table_size, p, &p);
5193 for (k = 0; k < patch_info->data.table->table_size; k++)
5194 encode_value ((int)(gssize)table [k], p, &p);
5197 case MONO_PATCH_INFO_METHODCONST:
5198 case MONO_PATCH_INFO_METHOD:
5199 case MONO_PATCH_INFO_METHOD_JUMP:
5200 case MONO_PATCH_INFO_ICALL_ADDR:
5201 case MONO_PATCH_INFO_METHOD_RGCTX:
5202 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5203 encode_method_ref (acfg, patch_info->data.method, p, &p);
5205 case MONO_PATCH_INFO_INTERNAL_METHOD:
5206 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5207 guint32 len = strlen (patch_info->data.name);
5209 encode_value (len, p, &p);
5211 memcpy (p, patch_info->data.name, len);
5216 case MONO_PATCH_INFO_LDSTR: {
5217 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5218 guint32 token = patch_info->data.token->token;
5219 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5220 encode_value (image_index, p, &p);
5221 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5224 case MONO_PATCH_INFO_RVA:
5225 case MONO_PATCH_INFO_DECLSEC:
5226 case MONO_PATCH_INFO_LDTOKEN:
5227 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5228 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5229 encode_value (patch_info->data.token->token, p, &p);
5230 encode_value (patch_info->data.token->has_context, p, &p);
5231 if (patch_info->data.token->has_context)
5232 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5234 case MONO_PATCH_INFO_EXC_NAME: {
5235 MonoClass *ex_class;
5238 mono_class_from_name (mono_defaults.exception_class->image,
5239 "System", patch_info->data.target);
5240 g_assert (ex_class);
5241 encode_klass_ref (acfg, ex_class, p, &p);
5244 case MONO_PATCH_INFO_R4:
5245 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5247 case MONO_PATCH_INFO_R8:
5248 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5249 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5251 case MONO_PATCH_INFO_VTABLE:
5252 case MONO_PATCH_INFO_CLASS:
5253 case MONO_PATCH_INFO_IID:
5254 case MONO_PATCH_INFO_ADJUSTED_IID:
5255 case MONO_PATCH_INFO_CLASS_INIT:
5256 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5258 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5259 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5260 if (patch_info->data.del_tramp->method) {
5261 encode_value (1, p, &p);
5262 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5264 encode_value (0, p, &p);
5266 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5268 case MONO_PATCH_INFO_FIELD:
5269 case MONO_PATCH_INFO_SFLDA:
5270 encode_field_info (acfg, patch_info->data.field, p, &p);
5272 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5274 case MONO_PATCH_INFO_RGCTX_FETCH: {
5275 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5280 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5281 * reference the same method, so encode the method only once.
5283 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5285 buf2 = g_malloc (1024);
5288 encode_method_ref (acfg, entry->method, p2, &p2);
5289 g_assert (p2 - buf2 < 1024);
5291 offset = add_to_blob (acfg, buf2, p2 - buf2);
5294 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5299 encode_value (offset, p, &p);
5300 g_assert ((int)entry->info_type < 256);
5301 g_assert (entry->data->type < 256);
5302 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5303 encode_patch (acfg, entry->data, p, &p);
5306 case MONO_PATCH_INFO_MONITOR_ENTER:
5307 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5308 case MONO_PATCH_INFO_MONITOR_EXIT:
5309 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5311 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5312 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5313 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5315 case MONO_PATCH_INFO_SIGNATURE:
5316 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5318 case MONO_PATCH_INFO_TLS_OFFSET:
5319 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5321 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5322 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5323 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5325 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5326 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5329 encode_method_ref (acfg, info->method, p, &p);
5330 encode_value (info->num_entries, p, &p);
5331 for (i = 0; i < info->num_entries; ++i) {
5332 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5334 encode_value (template->info_type, p, &p);
5335 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5336 case MONO_PATCH_INFO_CLASS:
5337 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5339 case MONO_PATCH_INFO_FIELD:
5340 encode_field_info (acfg, template->data, p, &p);
5343 g_assert_not_reached ();
5349 case MONO_PATCH_INFO_LDSTR_LIT: {
5350 const char *s = patch_info->data.target;
5351 int len = strlen (s);
5353 encode_value (len, p, &p);
5354 memcpy (p, s, len + 1);
5358 case MONO_PATCH_INFO_VIRT_METHOD:
5359 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5360 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5362 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5365 g_warning ("unable to handle jump info %d", patch_info->type);
5366 g_assert_not_reached ();
5373 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5376 guint32 pindex, offset;
5377 MonoJumpInfo *patch_info;
5379 encode_value (n_patches, p, &p);
5381 for (pindex = 0; pindex < patches->len; ++pindex) {
5382 patch_info = g_ptr_array_index (patches, pindex);
5384 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5388 offset = get_got_offset (acfg, llvm, patch_info);
5389 encode_value (offset, p, &p);
5396 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5399 int pindex, buf_size, n_patches;
5401 MonoJumpInfo *patch_info;
5402 guint32 method_index;
5404 guint32 first_got_offset;
5406 method = cfg->orig_method;
5408 method_index = get_method_index (acfg, method);
5410 /* Sort relocations */
5411 patches = g_ptr_array_new ();
5412 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5413 g_ptr_array_add (patches, patch_info);
5414 g_ptr_array_sort (patches, compare_patches);
5416 first_got_offset = acfg->cfgs [method_index]->got_offset;
5418 /**********************/
5419 /* Encode method info */
5420 /**********************/
5422 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5423 p = buf = g_malloc (buf_size);
5425 if (mono_class_get_cctor (method->klass))
5426 encode_klass_ref (acfg, method->klass, p, &p);
5428 /* Not needed when loading the method */
5429 encode_value (0, p, &p);
5431 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5434 for (pindex = 0; pindex < patches->len; ++pindex) {
5435 patch_info = g_ptr_array_index (patches, pindex);
5437 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5438 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5439 patch_info->type = MONO_PATCH_INFO_NONE;
5444 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5445 /* Stored in a GOT slot initialized at module load time */
5446 patch_info->type = MONO_PATCH_INFO_NONE;
5450 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5451 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START) {
5452 /* Stored in a GOT slot initialized at module load time */
5453 patch_info->type = MONO_PATCH_INFO_NONE;
5457 if (is_plt_patch (patch_info)) {
5458 /* Calls are made through the PLT */
5459 patch_info->type = MONO_PATCH_INFO_NONE;
5467 g_assert (cfg->has_got_slots);
5469 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5471 acfg->stats.info_size += p - buf;
5473 g_assert (p - buf < buf_size);
5475 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5480 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5482 guint32 cache_index;
5485 /* Reuse the unwind module to canonize and store unwind info entries */
5486 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5488 /* Use +/- 1 to distinguish 0s from missing entries */
5489 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5497 * It would be easier to use assembler symbols, but the caller needs an
5500 offset = acfg->unwind_info_offset;
5501 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5502 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5505 encode_value (encoded_len, p, &p);
5507 acfg->unwind_info_offset += encoded_len + (p - buf);
5513 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5516 guint32 debug_info_size, seq_points_size;
5518 MonoMethodHeader *header;
5519 guint8 *p, *buf, *debug_info;
5520 MonoJitInfo *jinfo = cfg->jit_info;
5522 gboolean use_unwind_ops = FALSE;
5523 MonoSeqPointInfo *seq_points;
5525 code = cfg->native_code;
5526 header = cfg->header;
5528 if (!acfg->aot_opts.nodebug) {
5529 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5532 debug_info_size = 0;
5535 seq_points = cfg->seq_point_info;
5536 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5538 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5540 p = buf = g_malloc (buf_size);
5542 use_unwind_ops = cfg->unwind_ops != NULL;
5544 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);
5546 encode_value (flags, p, &p);
5548 if (use_unwind_ops) {
5549 guint32 encoded_len;
5551 guint32 unwind_desc;
5553 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5555 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5556 encode_value (unwind_desc, p, &p);
5558 encode_value (jinfo->unwind_info, p, &p);
5561 /*Encode the number of holes before the number of clauses to make decoding easier*/
5562 if (jinfo->has_try_block_holes) {
5563 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5564 encode_value (table->num_holes, p, &p);
5567 if (jinfo->has_arch_eh_info) {
5569 * In AOT mode, the code length is calculated from the address of the previous method,
5570 * which could include alignment padding, so calculating the start of the epilog as
5571 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5573 encode_value (jinfo->code_size, p, &p);
5576 /* Exception table */
5577 if (cfg->compile_llvm) {
5579 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5580 * since the information is only available to llc. Instead, we let llc save the data
5581 * into the LSDA, and read it from there at runtime.
5583 /* The assembly might be CIL stripped so emit the data ourselves */
5584 if (header->num_clauses)
5585 encode_value (header->num_clauses, p, &p);
5587 for (k = 0; k < header->num_clauses; ++k) {
5588 MonoExceptionClause *clause;
5590 clause = &header->clauses [k];
5592 encode_value (clause->flags, p, &p);
5593 if (clause->data.catch_class) {
5594 encode_value (1, p, &p);
5595 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5597 encode_value (0, p, &p);
5600 /* Emit a list of nesting clauses */
5601 for (i = 0; i < header->num_clauses; ++i) {
5603 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5605 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5607 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5608 encode_value (i, p, &p);
5610 encode_value (-1, p, &p);
5613 if (jinfo->num_clauses)
5614 encode_value (jinfo->num_clauses, p, &p);
5616 for (k = 0; k < jinfo->num_clauses; ++k) {
5617 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5619 encode_value (ei->flags, p, &p);
5620 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5621 /* Not used for catch clauses */
5622 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5623 encode_value (ei->exvar_offset, p, &p);
5625 encode_value (ei->exvar_offset, p, &p);
5628 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5629 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5631 if (ei->data.catch_class) {
5635 buf2 = g_malloc (4096);
5637 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5639 g_assert (len < 4096);
5640 encode_value (len, p, &p);
5641 memcpy (p, buf2, len);
5645 encode_value (0, p, &p);
5649 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5650 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5651 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5655 if (jinfo->has_try_block_holes) {
5656 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5657 for (i = 0; i < table->num_holes; ++i) {
5658 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5659 encode_value (hole->clause, p, &p);
5660 encode_value (hole->length, p, &p);
5661 encode_value (hole->offset, p, &p);
5665 if (jinfo->has_arch_eh_info) {
5666 MonoArchEHJitInfo *eh_info;
5668 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5669 encode_value (eh_info->stack_size, p, &p);
5670 encode_value (eh_info->epilog_size, p, &p);
5673 if (jinfo->has_generic_jit_info) {
5674 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5675 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5679 encode_value (gi->nlocs, p, &p);
5681 for (i = 0; i < gi->nlocs; ++i) {
5682 MonoDwarfLocListEntry *entry = &gi->locations [i];
5684 encode_value (entry->is_reg ? 1 : 0, p, &p);
5685 encode_value (entry->reg, p, &p);
5687 encode_value (entry->offset, p, &p);
5689 g_assert (entry->from == 0);
5691 encode_value (entry->from, p, &p);
5692 encode_value (entry->to, p, &p);
5695 if (!cfg->compile_llvm) {
5696 encode_value (gi->has_this ? 1 : 0, p, &p);
5697 encode_value (gi->this_reg, p, &p);
5698 encode_value (gi->this_offset, p, &p);
5703 * Need to encode jinfo->method too, since it is not equal to 'method'
5704 * when using generic sharing.
5706 buf2 = g_malloc (4096);
5708 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5710 g_assert (len < 4096);
5711 encode_value (len, p, &p);
5712 memcpy (p, buf2, len);
5716 if (gsctx && gsctx->is_gsharedvt) {
5717 encode_value (1, 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);
5891 return sanitize_symbol (acfg, debug_sym);
5895 * Calls made from AOTed code are routed through a table of jumps similar to the
5896 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5897 * control to the AOT runtime through a trampoline.
5900 emit_plt (MonoAotCompile *acfg)
5906 sprintf (symbol, "plt");
5908 emit_section_change (acfg, ".text", 0);
5909 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5910 emit_label (acfg, symbol);
5911 emit_label (acfg, acfg->plt_symbol);
5913 for (i = 0; i < acfg->plt_offset; ++i) {
5914 char *debug_sym = NULL;
5915 MonoPltEntry *plt_entry = NULL;
5919 * The first plt entry is unused.
5923 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5925 debug_sym = plt_entry->debug_sym;
5927 if (acfg->thumb_mixed && !plt_entry->jit_used)
5928 /* Emit only a thumb version */
5931 /* Skip plt entries not actually called */
5932 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5935 if (acfg->llvm && !acfg->thumb_mixed) {
5936 emit_label (acfg, plt_entry->llvm_symbol);
5938 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5939 #if defined(TARGET_MACH)
5940 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5946 if (acfg->need_no_dead_strip) {
5947 emit_unset_mode (acfg);
5948 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5950 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5951 emit_label (acfg, debug_sym);
5954 emit_label (acfg, plt_entry->symbol);
5956 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
5959 emit_symbol_size (acfg, debug_sym, ".");
5962 if (acfg->thumb_mixed) {
5963 /* Make sure the ARM symbols don't alias the thumb ones */
5964 emit_zero_bytes (acfg, 16);
5967 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5970 for (i = 0; i < acfg->plt_offset; ++i) {
5971 char *debug_sym = NULL;
5972 MonoPltEntry *plt_entry = NULL;
5977 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5979 /* Skip plt entries not actually called by LLVM code */
5980 if (!plt_entry->llvm_used)
5983 if (acfg->aot_opts.write_symbols) {
5984 if (plt_entry->debug_sym)
5985 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5989 #if defined(TARGET_MACH)
5990 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5991 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5993 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5994 emit_label (acfg, debug_sym);
5996 fprintf (acfg->fp, "\n.thumb_func\n");
5998 emit_label (acfg, plt_entry->llvm_symbol);
6001 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6003 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6006 emit_symbol_size (acfg, debug_sym, ".");
6012 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6014 sprintf (symbol, "plt_end");
6015 emit_label (acfg, symbol);
6019 * emit_trampoline_full:
6021 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6022 * create_jit_info_for_trampoline ().
6024 static G_GNUC_UNUSED void
6025 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6027 char start_symbol [256];
6028 char end_symbol [256];
6030 guint32 buf_size, info_offset;
6031 MonoJumpInfo *patch_info;
6044 code_size = info->code_size;
6046 unwind_ops = info->unwind_ops;
6048 #ifdef __native_client_codegen__
6049 mono_nacl_fix_patches (code, ji);
6054 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6056 emit_section_change (acfg, ".text", 0);
6057 emit_global (acfg, start_symbol, TRUE);
6058 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6059 emit_label (acfg, start_symbol);
6061 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6062 emit_label (acfg, symbol);
6065 * The code should access everything through the GOT, so we pass
6068 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6070 emit_symbol_size (acfg, start_symbol, ".");
6073 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6074 emit_label (acfg, end_symbol);
6079 /* Sort relocations */
6080 patches = g_ptr_array_new ();
6081 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6082 if (patch_info->type != MONO_PATCH_INFO_NONE)
6083 g_ptr_array_add (patches, patch_info);
6084 g_ptr_array_sort (patches, compare_patches);
6086 buf_size = patches->len * 128 + 128;
6087 buf = g_malloc (buf_size);
6090 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6091 g_assert (p - buf < buf_size);
6093 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6095 info_offset = add_to_blob (acfg, buf, p - buf);
6097 emit_section_change (acfg, RODATA_SECT, 0);
6098 emit_global (acfg, symbol, FALSE);
6099 emit_label (acfg, symbol);
6101 emit_int32 (acfg, info_offset);
6105 guint32 encoded_len;
6109 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6111 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6112 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6115 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6116 emit_int32 (acfg, uw_offset);
6119 /* Emit debug info */
6123 sprintf (symbol, "%s", name);
6124 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6127 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6131 static G_GNUC_UNUSED void
6132 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6134 emit_trampoline_full (acfg, got_offset, info, FALSE);
6138 emit_trampolines (MonoAotCompile *acfg)
6141 char end_symbol [256];
6142 int i, tramp_got_offset;
6143 MonoAotTrampoline ntype;
6144 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6148 if (!mono_aot_mode_is_full (&acfg->aot_opts))
6151 g_assert (acfg->image->assembly);
6153 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6154 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6155 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6156 MonoTrampInfo *info;
6159 * Emit the generic trampolines.
6161 * We could save some code by treating the generic trampolines as a wrapper
6162 * method, but that approach has its own complexities, so we choose the simpler
6165 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6166 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6167 #ifdef DISABLE_REMOTING
6168 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6171 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6172 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6175 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6176 emit_trampoline (acfg, acfg->got_offset, info);
6179 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6180 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6181 emit_trampoline (acfg, acfg->got_offset, info);
6182 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6183 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6184 emit_trampoline (acfg, acfg->got_offset, info);
6186 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6187 emit_trampoline (acfg, acfg->got_offset, info);
6190 /* Emit the exception related code pieces */
6191 mono_arch_get_restore_context (&info, TRUE);
6192 emit_trampoline (acfg, acfg->got_offset, info);
6193 mono_arch_get_call_filter (&info, TRUE);
6194 emit_trampoline (acfg, acfg->got_offset, info);
6195 mono_arch_get_throw_exception (&info, TRUE);
6196 emit_trampoline (acfg, acfg->got_offset, info);
6197 mono_arch_get_rethrow_exception (&info, TRUE);
6198 emit_trampoline (acfg, acfg->got_offset, info);
6199 mono_arch_get_throw_corlib_exception (&info, TRUE);
6200 emit_trampoline (acfg, acfg->got_offset, info);
6202 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6203 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6204 emit_trampoline (acfg, acfg->got_offset, info);
6205 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6206 emit_trampoline (acfg, acfg->got_offset, info);
6209 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6210 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6212 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6214 /* Create a separate out trampoline for more information in stack traces */
6215 info->name = g_strdup ("gsharedvt_out_trampoline");
6216 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6220 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6222 GSList *l = mono_arch_get_trampolines (TRUE);
6225 MonoTrampInfo *info = l->data;
6227 emit_trampoline (acfg, acfg->got_offset, info);
6233 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6236 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6237 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6238 emit_trampoline (acfg, acfg->got_offset, info);
6240 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6241 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6242 emit_trampoline (acfg, acfg->got_offset, info);
6245 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6246 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6247 emit_trampoline (acfg, acfg->got_offset, info);
6253 /* delegate_invoke_impl trampolines */
6254 l = mono_arch_get_delegate_invoke_impls ();
6256 MonoTrampInfo *info = l->data;
6258 emit_trampoline (acfg, acfg->got_offset, info);
6263 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6265 /* Emit trampolines which are numerous */
6268 * These include the following:
6269 * - specific trampolines
6270 * - static rgctx invoke trampolines
6272 * These trampolines have the same code, they are parameterized by GOT
6274 * They are defined in this file, in the arch_... routines instead of
6275 * in tramp-<ARCH>.c, since it is easier to do it this way.
6279 * When running in aot-only mode, we can't create specific trampolines at
6280 * runtime, so we create a few, and save them in the AOT file.
6281 * Normal trampolines embed their argument as a literal inside the
6282 * trampoline code, we can't do that here, so instead we embed an offset
6283 * which needs to be added to the trampoline address to get the address of
6284 * the GOT slot which contains the argument value.
6285 * The generated trampolines jump to the generic trampolines using another
6286 * GOT slot, which will be setup by the AOT loader to point to the
6287 * generic trampoline code of the given type.
6291 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6295 emit_section_change (acfg, ".text", 0);
6297 tramp_got_offset = acfg->got_offset;
6299 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6301 case MONO_AOT_TRAMP_SPECIFIC:
6302 sprintf (symbol, "specific_trampolines");
6304 case MONO_AOT_TRAMP_STATIC_RGCTX:
6305 sprintf (symbol, "static_rgctx_trampolines");
6307 case MONO_AOT_TRAMP_IMT_THUNK:
6308 sprintf (symbol, "imt_thunks");
6310 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6311 sprintf (symbol, "gsharedvt_arg_trampolines");
6314 g_assert_not_reached ();
6317 sprintf (end_symbol, "%s_e", symbol);
6319 if (acfg->aot_opts.write_symbols)
6320 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6322 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6323 emit_label (acfg, symbol);
6325 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6327 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6331 case MONO_AOT_TRAMP_SPECIFIC:
6332 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6333 tramp_got_offset += 2;
6335 case MONO_AOT_TRAMP_STATIC_RGCTX:
6336 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6337 tramp_got_offset += 2;
6339 case MONO_AOT_TRAMP_IMT_THUNK:
6340 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6341 tramp_got_offset += 1;
6343 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6344 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6345 tramp_got_offset += 2;
6348 g_assert_not_reached ();
6350 #ifdef __native_client_codegen__
6351 /* align to avoid 32-byte boundary crossings */
6352 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6355 if (!acfg->trampoline_size [ntype]) {
6356 g_assert (tramp_size);
6357 acfg->trampoline_size [ntype] = tramp_size;
6361 emit_label (acfg, end_symbol);
6362 emit_int32 (acfg, 0);
6365 arch_emit_specific_trampoline_pages (acfg);
6367 /* Reserve some entries at the end of the GOT for our use */
6368 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6371 acfg->got_offset += acfg->num_trampoline_got_entries;
6375 str_begins_with (const char *str1, const char *str2)
6377 int len = strlen (str2);
6378 return strncmp (str1, str2, len) == 0;
6382 mono_aot_readonly_field_override (MonoClassField *field)
6385 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6386 char *p = rdv->name;
6388 len = strlen (field->parent->name_space);
6389 if (strncmp (p, field->parent->name_space, len))
6394 len = strlen (field->parent->name);
6395 if (strncmp (p, field->parent->name, len))
6400 if (strcmp (p, field->name))
6402 switch (rdv->type) {
6404 return &rdv->value.i1;
6406 return &rdv->value.i2;
6408 return &rdv->value.i4;
6417 add_readonly_value (MonoAotOptions *opts, const char *val)
6422 /* the format of val is:
6423 * namespace.typename.fieldname=type/value
6424 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6426 fval = strrchr (val, '/');
6428 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6431 tval = strrchr (val, '=');
6433 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6436 rdv = g_new0 (ReadOnlyValue, 1);
6437 rdv->name = g_malloc0 (tval - val + 1);
6438 memcpy (rdv->name, val, tval - val);
6441 if (strncmp (tval, "i1", 2) == 0) {
6442 rdv->value.i1 = atoi (fval);
6443 rdv->type = MONO_TYPE_I1;
6444 } else if (strncmp (tval, "i2", 2) == 0) {
6445 rdv->value.i2 = atoi (fval);
6446 rdv->type = MONO_TYPE_I2;
6447 } else if (strncmp (tval, "i4", 2) == 0) {
6448 rdv->value.i4 = atoi (fval);
6449 rdv->type = MONO_TYPE_I4;
6451 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6454 rdv->next = readonly_values;
6455 readonly_values = rdv;
6459 clean_path (gchar * path)
6464 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6467 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6474 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6476 gchar **args, **ptr;
6478 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6479 for (ptr = args; ptr && *ptr; ptr ++) {
6480 const char *arg = *ptr;
6482 if (str_begins_with (arg, "outfile=")) {
6483 opts->outfile = g_strdup (arg + strlen ("outfile="));
6484 } else if (str_begins_with (arg, "llvm-outfile=")) {
6485 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6486 } else if (str_begins_with (arg, "temp-path=")) {
6487 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6488 } else if (str_begins_with (arg, "save-temps")) {
6489 opts->save_temps = TRUE;
6490 } else if (str_begins_with (arg, "keep-temps")) {
6491 opts->save_temps = TRUE;
6492 } else if (str_begins_with (arg, "write-symbols")) {
6493 opts->write_symbols = TRUE;
6494 } else if (str_begins_with (arg, "no-write-symbols")) {
6495 opts->write_symbols = FALSE;
6496 } else if (str_begins_with (arg, "metadata-only")) {
6497 opts->metadata_only = TRUE;
6498 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6499 opts->bind_to_runtime_version = TRUE;
6500 } else if (str_begins_with (arg, "full")) {
6501 opts->mode = MONO_AOT_MODE_FULL;
6502 } else if (str_begins_with (arg, "hybrid")) {
6503 opts->mode = MONO_AOT_MODE_HYBRID;
6504 } else if (str_begins_with (arg, "threads=")) {
6505 opts->nthreads = atoi (arg + strlen ("threads="));
6506 } else if (str_begins_with (arg, "static")) {
6507 opts->static_link = TRUE;
6508 opts->no_dlsym = TRUE;
6509 } else if (str_begins_with (arg, "asmonly")) {
6510 opts->asm_only = TRUE;
6511 } else if (str_begins_with (arg, "asmwriter")) {
6512 opts->asm_writer = TRUE;
6513 } else if (str_begins_with (arg, "nodebug")) {
6514 opts->nodebug = TRUE;
6515 } else if (str_begins_with (arg, "dwarfdebug")) {
6516 opts->dwarf_debug = TRUE;
6517 } else if (str_begins_with (arg, "nopagetrampolines")) {
6518 opts->use_trampolines_page = FALSE;
6519 } else if (str_begins_with (arg, "ntrampolines=")) {
6520 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6521 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6522 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6523 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6524 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6525 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6526 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6527 } else if (str_begins_with (arg, "autoreg")) {
6528 opts->autoreg = TRUE;
6529 } else if (str_begins_with (arg, "tool-prefix=")) {
6530 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6531 } else if (str_begins_with (arg, "ld-flags=")) {
6532 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6533 } else if (str_begins_with (arg, "soft-debug")) {
6534 opts->soft_debug = TRUE;
6535 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6536 opts->gen_seq_points_file = TRUE;
6537 } else if (str_begins_with (arg, "direct-pinvoke")) {
6538 opts->direct_pinvoke = TRUE;
6539 } else if (str_begins_with (arg, "direct-icalls")) {
6540 opts->direct_icalls = TRUE;
6541 } else if (str_begins_with (arg, "no-direct-calls")) {
6542 opts->no_direct_calls = TRUE;
6543 } else if (str_begins_with (arg, "print-skipped")) {
6544 opts->print_skipped_methods = TRUE;
6545 } else if (str_begins_with (arg, "stats")) {
6547 } else if (str_begins_with (arg, "no-instances")) {
6548 opts->no_instances = TRUE;
6549 } else if (str_begins_with (arg, "log-generics")) {
6550 opts->log_generics = TRUE;
6551 } else if (str_begins_with (arg, "log-instances=")) {
6552 opts->log_instances = TRUE;
6553 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6554 } else if (str_begins_with (arg, "log-instances")) {
6555 opts->log_instances = TRUE;
6556 } else if (str_begins_with (arg, "internal-logfile=")) {
6557 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6558 } else if (str_begins_with (arg, "mtriple=")) {
6559 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6560 } else if (str_begins_with (arg, "llvm-path=")) {
6561 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6562 } else if (!strcmp (arg, "llvm")) {
6564 } else if (str_begins_with (arg, "readonly-value=")) {
6565 add_readonly_value (opts, arg + strlen ("readonly-value="));
6566 } else if (str_begins_with (arg, "info")) {
6567 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6569 } else if (str_begins_with (arg, "gc-maps")) {
6570 mini_gc_enable_gc_maps_for_aot ();
6571 } else if (str_begins_with (arg, "dump")) {
6572 opts->dump_json = TRUE;
6573 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6574 printf ("Supported options for --aot:\n");
6575 printf (" outfile=\n");
6576 printf (" llvm-outfile=\n");
6577 printf (" llvm-path=\n");
6578 printf (" temp-path=\n");
6579 printf (" save-temps\n");
6580 printf (" keep-temps\n");
6581 printf (" write-symbols\n");
6582 printf (" metadata-only\n");
6583 printf (" bind-to-runtime-version\n");
6585 printf (" threads=\n");
6586 printf (" static\n");
6587 printf (" asmonly\n");
6588 printf (" asmwriter\n");
6589 printf (" nodebug\n");
6590 printf (" dwarfdebug\n");
6591 printf (" ntrampolines=\n");
6592 printf (" nrgctx-trampolines=\n");
6593 printf (" nimt-trampolines=\n");
6594 printf (" ngsharedvt-trampolines=\n");
6595 printf (" autoreg\n");
6596 printf (" tool-prefix=\n");
6597 printf (" readonly-value=\n");
6598 printf (" soft-debug\n");
6599 printf (" gen-seq-points-file\n");
6600 printf (" gc-maps\n");
6601 printf (" print-skipped\n");
6602 printf (" no-instances\n");
6603 printf (" stats\n");
6606 printf (" help/?\n");
6609 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6614 if (opts->use_trampolines_page) {
6615 opts->ntrampolines = 0;
6616 opts->nrgctx_trampolines = 0;
6617 opts->nimt_trampolines = 0;
6618 opts->ngsharedvt_arg_trampolines = 0;
6624 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6626 MonoMethod *method = (MonoMethod*)key;
6627 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6628 MonoAotCompile *acfg = user_data;
6629 MonoJumpInfoToken *new_ji;
6631 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6632 new_ji->image = ji->image;
6633 new_ji->token = ji->token;
6634 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6638 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6640 if (klass->type_token)
6642 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6645 return can_encode_class (acfg, klass->element_class);
6650 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6652 if (method->wrapper_type) {
6653 switch (method->wrapper_type) {
6654 case MONO_WRAPPER_NONE:
6655 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6656 case MONO_WRAPPER_XDOMAIN_INVOKE:
6657 case MONO_WRAPPER_STFLD:
6658 case MONO_WRAPPER_LDFLD:
6659 case MONO_WRAPPER_LDFLDA:
6660 case MONO_WRAPPER_LDFLD_REMOTE:
6661 case MONO_WRAPPER_STFLD_REMOTE:
6662 case MONO_WRAPPER_STELEMREF:
6663 case MONO_WRAPPER_ISINST:
6664 case MONO_WRAPPER_PROXY_ISINST:
6665 case MONO_WRAPPER_ALLOC:
6666 case MONO_WRAPPER_REMOTING_INVOKE:
6667 case MONO_WRAPPER_UNKNOWN:
6668 case MONO_WRAPPER_WRITE_BARRIER:
6669 case MONO_WRAPPER_DELEGATE_INVOKE:
6670 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6671 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6672 case MONO_WRAPPER_SYNCHRONIZED:
6674 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6675 case MONO_WRAPPER_CASTCLASS: {
6676 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6685 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6689 if (!method->token) {
6690 /* The method is part of a constructed type like Int[,].Set (). */
6691 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6692 if (method->klass->rank)
6702 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6704 switch (patch_info->type) {
6705 case MONO_PATCH_INFO_METHOD:
6706 case MONO_PATCH_INFO_METHODCONST:
6707 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6708 MonoMethod *method = patch_info->data.method;
6710 return can_encode_method (acfg, method);
6712 case MONO_PATCH_INFO_VTABLE:
6713 case MONO_PATCH_INFO_CLASS_INIT:
6714 case MONO_PATCH_INFO_CLASS:
6715 case MONO_PATCH_INFO_IID:
6716 case MONO_PATCH_INFO_ADJUSTED_IID:
6717 if (!can_encode_class (acfg, patch_info->data.klass)) {
6718 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6722 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6723 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6724 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6729 case MONO_PATCH_INFO_RGCTX_FETCH: {
6730 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6732 if (!can_encode_method (acfg, entry->method))
6734 if (!can_encode_patch (acfg, entry->data))
6748 * AOT compile a given method.
6749 * This function might be called by multiple threads, so it must be thread-safe.
6752 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6755 MonoJumpInfo *patch_info;
6758 MonoMethod *wrapped;
6761 if (acfg->aot_opts.metadata_only)
6764 mono_acfg_lock (acfg);
6765 index = get_method_index (acfg, method);
6766 mono_acfg_unlock (acfg);
6768 /* fixme: maybe we can also precompile wrapper methods */
6769 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6770 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6771 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6772 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6776 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6779 wrapped = mono_marshal_method_from_wrapper (method);
6780 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6781 // FIXME: The wrapper should be generic too, but it is not
6784 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6787 InterlockedIncrement (&acfg->stats.mcount);
6790 if (method->is_generic || method->klass->generic_container) {
6791 InterlockedIncrement (&acfg->stats.genericcount);
6796 //acfg->aot_opts.print_skipped_methods = TRUE;
6799 * Since these methods are the only ones which are compiled with
6800 * AOT support, and they are not used by runtime startup/shutdown code,
6801 * the runtime will not see AOT methods during AOT compilation,so it
6802 * does not need to support them by creating a fake GOT etc.
6804 flags = JIT_FLAG_AOT;
6805 if (mono_aot_mode_is_full (&acfg->aot_opts))
6806 flags |= JIT_FLAG_FULL_AOT;
6808 flags |= JIT_FLAG_LLVM;
6809 if (acfg->aot_opts.no_direct_calls)
6810 flags |= JIT_FLAG_NO_DIRECT_ICALLS;
6811 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6812 mono_loader_clear_error ();
6814 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6815 if (acfg->aot_opts.print_skipped_methods)
6816 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6817 InterlockedIncrement (&acfg->stats.genericcount);
6820 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6821 if (acfg->aot_opts.print_skipped_methods)
6822 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6823 /* Let the exception happen at runtime */
6827 if (cfg->disable_aot) {
6828 if (acfg->aot_opts.print_skipped_methods)
6829 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6830 InterlockedIncrement (&acfg->stats.ocount);
6831 mono_destroy_compile (cfg);
6834 cfg->method_index = index;
6836 /* Nullify patches which need no aot processing */
6837 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6838 switch (patch_info->type) {
6839 case MONO_PATCH_INFO_LABEL:
6840 case MONO_PATCH_INFO_BB:
6841 patch_info->type = MONO_PATCH_INFO_NONE;
6848 /* Collect method->token associations from the cfg */
6849 mono_acfg_lock (acfg);
6850 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6851 mono_acfg_unlock (acfg);
6852 g_hash_table_destroy (cfg->token_info_hash);
6853 cfg->token_info_hash = NULL;
6856 * Check for absolute addresses.
6859 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6860 switch (patch_info->type) {
6861 case MONO_PATCH_INFO_ABS:
6862 /* unable to handle this */
6871 if (acfg->aot_opts.print_skipped_methods)
6872 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6873 InterlockedIncrement (&acfg->stats.abscount);
6874 mono_destroy_compile (cfg);
6878 /* Lock for the rest of the code */
6879 mono_acfg_lock (acfg);
6882 * Check for methods/klasses we can't encode.
6885 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6886 if (!can_encode_patch (acfg, patch_info))
6891 if (acfg->aot_opts.print_skipped_methods)
6892 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6893 acfg->stats.ocount++;
6894 mono_destroy_compile (cfg);
6895 mono_acfg_unlock (acfg);
6899 if (method->is_inflated && acfg->aot_opts.log_instances) {
6900 if (acfg->instances_logfile)
6901 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6903 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6906 /* Adds generic instances referenced by this method */
6908 * The depth is used to avoid infinite loops when generic virtual recursion is
6911 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6912 if (!acfg->aot_opts.no_instances && depth < 32) {
6913 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6914 switch (patch_info->type) {
6915 case MONO_PATCH_INFO_METHOD: {
6916 MonoMethod *m = patch_info->data.method;
6917 if (m->is_inflated) {
6918 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6919 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6920 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
6921 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6922 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
6923 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6925 add_extra_method_with_depth (acfg, m, depth + 1);
6926 add_types_from_method_header (acfg, m);
6929 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6931 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
6932 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
6934 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
6935 add_extra_method_with_depth (acfg, m, depth + 1);
6939 case MONO_PATCH_INFO_VTABLE: {
6940 MonoClass *klass = patch_info->data.klass;
6942 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6943 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6946 case MONO_PATCH_INFO_SFLDA: {
6947 MonoClass *klass = patch_info->data.field->parent;
6949 /* The .cctor needs to run at runtime. */
6950 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6951 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6960 /* Determine whenever the method has GOT slots */
6961 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6962 switch (patch_info->type) {
6963 case MONO_PATCH_INFO_GOT_OFFSET:
6964 case MONO_PATCH_INFO_NONE:
6965 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6966 case MONO_PATCH_INFO_GC_NURSERY_START:
6968 case MONO_PATCH_INFO_IMAGE:
6969 /* The assembly is stored in GOT slot 0 */
6970 if (patch_info->data.image != acfg->image)
6971 cfg->has_got_slots = TRUE;
6974 if (!is_plt_patch (patch_info))
6975 cfg->has_got_slots = TRUE;
6980 if (!cfg->has_got_slots)
6981 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6984 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6986 /* Make a copy of the patch info which is in the mempool */
6988 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6990 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6991 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6994 patches = new_patch_info;
6996 patches_end->next = new_patch_info;
6997 patches_end = new_patch_info;
6999 cfg->patch_info = patches;
7001 /* Make a copy of the unwind info */
7003 GSList *l, *unwind_ops;
7007 for (l = cfg->unwind_ops; l; l = l->next) {
7008 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7009 memcpy (op, l->data, sizeof (MonoUnwindOp));
7010 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7012 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7014 /* Make a copy of the argument/local info */
7016 MonoInst **args, **locals;
7017 MonoMethodSignature *sig;
7018 MonoMethodHeader *header;
7021 sig = mono_method_signature (method);
7022 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7023 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7024 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7025 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7029 header = mono_method_get_header (method);
7030 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7031 for (i = 0; i < header->num_locals; ++i) {
7032 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7033 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7035 cfg->locals = locals;
7038 /* Free some fields used by cfg to conserve memory */
7039 mono_mempool_destroy (cfg->mempool);
7040 cfg->mempool = NULL;
7041 g_free (cfg->varinfo);
7042 cfg->varinfo = NULL;
7046 mono_regstate_free (cfg->rs);
7050 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7052 while (index >= acfg->cfgs_size) {
7053 MonoCompile **new_cfgs;
7056 new_size = acfg->cfgs_size * 2;
7057 new_cfgs = g_new0 (MonoCompile*, new_size);
7058 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7059 g_free (acfg->cfgs);
7060 acfg->cfgs = new_cfgs;
7061 acfg->cfgs_size = new_size;
7063 acfg->cfgs [index] = cfg;
7065 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7068 if (cfg->orig_method->wrapper_type)
7069 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7072 mono_acfg_unlock (acfg);
7074 InterlockedIncrement (&acfg->stats.ccount);
7078 compile_thread_main (gpointer *user_data)
7080 MonoDomain *domain = user_data [0];
7081 MonoAotCompile *acfg = user_data [1];
7082 GPtrArray *methods = user_data [2];
7085 mono_thread_attach (domain);
7087 for (i = 0; i < methods->len; ++i)
7088 compile_method (acfg, g_ptr_array_index (methods, i));
7092 load_profile_files (MonoAotCompile *acfg)
7096 int file_index, res, method_index, i;
7099 GList *unordered, *l;
7104 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7106 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7111 infile = fopen (tmp, "r");
7114 printf ("Using profile data file '%s'\n", tmp);
7119 res = fscanf (infile, "%32s\n", ver);
7120 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7121 printf ("Profile file has wrong version or invalid.\n");
7128 MonoMethodDesc *desc;
7131 if (fgets (name, 1023, infile) == NULL)
7134 /* Kill the newline */
7135 if (strlen (name) > 0)
7136 name [strlen (name) - 1] = '\0';
7138 desc = mono_method_desc_new (name, TRUE);
7140 method = mono_method_desc_search_in_image (desc, acfg->image);
7142 if (method && mono_method_get_token (method)) {
7143 token = mono_method_get_token (method);
7144 method_index = mono_metadata_token_index (token) - 1;
7147 for (i = 0; i < acfg->method_order->len; ++i) {
7148 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7154 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7156 //printf ("No method found matching '%s'.\n", name);
7162 /* Add missing methods */
7164 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7166 for (i = 0; i < acfg->method_order->len; ++i) {
7167 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7173 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7175 unordered = g_list_reverse (unordered);
7176 for (l = unordered; l; l = l->next)
7177 g_ptr_array_add (acfg->method_order, l->data);
7180 /* Used by the LLVM backend */
7182 mono_aot_get_got_offset (MonoJumpInfo *ji)
7184 return get_got_offset (llvm_acfg, TRUE, ji);
7188 mono_aot_get_method_name (MonoCompile *cfg)
7190 if (llvm_acfg->aot_opts.static_link)
7191 /* Include the assembly name too to avoid duplicate symbol errors */
7192 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7194 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7198 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7200 return is_direct_callable (llvm_acfg, NULL, patch_info);
7204 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7206 MonoPltEntry *plt_entry;
7208 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7209 plt_entry->llvm_used = FALSE;
7213 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7215 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7216 MonoPltEntry *plt_entry;
7217 const char *sym = NULL;
7220 ji->data.target = data;
7222 if (!can_encode_patch (llvm_acfg, ji))
7225 if (llvm_acfg->aot_opts.direct_icalls) {
7226 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7227 /* Call to a C function implementing a jit icall */
7228 sym = mono_lookup_jit_icall_symbol (data);
7229 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7230 MonoMethod *method = (gpointer)data;
7231 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7232 sym = mono_lookup_icall_symbol (method);
7235 return g_strdup (sym);
7238 plt_entry = get_plt_entry (llvm_acfg, ji);
7239 plt_entry->llvm_used = TRUE;
7241 #if defined(TARGET_MACH)
7242 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7244 return g_strdup_printf (plt_entry->llvm_symbol);
7249 mono_aot_get_method_index (MonoMethod *method)
7251 g_assert (llvm_acfg);
7252 return get_method_index (llvm_acfg, method);
7256 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7260 mono_acfg_lock (llvm_acfg);
7261 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7262 mono_acfg_unlock (llvm_acfg);
7268 execute_system (const char * command)
7273 // We need an extra set of quotes around the whole command to properly handle commands
7274 // with spaces since internally the command is called through "cmd /c.
7275 command = g_strdup_printf ("\"%s\"", command);
7277 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7278 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7279 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7280 status = _wsystem (wstr);
7284 #elif defined (HAVE_SYSTEM)
7285 status = system (command);
7287 g_assert_not_reached ();
7298 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7302 emit_llvm_file (MonoAotCompile *acfg)
7304 char *command, *opts, *tempbc, *output_fname;
7306 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7307 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7311 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7312 * a lot of time, and doesn't seem to save much space.
7313 * The following optimizations cannot be enabled:
7315 * - 'jump-threading' changes our blockaddress references to int constants.
7316 * - 'basiccg' fails because it contains:
7317 * if (CS && !isa<IntrinsicInst>(II)) {
7318 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7319 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7320 * The opt list below was produced by taking the output of:
7321 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7322 * then removing tailcallelim + the global opts.
7323 * strip-dead-prototypes deletes unused intrinsics definitions.
7325 opts = g_strdup ("-instcombine -simplifycfg");
7326 //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");
7327 /* The dse pass is disabled because of #13734 and #17616 */
7329 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7330 * // If we have no DataLayout information around, then the size of the store
7331 * // is inferrable from the pointee type. If they are the same type, then
7332 * // we know that the store is safe.
7333 * if (AA.getDataLayout() == 0 &&
7334 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7335 * return OverwriteComplete;
7336 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7338 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");
7340 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7341 aot_printf (acfg, "Executing opt: %s\n", command);
7342 if (execute_system (command) != 0)
7347 if (!acfg->llc_args)
7348 acfg->llc_args = g_string_new ("");
7350 /* Verbose asm slows down llc greatly */
7351 g_string_append (acfg->llc_args, " -asm-verbose=false");
7353 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7355 if (acfg->aot_opts.mtriple)
7356 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7358 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7360 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7361 /* ios requires PIC code now */
7362 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7364 if (llvm_acfg->aot_opts.static_link)
7365 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7367 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7369 unlink (acfg->tmpfname);
7371 if (acfg->llvm_owriter) {
7372 /* Emit an object file directly */
7373 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7374 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7376 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7378 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7379 g_free (output_fname);
7381 aot_printf (acfg, "Executing llc: %s\n", command);
7383 if (execute_system (command) != 0)
7390 emit_code (MonoAotCompile *acfg)
7392 int oindex, i, prev_index;
7395 #if defined(TARGET_POWERPC64)
7396 sprintf (symbol, ".Lgot_addr");
7397 emit_section_change (acfg, ".text", 0);
7398 emit_alignment (acfg, 8);
7399 emit_label (acfg, symbol);
7400 emit_pointer (acfg, acfg->got_symbol);
7404 * This global symbol is used to compute the address of each method using the
7405 * code_offsets array. It is also used to compute the memory ranges occupied by
7406 * AOT code, so it must be equal to the address of the first emitted method.
7408 emit_section_change (acfg, ".text", 0);
7409 emit_alignment_code (acfg, 8);
7411 for (i = 0; i < acfg->nmethods; ++i) {
7412 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7413 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7418 if (!acfg->methods_symbol) {
7419 sprintf (symbol, "methods");
7420 emit_label (acfg, symbol);
7421 acfg->methods_symbol = g_strdup (symbol);
7423 emit_label (acfg, "jit_code_start");
7426 * Emit some padding so the local symbol for the first method doesn't have the
7427 * same address as 'methods'.
7429 #if defined(__default_codegen__)
7430 emit_padding (acfg, 16);
7431 #elif defined(__native_client_codegen__)
7433 const int kPaddingSize = 16;
7434 guint8 pad_buffer[kPaddingSize];
7435 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7436 emit_bytes (acfg, pad_buffer, kPaddingSize);
7440 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7444 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7446 cfg = acfg->cfgs [i];
7451 method = cfg->orig_method;
7453 /* Emit unbox trampoline */
7454 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7455 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7457 emit_section_change (acfg, ".text", 0);
7458 #ifdef __native_client_codegen__
7459 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7462 if (acfg->thumb_mixed && cfg->compile_llvm) {
7463 emit_set_thumb_mode (acfg);
7464 fprintf (acfg->fp, "\n.thumb_func\n");
7467 emit_label (acfg, symbol);
7469 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7471 if (acfg->thumb_mixed && cfg->compile_llvm)
7472 emit_set_arm_mode (acfg);
7475 if (cfg->compile_llvm)
7476 acfg->stats.llvm_count ++;
7478 emit_method_code (acfg, cfg);
7481 emit_section_change (acfg, ".text", 0);
7482 emit_alignment_code (acfg, 8);
7483 emit_label (acfg, "jit_code_end");
7485 /* To distinguish it from the next symbol */
7486 emit_padding (acfg, 4);
7489 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7490 * from optimizing them away, since it doesn't see that code_offsets references them.
7491 * JITted methods don't need this since they are referenced using assembler local
7493 * FIXME: This is why write-symbols doesn't work on OSX ?
7495 if (acfg->llvm && acfg->need_no_dead_strip) {
7496 fprintf (acfg->fp, "\n");
7497 for (i = 0; i < acfg->nmethods; ++i) {
7498 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7499 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7504 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7505 * This is PIE code, and the linker can update it if needed.
7507 sprintf (symbol, "method_addresses");
7508 emit_section_change (acfg, ".text", 1);
7509 emit_alignment_code (acfg, 8);
7510 emit_label (acfg, symbol);
7511 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7512 emit_unset_mode (acfg);
7513 if (acfg->need_no_dead_strip)
7514 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7516 for (i = 0; i < acfg->nmethods; ++i) {
7517 #ifdef MONO_ARCH_AOT_SUPPORTED
7521 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7523 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7527 sprintf (symbol, "method_addresses_end");
7528 emit_label (acfg, symbol);
7531 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7532 sprintf (symbol, "unbox_trampolines");
7533 emit_section_change (acfg, RODATA_SECT, 0);
7534 emit_alignment (acfg, 8);
7535 emit_label (acfg, symbol);
7538 for (i = 0; i < acfg->nmethods; ++i) {
7543 cfg = acfg->cfgs [i];
7547 method = cfg->orig_method;
7549 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7550 index = get_method_index (acfg, method);
7552 emit_int32 (acfg, index);
7553 /* Make sure the table is sorted by index */
7554 g_assert (index > prev_index);
7558 sprintf (symbol, "unbox_trampolines_end");
7559 emit_label (acfg, symbol);
7560 emit_int32 (acfg, 0);
7562 /* Emit a separate table with the trampoline addresses/offsets */
7563 sprintf (symbol, "unbox_trampoline_addresses");
7564 emit_section_change (acfg, ".text", 0);
7565 emit_alignment_code (acfg, 8);
7566 emit_label (acfg, symbol);
7568 for (i = 0; i < acfg->nmethods; ++i) {
7573 cfg = acfg->cfgs [i];
7577 method = cfg->orig_method;
7579 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7580 #ifdef MONO_ARCH_AOT_SUPPORTED
7583 index = get_method_index (acfg, method);
7584 sprintf (symbol, "ut_%d", index);
7586 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7590 emit_int32 (acfg, 0);
7594 emit_info (MonoAotCompile *acfg)
7600 offsets = g_new0 (gint32, acfg->nmethods);
7602 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7603 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7605 if (acfg->cfgs [i]) {
7606 emit_method_info (acfg, acfg->cfgs [i]);
7607 offsets [i] = acfg->cfgs [i]->method_info_offset;
7613 sprintf (symbol, "method_info_offsets");
7614 emit_section_change (acfg, RODATA_SECT, 1);
7615 emit_alignment (acfg, 8);
7616 emit_label (acfg, symbol);
7618 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7623 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7625 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7626 #define mix(a,b,c) { \
7627 a -= c; a ^= rot(c, 4); c += b; \
7628 b -= a; b ^= rot(a, 6); a += c; \
7629 c -= b; c ^= rot(b, 8); b += a; \
7630 a -= c; a ^= rot(c,16); c += b; \
7631 b -= a; b ^= rot(a,19); a += c; \
7632 c -= b; c ^= rot(b, 4); b += a; \
7634 #define final(a,b,c) { \
7635 c ^= b; c -= rot(b,14); \
7636 a ^= c; a -= rot(c,11); \
7637 b ^= a; b -= rot(a,25); \
7638 c ^= b; c -= rot(b,16); \
7639 a ^= c; a -= rot(c,4); \
7640 b ^= a; b -= rot(a,14); \
7641 c ^= b; c -= rot(b,24); \
7645 mono_aot_type_hash (MonoType *t1)
7647 guint hash = t1->type;
7649 hash |= t1->byref << 6; /* do not collide with t1->type values */
7651 case MONO_TYPE_VALUETYPE:
7652 case MONO_TYPE_CLASS:
7653 case MONO_TYPE_SZARRAY:
7654 /* check if the distribution is good enough */
7655 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7657 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7658 case MONO_TYPE_ARRAY:
7659 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7660 case MONO_TYPE_GENERICINST:
7661 return ((hash << 5) - hash) ^ 0;
7668 * mono_aot_method_hash:
7670 * Return a hash code for methods which only depends on metadata.
7673 mono_aot_method_hash (MonoMethod *method)
7675 MonoMethodSignature *sig;
7679 guint32 *hashes_start, *hashes;
7681 MonoGenericInst *class_ginst = NULL;
7682 MonoGenericInst *ginst = NULL;
7684 /* Similar to the hash in mono_method_get_imt_slot () */
7686 sig = mono_method_signature (method);
7688 if (method->klass->generic_class)
7689 class_ginst = method->klass->generic_class->context.class_inst;
7690 if (method->is_inflated)
7691 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7693 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7694 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7695 hashes = hashes_start;
7697 /* Some wrappers are assigned to random classes */
7698 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7699 klass = method->klass;
7701 klass = mono_defaults.object_class;
7703 if (!method->wrapper_type) {
7706 if (klass->generic_class)
7707 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7709 full_name = mono_type_full_name (&klass->byval_arg);
7711 hashes [0] = mono_metadata_str_hash (full_name);
7715 hashes [0] = mono_metadata_str_hash (klass->name);
7716 hashes [1] = mono_metadata_str_hash (klass->name_space);
7718 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7719 /* The method name includes a stringified pointer */
7722 hashes [2] = mono_metadata_str_hash (method->name);
7723 hashes [3] = method->wrapper_type;
7724 hashes [4] = mono_aot_type_hash (sig->ret);
7726 for (i = 0; i < sig->param_count; i++) {
7727 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7730 for (i = 0; i < class_ginst->type_argc; ++i)
7731 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7734 for (i = 0; i < ginst->type_argc; ++i)
7735 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7737 g_assert (hindex == hashes_count);
7739 /* Setup internal state */
7740 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7742 /* Handle most of the hashes */
7743 while (hashes_count > 3) {
7752 /* Handle the last 3 hashes (all the case statements fall through) */
7753 switch (hashes_count) {
7754 case 3 : c += hashes [2];
7755 case 2 : b += hashes [1];
7756 case 1 : a += hashes [0];
7758 case 0: /* nothing left to add */
7762 free (hashes_start);
7771 * mono_aot_get_array_helper_from_wrapper;
7773 * Get the helper method in Array called by an array wrapper method.
7776 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7780 MonoGenericContext ctx;
7781 MonoType *args [16];
7782 char *mname, *iname, *s, *s2, *helper_name = NULL;
7784 prefix = "System.Collections.Generic";
7785 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7786 s2 = strstr (s, "`1.");
7792 //printf ("X: %s %s\n", iname, mname);
7794 if (!strcmp (iname, "IList"))
7795 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7797 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7798 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7800 g_free (helper_name);
7803 if (m->is_generic) {
7805 memset (&ctx, 0, sizeof (ctx));
7806 args [0] = &method->klass->element_class->byval_arg;
7807 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7808 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7809 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7815 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7817 typedef struct HashEntry {
7818 guint32 key, value, index;
7819 struct HashEntry *next;
7823 * emit_extra_methods:
7825 * Emit methods which are not in the METHOD table, like wrappers.
7828 emit_extra_methods (MonoAotCompile *acfg)
7830 int i, table_size, buf_size;
7833 guint32 *info_offsets;
7836 HashEntry *entry, *new_entry;
7837 int nmethods, max_chain_length;
7840 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7842 /* Emit method info */
7844 for (i = 0; i < acfg->extra_methods->len; ++i) {
7845 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7846 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7852 p = buf = g_malloc (buf_size);
7856 method = cfg->method_to_register;
7858 encode_method_ref (acfg, method, p, &p);
7860 g_assert ((p - buf) < buf_size);
7862 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7867 * Construct a chained hash table for mapping indexes in extra_method_info to
7870 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7871 table = g_ptr_array_sized_new (table_size);
7872 for (i = 0; i < table_size; ++i)
7873 g_ptr_array_add (table, NULL);
7874 chain_lengths = g_new0 (int, table_size);
7875 max_chain_length = 0;
7876 for (i = 0; i < acfg->extra_methods->len; ++i) {
7877 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7878 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7884 key = info_offsets [i];
7885 value = get_method_index (acfg, method);
7887 hash = mono_aot_method_hash (method) % table_size;
7888 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
7890 chain_lengths [hash] ++;
7891 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7893 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7894 new_entry->key = key;
7895 new_entry->value = value;
7897 entry = g_ptr_array_index (table, hash);
7898 if (entry == NULL) {
7899 new_entry->index = hash;
7900 g_ptr_array_index (table, hash) = new_entry;
7903 entry = entry->next;
7905 entry->next = new_entry;
7906 new_entry->index = table->len;
7907 g_ptr_array_add (table, new_entry);
7911 //printf ("MAX: %d\n", max_chain_length);
7913 /* Emit the table */
7914 sprintf (symbol, "extra_method_table");
7915 emit_section_change (acfg, RODATA_SECT, 0);
7916 emit_alignment (acfg, 8);
7917 emit_label (acfg, symbol);
7919 emit_int32 (acfg, table_size);
7920 for (i = 0; i < table->len; ++i) {
7921 HashEntry *entry = g_ptr_array_index (table, i);
7923 if (entry == NULL) {
7924 emit_int32 (acfg, 0);
7925 emit_int32 (acfg, 0);
7926 emit_int32 (acfg, 0);
7928 //g_assert (entry->key > 0);
7929 emit_int32 (acfg, entry->key);
7930 emit_int32 (acfg, entry->value);
7932 emit_int32 (acfg, entry->next->index);
7934 emit_int32 (acfg, 0);
7939 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7940 * This is used by mono_aot_find_jit_info ().
7942 sprintf (symbol, "extra_method_info_offsets");
7943 emit_section_change (acfg, RODATA_SECT, 0);
7944 emit_alignment (acfg, 8);
7945 emit_label (acfg, symbol);
7947 emit_int32 (acfg, acfg->extra_methods->len);
7948 for (i = 0; i < acfg->extra_methods->len; ++i) {
7949 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7951 emit_int32 (acfg, get_method_index (acfg, method));
7952 emit_int32 (acfg, info_offsets [i]);
7957 emit_exception_info (MonoAotCompile *acfg)
7962 SeqPointData sp_data;
7963 gboolean seq_points_to_file = FALSE;
7965 offsets = g_new0 (gint32, acfg->nmethods);
7966 for (i = 0; i < acfg->nmethods; ++i) {
7967 if (acfg->cfgs [i]) {
7968 MonoCompile *cfg = acfg->cfgs [i];
7970 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
7971 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
7972 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
7973 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
7974 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
7976 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
7977 offsets [i] = cfg->ex_info_offset;
7979 if (method_seq_points_to_file) {
7980 if (!seq_points_to_file) {
7981 mono_seq_point_data_init (&sp_data, acfg->nmethods);
7982 seq_points_to_file = TRUE;
7984 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
7991 if (seq_points_to_file) {
7992 char *seq_points_aot_file;
7993 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
7994 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
7995 mono_seq_point_data_free (&sp_data);
7996 g_free (seq_points_aot_file);
7999 sprintf (symbol, "ex_info_offsets");
8000 emit_section_change (acfg, RODATA_SECT, 1);
8001 emit_alignment (acfg, 8);
8002 emit_label (acfg, symbol);
8004 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
8009 emit_unwind_info (MonoAotCompile *acfg)
8015 * The unwind info contains a lot of duplicates so we emit each unique
8016 * entry once, and only store the offset from the start of the table in the
8020 sprintf (symbol, "unwind_info");
8021 emit_section_change (acfg, RODATA_SECT, 1);
8022 emit_alignment (acfg, 8);
8023 emit_label (acfg, symbol);
8025 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8026 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8027 guint8 *unwind_info;
8028 guint32 unwind_info_len;
8032 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8035 encode_value (unwind_info_len, p, &p);
8036 emit_bytes (acfg, buf, p - buf);
8037 emit_bytes (acfg, unwind_info, unwind_info_len);
8039 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8044 emit_class_info (MonoAotCompile *acfg)
8050 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8051 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8052 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8054 sprintf (symbol, "class_info_offsets");
8055 emit_section_change (acfg, RODATA_SECT, 1);
8056 emit_alignment (acfg, 8);
8057 emit_label (acfg, symbol);
8059 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8063 typedef struct ClassNameTableEntry {
8064 guint32 token, index;
8065 struct ClassNameTableEntry *next;
8066 } ClassNameTableEntry;
8069 emit_class_name_table (MonoAotCompile *acfg)
8072 guint32 token, hash;
8077 ClassNameTableEntry *entry, *new_entry;
8080 * Construct a chained hash table for mapping class names to typedef tokens.
8082 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8083 table = g_ptr_array_sized_new (table_size);
8084 for (i = 0; i < table_size; ++i)
8085 g_ptr_array_add (table, NULL);
8086 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8088 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8089 klass = mono_class_get_checked (acfg->image, token, &error);
8091 mono_error_cleanup (&error);
8094 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8095 hash = mono_metadata_str_hash (full_name) % table_size;
8098 /* FIXME: Allocate from the mempool */
8099 new_entry = g_new0 (ClassNameTableEntry, 1);
8100 new_entry->token = token;
8102 entry = g_ptr_array_index (table, hash);
8103 if (entry == NULL) {
8104 new_entry->index = hash;
8105 g_ptr_array_index (table, hash) = new_entry;
8108 entry = entry->next;
8110 entry->next = new_entry;
8111 new_entry->index = table->len;
8112 g_ptr_array_add (table, new_entry);
8116 /* Emit the table */
8117 sprintf (symbol, "class_name_table");
8118 emit_section_change (acfg, RODATA_SECT, 0);
8119 emit_alignment (acfg, 8);
8120 emit_label (acfg, symbol);
8122 /* FIXME: Optimize memory usage */
8123 g_assert (table_size < 65000);
8124 emit_int16 (acfg, table_size);
8125 g_assert (table->len < 65000);
8126 for (i = 0; i < table->len; ++i) {
8127 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8129 if (entry == NULL) {
8130 emit_int16 (acfg, 0);
8131 emit_int16 (acfg, 0);
8133 emit_int16 (acfg, mono_metadata_token_index (entry->token));
8135 emit_int16 (acfg, entry->next->index);
8137 emit_int16 (acfg, 0);
8143 emit_image_table (MonoAotCompile *acfg)
8149 * The image table is small but referenced in a lot of places.
8150 * So we emit it at once, and reference its elements by an index.
8153 sprintf (symbol, "image_table");
8154 emit_section_change (acfg, RODATA_SECT, 1);
8155 emit_alignment (acfg, 8);
8156 emit_label (acfg, symbol);
8158 emit_int32 (acfg, acfg->image_table->len);
8159 for (i = 0; i < acfg->image_table->len; i++) {
8160 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8161 MonoAssemblyName *aname = &image->assembly->aname;
8163 /* FIXME: Support multi-module assemblies */
8164 g_assert (image->assembly->image == image);
8166 emit_string (acfg, image->assembly_name);
8167 emit_string (acfg, image->guid);
8168 emit_string (acfg, aname->culture ? aname->culture : "");
8169 emit_string (acfg, (const char*)aname->public_key_token);
8171 emit_alignment (acfg, 8);
8172 emit_int32 (acfg, aname->flags);
8173 emit_int32 (acfg, aname->major);
8174 emit_int32 (acfg, aname->minor);
8175 emit_int32 (acfg, aname->build);
8176 emit_int32 (acfg, aname->revision);
8181 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8184 int i, first_plt_got_patch = 0, buf_size;
8186 guint32 *got_info_offsets;
8187 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8189 /* Add the patches needed by the PLT to the GOT */
8191 acfg->plt_got_offset_base = acfg->got_offset;
8192 first_plt_got_patch = info->got_patches->len;
8193 for (i = 1; i < acfg->plt_offset; ++i) {
8194 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8196 g_ptr_array_add (info->got_patches, plt_entry->ji);
8198 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8201 acfg->got_offset += acfg->plt_offset;
8206 * - optimize offsets table.
8207 * - reduce number of exported symbols.
8208 * - emit info for a klass only once.
8209 * - determine when a method uses a GOT slot which is guaranteed to be already
8211 * - clean up and document the code.
8212 * - use String.Empty in class libs.
8215 /* Encode info required to decode shared GOT entries */
8216 buf_size = info->got_patches->len * 128;
8217 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8218 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8220 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8222 if (acfg->plt_offset)
8223 acfg->plt_got_info_offsets [0] = 0;
8225 for (i = 0; i < info->got_patches->len; ++i) {
8226 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8231 encode_value (ji->type, p, &p);
8233 encode_patch (acfg, ji, p, &p);
8234 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8235 g_assert (p - buf <= buf_size);
8236 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8238 if (!llvm && i >= first_plt_got_patch)
8239 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8240 acfg->stats.got_info_size += p - buf;
8243 /* Emit got_info_offsets table */
8245 sprintf (symbol, "llvm_got_info_offsets");
8247 sprintf (symbol, "got_info_offsets");
8248 emit_section_change (acfg, RODATA_SECT, 1);
8249 emit_alignment (acfg, 8);
8250 emit_label (acfg, symbol);
8252 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8253 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8257 emit_got (MonoAotCompile *acfg)
8261 /* Don't make GOT global so accesses to it don't need relocations */
8262 sprintf (symbol, "%s", acfg->got_symbol);
8263 emit_section_change (acfg, ".bss", 0);
8264 emit_alignment (acfg, 8);
8265 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8266 emit_label (acfg, symbol);
8267 if (acfg->got_offset > 0)
8268 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8270 sprintf (symbol, "got_end");
8271 emit_label (acfg, symbol);
8274 typedef struct GlobalsTableEntry {
8275 guint32 value, index;
8276 struct GlobalsTableEntry *next;
8277 } GlobalsTableEntry;
8280 emit_globals (MonoAotCompile *acfg)
8286 GlobalsTableEntry *entry, *new_entry;
8288 if (!acfg->aot_opts.static_link)
8292 * When static linking, we emit a table containing our globals.
8296 * Construct a chained hash table for mapping global names to their index in
8297 * the globals table.
8299 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8300 table = g_ptr_array_sized_new (table_size);
8301 for (i = 0; i < table_size; ++i)
8302 g_ptr_array_add (table, NULL);
8303 for (i = 0; i < acfg->globals->len; ++i) {
8304 char *name = g_ptr_array_index (acfg->globals, i);
8306 hash = mono_metadata_str_hash (name) % table_size;
8308 /* FIXME: Allocate from the mempool */
8309 new_entry = g_new0 (GlobalsTableEntry, 1);
8310 new_entry->value = i;
8312 entry = g_ptr_array_index (table, hash);
8313 if (entry == NULL) {
8314 new_entry->index = hash;
8315 g_ptr_array_index (table, hash) = new_entry;
8318 entry = entry->next;
8320 entry->next = new_entry;
8321 new_entry->index = table->len;
8322 g_ptr_array_add (table, new_entry);
8326 /* Emit the table */
8327 sprintf (symbol, ".Lglobals_hash");
8328 emit_section_change (acfg, RODATA_SECT, 0);
8329 emit_alignment (acfg, 8);
8330 emit_label (acfg, symbol);
8332 /* FIXME: Optimize memory usage */
8333 g_assert (table_size < 65000);
8334 emit_int16 (acfg, table_size);
8335 for (i = 0; i < table->len; ++i) {
8336 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8338 if (entry == NULL) {
8339 emit_int16 (acfg, 0);
8340 emit_int16 (acfg, 0);
8342 emit_int16 (acfg, entry->value + 1);
8344 emit_int16 (acfg, entry->next->index);
8346 emit_int16 (acfg, 0);
8350 /* Emit the names */
8351 for (i = 0; i < acfg->globals->len; ++i) {
8352 char *name = g_ptr_array_index (acfg->globals, i);
8354 sprintf (symbol, "name_%d", i);
8355 emit_section_change (acfg, RODATA_SECT, 1);
8357 emit_alignment (acfg, 4);
8359 emit_label (acfg, symbol);
8360 emit_string (acfg, name);
8363 /* Emit the globals table */
8364 sprintf (symbol, "globals");
8365 emit_section_change (acfg, ".data", 0);
8366 /* This is not a global, since it is accessed by the init function */
8367 emit_alignment (acfg, 8);
8368 emit_label (acfg, symbol);
8370 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8371 emit_pointer (acfg, symbol);
8373 for (i = 0; i < acfg->globals->len; ++i) {
8374 char *name = g_ptr_array_index (acfg->globals, i);
8376 sprintf (symbol, "name_%d", i);
8377 emit_pointer (acfg, symbol);
8379 g_assert (strlen (name) < sizeof (symbol));
8380 sprintf (symbol, "%s", name);
8381 emit_pointer (acfg, symbol);
8383 /* Null terminate the table */
8384 emit_int32 (acfg, 0);
8385 emit_int32 (acfg, 0);
8389 emit_autoreg (MonoAotCompile *acfg)
8394 * Emit a function into the .ctor section which will be called by the ELF
8395 * loader to register this module with the runtime.
8397 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8400 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8402 arch_emit_autoreg (acfg, symbol);
8408 emit_mem_end (MonoAotCompile *acfg)
8412 sprintf (symbol, "mem_end");
8413 emit_section_change (acfg, ".text", 1);
8414 emit_alignment_code (acfg, 8);
8415 emit_label (acfg, symbol);
8419 * Emit a structure containing all the information not stored elsewhere.
8422 emit_file_info (MonoAotCompile *acfg)
8427 const char *gc_name;
8430 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8432 if (acfg->aot_opts.bind_to_runtime_version) {
8433 build_info = mono_get_runtime_build_info ();
8434 emit_string_symbol (acfg, "runtime_version", build_info);
8435 g_free (build_info);
8437 emit_string_symbol (acfg, "runtime_version", "");
8440 /* Emit a string holding the assembly name */
8441 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8444 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8447 gc_name = mono_gc_get_gc_name ();
8448 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8450 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8451 emit_section_change (acfg, ".data", 0);
8452 emit_alignment (acfg, 8);
8453 emit_label (acfg, symbol);
8454 if (!acfg->aot_opts.static_link)
8455 emit_global (acfg, symbol, FALSE);
8457 /* The data emitted here must match MonoAotFileInfo. */
8459 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8460 emit_int32 (acfg, 0);
8463 * We emit pointers to our data structures instead of emitting global symbols which
8464 * point to them, to reduce the number of globals, and because using globals leads to
8465 * various problems (i.e. arm/thumb).
8467 emit_pointer (acfg, acfg->got_symbol);
8469 emit_pointer (acfg, acfg->llvm_got_symbol);
8471 emit_pointer (acfg, NULL);
8472 emit_pointer (acfg, acfg->methods_symbol);
8473 emit_pointer (acfg, "jit_code_start");
8474 emit_pointer (acfg, "jit_code_end");
8477 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8479 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8481 emit_pointer (acfg, NULL);
8483 emit_pointer (acfg, "blob");
8484 emit_pointer (acfg, "class_name_table");
8485 emit_pointer (acfg, "class_info_offsets");
8486 emit_pointer (acfg, "method_info_offsets");
8487 emit_pointer (acfg, "ex_info_offsets");
8488 emit_pointer (acfg, "method_addresses");
8489 emit_pointer (acfg, "extra_method_info_offsets");
8490 emit_pointer (acfg, "extra_method_table");
8491 emit_pointer (acfg, "got_info_offsets");
8493 emit_pointer (acfg, "llvm_got_info_offsets");
8495 emit_pointer (acfg, NULL);
8496 emit_pointer (acfg, "unwind_info");
8497 emit_pointer (acfg, "mem_end");
8498 emit_pointer (acfg, "image_table");
8499 emit_pointer (acfg, "plt");
8500 emit_pointer (acfg, "plt_end");
8501 emit_pointer (acfg, "assembly_guid");
8502 emit_pointer (acfg, "runtime_version");
8503 if (acfg->num_trampoline_got_entries) {
8504 emit_pointer (acfg, "specific_trampolines");
8505 emit_pointer (acfg, "static_rgctx_trampolines");
8506 emit_pointer (acfg, "imt_thunks");
8507 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8509 emit_pointer (acfg, NULL);
8510 emit_pointer (acfg, NULL);
8511 emit_pointer (acfg, NULL);
8512 emit_pointer (acfg, NULL);
8514 if (acfg->aot_opts.static_link) {
8515 emit_pointer (acfg, "globals");
8517 emit_pointer (acfg, NULL);
8519 emit_pointer (acfg, "assembly_name");
8520 emit_pointer (acfg, "unbox_trampolines");
8521 emit_pointer (acfg, "unbox_trampolines_end");
8522 emit_pointer (acfg, "unbox_trampoline_addresses");
8524 emit_int32 (acfg, acfg->plt_got_offset_base);
8525 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8526 emit_int32 (acfg, acfg->plt_offset);
8527 emit_int32 (acfg, acfg->nmethods);
8528 emit_int32 (acfg, acfg->flags);
8529 emit_int32 (acfg, acfg->opts);
8530 emit_int32 (acfg, acfg->simd_opts);
8531 emit_int32 (acfg, gc_name_offset);
8533 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8534 emit_int32 (acfg, acfg->num_trampolines [i]);
8535 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8536 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8537 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8538 emit_int32 (acfg, acfg->trampoline_size [i]);
8539 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8541 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8546 memset (&t, 0, sizeof (MonoType));
8547 t.type = MONO_TYPE_R8;
8548 mono_type_size (&t, &align);
8549 emit_int32 (acfg, align);
8551 memset (&t, 0, sizeof (MonoType));
8552 t.type = MONO_TYPE_I8;
8553 mono_type_size (&t, &align);
8555 emit_int32 (acfg, align);
8558 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8559 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8561 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8562 emit_int32 (acfg, acfg->tramp_page_size);
8563 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8564 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8566 if (acfg->aot_opts.static_link) {
8570 * Emit a global symbol which can be passed by an embedding app to
8571 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8574 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8576 /* Get rid of characters which cannot occur in symbols */
8578 for (p = symbol; *p; ++p) {
8579 if (!(isalnum (*p) || *p == '_'))
8582 acfg->static_linking_symbol = g_strdup (symbol);
8583 emit_global_inner (acfg, symbol, FALSE);
8584 emit_alignment (acfg, sizeof (gpointer));
8585 emit_label (acfg, symbol);
8586 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8591 emit_blob (MonoAotCompile *acfg)
8595 sprintf (symbol, "blob");
8596 emit_section_change (acfg, RODATA_SECT, 1);
8597 emit_alignment (acfg, 8);
8598 emit_label (acfg, symbol);
8600 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8604 emit_objc_selectors (MonoAotCompile *acfg)
8609 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8614 * cat > foo.m << EOF
8617 * return @selector(print:);
8622 mono_img_writer_emit_unset_mode (acfg->w);
8623 g_assert (acfg->fp);
8624 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8625 fprintf (acfg->fp, ".align 3\n");
8626 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8627 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8628 emit_label (acfg, symbol);
8629 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8630 emit_pointer (acfg, symbol);
8633 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8634 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8635 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8636 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8639 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8640 fprintf (acfg->fp, ".align 3\n");
8641 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8642 fprintf (acfg->fp, ".long 0\n");
8643 fprintf (acfg->fp, ".long 16\n");
8647 emit_dwarf_info (MonoAotCompile *acfg)
8649 #ifdef EMIT_DWARF_INFO
8653 /* DIEs for methods */
8654 for (i = 0; i < acfg->nmethods; ++i) {
8655 MonoCompile *cfg = acfg->cfgs [i];
8660 // FIXME: LLVM doesn't define .Lme_...
8661 if (cfg->compile_llvm)
8664 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8666 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 ()));
8672 collect_methods (MonoAotCompile *acfg)
8675 MonoImage *image = acfg->image;
8677 /* Collect methods */
8678 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8681 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8683 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8686 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8687 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8688 mono_error_cleanup (&error);
8692 /* Load all methods eagerly to skip the slower lazy loading code */
8693 mono_class_setup_methods (method->klass);
8695 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8696 /* Compile the wrapper instead */
8697 /* We do this here instead of add_wrappers () because it is easy to do it here */
8698 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8702 /* FIXME: Some mscorlib methods don't have debug info */
8704 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8705 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8706 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8707 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8708 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8709 if (!mono_debug_lookup_method (method)) {
8710 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8717 if (method->is_generic || method->klass->generic_container)
8718 /* Compile the ref shared version instead */
8719 method = mini_get_shared_method (method);
8721 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8722 add_method_with_index (acfg, method, i, FALSE);
8723 acfg->method_index ++;
8726 /* gsharedvt methods */
8727 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8730 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8732 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8735 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8736 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8738 if (method->is_generic || method->klass->generic_container) {
8739 MonoMethod *gshared;
8741 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8742 add_extra_method (acfg, gshared);
8746 add_generic_instances (acfg);
8748 if (mono_aot_mode_is_full (&acfg->aot_opts))
8749 add_wrappers (acfg);
8754 compile_methods (MonoAotCompile *acfg)
8758 if (acfg->aot_opts.nthreads > 0) {
8763 gpointer *user_data;
8764 MonoMethod **methods;
8766 methods_len = acfg->methods->len;
8768 len = acfg->methods->len / acfg->aot_opts.nthreads;
8771 * Partition the list of methods into fragments, and hand it to threads to
8774 threads = g_ptr_array_new ();
8775 /* Make a copy since acfg->methods is modified by compile_method () */
8776 methods = g_new0 (MonoMethod*, methods_len);
8777 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8778 for (i = 0; i < methods_len; ++i)
8779 methods [i] = g_ptr_array_index (acfg->methods, i);
8781 while (i < methods_len) {
8782 frag = g_ptr_array_new ();
8783 for (j = 0; j < len; ++j) {
8784 if (i < methods_len) {
8785 g_ptr_array_add (frag, methods [i]);
8790 user_data = g_new0 (gpointer, 3);
8791 user_data [0] = mono_domain_get ();
8792 user_data [1] = acfg;
8793 user_data [2] = frag;
8795 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8796 g_ptr_array_add (threads, handle);
8800 for (i = 0; i < threads->len; ++i) {
8801 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8807 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8808 for (i = methods_len; i < acfg->methods->len; ++i) {
8809 /* This can new methods to acfg->methods */
8810 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8815 compile_asm (MonoAotCompile *acfg)
8817 char *command, *objfile;
8818 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8819 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8820 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
8822 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8823 #define AS_OPTIONS "--64"
8824 #elif defined(TARGET_POWERPC64)
8825 #define AS_OPTIONS "-a64 -mppc64"
8826 #define LD_OPTIONS "-m elf64ppc"
8827 #elif defined(sparc) && SIZEOF_VOID_P == 8
8828 #define AS_OPTIONS "-xarch=v9"
8829 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8830 #define AS_OPTIONS "-arch i386"
8832 #define AS_OPTIONS ""
8835 #ifdef __native_client_codegen__
8836 #if defined(TARGET_AMD64)
8837 #define AS_NAME "nacl64-as"
8839 #define AS_NAME "nacl-as"
8841 #elif defined(TARGET_OSX)
8842 #define AS_NAME "clang"
8844 #define AS_NAME "as"
8848 #define LD_OPTIONS ""
8852 #define LD_NAME "ld -shared -G"
8853 #elif defined(__ppc__) && defined(TARGET_MACH)
8854 #define LD_NAME "gcc -dynamiclib"
8855 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8856 #define LD_NAME "clang --shared"
8857 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
8858 #define LD_NAME "gcc -shared --dll"
8859 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8860 #define LD_NAME "clang -m32 -dynamiclib"
8861 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
8862 #define LD_NAME "gcc --shared"
8865 if (acfg->aot_opts.asm_only) {
8866 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8867 if (acfg->aot_opts.static_link)
8868 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8870 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8874 if (acfg->aot_opts.static_link) {
8875 if (acfg->aot_opts.outfile)
8876 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8878 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8880 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8884 g_string_append (acfg->as_args, "-c -x assembler");
8887 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);
8888 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8889 if (execute_system (command) != 0) {
8895 if (acfg->llvm && !acfg->llvm_owriter) {
8896 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);
8897 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8898 if (execute_system (command) != 0) {
8907 if (acfg->aot_opts.static_link) {
8908 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8909 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8914 if (acfg->aot_opts.outfile)
8915 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8917 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8919 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8922 llvm_ofile = g_strdup (acfg->llvm_ofile);
8924 llvm_ofile = g_strdup ("");
8927 /* replace the ; flags separators with spaces */
8928 g_strdelimit (ld_flags, ";", ' ');
8931 command = g_strdup_printf ("%s -o %s %s %s.o %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
8933 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
8934 acfg->tmpfname, ld_flags);
8936 aot_printf (acfg, "Executing the native linker: %s\n", command);
8937 if (execute_system (command) != 0) {
8938 g_free (tmp_outfile_name);
8939 g_free (outfile_name);
8948 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8949 printf ("Stripping the binary: %s\n", com);
8950 execute_system (com);
8953 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8955 * gas generates 'mapping symbols' each time code and data is mixed, which
8956 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8958 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8959 aot_printf (acfg, "Stripping the binary: %s\n", command);
8960 if (execute_system (command) != 0) {
8961 g_free (tmp_outfile_name);
8962 g_free (outfile_name);
8969 rename (tmp_outfile_name, outfile_name);
8971 #if defined(TARGET_MACH)
8972 command = g_strdup_printf ("dsymutil %s", outfile_name);
8973 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8974 if (execute_system (command) != 0) {
8979 if (!acfg->aot_opts.save_temps)
8982 g_free (tmp_outfile_name);
8983 g_free (outfile_name);
8986 if (acfg->aot_opts.save_temps)
8987 aot_printf (acfg, "Retained input file.\n");
8989 unlink (acfg->tmpfname);
8994 static void init_got_info (GotInfo *info)
8998 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8999 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9000 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9001 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9002 info->got_patches = g_ptr_array_new ();
9005 static MonoAotCompile*
9006 acfg_create (MonoAssembly *ass, guint32 opts)
9008 MonoImage *image = ass->image;
9009 MonoAotCompile *acfg;
9011 acfg = g_new0 (MonoAotCompile, 1);
9012 acfg->methods = g_ptr_array_new ();
9013 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9014 acfg->method_depth = g_hash_table_new (NULL, NULL);
9015 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9016 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9017 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9018 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9019 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9020 acfg->image_hash = g_hash_table_new (NULL, NULL);
9021 acfg->image_table = g_ptr_array_new ();
9022 acfg->globals = g_ptr_array_new ();
9023 acfg->image = image;
9025 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9026 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9027 acfg->mempool = mono_mempool_new ();
9028 acfg->extra_methods = g_ptr_array_new ();
9029 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9030 acfg->unwind_ops = g_ptr_array_new ();
9031 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9032 acfg->method_order = g_ptr_array_new ();
9033 acfg->export_names = g_hash_table_new (NULL, NULL);
9034 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9035 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9036 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9037 mono_mutex_init_recursive (&acfg->mutex);
9039 init_got_info (&acfg->got_info);
9040 init_got_info (&acfg->llvm_got_info);
9046 got_info_free (GotInfo *info)
9050 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9051 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9052 g_free (info->patch_to_got_offset_by_type);
9053 g_hash_table_destroy (info->patch_to_got_offset);
9054 g_ptr_array_free (info->got_patches, TRUE);
9058 acfg_free (MonoAotCompile *acfg)
9062 mono_img_writer_destroy (acfg->w);
9063 for (i = 0; i < acfg->nmethods; ++i)
9065 g_free (acfg->cfgs [i]);
9066 g_free (acfg->cfgs);
9067 g_free (acfg->static_linking_symbol);
9068 g_free (acfg->got_symbol);
9069 g_free (acfg->plt_symbol);
9070 g_ptr_array_free (acfg->methods, TRUE);
9071 g_ptr_array_free (acfg->image_table, TRUE);
9072 g_ptr_array_free (acfg->globals, TRUE);
9073 g_ptr_array_free (acfg->unwind_ops, TRUE);
9074 g_hash_table_destroy (acfg->method_indexes);
9075 g_hash_table_destroy (acfg->method_depth);
9076 g_hash_table_destroy (acfg->plt_offset_to_entry);
9077 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9078 if (acfg->patch_to_plt_entry [i])
9079 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9081 g_free (acfg->patch_to_plt_entry);
9082 g_hash_table_destroy (acfg->method_to_cfg);
9083 g_hash_table_destroy (acfg->token_info_hash);
9084 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9085 g_hash_table_destroy (acfg->image_hash);
9086 g_hash_table_destroy (acfg->unwind_info_offsets);
9087 g_hash_table_destroy (acfg->method_label_hash);
9088 g_hash_table_destroy (acfg->export_names);
9089 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9090 g_hash_table_destroy (acfg->klass_blob_hash);
9091 g_hash_table_destroy (acfg->method_blob_hash);
9092 got_info_free (&acfg->got_info);
9093 got_info_free (&acfg->llvm_got_info);
9094 mono_mempool_destroy (acfg->mempool);
9098 #define WRAPPER(e,n) n,
9099 static const char* const
9100 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9101 #include "mono/metadata/wrapper-types.h"
9105 static G_GNUC_UNUSED const char*
9106 get_wrapper_type_name (int type)
9108 return wrapper_type_names [type];
9114 static void aot_dump (MonoAotCompile *acfg)
9120 mono_json_writer_init (&writer);
9122 mono_json_writer_object_begin(&writer);
9125 mono_json_writer_indent (&writer);
9126 mono_json_writer_object_key(&writer, "methods");
9127 mono_json_writer_array_begin (&writer);
9130 for (i = 0; i < acfg->nmethods; ++i) {
9135 cfg = acfg->cfgs [i];
9139 method = cfg->orig_method;
9141 mono_json_writer_indent (&writer);
9142 mono_json_writer_object_begin(&writer);
9144 mono_json_writer_indent (&writer);
9145 mono_json_writer_object_key(&writer, "name");
9146 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9148 mono_json_writer_indent (&writer);
9149 mono_json_writer_object_key(&writer, "signature");
9150 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9151 /*signature=*/TRUE));
9153 mono_json_writer_indent (&writer);
9154 mono_json_writer_object_key(&writer, "code_size");
9155 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9157 klass = method->klass;
9159 mono_json_writer_indent (&writer);
9160 mono_json_writer_object_key(&writer, "class");
9161 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9163 mono_json_writer_indent (&writer);
9164 mono_json_writer_object_key(&writer, "namespace");
9165 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9167 mono_json_writer_indent (&writer);
9168 mono_json_writer_object_key(&writer, "wrapper_type");
9169 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9171 mono_json_writer_indent_pop (&writer);
9172 mono_json_writer_indent (&writer);
9173 mono_json_writer_object_end (&writer);
9174 mono_json_writer_printf (&writer, ",\n");
9177 mono_json_writer_indent_pop (&writer);
9178 mono_json_writer_indent (&writer);
9179 mono_json_writer_array_end (&writer);
9180 mono_json_writer_printf (&writer, ",\n");
9184 mono_json_writer_indent_push (&writer);
9185 mono_json_writer_indent (&writer);
9186 mono_json_writer_object_key(&writer, "plt");
9187 mono_json_writer_array_begin (&writer);
9189 for (i = 0; i < acfg->plt_offset; ++i) {
9190 MonoPltEntry *plt_entry = NULL;
9195 * The first plt entry is unused.
9199 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9202 mono_json_writer_indent (&writer);
9203 mono_json_writer_printf (&writer, "{ ");
9204 mono_json_writer_object_key(&writer, "symbol");
9205 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9208 mono_json_writer_indent_pop (&writer);
9209 mono_json_writer_indent (&writer);
9210 mono_json_writer_array_end (&writer);
9211 mono_json_writer_printf (&writer, ",\n");
9216 mono_json_writer_indent_push (&writer);
9217 mono_json_writer_indent (&writer);
9218 mono_json_writer_object_key(&writer, "got");
9219 mono_json_writer_array_begin (&writer);
9221 mono_json_writer_indent_push (&writer);
9222 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9223 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9225 mono_json_writer_indent (&writer);
9226 mono_json_writer_printf (&writer, "{ ");
9227 mono_json_writer_object_key(&writer, "patch_name");
9228 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9231 mono_json_writer_indent_pop (&writer);
9232 mono_json_writer_indent (&writer);
9233 mono_json_writer_array_end (&writer);
9234 mono_json_writer_printf (&writer, ",\n");
9237 mono_json_writer_indent_pop (&writer);
9238 mono_json_writer_indent (&writer);
9239 mono_json_writer_object_end (&writer);
9241 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9242 dumpfile = fopen (dumpname, "w+");
9245 fprintf (dumpfile, "%s", writer.text->str);
9248 mono_json_writer_destroy (&writer);
9252 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9254 MonoImage *image = ass->image;
9257 MonoAotCompile *acfg;
9258 char *outfile_name, *tmp_outfile_name, *p;
9259 char llvm_stats_msg [256];
9263 acfg = acfg_create (ass, opts);
9265 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9266 acfg->aot_opts.write_symbols = TRUE;
9267 acfg->aot_opts.ntrampolines = 1024;
9268 acfg->aot_opts.nrgctx_trampolines = 1024;
9269 acfg->aot_opts.nimt_trampolines = 128;
9270 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9271 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9272 acfg->aot_opts.llvm_path = g_strdup ("");
9273 acfg->aot_opts.temp_path = g_strdup ("");
9275 acfg->aot_opts.use_trampolines_page = TRUE;
9278 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9280 if (acfg->aot_opts.logfile) {
9281 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9284 if (acfg->aot_opts.static_link)
9285 acfg->aot_opts.autoreg = TRUE;
9287 //acfg->aot_opts.print_skipped_methods = TRUE;
9289 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9290 if (opts & MONO_OPT_GSHAREDVT) {
9291 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9296 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9298 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9299 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9300 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9305 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9306 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9310 if (acfg->aot_opts.static_link)
9311 acfg->aot_opts.asm_writer = TRUE;
9313 if (acfg->aot_opts.soft_debug) {
9314 MonoDebugOptions *opt = mini_get_debug_options ();
9316 opt->mdb_optimizations = TRUE;
9317 opt->gen_sdb_seq_points = TRUE;
9319 if (!mono_debug_enabled ()) {
9320 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9323 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9326 if (mono_use_llvm || acfg->aot_opts.llvm) {
9328 acfg->aot_opts.asm_writer = TRUE;
9329 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9331 if (acfg->aot_opts.soft_debug) {
9332 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9338 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9339 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9344 * Emit all LLVM code into a separate assembly/object file and link with it
9347 if (!acfg->aot_opts.asm_only) {
9348 acfg->llvm_owriter = TRUE;
9349 } else if (acfg->aot_opts.llvm_outfile) {
9350 int len = strlen (acfg->aot_opts.llvm_outfile);
9352 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
9353 acfg->llvm_owriter = TRUE;
9357 if (mono_aot_mode_is_full (&acfg->aot_opts))
9358 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9360 if (acfg->aot_opts.instances_logfile_path) {
9361 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9362 if (!acfg->instances_logfile) {
9363 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9368 load_profile_files (acfg);
9370 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9371 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9372 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9374 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9375 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9376 if (acfg->opts & MONO_OPT_GSHAREDVT)
9377 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9380 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9384 if (acfg->llvm && acfg->thumb_mixed)
9385 acfg->flags |= MONO_AOT_FILE_FLAG_LLVM_THUMB;
9387 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9388 /* Get rid of characters which cannot occur in symbols */
9389 for (p = acfg->assembly_name_sym; *p; ++p) {
9390 if (!(isalnum (*p) || *p == '_'))
9394 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9395 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9396 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9398 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9400 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9401 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9404 acfg->method_index = 1;
9406 if (mono_aot_mode_is_full (&acfg->aot_opts))
9407 mono_set_partial_sharing_supported (TRUE);
9409 res = collect_methods (acfg);
9413 acfg->cfgs_size = acfg->methods->len + 32;
9414 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9416 /* PLT offset 0 is reserved for the PLT trampoline */
9417 acfg->plt_offset = 1;
9422 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, TRUE, TRUE);
9426 /* GOT offset 0 is reserved for the address of the current assembly */
9430 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9431 ji->type = MONO_PATCH_INFO_IMAGE;
9432 ji->data.image = acfg->image;
9434 get_got_offset (acfg, FALSE, ji);
9435 get_got_offset (acfg, TRUE, ji);
9437 /* Slot 1 is reserved for the mscorlib got addr */
9438 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9439 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9440 get_got_offset (acfg, FALSE, ji);
9441 get_got_offset (acfg, TRUE, ji);
9443 /* This is very common */
9444 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9445 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9446 get_got_offset (acfg, FALSE, ji);
9447 get_got_offset (acfg, TRUE, ji);
9449 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9450 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9451 get_got_offset (acfg, FALSE, ji);
9452 get_got_offset (acfg, TRUE, ji);
9454 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9455 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9456 get_got_offset (acfg, FALSE, ji);
9457 get_got_offset (acfg, TRUE, ji);
9462 compile_methods (acfg);
9466 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9474 if (acfg->aot_opts.asm_only) {
9475 if (acfg->aot_opts.outfile) {
9476 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9477 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9479 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9480 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9482 g_assert (acfg->aot_opts.llvm_outfile);
9483 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9484 if (acfg->llvm_owriter)
9485 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
9487 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9489 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
9490 g_strdup_printf ("%s", "temp") :
9491 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
9493 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9494 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
9495 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
9498 res = emit_llvm_file (acfg);
9504 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && mono_bin_writer_supported ()) {
9505 if (acfg->aot_opts.outfile)
9506 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9508 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9511 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9512 * it might be in another file system so the rename () won't work.
9514 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9516 acfg->fp = fopen (tmp_outfile_name, "w");
9518 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9522 acfg->w = mono_img_writer_create (acfg->fp, TRUE);
9523 acfg->use_bin_writer = TRUE;
9525 if (acfg->aot_opts.asm_only) {
9526 if (acfg->aot_opts.outfile)
9527 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9529 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9530 acfg->fp = fopen (acfg->tmpfname, "w+");
9532 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9533 acfg->fp = fdopen (i, "w+");
9535 if (acfg->fp == 0) {
9536 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9539 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9541 tmp_outfile_name = NULL;
9542 outfile_name = NULL;
9545 /* Compute symbols for methods */
9546 for (i = 0; i < acfg->nmethods; ++i) {
9547 if (acfg->cfgs [i]) {
9548 MonoCompile *cfg = acfg->cfgs [i];
9549 int method_index = get_method_index (acfg, cfg->orig_method);
9551 if (COMPILE_LLVM (cfg))
9552 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9553 else if (acfg->global_symbols || acfg->llvm)
9554 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9556 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9557 cfg->asm_debug_symbol = cfg->asm_symbol;
9561 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9563 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9564 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9567 //acfg->gas_line_numbers = TRUE;
9570 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9571 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9572 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9575 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9578 mono_img_writer_emit_start (acfg->w);
9581 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9587 emit_extra_methods (acfg);
9589 emit_trampolines (acfg);
9591 emit_class_name_table (acfg);
9593 emit_got_info (acfg, FALSE);
9595 emit_got_info (acfg, TRUE);
9597 emit_exception_info (acfg);
9599 emit_unwind_info (acfg);
9601 emit_class_info (acfg);
9605 emit_image_table (acfg);
9609 emit_file_info (acfg);
9613 emit_objc_selectors (acfg);
9615 emit_globals (acfg);
9617 emit_autoreg (acfg);
9620 emit_dwarf_info (acfg);
9621 mono_dwarf_writer_close (acfg->dwarf);
9624 emit_mem_end (acfg);
9626 if (acfg->need_pt_gnu_stack) {
9627 /* This is required so the .so doesn't have an executable stack */
9628 /* The bin writer already emits this */
9629 if (!acfg->use_bin_writer)
9630 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9635 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9638 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9640 strcpy (llvm_stats_msg, "");
9642 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;
9644 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",
9645 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9646 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9647 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9648 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9649 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9650 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,
9651 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9652 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9653 (int)(acfg->got_offset * sizeof (gpointer)));
9654 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9655 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9657 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9658 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9659 if (acfg->stats.genericcount)
9660 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9661 if (acfg->stats.abscount)
9662 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9663 if (acfg->stats.lmfcount)
9664 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9665 if (acfg->stats.ocount)
9666 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9669 res = mono_img_writer_emit_writeout (acfg->w);
9674 if (acfg->use_bin_writer) {
9675 int err = rename (tmp_outfile_name, outfile_name);
9678 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9682 res = compile_asm (acfg);
9689 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9691 if (acfg->aot_opts.stats) {
9694 aot_printf (acfg, "GOT slot distribution:\n");
9695 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9696 if (acfg->stats.got_slot_types [i])
9697 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]);
9700 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);
9702 if (acfg->aot_opts.dump_json)
9715 mono_aot_readonly_field_override (MonoClassField *field)
9721 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)