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 #define COMMON_TRAMP_SIZE 16
1171 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1172 int imm8, rot_amount;
1175 if (!acfg->aot_opts.use_trampolines_page)
1178 acfg->tramp_page_size = mono_pagesize ();
1180 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1181 emit_alignment (acfg, mono_pagesize ());
1182 emit_global (acfg, symbol, TRUE);
1183 emit_label (acfg, symbol);
1185 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1187 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1188 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1189 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1190 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1192 g_assert (code - buf == COMMON_TRAMP_SIZE);
1195 emit_bytes (acfg, buf, code - buf);
1197 for (i = 0; i < count; ++i) {
1199 ARM_PUSH (code, 0x5fff);
1201 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1202 g_assert (code - buf == 8);
1203 emit_bytes (acfg, buf, code - buf);
1206 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1207 * the instruction pointer address, so the generic trampoline at the start of the page
1208 * subtracts 4096 to get to the data page and loads the values
1209 * We again fit the generic trampiline in 16 bytes.
1211 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1212 emit_global (acfg, symbol, TRUE);
1213 emit_label (acfg, symbol);
1215 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1216 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1217 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1218 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1220 g_assert (code - buf == COMMON_TRAMP_SIZE);
1223 emit_bytes (acfg, buf, code - buf);
1225 for (i = 0; i < count; ++i) {
1227 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1229 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1230 g_assert (code - buf == 8);
1231 emit_bytes (acfg, buf, code - buf);
1235 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1237 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1238 emit_global (acfg, symbol, TRUE);
1239 emit_label (acfg, symbol);
1241 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1242 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1243 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1244 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1245 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1246 g_assert (code - buf == COMMON_TRAMP_SIZE);
1248 emit_bytes (acfg, buf, code - buf);
1250 for (i = 0; i < count; ++i) {
1252 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1254 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1255 g_assert (code - buf == 8);
1256 emit_bytes (acfg, buf, code - buf);
1259 /* now the imt trampolines: each specific trampolines puts in the ip register
1260 * the instruction pointer address, so the generic trampoline at the start of the page
1261 * subtracts 4096 to get to the data page and loads the values
1262 * We again fit the generic trampiline in 16 bytes.
1264 #define IMT_TRAMP_SIZE 72
1265 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1266 emit_global (acfg, symbol, TRUE);
1267 emit_label (acfg, symbol);
1269 /* Need at least two free registers, plus a slot for storing the pc */
1270 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1272 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1273 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1274 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1276 /* The IMT method is in v5, r0 has the imt array address */
1279 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1280 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1281 imt_found_check = code;
1282 ARM_B_COND (code, ARMCOND_EQ, 0);
1284 /* End-of-loop check */
1285 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1286 loop_end_check = code;
1287 ARM_B_COND (code, ARMCOND_EQ, 0);
1290 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1291 loop_branch_back = code;
1293 arm_patch (loop_branch_back, loop_start);
1296 arm_patch (imt_found_check, code);
1297 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1298 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1299 /* Save it to the third stack slot */
1300 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1301 /* Restore the registers and branch */
1302 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1305 arm_patch (loop_end_check, code);
1306 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1307 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1308 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1312 g_assert (code - buf == IMT_TRAMP_SIZE);
1313 emit_bytes (acfg, buf, code - buf);
1315 for (i = 0; i < count; ++i) {
1317 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1319 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1320 g_assert (code - buf == 8);
1321 emit_bytes (acfg, buf, code - buf);
1324 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1325 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1326 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1327 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1328 #elif defined(TARGET_ARM64)
1329 arm64_emit_specific_trampoline_pages (acfg);
1334 * arch_emit_specific_trampoline:
1336 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1337 * two GOT slots which contain the generic trampoline address and the trampoline
1338 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1341 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1344 * The trampolines created here are variations of the specific
1345 * trampolines created in mono_arch_create_specific_trampoline (). The
1347 * - the generic trampoline address is taken from a got slot.
1348 * - the offset of the got slot where the trampoline argument is stored
1349 * is embedded in the instruction stream, and the generic trampoline
1350 * can load the argument by loading the offset, adding it to the
1351 * address of the trampoline to get the address of the got slot, and
1352 * loading the argument from there.
1353 * - all the trampolines should be of the same length.
1355 #if defined(TARGET_AMD64)
1356 #if defined(__default_codegen__)
1357 /* This should be exactly 8 bytes long */
1359 /* call *<offset>(%rip) */
1361 emit_unset_mode (acfg);
1362 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1363 emit_zero_bytes (acfg, 2);
1365 emit_byte (acfg, '\x41');
1366 emit_byte (acfg, '\xff');
1367 emit_byte (acfg, '\x15');
1368 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1369 emit_zero_bytes (acfg, 1);
1371 #elif defined(__native_client_codegen__)
1373 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1374 guint8 *code = buf_aligned;
1379 /* Emit this call in 'code' so we can find out how long it is. */
1380 amd64_call_reg (code, AMD64_R11);
1381 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1382 call_len = code - call_start;
1384 /* The tramp_size is twice the NaCl alignment because it starts with */
1385 /* a call which needs to be aligned to the end of the boundary. */
1386 *tramp_size = kNaClAlignment*2;
1388 /* Emit nops to align call site below which is 7 bytes plus */
1389 /* the length of the call sequence emitted above. */
1390 /* Note: this requires the specific trampoline starts on a */
1391 /* kNaclAlignedment aligned address, which it does because */
1392 /* it's its own function that is aligned. */
1393 guint8 nop_buf[256];
1394 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1395 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1396 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1398 /* The trampoline is stored at the offset'th pointer, the -4 is */
1399 /* present because RIP relative addressing starts at the end of */
1400 /* the current instruction, while the label "." is relative to */
1401 /* the beginning of the current asm location, which in this case */
1402 /* is not the mov instruction, but the offset itself, due to the */
1403 /* way the bytes and ints are emitted here. */
1404 got_offset = (offset * sizeof(gpointer)) - 4;
1406 /* mov <OFFSET>(%rip), %r11d */
1407 emit_byte (acfg, '\x45');
1408 emit_byte (acfg, '\x8b');
1409 emit_byte (acfg, '\x1d');
1410 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1413 emit_bytes (acfg, call_start, call_len);
1415 /* The arg is stored at the offset+1 pointer, relative to beginning */
1416 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1417 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1419 /* We can't emit this data directly, hide in a "push imm32" */
1420 emit_byte (acfg, '\x68'); /* push */
1421 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1422 emit_alignment (acfg, kNaClAlignment);
1423 #endif /*__native_client_codegen__*/
1424 #elif defined(TARGET_ARM)
1428 /* This should be exactly 20 bytes long */
1431 ARM_PUSH (code, 0x5fff);
1432 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1433 /* Load the value from the GOT */
1434 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1436 ARM_BLX_REG (code, ARMREG_R1);
1438 g_assert (code - buf == 16);
1441 emit_bytes (acfg, buf, code - buf);
1443 * Only one offset is needed, since the second one would be equal to the
1446 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1447 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1448 #elif defined(TARGET_ARM64)
1449 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1450 #elif defined(TARGET_POWERPC)
1457 g_assert (!acfg->use_bin_writer);
1460 * PPC has no ip relative addressing, so we need to compute the address
1461 * of the mscorlib got. That is slow and complex, so instead, we store it
1462 * in the second got slot of every aot image. The caller already computed
1463 * the address of its got and placed it into r30.
1465 emit_unset_mode (acfg);
1466 /* Load mscorlib got address */
1467 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1468 /* Load generic trampoline address */
1469 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1470 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1471 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1472 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1473 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1475 fprintf (acfg->fp, "mtctr 11\n");
1476 /* Load trampoline argument */
1477 /* On ppc, we pass it normally to the generic trampoline */
1478 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1479 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1480 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1481 /* Branch to generic trampoline */
1482 fprintf (acfg->fp, "bctr\n");
1484 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1485 *tramp_size = 10 * 4;
1487 *tramp_size = 9 * 4;
1489 #elif defined(TARGET_X86)
1493 /* Similar to the PPC code above */
1495 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1497 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1498 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1499 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1500 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1501 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1506 /* Load mscorlib got address */
1507 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1508 /* Push trampoline argument */
1509 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1510 /* Load generic trampoline address */
1511 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1512 /* Branch to generic trampoline */
1513 x86_jump_reg (code, X86_ECX);
1515 #ifdef __native_client_codegen__
1517 /* emit nops to next 32 byte alignment */
1518 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1519 while (code < (buf + a)) x86_nop(code);
1522 emit_bytes (acfg, buf, code - buf);
1524 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1525 g_assert (code - buf == *tramp_size);
1527 g_assert_not_reached ();
1532 * arch_emit_unbox_trampoline:
1534 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1535 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1538 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1540 #if defined(TARGET_AMD64)
1545 this_reg = mono_arch_get_this_arg_reg (NULL);
1547 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1549 emit_bytes (acfg, buf, code - buf);
1552 emit_unset_mode (acfg);
1553 fprintf (acfg->fp, "jmp %s\n", call_target);
1555 emit_byte (acfg, '\xe9');
1556 emit_symbol_diff (acfg, call_target, ".", -4);
1558 #elif defined(TARGET_X86)
1565 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1567 emit_bytes (acfg, buf, code - buf);
1570 emit_byte (acfg, '\xe9');
1571 emit_symbol_diff (acfg, call_target, ".", -4);
1572 #elif defined(TARGET_ARM)
1576 if (acfg->thumb_mixed && cfg->compile_llvm) {
1577 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1578 fprintf (acfg->fp, "b %s\n", call_target);
1579 fprintf (acfg->fp, ".arm\n");
1580 fprintf (acfg->fp, ".align 2\n");
1586 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1588 emit_bytes (acfg, buf, code - buf);
1589 /* jump to method */
1590 if (acfg->use_bin_writer) {
1597 mono_img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1598 emit_bytes (acfg, buf, 4);
1600 if (acfg->thumb_mixed && cfg->compile_llvm)
1601 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1603 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1605 #elif defined(TARGET_ARM64)
1606 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1607 #elif defined(TARGET_POWERPC)
1610 g_assert (!acfg->use_bin_writer);
1612 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1613 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1615 g_assert_not_reached ();
1620 * arch_emit_static_rgctx_trampoline:
1622 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1623 * two GOT slots which contain the rgctx argument, and the method to jump to.
1624 * TRAMP_SIZE is set to the size of the emitted trampoline.
1625 * These kinds of trampolines cannot be enumerated statically, since there could
1626 * be one trampoline per method instantiation, so we emit the same code for all
1627 * trampolines, and parameterize them using two GOT slots.
1630 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1632 #if defined(TARGET_AMD64)
1633 #if defined(__default_codegen__)
1634 /* This should be exactly 13 bytes long */
1638 emit_unset_mode (acfg);
1639 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1640 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1642 /* mov <OFFSET>(%rip), %r10 */
1643 emit_byte (acfg, '\x4d');
1644 emit_byte (acfg, '\x8b');
1645 emit_byte (acfg, '\x15');
1646 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1648 /* jmp *<offset>(%rip) */
1649 emit_byte (acfg, '\xff');
1650 emit_byte (acfg, '\x25');
1651 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1653 #elif defined(__native_client_codegen__)
1655 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1656 guint8 *code = buf_aligned;
1658 /* mov <OFFSET>(%rip), %r10d */
1659 emit_byte (acfg, '\x45');
1660 emit_byte (acfg, '\x8b');
1661 emit_byte (acfg, '\x15');
1662 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1664 /* mov <OFFSET>(%rip), %r11d */
1665 emit_byte (acfg, '\x45');
1666 emit_byte (acfg, '\x8b');
1667 emit_byte (acfg, '\x1d');
1668 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1671 amd64_jump_reg (code, AMD64_R11);
1672 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1674 emit_alignment (acfg, kNaClAlignment);
1675 *tramp_size = kNaClAlignment;
1676 #endif /*__native_client_codegen__*/
1678 #elif defined(TARGET_ARM)
1682 /* This should be exactly 24 bytes long */
1685 /* Load rgctx value */
1686 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1687 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1688 /* Load branch addr + branch */
1689 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1690 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1692 g_assert (code - buf == 16);
1695 emit_bytes (acfg, buf, code - buf);
1696 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1697 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1698 #elif defined(TARGET_ARM64)
1699 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1700 #elif defined(TARGET_POWERPC)
1707 g_assert (!acfg->use_bin_writer);
1710 * PPC has no ip relative addressing, so we need to compute the address
1711 * of the mscorlib got. That is slow and complex, so instead, we store it
1712 * in the second got slot of every aot image. The caller already computed
1713 * the address of its got and placed it into r30.
1715 emit_unset_mode (acfg);
1716 /* Load mscorlib got address */
1717 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1719 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1720 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1721 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1722 /* Load target address */
1723 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1724 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1725 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1726 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1727 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1728 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1730 fprintf (acfg->fp, "mtctr 11\n");
1731 /* Branch to the target address */
1732 fprintf (acfg->fp, "bctr\n");
1734 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1735 *tramp_size = 11 * 4;
1737 *tramp_size = 9 * 4;
1740 #elif defined(TARGET_X86)
1744 /* Similar to the PPC code above */
1746 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1749 /* Load mscorlib got address */
1750 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1752 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1753 /* Branch to the target address */
1754 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1756 #ifdef __native_client_codegen__
1758 /* emit nops to next 32 byte alignment */
1759 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1760 while (code < (buf + a)) x86_nop(code);
1764 emit_bytes (acfg, buf, code - buf);
1766 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1767 g_assert (code - buf == *tramp_size);
1769 g_assert_not_reached ();
1774 * arch_emit_imt_thunk:
1776 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1777 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1778 * key is the IMT key, and ptr holds the address of a memory location holding
1779 * the address to branch to if the IMT arg matches the key. The array is
1780 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1782 * TRAMP_SIZE is set to the size of the emitted trampoline.
1785 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1787 #if defined(TARGET_AMD64)
1789 #if defined(__native_client_codegen__)
1792 guint8 *labels [16];
1794 guint8 *mov_buf_ptr = mov_buf;
1796 const int kSizeOfMove = 7;
1797 #if defined(__default_codegen__)
1798 code = buf = g_malloc (256);
1799 #elif defined(__native_client_codegen__)
1800 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1801 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1802 /* The RIP relative move below is emitted first */
1807 /* FIXME: Optimize this, i.e. use binary search etc. */
1808 /* Maybe move the body into a separate function (slower, but much smaller) */
1810 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1813 emit_unset_mode (acfg);
1814 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1818 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1820 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1823 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1825 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1828 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1829 amd64_jump_code (code, labels [0]);
1832 mono_amd64_patch (labels [2], code);
1833 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1834 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1837 mono_amd64_patch (labels [1], code);
1838 /* Load fail tramp */
1839 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1840 /* Check if there is a fail tramp */
1841 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1843 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1844 /* Jump to fail tramp */
1845 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1848 mono_amd64_patch (labels [3], code);
1849 x86_breakpoint (code);
1852 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1853 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1854 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1855 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1856 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1857 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1859 emit_bytes (acfg, buf, code - buf);
1861 *tramp_size = code - buf + kSizeOfMove;
1862 #if defined(__native_client_codegen__)
1863 /* The tramp will be padded to the next kNaClAlignment bundle. */
1864 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1867 #if defined(__default_codegen__)
1869 #elif defined(__native_client_codegen__)
1873 #elif defined(TARGET_X86)
1875 #ifdef __native_client_codegen__
1878 guint8 *labels [16];
1880 #if defined(__default_codegen__)
1881 code = buf = g_malloc (256);
1882 #elif defined(__native_client_codegen__)
1883 buf_alloc = g_malloc (256 + kNaClAlignment);
1884 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1887 /* Allocate a temporary stack slot */
1888 x86_push_reg (code, X86_EAX);
1890 x86_push_reg (code, X86_EAX);
1892 /* Load mscorlib got address */
1893 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1895 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1898 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1900 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1903 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1905 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1908 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1909 x86_jump_code (code, labels [0]);
1912 mono_x86_patch (labels [2], code);
1913 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1914 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1915 /* Save the target address to the temporary stack location */
1916 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1918 x86_pop_reg (code, X86_EAX);
1919 /* Jump to the target address */
1923 mono_x86_patch (labels [1], code);
1924 /* Load fail tramp */
1925 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1926 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1928 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1929 /* Jump to fail tramp */
1930 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1931 x86_pop_reg (code, X86_EAX);
1935 mono_x86_patch (labels [3], code);
1936 x86_breakpoint (code);
1938 #ifdef __native_client_codegen__
1940 /* emit nops to next 32 byte alignment */
1941 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1942 while (code < (buf + a)) x86_nop(code);
1945 emit_bytes (acfg, buf, code - buf);
1947 *tramp_size = code - buf;
1949 #if defined(__default_codegen__)
1951 #elif defined(__native_client_codegen__)
1955 #elif defined(TARGET_ARM)
1957 guint8 *code, *code2, *labels [16];
1961 /* The IMT method is in v5 */
1963 /* Need at least two free registers, plus a slot for storing the pc */
1964 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1966 /* Load the parameter from the GOT */
1967 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1968 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1971 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1972 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1974 ARM_B_COND (code, ARMCOND_EQ, 0);
1976 /* End-of-loop check */
1977 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1979 ARM_B_COND (code, ARMCOND_EQ, 0);
1982 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1985 arm_patch (labels [4], labels [1]);
1988 arm_patch (labels [2], code);
1989 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1990 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1991 /* Save it to the third stack slot */
1992 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1993 /* Restore the registers and branch */
1994 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1997 arm_patch (labels [3], code);
1998 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1999 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2000 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2004 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2006 emit_bytes (acfg, buf, code - buf);
2007 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2009 *tramp_size = code - buf + 4;
2010 #elif defined(TARGET_ARM64)
2011 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2012 #elif defined(TARGET_POWERPC)
2014 guint8 *code, *labels [16];
2018 /* Load the mscorlib got address */
2019 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2020 /* Load the parameter from the GOT */
2021 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2022 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2024 /* Load and check key */
2026 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2027 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2029 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2031 /* End-of-loop check */
2032 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2034 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2037 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2040 mono_ppc_patch (labels [4], labels [1]);
2043 mono_ppc_patch (labels [2], code);
2044 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2045 /* r12 now contains the value of the vtable slot */
2046 /* this is not a function descriptor on ppc64 */
2047 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2048 ppc_mtctr (code, ppc_r12);
2049 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2052 mono_ppc_patch (labels [3], code);
2056 *tramp_size = code - buf;
2058 emit_bytes (acfg, buf, code - buf);
2060 g_assert_not_reached ();
2065 * arch_emit_gsharedvt_arg_trampoline:
2067 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2068 * two GOT slots which contain the argument, and the code to jump to.
2069 * TRAMP_SIZE is set to the size of the emitted trampoline.
2070 * These kinds of trampolines cannot be enumerated statically, since there could
2071 * be one trampoline per method instantiation, so we emit the same code for all
2072 * trampolines, and parameterize them using two GOT slots.
2075 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2077 #if defined(TARGET_X86)
2081 /* Similar to the PPC code above */
2083 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2086 /* Load mscorlib got address */
2087 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2089 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2090 /* Branch to the target address */
2091 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2093 #ifdef __native_client_codegen__
2095 /* emit nops to next 32 byte alignment */
2096 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2097 while (code < (buf + a)) x86_nop(code);
2101 emit_bytes (acfg, buf, code - buf);
2103 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2104 g_assert (code - buf == *tramp_size);
2105 #elif defined(TARGET_ARM)
2109 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2110 /* Similar to arch_emit_specific_trampoline () */
2113 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2114 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2115 /* Load the arg value from the GOT */
2116 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2117 /* Load the addr from the GOT */
2118 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2120 ARM_BX (code, ARMREG_R1);
2122 g_assert (code - buf == 20);
2125 emit_bytes (acfg, buf, code - buf);
2126 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2127 #elif defined(TARGET_ARM64)
2128 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2130 g_assert_not_reached ();
2135 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2137 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2138 /* Based on code generated by gcc */
2139 emit_unset_mode (acfg);
2142 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2143 ".section .ctors,\"aw\",@progbits\n"
2147 ".section .opd,\"aw\"\n"
2150 ".long .%s,.TOC.@tocbase32\n"
2153 ".type .%s,@function\n"
2155 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2157 ".section .ctors,\"aw\",@progbits\n"
2161 ".section .opd,\"aw\"\n"
2164 ".long .%1$s,.TOC.@tocbase32\n"
2165 ".size %1$s,.-%1$s\n"
2167 ".type .%1$s,@function\n"
2169 ".%1$s:\n", symbol);
2180 "lis 3, .Lglobals@h\n"
2181 "ori 3, 3, .Lglobals@l\n"
2182 "bl .mono_aot_register_module\n"
2190 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2192 ".size .%s,.-.%s\n", symbol, symbol);
2195 ".size .%1$s,.-.%1$s\n", symbol);
2201 /* END OF ARCH SPECIFIC CODE */
2204 mono_get_field_token (MonoClassField *field)
2206 MonoClass *klass = field->parent;
2209 for (i = 0; i < klass->field.count; ++i) {
2210 if (field == &klass->fields [i])
2211 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2214 g_assert_not_reached ();
2219 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2223 //printf ("ENCODE: %d 0x%x.\n", value, value);
2226 * Same encoding as the one used in the metadata, extended to handle values
2227 * greater than 0x1fffffff.
2229 if ((value >= 0) && (value <= 127))
2231 else if ((value >= 0) && (value <= 16383)) {
2232 p [0] = 0x80 | (value >> 8);
2233 p [1] = value & 0xff;
2235 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2236 p [0] = (value >> 24) | 0xc0;
2237 p [1] = (value >> 16) & 0xff;
2238 p [2] = (value >> 8) & 0xff;
2239 p [3] = value & 0xff;
2244 p [1] = (value >> 24) & 0xff;
2245 p [2] = (value >> 16) & 0xff;
2246 p [3] = (value >> 8) & 0xff;
2247 p [4] = value & 0xff;
2255 stream_init (MonoDynamicStream *sh)
2258 sh->alloc_size = 4096;
2259 sh->data = g_malloc (4096);
2261 /* So offsets are > 0 */
2267 make_room_in_stream (MonoDynamicStream *stream, int size)
2269 if (size <= stream->alloc_size)
2272 while (stream->alloc_size <= size) {
2273 if (stream->alloc_size < 4096)
2274 stream->alloc_size = 4096;
2276 stream->alloc_size *= 2;
2279 stream->data = g_realloc (stream->data, stream->alloc_size);
2283 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2287 make_room_in_stream (stream, stream->index + len);
2288 memcpy (stream->data + stream->index, data, len);
2289 idx = stream->index;
2290 stream->index += len;
2297 * Add data to the binary blob inside the aot image. Returns the offset inside the
2298 * blob where the data was stored.
2301 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2303 if (acfg->blob.alloc_size == 0)
2304 stream_init (&acfg->blob);
2306 return add_stream_data (&acfg->blob, (char*)data, data_len);
2310 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2315 if (acfg->blob.alloc_size == 0)
2316 stream_init (&acfg->blob);
2318 count = acfg->blob.index % align;
2320 /* we assume the stream data will be aligned */
2322 add_stream_data (&acfg->blob, buf, 4 - count);
2324 return add_stream_data (&acfg->blob, (char*)data, data_len);
2328 * emit_offset_table:
2330 * Emit a table of increasing offsets in a compact form using differential encoding.
2331 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2332 * group size, the more compact the table becomes, but the slower it becomes to compute
2333 * a given entry. Returns the size of the table.
2336 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2338 gint32 current_offset;
2339 int i, buf_size, ngroups, index_entry_size;
2341 guint32 *index_offsets;
2343 ngroups = (noffsets + (group_size - 1)) / group_size;
2345 index_offsets = g_new0 (guint32, ngroups);
2347 buf_size = noffsets * 4;
2348 p = buf = g_malloc0 (buf_size);
2351 for (i = 0; i < noffsets; ++i) {
2352 //printf ("D: %d -> %d\n", i, offsets [i]);
2353 if ((i % group_size) == 0) {
2354 index_offsets [i / group_size] = p - buf;
2355 /* Emit the full value for these entries */
2356 encode_value (offsets [i], p, &p);
2358 /* The offsets are allowed to be non-increasing */
2359 //g_assert (offsets [i] >= current_offset);
2360 encode_value (offsets [i] - current_offset, p, &p);
2362 current_offset = offsets [i];
2365 if (ngroups && index_offsets [ngroups - 1] < 65000)
2366 index_entry_size = 2;
2368 index_entry_size = 4;
2370 /* Emit the header */
2371 emit_int32 (acfg, noffsets);
2372 emit_int32 (acfg, group_size);
2373 emit_int32 (acfg, ngroups);
2374 emit_int32 (acfg, index_entry_size);
2376 /* Emit the index */
2377 for (i = 0; i < ngroups; ++i) {
2378 if (index_entry_size == 2)
2379 emit_int16 (acfg, index_offsets [i]);
2381 emit_int32 (acfg, index_offsets [i]);
2385 emit_bytes (acfg, buf, p - buf);
2387 return (int)(p - buf) + (ngroups * 4);
2391 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2395 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2399 index = g_hash_table_size (cfg->image_hash);
2400 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2401 g_ptr_array_add (cfg->image_table, image);
2407 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2410 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2412 /* FIXME: Search referenced images as well */
2413 if (!acfg->typespec_classes) {
2414 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2415 for (i = 0; i < len; ++i) {
2417 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2418 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2421 for (i = 0; i < len; ++i) {
2422 if (acfg->typespec_classes [i] == klass)
2427 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2433 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2436 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2439 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2442 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2445 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2450 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2454 if (klass->generic_class) {
2456 g_assert (klass->type_token);
2458 /* Find a typespec for a class if possible */
2459 token = find_typespec_for_class (acfg, klass);
2461 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2462 encode_value (token, p, &p);
2464 MonoClass *gclass = klass->generic_class->container_class;
2465 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2466 static int count = 0;
2469 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2470 encode_klass_ref (acfg, gclass, p, &p);
2471 encode_ginst (acfg, inst, p, &p);
2475 } else if (klass->type_token) {
2476 int iindex = get_image_index (acfg, klass->image);
2478 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2480 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2481 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2483 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2484 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2485 encode_value (get_image_index (acfg, klass->image), p, &p);
2487 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2488 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2489 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2491 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2492 encode_value (klass->byval_arg.type, p, &p);
2493 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2495 encode_value (container ? 1 : 0, p, &p);
2497 encode_value (container->is_method, p, &p);
2498 g_assert (!par->gshared_constraint);
2499 if (container->is_method)
2500 encode_method_ref (acfg, container->owner.method, p, &p);
2502 encode_klass_ref (acfg, container->owner.klass, p, &p);
2504 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2505 if (par->gshared_constraint) {
2508 encode_type (acfg, par->gshared_constraint, p, &p);
2510 name = mono_generic_param_name (par);
2512 int len = strlen (name);
2514 encode_value (len, p, &p);
2515 memcpy (p, name, len);
2518 encode_value (0, p, &p);
2522 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2523 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2524 encode_type (acfg, &klass->byval_arg, p, &p);
2527 g_assert (klass->rank > 0);
2528 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2529 encode_value (klass->rank, p, &p);
2530 encode_klass_ref (acfg, klass->element_class, p, &p);
2538 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2539 * standard metadata encoding.
2542 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2544 gboolean shared = FALSE;
2547 * The encoding of generic instances is large so emit them only once.
2549 if (klass->generic_class) {
2551 g_assert (klass->type_token);
2553 /* Find a typespec for a class if possible */
2554 token = find_typespec_for_class (acfg, klass);
2557 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2562 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2566 buf2 = g_malloc (1024);
2569 encode_klass_ref_inner (acfg, klass, p, &p);
2570 g_assert (p - buf2 < 1024);
2572 offset = add_to_blob (acfg, buf2, p - buf2);
2575 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2581 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2582 encode_value (offset, p, &p);
2587 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2591 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2593 guint32 token = mono_get_field_token (field);
2596 encode_klass_ref (cfg, field->parent, p, &p);
2597 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2598 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2603 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2608 encode_value (inst->type_argc, p, &p);
2609 for (i = 0; i < inst->type_argc; ++i)
2610 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2615 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2618 MonoGenericInst *inst;
2620 inst = context->class_inst;
2622 g_assert (inst->type_argc);
2623 encode_ginst (acfg, inst, p, &p);
2625 encode_value (0, p, &p);
2627 inst = context->method_inst;
2629 g_assert (inst->type_argc);
2630 encode_ginst (acfg, inst, p, &p);
2632 encode_value (0, p, &p);
2638 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2642 g_assert (t->num_mods == 0);
2643 /* t->attrs can be ignored */
2644 //g_assert (t->attrs == 0);
2647 *p = MONO_TYPE_PINNED;
2651 *p = MONO_TYPE_BYREF;
2659 case MONO_TYPE_VOID:
2660 case MONO_TYPE_BOOLEAN:
2661 case MONO_TYPE_CHAR:
2674 case MONO_TYPE_STRING:
2675 case MONO_TYPE_OBJECT:
2676 case MONO_TYPE_TYPEDBYREF:
2678 case MONO_TYPE_VALUETYPE:
2679 case MONO_TYPE_CLASS:
2680 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2682 case MONO_TYPE_SZARRAY:
2683 encode_klass_ref (acfg, t->data.klass, p, &p);
2686 encode_type (acfg, t->data.type, p, &p);
2688 case MONO_TYPE_GENERICINST: {
2689 MonoClass *gclass = t->data.generic_class->container_class;
2690 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2692 encode_klass_ref (acfg, gclass, p, &p);
2693 encode_ginst (acfg, inst, p, &p);
2696 case MONO_TYPE_ARRAY: {
2697 MonoArrayType *array = t->data.array;
2700 encode_klass_ref (acfg, array->eklass, p, &p);
2701 encode_value (array->rank, p, &p);
2702 encode_value (array->numsizes, p, &p);
2703 for (i = 0; i < array->numsizes; ++i)
2704 encode_value (array->sizes [i], p, &p);
2705 encode_value (array->numlobounds, p, &p);
2706 for (i = 0; i < array->numlobounds; ++i)
2707 encode_value (array->lobounds [i], p, &p);
2711 case MONO_TYPE_MVAR:
2712 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2715 g_assert_not_reached ();
2722 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2728 /* Similar to the metadata encoding */
2729 if (sig->generic_param_count)
2733 if (sig->explicit_this)
2735 flags |= (sig->call_convention & 0x0F);
2739 if (sig->generic_param_count)
2740 encode_value (sig->generic_param_count, p, &p);
2741 encode_value (sig->param_count, p, &p);
2743 encode_type (acfg, sig->ret, p, &p);
2744 for (i = 0; i < sig->param_count; ++i) {
2745 if (sig->sentinelpos == i) {
2746 *p = MONO_TYPE_SENTINEL;
2749 encode_type (acfg, sig->params [i], p, &p);
2755 #define MAX_IMAGE_INDEX 250
2758 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2760 guint32 image_index = get_image_index (acfg, method->klass->image);
2761 guint32 token = method->token;
2762 MonoJumpInfoToken *ji;
2766 * The encoding for most methods is as follows:
2767 * - image index encoded as a leb128
2768 * - token index encoded as a leb128
2769 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2770 * types of method encodings.
2773 /* Mark methods which can't use aot trampolines because they need the further
2774 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2776 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2777 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2778 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2780 if (method->wrapper_type) {
2781 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2783 encode_value (method->wrapper_type, p, &p);
2785 switch (method->wrapper_type) {
2786 case MONO_WRAPPER_REMOTING_INVOKE:
2787 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2788 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2791 m = mono_marshal_method_from_wrapper (method);
2793 encode_method_ref (acfg, m, p, &p);
2796 case MONO_WRAPPER_PROXY_ISINST:
2797 case MONO_WRAPPER_LDFLD:
2798 case MONO_WRAPPER_LDFLDA:
2799 case MONO_WRAPPER_STFLD:
2800 case MONO_WRAPPER_ISINST: {
2801 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2804 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2807 case MONO_WRAPPER_LDFLD_REMOTE:
2808 case MONO_WRAPPER_STFLD_REMOTE:
2810 case MONO_WRAPPER_ALLOC: {
2811 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2813 /* The GC name is saved once in MonoAotFileInfo */
2814 g_assert (info->alloc_type != -1);
2815 encode_value (info->alloc_type, p, &p);
2818 case MONO_WRAPPER_WRITE_BARRIER:
2820 case MONO_WRAPPER_STELEMREF: {
2821 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2824 encode_value (info->subtype, p, &p);
2825 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2826 encode_value (info->d.virtual_stelemref.kind, p, &p);
2829 case MONO_WRAPPER_UNKNOWN: {
2830 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2833 encode_value (info->subtype, p, &p);
2834 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2835 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2836 encode_klass_ref (acfg, method->klass, p, &p);
2837 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2838 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2839 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2840 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2843 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2844 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2847 encode_value (info->subtype, p, &p);
2848 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2849 strcpy ((char*)p, method->name);
2850 p += strlen (method->name) + 1;
2851 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2852 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2854 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2855 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2859 case MONO_WRAPPER_SYNCHRONIZED: {
2862 m = mono_marshal_method_from_wrapper (method);
2864 g_assert (m != method);
2865 encode_method_ref (acfg, m, p, &p);
2868 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2869 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2872 encode_value (info->subtype, p, &p);
2874 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2875 encode_value (info->d.element_addr.rank, p, &p);
2876 encode_value (info->d.element_addr.elem_size, p, &p);
2877 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2878 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2880 g_assert_not_reached ();
2884 case MONO_WRAPPER_CASTCLASS: {
2885 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2888 encode_value (info->subtype, p, &p);
2891 case MONO_WRAPPER_RUNTIME_INVOKE: {
2892 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2895 encode_value (info->subtype, p, &p);
2896 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2897 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2898 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2899 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2902 case MONO_WRAPPER_DELEGATE_INVOKE:
2903 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2904 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2905 if (method->is_inflated) {
2906 /* These wrappers are identified by their class */
2907 encode_value (1, p, &p);
2908 encode_klass_ref (acfg, method->klass, p, &p);
2910 MonoMethodSignature *sig = mono_method_signature (method);
2911 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2913 encode_value (0, p, &p);
2914 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2915 encode_value (info ? info->subtype : 0, p, &p);
2916 encode_signature (acfg, sig, p, &p);
2920 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2921 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2924 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2925 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2929 g_assert_not_reached ();
2931 } else if (mono_method_signature (method)->is_inflated) {
2933 * This is a generic method, find the original token which referenced it and
2935 * Obtain the token from information recorded by the JIT.
2937 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2939 image_index = get_image_index (acfg, ji->image);
2940 g_assert (image_index < MAX_IMAGE_INDEX);
2943 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2944 encode_value (image_index, p, &p);
2945 encode_value (token, p, &p);
2947 MonoMethod *declaring;
2948 MonoGenericContext *context = mono_method_get_context (method);
2950 g_assert (method->is_inflated);
2951 declaring = ((MonoMethodInflated*)method)->declaring;
2954 * This might be a non-generic method of a generic instance, which
2955 * doesn't have a token since the reference is generated by the JIT
2956 * like Nullable:Box/Unbox, or by generic sharing.
2958 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2959 /* Encode the klass */
2960 encode_klass_ref (acfg, method->klass, p, &p);
2961 /* Encode the method */
2962 image_index = get_image_index (acfg, method->klass->image);
2963 g_assert (image_index < MAX_IMAGE_INDEX);
2964 g_assert (declaring->token);
2965 token = declaring->token;
2966 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2967 encode_value (image_index, p, &p);
2968 encode_value (token, p, &p);
2969 encode_generic_context (acfg, context, p, &p);
2971 } else if (token == 0) {
2972 /* This might be a method of a constructed type like int[,].Set */
2973 /* Obtain the token from information recorded by the JIT */
2974 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2976 image_index = get_image_index (acfg, ji->image);
2977 g_assert (image_index < MAX_IMAGE_INDEX);
2980 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2981 encode_value (image_index, p, &p);
2982 encode_value (token, p, &p);
2985 g_assert (method->klass->rank);
2987 /* Encode directly */
2988 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2989 encode_klass_ref (acfg, method->klass, p, &p);
2990 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2991 encode_value (0, p, &p);
2992 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2993 encode_value (1, p, &p);
2994 else if (!strcmp (method->name, "Get"))
2995 encode_value (2, p, &p);
2996 else if (!strcmp (method->name, "Address"))
2997 encode_value (3, p, &p);
2998 else if (!strcmp (method->name, "Set"))
2999 encode_value (4, p, &p);
3001 g_assert_not_reached ();
3004 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3006 if (image_index >= MONO_AOT_METHODREF_MIN) {
3007 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3008 encode_value (image_index, p, &p);
3009 encode_value (mono_metadata_token_index (token), p, &p);
3011 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3018 compare_patches (gconstpointer a, gconstpointer b)
3022 i = (*(MonoJumpInfo**)a)->ip.i;
3023 j = (*(MonoJumpInfo**)b)->ip.i;
3034 static G_GNUC_UNUSED char*
3035 patch_to_string (MonoJumpInfo *patch_info)
3039 str = g_string_new ("");
3041 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3043 switch (patch_info->type) {
3044 case MONO_PATCH_INFO_VTABLE:
3045 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3050 g_string_append_printf (str, ")");
3051 return g_string_free (str, FALSE);
3057 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3060 static inline gboolean
3061 is_plt_patch (MonoJumpInfo *patch_info)
3063 switch (patch_info->type) {
3064 case MONO_PATCH_INFO_METHOD:
3065 case MONO_PATCH_INFO_INTERNAL_METHOD:
3066 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3067 case MONO_PATCH_INFO_ICALL_ADDR:
3068 case MONO_PATCH_INFO_CLASS_INIT:
3069 case MONO_PATCH_INFO_RGCTX_FETCH:
3070 case MONO_PATCH_INFO_MONITOR_ENTER:
3071 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3072 case MONO_PATCH_INFO_MONITOR_EXIT:
3073 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3083 * Return the symbol identifying the plt entry PLT_OFFSET.
3086 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3090 * The Apple linker reorganizes object files, so it doesn't like branches to local
3091 * labels, since those have no relocations.
3093 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3095 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3102 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3104 static MonoPltEntry*
3105 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3108 gboolean synchronized = FALSE;
3109 static int synchronized_symbol_idx;
3111 if (!is_plt_patch (patch_info))
3114 if (!acfg->patch_to_plt_entry [patch_info->type])
3115 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3116 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3118 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3120 * Allocate a separate PLT slot for each such patch, since some plt
3121 * entries will refer to the method itself, and some will refer to the
3125 synchronized = TRUE;
3129 MonoJumpInfo *new_ji;
3131 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3133 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3134 res->plt_offset = acfg->plt_offset;
3136 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3137 if (acfg->aot_opts.write_symbols)
3138 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3140 /* Avoid duplicate symbols because we don't cache */
3141 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3143 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3144 synchronized_symbol_idx ++;
3147 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3149 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3151 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3153 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3155 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3156 //mono_print_ji (patch_info); printf ("\n");
3157 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3159 acfg->plt_offset ++;
3168 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3169 * JI could be found if it exists, otherwise allocates a new one.
3172 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3175 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3177 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3179 return got_offset - 1;
3182 got_offset = acfg->llvm_got_offset;
3183 acfg->llvm_got_offset ++;
3185 got_offset = acfg->got_offset;
3186 acfg->got_offset ++;
3189 acfg->stats.got_slots ++;
3190 acfg->stats.got_slot_types [ji->type] ++;
3192 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3193 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3194 g_ptr_array_add (info->got_patches, ji);
3199 /* Add a method to the list of methods which need to be emitted */
3201 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3204 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3205 g_ptr_array_add (acfg->methods, method);
3206 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3207 acfg->nmethods = acfg->methods->len + 1;
3210 if (method->wrapper_type || extra)
3211 g_ptr_array_add (acfg->extra_methods, method);
3215 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3217 /* One instantiation with valuetypes is generated for each async method */
3218 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3225 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3227 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3235 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3239 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3243 index = acfg->method_index;
3244 add_method_with_index (acfg, method, index, extra);
3246 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3248 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3250 acfg->method_index ++;
3256 add_method (MonoAotCompile *acfg, MonoMethod *method)
3258 return add_method_full (acfg, method, FALSE, 0);
3262 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3264 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3265 method = mini_get_shared_method (method);
3266 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3267 /* Use the gsharedvt version */
3270 if (acfg->aot_opts.log_generics)
3271 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3273 add_method_full (acfg, method, TRUE, depth);
3277 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3279 add_extra_method_with_depth (acfg, method, 0);
3283 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3285 MonoAotCompile *acfg = user_data;
3286 MonoJitICallInfo *callinfo = value;
3287 MonoMethod *wrapper;
3293 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3294 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3297 add_method (acfg, wrapper);
3301 get_runtime_invoke_sig (MonoMethodSignature *sig)
3303 MonoMethodBuilder *mb;
3306 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3307 m = mono_mb_create_method (mb, sig, 16);
3308 return mono_marshal_get_runtime_invoke (m, FALSE);
3312 can_marshal_struct (MonoClass *klass)
3314 MonoClassField *field;
3315 gboolean can_marshal = TRUE;
3316 gpointer iter = NULL;
3317 MonoMarshalType *info;
3320 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3323 info = mono_marshal_load_type_info (klass);
3325 /* Only allow a few field types to avoid asserts in the marshalling code */
3326 while ((field = mono_class_get_fields (klass, &iter))) {
3327 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3330 switch (field->type->type) {
3335 case MONO_TYPE_BOOLEAN:
3338 case MONO_TYPE_CHAR:
3346 case MONO_TYPE_STRING:
3348 case MONO_TYPE_VALUETYPE:
3349 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3350 can_marshal = FALSE;
3352 case MONO_TYPE_SZARRAY: {
3353 gboolean has_mspec = FALSE;
3356 for (i = 0; i < info->num_fields; ++i) {
3357 if (info->fields [i].field == field && info->fields [i].mspec)
3362 can_marshal = FALSE;
3366 can_marshal = FALSE;
3372 /* Its hard to compute whenever these can be marshalled or not */
3373 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3380 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3382 /* Create a vtype instantiation */
3383 MonoGenericContext shared_context;
3385 MonoGenericInst *inst;
3386 MonoGenericContainer *container;
3387 MonoClass **constraints;
3390 memset (ctx, 0, sizeof (MonoGenericContext));
3392 if (method->klass->generic_container) {
3393 shared_context = method->klass->generic_container->context;
3394 inst = shared_context.class_inst;
3396 args = g_new0 (MonoType*, inst->type_argc);
3397 for (i = 0; i < inst->type_argc; ++i) {
3398 args [i] = &mono_defaults.int_class->byval_arg;
3400 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3402 if (method->is_generic) {
3403 container = mono_method_get_generic_container (method);
3404 shared_context = container->context;
3405 inst = shared_context.method_inst;
3407 args = g_new0 (MonoType*, inst->type_argc);
3408 for (i = 0; i < container->type_argc; ++i) {
3409 MonoGenericParamInfo *info = &container->type_params [i].info;
3410 gboolean ref_only = FALSE;
3412 if (info && info->constraints) {
3413 constraints = info->constraints;
3415 while (*constraints) {
3416 MonoClass *cklass = *constraints;
3417 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3418 /* Inflaring the method with our vtype would not be valid */
3425 args [i] = &mono_defaults.object_class->byval_arg;
3427 args [i] = &mono_defaults.int_class->byval_arg;
3429 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3434 add_wrappers (MonoAotCompile *acfg)
3436 MonoMethod *method, *m;
3438 MonoMethodSignature *sig, *csig;
3442 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3443 * so there is only one wrapper of a given type, or inlining their contents into their
3446 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3449 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3450 gboolean skip = FALSE;
3452 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3453 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3455 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3456 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3457 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3460 /* Skip methods which can not be handled by get_runtime_invoke () */
3461 sig = mono_method_signature (method);
3464 if ((sig->ret->type == MONO_TYPE_PTR) ||
3465 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3467 if (mono_class_is_open_constructed_type (sig->ret))
3470 for (j = 0; j < sig->param_count; j++) {
3471 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3473 if (mono_class_is_open_constructed_type (sig->params [j]))
3477 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3478 if (!mono_class_is_contextbound (method->klass)) {
3479 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3480 gboolean has_nullable = FALSE;
3482 for (j = 0; j < sig->param_count; j++) {
3483 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3484 has_nullable = TRUE;
3487 if (info && !has_nullable) {
3488 /* Supported by the dynamic runtime-invoke wrapper */
3492 mono_arch_dyn_call_free (info);
3497 //printf ("%s\n", mono_method_full_name (method, TRUE));
3498 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3502 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3505 /* Runtime invoke wrappers */
3507 /* void runtime-invoke () [.cctor] */
3508 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3509 csig->ret = &mono_defaults.void_class->byval_arg;
3510 add_method (acfg, get_runtime_invoke_sig (csig));
3512 /* void runtime-invoke () [Finalize] */
3513 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3515 csig->ret = &mono_defaults.void_class->byval_arg;
3516 add_method (acfg, get_runtime_invoke_sig (csig));
3518 /* void runtime-invoke (string) [exception ctor] */
3519 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3521 csig->ret = &mono_defaults.void_class->byval_arg;
3522 csig->params [0] = &mono_defaults.string_class->byval_arg;
3523 add_method (acfg, get_runtime_invoke_sig (csig));
3525 /* void runtime-invoke (string, string) [exception ctor] */
3526 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3528 csig->ret = &mono_defaults.void_class->byval_arg;
3529 csig->params [0] = &mono_defaults.string_class->byval_arg;
3530 csig->params [1] = &mono_defaults.string_class->byval_arg;
3531 add_method (acfg, get_runtime_invoke_sig (csig));
3533 /* string runtime-invoke () [Exception.ToString ()] */
3534 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3536 csig->ret = &mono_defaults.string_class->byval_arg;
3537 add_method (acfg, get_runtime_invoke_sig (csig));
3539 /* void runtime-invoke (string, Exception) [exception ctor] */
3540 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3542 csig->ret = &mono_defaults.void_class->byval_arg;
3543 csig->params [0] = &mono_defaults.string_class->byval_arg;
3544 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3545 add_method (acfg, get_runtime_invoke_sig (csig));
3547 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3548 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3550 csig->ret = &(mono_class_from_name (
3551 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3552 csig->params [0] = &mono_defaults.string_class->byval_arg;
3553 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3554 add_method (acfg, get_runtime_invoke_sig (csig));
3556 /* runtime-invoke used by finalizers */
3557 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3559 /* This is used by mono_runtime_capture_context () */
3560 method = mono_get_context_capture_method ();
3562 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3564 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3565 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3569 add_method (acfg, mono_marshal_get_stelemref ());
3571 if (MONO_ARCH_HAVE_TLS_GET) {
3572 /* Managed Allocators */
3573 nallocators = mono_gc_get_managed_allocator_types ();
3574 for (i = 0; i < nallocators; ++i) {
3575 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3577 add_method (acfg, m);
3579 for (i = 0; i < nallocators; ++i) {
3580 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3582 add_method (acfg, m);
3586 /* write barriers */
3587 if (mono_gc_is_moving ()) {
3588 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3589 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3592 /* Stelemref wrappers */
3594 MonoMethod **wrappers;
3597 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3598 for (i = 0; i < nwrappers; ++i)
3599 add_method (acfg, wrappers [i]);
3603 /* castclass_with_check wrapper */
3604 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3605 /* isinst_with_check wrapper */
3606 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3608 /* JIT icall wrappers */
3609 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3610 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3614 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3615 * we use the original method instead at runtime.
3616 * Since full-aot doesn't support remoting, this is not a problem.
3619 /* remoting-invoke wrappers */
3620 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3621 MonoMethodSignature *sig;
3623 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3624 method = mono_get_method (acfg->image, token, NULL);
3626 sig = mono_method_signature (method);
3628 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3629 m = mono_marshal_get_remoting_invoke_with_check (method);
3631 add_method (acfg, m);
3636 /* delegate-invoke wrappers */
3637 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3640 MonoCustomAttrInfo *cattr;
3642 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3643 klass = mono_class_get_checked (acfg->image, token, &error);
3646 mono_error_cleanup (&error);
3650 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3653 if (!klass->generic_container) {
3654 method = mono_get_delegate_invoke (klass);
3656 m = mono_marshal_get_delegate_invoke (method, NULL);
3658 add_method (acfg, m);
3660 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3662 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3664 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3666 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3668 cattr = mono_custom_attrs_from_class (klass);
3673 for (j = 0; j < cattr->num_attrs; ++j)
3674 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3676 if (j < cattr->num_attrs) {
3678 MonoMethod *wrapper;
3679 MonoMethod *del_invoke;
3681 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3682 invoke = mono_get_delegate_invoke (klass);
3683 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3684 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3685 add_method (acfg, wrapper);
3686 add_method (acfg, del_invoke);
3689 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3691 MonoGenericContext ctx;
3692 MonoMethod *inst, *gshared;
3695 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3698 method = mono_get_delegate_invoke (klass);
3699 create_gsharedvt_inst (acfg, method, &ctx);
3701 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3702 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3704 m = mono_marshal_get_delegate_invoke (inst, NULL);
3705 g_assert (m->is_inflated);
3707 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3708 add_extra_method (acfg, gshared);
3711 method = mono_get_delegate_begin_invoke (klass);
3712 create_gsharedvt_inst (acfg, method, &ctx);
3714 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3715 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3717 m = mono_marshal_get_delegate_begin_invoke (inst);
3718 g_assert (m->is_inflated);
3720 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3721 add_extra_method (acfg, gshared);
3724 method = mono_get_delegate_end_invoke (klass);
3725 create_gsharedvt_inst (acfg, method, &ctx);
3727 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3728 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3730 m = mono_marshal_get_delegate_end_invoke (inst);
3731 g_assert (m->is_inflated);
3733 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3734 add_extra_method (acfg, gshared);
3739 /* array access wrappers */
3740 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3744 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3745 klass = mono_class_get_checked (acfg->image, token, &error);
3748 mono_error_cleanup (&error);
3752 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3753 MonoMethod *m, *wrapper;
3755 /* Add runtime-invoke wrappers too */
3757 m = mono_class_get_method_from_name (klass, "Get", -1);
3759 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3760 add_extra_method (acfg, wrapper);
3761 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3763 m = mono_class_get_method_from_name (klass, "Set", -1);
3765 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3766 add_extra_method (acfg, wrapper);
3767 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3771 /* Synchronized wrappers */
3772 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3774 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3775 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3776 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3778 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3779 if (method->is_generic) {
3781 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3783 MonoGenericContext ctx;
3784 MonoMethod *inst, *gshared, *m;
3787 * Create a generic wrapper for a generic instance, and AOT that.
3789 create_gsharedvt_inst (acfg, method, &ctx);
3790 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3791 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3792 m = mono_marshal_get_synchronized_wrapper (inst);
3793 g_assert (m->is_inflated);
3794 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3795 add_method (acfg, gshared);
3797 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3802 /* pinvoke wrappers */
3803 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3806 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3808 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3809 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3811 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3812 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3813 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3817 /* native-to-managed wrappers */
3818 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3821 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3822 MonoCustomAttrInfo *cattr;
3825 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3826 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3829 * Only generate native-to-managed wrappers for methods which have an
3830 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3831 * name to avoid defining a new assembly to contain it.
3833 cattr = mono_custom_attrs_from_method (method);
3836 for (j = 0; j < cattr->num_attrs; ++j)
3837 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3839 if (j < cattr->num_attrs) {
3840 MonoCustomAttrEntry *e = &cattr->attrs [j];
3841 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3842 const char *p = (const char*)e->data;
3844 int slen, num_named, named_type;
3848 char *export_name = NULL;
3849 MonoMethod *wrapper;
3851 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3852 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3853 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3854 mono_method_full_name (method, TRUE));
3858 g_assert (sig->param_count == 1);
3859 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3862 * Decode the cattr manually since we can't create objects
3863 * during aot compilation.
3869 /* From load_cattr_value () in reflection.c */
3870 slen = mono_metadata_decode_value (p, &p);
3871 n = g_memdup (p, slen + 1);
3873 t = mono_reflection_type_from_name (n, acfg->image);
3877 klass = mono_class_from_mono_type (t);
3878 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3882 num_named = read16 (p);
3885 g_assert (num_named < 2);
3886 if (num_named == 1) {
3890 /* parse ExportSymbol attribute */
3892 named_type = *named;
3894 /* data_type = *named; */
3897 name_len = mono_metadata_decode_blob_size (named, &named);
3898 name = g_malloc (name_len + 1);
3899 memcpy (name, named, name_len);
3900 name [name_len] = 0;
3903 g_assert (named_type == 0x54);
3904 g_assert (!strcmp (name, "ExportSymbol"));
3906 /* load_cattr_value (), string case */
3907 g_assert (*named != (char)0xff);
3908 slen = mono_metadata_decode_value (named, &named);
3909 export_name = g_malloc (slen + 1);
3910 memcpy (export_name, named, slen);
3911 export_name [slen] = 0;
3915 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3916 add_method (acfg, wrapper);
3918 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3922 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3923 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3924 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3928 /* StructureToPtr/PtrToStructure wrappers */
3929 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3933 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3934 klass = mono_class_get_checked (acfg->image, token, &error);
3937 mono_error_cleanup (&error);
3941 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3942 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3943 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3944 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3950 has_type_vars (MonoClass *klass)
3952 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3955 return has_type_vars (klass->element_class);
3956 if (klass->generic_class) {
3957 MonoGenericContext *context = &klass->generic_class->context;
3958 if (context->class_inst) {
3961 for (i = 0; i < context->class_inst->type_argc; ++i)
3962 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3966 if (klass->generic_container)
3972 is_vt_inst (MonoGenericInst *inst)
3976 for (i = 0; i < inst->type_argc; ++i) {
3977 MonoType *t = inst->type_argv [i];
3978 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3985 method_has_type_vars (MonoMethod *method)
3987 if (has_type_vars (method->klass))
3990 if (method->is_inflated) {
3991 MonoGenericContext *context = mono_method_get_context (method);
3992 if (context->method_inst) {
3995 for (i = 0; i < context->method_inst->type_argc; ++i)
3996 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4004 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4006 return opts->mode == MONO_AOT_MODE_FULL;
4009 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4012 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4014 /* This might lead to a huge code blowup so only do it if neccesary */
4015 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4018 add_generic_class_with_depth (acfg, klass, 0, ref);
4022 check_type_depth (MonoType *t, int depth)
4030 case MONO_TYPE_GENERICINST: {
4031 MonoGenericClass *gklass = t->data.generic_class;
4032 MonoGenericInst *ginst = gklass->context.class_inst;
4035 for (i = 0; i < ginst->type_argc; ++i) {
4036 if (check_type_depth (ginst->type_argv [i], depth + 1))
4050 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4053 * add_generic_class:
4055 * Add all methods of a generic class.
4058 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4061 MonoClassField *field;
4063 gboolean use_gsharedvt = FALSE;
4065 if (!acfg->ginst_hash)
4066 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4068 mono_class_init (klass);
4070 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4073 if (has_type_vars (klass))
4076 if (!klass->generic_class && !klass->rank)
4079 if (klass->exception_type)
4082 if (!acfg->ginst_hash)
4083 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4085 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4088 if (check_type_depth (&klass->byval_arg, 0))
4091 if (acfg->aot_opts.log_generics)
4092 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4094 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4097 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4098 * Enable this only for some classes since gsharedvt might not support all methods.
4100 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && klass->generic_class && klass->generic_class->context.class_inst && is_vt_inst (klass->generic_class->context.class_inst) &&
4101 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4102 use_gsharedvt = TRUE;
4105 while ((method = mono_class_get_methods (klass, &iter))) {
4106 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4108 * This is partial sharing, and we can't handle it yet
4113 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4115 add_types_from_method_header (acfg, method);
4119 if (method->is_generic)
4124 * FIXME: Instances which are referenced by these methods are not added,
4125 * for example Array.Resize<int> for List<int>.Add ().
4127 add_extra_method_with_depth (acfg, method, depth + 1);
4131 while ((field = mono_class_get_fields (klass, &iter))) {
4132 if (field->type->type == MONO_TYPE_GENERICINST)
4133 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4136 if (klass->delegate) {
4137 method = mono_get_delegate_invoke (klass);
4139 method = mono_marshal_get_delegate_invoke (method, NULL);
4141 if (acfg->aot_opts.log_generics)
4142 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4144 add_method (acfg, method);
4147 /* Add superclasses */
4149 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4152 * For ICollection<T>, add instances of the helper methods
4153 * in Array, since a T[] could be cast to ICollection<T>.
4155 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4156 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1") || !strcmp (klass->name, "IReadOnlyList`1"))) {
4157 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4158 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4162 if (!strcmp (klass->name, "IEnumerator`1"))
4163 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4165 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4167 /* Add the T[]/InternalEnumerator class */
4168 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4172 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4173 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4177 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4178 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4182 while ((method = mono_class_get_methods (array_class, &iter))) {
4183 if (strstr (method->name, name_prefix)) {
4184 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4186 add_extra_method_with_depth (acfg, m, depth);
4190 g_free (name_prefix);
4193 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4194 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4195 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4196 MonoClass *icomparable, *gcomparer;
4197 MonoGenericContext ctx;
4198 MonoType *args [16];
4200 memset (&ctx, 0, sizeof (ctx));
4202 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4203 g_assert (icomparable);
4204 args [0] = &tclass->byval_arg;
4205 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4207 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4208 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4209 g_assert (gcomparer);
4210 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4214 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4215 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4216 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4217 MonoClass *iface, *gcomparer;
4218 MonoGenericContext ctx;
4219 MonoType *args [16];
4221 memset (&ctx, 0, sizeof (ctx));
4223 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4225 args [0] = &tclass->byval_arg;
4226 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4228 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4229 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4230 g_assert (gcomparer);
4231 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4235 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4236 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4237 MonoClass *enum_comparer;
4238 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4239 MonoGenericContext ctx;
4240 MonoType *args [16];
4242 if (mono_class_is_enum (tclass)) {
4243 memset (&ctx, 0, sizeof (ctx));
4244 args [0] = &tclass->byval_arg;
4245 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4247 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4248 g_assert (enum_comparer);
4249 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4255 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4258 MonoGenericContext ctx;
4259 MonoType *args [16];
4261 if (acfg->aot_opts.no_instances)
4264 memset (&ctx, 0, sizeof (ctx));
4266 for (i = 0; i < ninsts; ++i) {
4267 args [0] = insts [i];
4268 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4269 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4274 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4276 MonoMethodHeader *header;
4277 MonoMethodSignature *sig;
4280 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4282 sig = mono_method_signature (method);
4285 for (j = 0; j < sig->param_count; ++j)
4286 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4287 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4290 header = mono_method_get_header (method);
4293 for (j = 0; j < header->num_locals; ++j)
4294 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4295 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4297 mono_loader_clear_error ();
4302 * add_generic_instances:
4304 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4307 add_generic_instances (MonoAotCompile *acfg)
4312 MonoGenericContext *context;
4314 if (acfg->aot_opts.no_instances)
4317 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4319 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4320 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4323 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4324 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4325 mono_error_cleanup (&error);
4329 if (method->klass->image != acfg->image)
4332 context = mono_method_get_context (method);
4334 if (context && ((context->class_inst && context->class_inst->is_open)))
4338 * For open methods, create an instantiation which can be passed to the JIT.
4339 * FIXME: Handle class_inst as well.
4341 if (context && context->method_inst && context->method_inst->is_open) {
4343 MonoGenericContext shared_context;
4344 MonoGenericInst *inst;
4345 MonoType **type_argv;
4347 MonoMethod *declaring_method;
4348 gboolean supported = TRUE;
4350 /* Check that the context doesn't contain open constructed types */
4351 if (context->class_inst) {
4352 inst = context->class_inst;
4353 for (i = 0; i < inst->type_argc; ++i) {
4354 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)
4356 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4360 if (context->method_inst) {
4361 inst = context->method_inst;
4362 for (i = 0; i < inst->type_argc; ++i) {
4363 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)
4365 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4373 memset (&shared_context, 0, sizeof (MonoGenericContext));
4375 inst = context->class_inst;
4377 type_argv = g_new0 (MonoType*, inst->type_argc);
4378 for (i = 0; i < inst->type_argc; ++i) {
4379 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)
4380 type_argv [i] = &mono_defaults.object_class->byval_arg;
4382 type_argv [i] = inst->type_argv [i];
4385 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4389 inst = context->method_inst;
4391 type_argv = g_new0 (MonoType*, inst->type_argc);
4392 for (i = 0; i < inst->type_argc; ++i) {
4393 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)
4394 type_argv [i] = &mono_defaults.object_class->byval_arg;
4396 type_argv [i] = inst->type_argv [i];
4399 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4403 if (method->is_generic || method->klass->generic_container)
4404 declaring_method = method;
4406 declaring_method = mono_method_get_declaring_generic_method (method);
4408 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4409 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4413 * If the method is fully sharable, it was already added in place of its
4414 * generic definition.
4416 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4420 * FIXME: Partially shared methods are not shared here, so we end up with
4421 * many identical methods.
4423 add_extra_method (acfg, method);
4426 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4430 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4432 klass = mono_class_get_checked (acfg->image, token, &error);
4433 if (!klass || klass->rank) {
4434 mono_error_cleanup (&error);
4438 add_generic_class (acfg, klass, FALSE, "typespec");
4441 /* Add types of args/locals */
4442 for (i = 0; i < acfg->methods->len; ++i) {
4443 method = g_ptr_array_index (acfg->methods, i);
4444 add_types_from_method_header (acfg, method);
4447 if (acfg->image == mono_defaults.corlib) {
4449 MonoType *insts [256];
4452 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4453 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4454 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4455 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4456 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4457 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4458 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4459 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4460 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4461 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4462 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4463 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4465 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4466 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4468 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4469 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4471 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4473 /* Add instances of the array generic interfaces for primitive types */
4474 /* This will add instances of the InternalArray_ helper methods in Array too */
4475 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4477 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4478 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4480 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4481 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4483 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4486 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4487 * used for all instances of GetGenericValueImpl by the AOT runtime.
4490 MonoGenericContext ctx;
4491 MonoType *args [16];
4492 MonoMethod *get_method;
4493 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4495 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4499 memset (&ctx, 0, sizeof (ctx));
4500 args [0] = &mono_defaults.object_class->byval_arg;
4501 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4502 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4503 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4507 /* Same for CompareExchange<T>/Exchange<T> */
4509 MonoGenericContext ctx;
4510 MonoType *args [16];
4512 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4513 gpointer iter = NULL;
4515 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4516 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
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 (m, &ctx, &error), TRUE, TRUE));
4522 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4527 /* Same for Volatile.Read/Write<T> */
4529 MonoGenericContext ctx;
4530 MonoType *args [16];
4532 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4533 gpointer iter = NULL;
4535 if (volatile_klass) {
4536 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4537 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4539 memset (&ctx, 0, sizeof (ctx));
4540 args [0] = &mono_defaults.object_class->byval_arg;
4541 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4542 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4543 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4552 * is_direct_callable:
4554 * Return whenever the method identified by JI is directly callable without
4555 * going through the PLT.
4558 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4560 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4561 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4563 gboolean direct_callable = TRUE;
4565 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4566 direct_callable = FALSE;
4567 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4568 // FIXME: Maybe call the wrapper directly ?
4569 direct_callable = FALSE;
4571 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4572 /* Disable this so all calls go through load_method (), see the
4573 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4574 * mono_debugger_agent_init ().
4576 direct_callable = FALSE;
4579 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4580 /* sgen does some initialization when the allocator method is created */
4581 direct_callable = FALSE;
4582 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4583 /* we don't know at compile time whether sgen is concurrent or not */
4584 direct_callable = FALSE;
4586 if (direct_callable)
4589 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4590 if (acfg->aot_opts.direct_pinvoke)
4592 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4593 if (acfg->aot_opts.direct_icalls)
4601 #ifdef MONO_ARCH_AOT_SUPPORTED
4603 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4605 MonoImage *image = method->klass->image;
4606 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4607 MonoTableInfo *tables = image->tables;
4608 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4609 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4610 guint32 im_cols [MONO_IMPLMAP_SIZE];
4613 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4617 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4620 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4622 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4625 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4627 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4634 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4636 if (a->native_offset == b->native_offset)
4637 return a->il_offset - b->il_offset;
4639 return a->native_offset - b->native_offset;
4643 * compute_line_numbers:
4645 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4648 static MonoDebugSourceLocation**
4649 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4651 MonoDebugMethodInfo *minfo;
4652 MonoDebugLineNumberEntry *ln_array;
4653 MonoDebugSourceLocation *loc;
4654 int i, prev_line, prev_il_offset;
4655 int *native_to_il_offset = NULL;
4656 MonoDebugSourceLocation **res;
4659 minfo = mono_debug_lookup_method (method);
4662 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4663 if (debug_info->code_size != code_size)
4666 g_assert (code_size);
4668 /* Compute the native->IL offset mapping */
4670 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4671 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4673 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4675 native_to_il_offset = g_new0 (int, code_size + 1);
4677 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4679 MonoDebugLineNumberEntry *lne = &ln_array [i];
4682 for (j = 0; j < lne->native_offset; ++j)
4683 native_to_il_offset [j] = -1;
4686 if (i < debug_info->num_line_numbers - 1) {
4687 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4689 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4690 native_to_il_offset [j] = lne->il_offset;
4692 for (j = lne->native_offset; j < code_size; ++j)
4693 native_to_il_offset [j] = lne->il_offset;
4698 /* Compute the native->line number mapping */
4699 res = g_new0 (MonoDebugSourceLocation*, code_size);
4700 prev_il_offset = -1;
4703 for (i = 0; i < code_size; ++i) {
4704 int il_offset = native_to_il_offset [i];
4706 if (il_offset == -1 || il_offset == prev_il_offset)
4708 prev_il_offset = il_offset;
4709 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4710 if (!(loc && loc->source_file))
4712 if (loc->row == prev_line) {
4713 mono_debug_symfile_free_location (loc);
4716 prev_line = loc->row;
4717 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4719 /* This will cover the prolog too */
4729 get_file_index (MonoAotCompile *acfg, const char *source_file)
4733 // FIXME: Free these
4734 if (!acfg->dwarf_ln_filenames)
4735 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4736 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4738 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4739 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4740 emit_unset_mode (acfg);
4741 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4753 * emit_and_reloc_code:
4755 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4756 * is true, calls are made through the GOT too. This is used for emitting trampolines
4757 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4758 * since trampolines are needed to make PTL work.
4761 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4763 int i, pindex, start_index;
4765 MonoJumpInfo *patch_info;
4766 MonoDebugSourceLocation **locs = NULL;
4768 #ifdef MONO_ARCH_AOT_SUPPORTED
4769 gboolean direct_call, external_call;
4771 const char *direct_call_target = 0;
4772 const char *direct_pinvoke;
4775 if (acfg->gas_line_numbers && method && debug_info) {
4776 locs = compute_line_numbers (method, code_len, debug_info);
4778 int findex = get_file_index (acfg, "<unknown>");
4779 emit_unset_mode (acfg);
4780 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4784 /* Collect and sort relocations */
4785 patches = g_ptr_array_new ();
4786 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4787 g_ptr_array_add (patches, patch_info);
4788 g_ptr_array_sort (patches, compare_patches);
4791 for (i = 0; i < code_len; i += INST_LEN) {
4793 for (pindex = start_index; pindex < patches->len; ++pindex) {
4794 patch_info = g_ptr_array_index (patches, pindex);
4795 if (patch_info->ip.i >= i)
4799 if (locs && locs [i]) {
4800 MonoDebugSourceLocation *loc = locs [i];
4803 findex = get_file_index (acfg, loc->source_file);
4804 emit_unset_mode (acfg);
4805 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4806 mono_debug_symfile_free_location (loc);
4810 #ifdef MONO_ARCH_AOT_SUPPORTED
4811 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4812 start_index = pindex;
4814 switch (patch_info->type) {
4815 case MONO_PATCH_INFO_NONE:
4817 case MONO_PATCH_INFO_GOT_OFFSET: {
4820 arch_emit_got_offset (acfg, code + i, &code_size);
4821 i += code_size - INST_LEN;
4823 patch_info->type = MONO_PATCH_INFO_NONE;
4826 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4827 int code_size, index;
4828 char *selector = (void*)patch_info->data.target;
4830 if (!acfg->objc_selector_to_index)
4831 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4832 if (!acfg->objc_selectors)
4833 acfg->objc_selectors = g_ptr_array_new ();
4834 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4838 index = acfg->objc_selector_index;
4839 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4840 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4841 acfg->objc_selector_index ++;
4844 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4845 i += code_size - INST_LEN;
4847 patch_info->type = MONO_PATCH_INFO_NONE;
4852 * If this patch is a call, try emitting a direct call instead of
4853 * through a PLT entry. This is possible if the called method is in
4854 * the same assembly and requires no initialization.
4856 direct_call = FALSE;
4857 external_call = FALSE;
4858 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4859 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4860 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4861 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4863 direct_call_target = callee_cfg->asm_symbol;
4864 patch_info->type = MONO_PATCH_INFO_NONE;
4865 acfg->stats.direct_calls ++;
4868 acfg->stats.all_calls ++;
4869 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4870 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4871 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4872 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4874 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4875 if (direct_pinvoke) {
4877 g_assert (strlen (direct_pinvoke) < 1000);
4878 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4881 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4882 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4883 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4884 /* Call to a C function implementing a jit icall */
4886 external_call = TRUE;
4887 g_assert (strlen (sym) < 1000);
4888 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4890 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4891 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4892 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4893 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4894 /* Call to a jit icall without a wrapper */
4896 external_call = TRUE;
4897 g_assert (strlen (sym) < 1000);
4898 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4903 patch_info->type = MONO_PATCH_INFO_NONE;
4904 acfg->stats.direct_calls ++;
4907 if (!got_only && !direct_call) {
4908 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4910 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4912 direct_call_target = plt_entry->symbol;
4914 /* Nullify the patch */
4915 patch_info->type = MONO_PATCH_INFO_NONE;
4916 plt_entry->jit_used = TRUE;
4923 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4924 i += call_size - INST_LEN;
4928 got_slot = get_got_offset (acfg, FALSE, patch_info);
4930 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
4931 i += code_size - INST_LEN;
4937 #endif /* MONO_ARCH_AOT_SUPPORTED */
4940 /* Find next patch */
4942 for (pindex = start_index; pindex < patches->len; ++pindex) {
4943 patch_info = g_ptr_array_index (patches, pindex);
4944 if (patch_info->ip.i >= i)
4948 /* Try to emit multiple bytes at once */
4949 if (pindex < patches->len && patch_info->ip.i > i) {
4952 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4953 if (locs && locs [limit])
4957 emit_code_bytes (acfg, code + i, limit - i);
4958 i = limit - INST_LEN;
4960 emit_code_bytes (acfg, code + i, INST_LEN);
4971 * Return a modified version of S which only includes characters permissible in symbols.
4974 sanitize_symbol (MonoAotCompile *acfg, char *s)
4976 gboolean process = FALSE;
4985 for (i = 0; i < len; ++i)
4986 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4991 gs = g_string_sized_new (len);
4992 for (i = 0; i < len; ++i) {
4994 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4995 g_string_append_c (gs, c);
4996 } else if (c > 0x7f) {
4997 /* multi-byte utf8 */
4998 g_string_append_printf (gs, "_0x%x", c);
5001 while (c >> 6 == 0x2) {
5002 g_string_append_printf (gs, "%x", c);
5006 g_string_append_printf (gs, "_");
5009 g_string_append_c (gs, '_');
5013 res = mono_mempool_strdup (acfg->mempool, gs->str);
5014 g_string_free (gs, TRUE);
5019 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5021 char *name1, *name2, *cached;
5022 int i, j, len, count;
5023 MonoMethod *cached_method;
5025 name1 = mono_method_full_name (method, TRUE);
5028 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5029 if ((!prefix || !*prefix) && name1 [0] == 'L')
5033 len = strlen (name1);
5034 name2 = malloc (strlen (prefix) + len + 16);
5035 memcpy (name2, prefix, strlen (prefix));
5036 j = strlen (prefix);
5037 for (i = 0; i < len; ++i) {
5038 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5040 } else if (isalnum (name1 [i])) {
5041 name2 [j ++] = name1 [i];
5042 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5044 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5047 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5057 cached_method = g_hash_table_lookup (cache, name2);
5058 if (!(cached_method && cached_method != method))
5060 sprintf (name2 + j, "_%d", count);
5064 cached = g_strdup (name2);
5065 g_hash_table_insert (cache, cached, method);
5071 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5076 char *debug_sym = NULL;
5077 char *symbol = NULL;
5078 int func_alignment = AOT_FUNC_ALIGNMENT;
5081 method = cfg->orig_method;
5082 code = cfg->native_code;
5084 method_index = get_method_index (acfg, method);
5085 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5087 /* Make the labels local */
5088 emit_section_change (acfg, ".text", 0);
5089 emit_alignment_code (acfg, func_alignment);
5091 if (acfg->global_symbols && acfg->need_no_dead_strip)
5092 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5094 emit_label (acfg, cfg->asm_symbol);
5096 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5098 * Write a C style symbol for every method, this has two uses:
5099 * - it works on platforms where the dwarf debugging info is not
5101 * - it allows the setting of breakpoints of aot-ed methods.
5103 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5104 cfg->asm_debug_symbol = g_strdup (debug_sym);
5106 if (acfg->need_no_dead_strip)
5107 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5108 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5109 emit_label (acfg, debug_sym);
5112 export_name = g_hash_table_lookup (acfg->export_names, method);
5114 /* Emit a global symbol for the method */
5115 emit_global_inner (acfg, export_name, TRUE);
5116 emit_label (acfg, export_name);
5119 if (cfg->verbose_level > 0)
5120 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5122 acfg->stats.code_size += cfg->code_len;
5124 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5126 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 ()));
5130 if (acfg->aot_opts.write_symbols) {
5132 emit_symbol_size (acfg, debug_sym, ".");
5134 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5138 emit_label (acfg, symbol);
5145 * Encode PATCH_INFO into its disk representation.
5148 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5152 switch (patch_info->type) {
5153 case MONO_PATCH_INFO_NONE:
5155 case MONO_PATCH_INFO_IMAGE:
5156 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5158 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5159 case MONO_PATCH_INFO_JIT_TLS_ID:
5160 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5161 case MONO_PATCH_INFO_GC_NURSERY_START:
5163 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5164 encode_value (patch_info->data.index, p, &p);
5166 case MONO_PATCH_INFO_METHOD_REL:
5167 encode_value ((gint)patch_info->data.offset, p, &p);
5169 case MONO_PATCH_INFO_SWITCH: {
5170 gpointer *table = (gpointer *)patch_info->data.table->table;
5173 encode_value (patch_info->data.table->table_size, p, &p);
5174 for (k = 0; k < patch_info->data.table->table_size; k++)
5175 encode_value ((int)(gssize)table [k], p, &p);
5178 case MONO_PATCH_INFO_METHODCONST:
5179 case MONO_PATCH_INFO_METHOD:
5180 case MONO_PATCH_INFO_METHOD_JUMP:
5181 case MONO_PATCH_INFO_ICALL_ADDR:
5182 case MONO_PATCH_INFO_METHOD_RGCTX:
5183 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5184 encode_method_ref (acfg, patch_info->data.method, p, &p);
5186 case MONO_PATCH_INFO_INTERNAL_METHOD:
5187 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5188 guint32 len = strlen (patch_info->data.name);
5190 encode_value (len, p, &p);
5192 memcpy (p, patch_info->data.name, len);
5197 case MONO_PATCH_INFO_LDSTR: {
5198 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5199 guint32 token = patch_info->data.token->token;
5200 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5201 encode_value (image_index, p, &p);
5202 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5205 case MONO_PATCH_INFO_RVA:
5206 case MONO_PATCH_INFO_DECLSEC:
5207 case MONO_PATCH_INFO_LDTOKEN:
5208 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5209 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5210 encode_value (patch_info->data.token->token, p, &p);
5211 encode_value (patch_info->data.token->has_context, p, &p);
5212 if (patch_info->data.token->has_context)
5213 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5215 case MONO_PATCH_INFO_EXC_NAME: {
5216 MonoClass *ex_class;
5219 mono_class_from_name (mono_defaults.exception_class->image,
5220 "System", patch_info->data.target);
5221 g_assert (ex_class);
5222 encode_klass_ref (acfg, ex_class, p, &p);
5225 case MONO_PATCH_INFO_R4:
5226 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5228 case MONO_PATCH_INFO_R8:
5229 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5230 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5232 case MONO_PATCH_INFO_VTABLE:
5233 case MONO_PATCH_INFO_CLASS:
5234 case MONO_PATCH_INFO_IID:
5235 case MONO_PATCH_INFO_ADJUSTED_IID:
5236 case MONO_PATCH_INFO_CLASS_INIT:
5237 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5239 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5240 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5241 if (patch_info->data.del_tramp->method) {
5242 encode_value (1, p, &p);
5243 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5245 encode_value (0, p, &p);
5247 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5249 case MONO_PATCH_INFO_FIELD:
5250 case MONO_PATCH_INFO_SFLDA:
5251 encode_field_info (acfg, patch_info->data.field, p, &p);
5253 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5255 case MONO_PATCH_INFO_RGCTX_FETCH: {
5256 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5261 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5262 * reference the same method, so encode the method only once.
5264 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5266 buf2 = g_malloc (1024);
5269 encode_method_ref (acfg, entry->method, p2, &p2);
5270 g_assert (p2 - buf2 < 1024);
5272 offset = add_to_blob (acfg, buf2, p2 - buf2);
5275 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5280 encode_value (offset, p, &p);
5281 g_assert ((int)entry->info_type < 256);
5282 g_assert (entry->data->type < 256);
5283 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5284 encode_patch (acfg, entry->data, p, &p);
5287 case MONO_PATCH_INFO_MONITOR_ENTER:
5288 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5289 case MONO_PATCH_INFO_MONITOR_EXIT:
5290 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5292 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5293 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5294 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5296 case MONO_PATCH_INFO_SIGNATURE:
5297 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5299 case MONO_PATCH_INFO_TLS_OFFSET:
5300 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5302 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5303 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5304 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5306 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5307 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5310 encode_method_ref (acfg, info->method, p, &p);
5311 encode_value (info->num_entries, p, &p);
5312 for (i = 0; i < info->num_entries; ++i) {
5313 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5315 encode_value (template->info_type, p, &p);
5316 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5317 case MONO_PATCH_INFO_CLASS:
5318 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5320 case MONO_PATCH_INFO_FIELD:
5321 encode_field_info (acfg, template->data, p, &p);
5324 g_assert_not_reached ();
5330 case MONO_PATCH_INFO_LDSTR_LIT: {
5331 const char *s = patch_info->data.target;
5332 int len = strlen (s);
5334 encode_value (len, p, &p);
5335 memcpy (p, s, len + 1);
5339 case MONO_PATCH_INFO_VIRT_METHOD:
5340 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5341 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5343 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5346 g_warning ("unable to handle jump info %d", patch_info->type);
5347 g_assert_not_reached ();
5354 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5357 guint32 pindex, offset;
5358 MonoJumpInfo *patch_info;
5360 encode_value (n_patches, p, &p);
5362 for (pindex = 0; pindex < patches->len; ++pindex) {
5363 patch_info = g_ptr_array_index (patches, pindex);
5365 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5369 offset = get_got_offset (acfg, llvm, patch_info);
5370 encode_value (offset, p, &p);
5377 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5381 int pindex, buf_size, n_patches;
5383 MonoJumpInfo *patch_info;
5384 guint32 method_index;
5386 guint32 first_got_offset;
5388 method = cfg->orig_method;
5390 method_index = get_method_index (acfg, method);
5392 /* Sort relocations */
5393 patches = g_ptr_array_new ();
5394 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5395 g_ptr_array_add (patches, patch_info);
5396 g_ptr_array_sort (patches, compare_patches);
5398 first_got_offset = acfg->cfgs [method_index]->got_offset;
5400 /**********************/
5401 /* Encode method info */
5402 /**********************/
5404 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5405 p = buf = g_malloc (buf_size);
5407 if (mono_class_get_cctor (method->klass))
5408 encode_klass_ref (acfg, method->klass, p, &p);
5410 /* Not needed when loading the method */
5411 encode_value (0, p, &p);
5414 if (cfg->opt & MONO_OPT_SHARED) {
5415 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5416 for (l = cfg->ldstr_list; l; l = l->next) {
5417 encode_value ((long)l->data, p, &p);
5421 /* Used only in shared mode */
5422 g_assert (!cfg->ldstr_list);
5425 for (pindex = 0; pindex < patches->len; ++pindex) {
5426 patch_info = g_ptr_array_index (patches, pindex);
5428 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5429 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5430 patch_info->type = MONO_PATCH_INFO_NONE;
5435 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5436 /* Stored in a GOT slot initialized at module load time */
5437 patch_info->type = MONO_PATCH_INFO_NONE;
5441 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5442 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START) {
5443 /* Stored in a GOT slot initialized at module load time */
5444 patch_info->type = MONO_PATCH_INFO_NONE;
5448 if (is_plt_patch (patch_info)) {
5449 /* Calls are made through the PLT */
5450 patch_info->type = MONO_PATCH_INFO_NONE;
5458 g_assert (cfg->has_got_slots);
5460 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5462 acfg->stats.info_size += p - buf;
5464 g_assert (p - buf < buf_size);
5466 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5471 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5473 guint32 cache_index;
5476 /* Reuse the unwind module to canonize and store unwind info entries */
5477 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5479 /* Use +/- 1 to distinguish 0s from missing entries */
5480 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5488 * It would be easier to use assembler symbols, but the caller needs an
5491 offset = acfg->unwind_info_offset;
5492 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5493 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5496 encode_value (encoded_len, p, &p);
5498 acfg->unwind_info_offset += encoded_len + (p - buf);
5504 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5507 guint32 debug_info_size, seq_points_size;
5509 MonoMethodHeader *header;
5510 guint8 *p, *buf, *debug_info;
5511 MonoJitInfo *jinfo = cfg->jit_info;
5513 gboolean use_unwind_ops = FALSE;
5514 MonoSeqPointInfo *seq_points;
5516 code = cfg->native_code;
5517 header = cfg->header;
5519 if (!acfg->aot_opts.nodebug) {
5520 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5523 debug_info_size = 0;
5526 seq_points = cfg->seq_point_info;
5527 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5529 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5531 p = buf = g_malloc (buf_size);
5533 use_unwind_ops = cfg->unwind_ops != NULL;
5535 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);
5537 encode_value (flags, p, &p);
5539 if (use_unwind_ops) {
5540 guint32 encoded_len;
5542 guint32 unwind_desc;
5544 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5546 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5547 encode_value (unwind_desc, p, &p);
5549 encode_value (jinfo->unwind_info, p, &p);
5552 /*Encode the number of holes before the number of clauses to make decoding easier*/
5553 if (jinfo->has_try_block_holes) {
5554 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5555 encode_value (table->num_holes, p, &p);
5558 if (jinfo->has_arch_eh_info) {
5560 * In AOT mode, the code length is calculated from the address of the previous method,
5561 * which could include alignment padding, so calculating the start of the epilog as
5562 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5564 encode_value (jinfo->code_size, p, &p);
5567 /* Exception table */
5568 if (cfg->compile_llvm) {
5570 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5571 * since the information is only available to llc. Instead, we let llc save the data
5572 * into the LSDA, and read it from there at runtime.
5574 /* The assembly might be CIL stripped so emit the data ourselves */
5575 if (header->num_clauses)
5576 encode_value (header->num_clauses, p, &p);
5578 for (k = 0; k < header->num_clauses; ++k) {
5579 MonoExceptionClause *clause;
5581 clause = &header->clauses [k];
5583 encode_value (clause->flags, p, &p);
5584 if (clause->data.catch_class) {
5585 encode_value (1, p, &p);
5586 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5588 encode_value (0, p, &p);
5591 /* Emit a list of nesting clauses */
5592 for (i = 0; i < header->num_clauses; ++i) {
5594 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5596 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5598 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5599 encode_value (i, p, &p);
5601 encode_value (-1, p, &p);
5604 if (jinfo->num_clauses)
5605 encode_value (jinfo->num_clauses, p, &p);
5607 for (k = 0; k < jinfo->num_clauses; ++k) {
5608 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5610 encode_value (ei->flags, p, &p);
5611 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5612 /* Not used for catch clauses */
5613 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5614 encode_value (ei->exvar_offset, p, &p);
5616 encode_value (ei->exvar_offset, p, &p);
5619 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5620 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5622 if (ei->data.catch_class) {
5626 buf2 = g_malloc (4096);
5628 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5630 g_assert (len < 4096);
5631 encode_value (len, p, &p);
5632 memcpy (p, buf2, len);
5636 encode_value (0, p, &p);
5640 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5641 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5642 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5646 if (jinfo->has_try_block_holes) {
5647 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5648 for (i = 0; i < table->num_holes; ++i) {
5649 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5650 encode_value (hole->clause, p, &p);
5651 encode_value (hole->length, p, &p);
5652 encode_value (hole->offset, p, &p);
5656 if (jinfo->has_arch_eh_info) {
5657 MonoArchEHJitInfo *eh_info;
5659 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5660 encode_value (eh_info->stack_size, p, &p);
5661 encode_value (eh_info->epilog_size, p, &p);
5664 if (jinfo->has_generic_jit_info) {
5665 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5666 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5670 encode_value (gi->nlocs, p, &p);
5672 for (i = 0; i < gi->nlocs; ++i) {
5673 MonoDwarfLocListEntry *entry = &gi->locations [i];
5675 encode_value (entry->is_reg ? 1 : 0, p, &p);
5676 encode_value (entry->reg, p, &p);
5678 encode_value (entry->offset, p, &p);
5680 g_assert (entry->from == 0);
5682 encode_value (entry->from, p, &p);
5683 encode_value (entry->to, p, &p);
5686 if (!cfg->compile_llvm) {
5687 encode_value (gi->has_this ? 1 : 0, p, &p);
5688 encode_value (gi->this_reg, p, &p);
5689 encode_value (gi->this_offset, p, &p);
5694 * Need to encode jinfo->method too, since it is not equal to 'method'
5695 * when using generic sharing.
5697 buf2 = g_malloc (4096);
5699 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5701 g_assert (len < 4096);
5702 encode_value (len, p, &p);
5703 memcpy (p, buf2, len);
5707 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5708 MonoMethodInflated *inflated;
5709 MonoGenericContext *context;
5710 MonoGenericInst *inst;
5712 g_assert (jinfo->d.method->is_inflated);
5713 inflated = (MonoMethodInflated*)jinfo->d.method;
5714 context = &inflated->context;
5716 encode_value (1, p, &p);
5717 if (context->class_inst) {
5718 inst = context->class_inst;
5720 encode_value (inst->type_argc, p, &p);
5721 for (i = 0; i < inst->type_argc; ++i)
5722 encode_value (gsctx->var_is_vt [i], p, &p);
5724 encode_value (0, p, &p);
5726 if (context->method_inst) {
5727 inst = context->method_inst;
5729 encode_value (inst->type_argc, p, &p);
5730 for (i = 0; i < inst->type_argc; ++i)
5731 encode_value (gsctx->mvar_is_vt [i], p, &p);
5733 encode_value (0, p, &p);
5736 encode_value (0, p, &p);
5740 if (seq_points_size)
5741 p += mono_seq_point_info_write (seq_points, p);
5743 g_assert (debug_info_size < buf_size);
5745 encode_value (debug_info_size, p, &p);
5746 if (debug_info_size) {
5747 memcpy (p, debug_info, debug_info_size);
5748 p += debug_info_size;
5749 g_free (debug_info);
5754 encode_value (cfg->gc_map_size, p, &p);
5755 /* The GC map requires 4 bytes of alignment */
5756 while ((gsize)p % 4)
5758 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5759 p += cfg->gc_map_size;
5762 acfg->stats.ex_info_size += p - buf;
5764 g_assert (p - buf < buf_size);
5767 /* The GC Map requires 4 byte alignment */
5768 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5773 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5776 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5778 int i, buf_size, res;
5779 gboolean no_special_static, cant_encode;
5780 gpointer iter = NULL;
5783 mono_error_cleanup (&error);
5787 p = buf = g_malloc (buf_size);
5789 /* Mark as unusable */
5790 encode_value (-1, p, &p);
5792 res = add_to_blob (acfg, buf, p - buf);
5798 buf_size = 10240 + (klass->vtable_size * 16);
5799 p = buf = g_malloc (buf_size);
5803 mono_class_init (klass);
5805 mono_class_get_nested_types (klass, &iter);
5806 g_assert (klass->nested_classes_inited);
5808 mono_class_setup_vtable (klass);
5811 * Emit all the information which is required for creating vtables so
5812 * the runtime does not need to create the MonoMethod structures which
5813 * take up a lot of space.
5816 no_special_static = !mono_class_has_special_static_fields (klass);
5818 /* Check whenever we have enough info to encode the vtable */
5819 cant_encode = FALSE;
5820 for (i = 0; i < klass->vtable_size; ++i) {
5821 MonoMethod *cm = klass->vtable [i];
5823 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5827 mono_class_has_finalizer (klass);
5829 if (klass->generic_container || cant_encode) {
5830 encode_value (-1, p, &p);
5832 encode_value (klass->vtable_size, p, &p);
5833 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);
5834 if (klass->has_cctor)
5835 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5836 if (klass->has_finalize)
5837 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5839 encode_value (klass->instance_size, p, &p);
5840 encode_value (mono_class_data_size (klass), p, &p);
5841 encode_value (klass->packing_size, p, &p);
5842 encode_value (klass->min_align, p, &p);
5844 for (i = 0; i < klass->vtable_size; ++i) {
5845 MonoMethod *cm = klass->vtable [i];
5848 encode_method_ref (acfg, cm, p, &p);
5850 encode_value (0, p, &p);
5854 acfg->stats.class_info_size += p - buf;
5856 g_assert (p - buf < buf_size);
5857 res = add_to_blob (acfg, buf, p - buf);
5864 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5866 char *debug_sym = NULL;
5870 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5871 /* Need to add a prefix to create unique symbols */
5872 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5874 prefix = g_strdup ("plt_");
5878 case MONO_PATCH_INFO_METHOD:
5879 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5881 case MONO_PATCH_INFO_INTERNAL_METHOD:
5882 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5884 case MONO_PATCH_INFO_CLASS_INIT:
5885 s = mono_type_get_name (&ji->data.klass->byval_arg);
5886 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5889 case MONO_PATCH_INFO_RGCTX_FETCH:
5890 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5892 case MONO_PATCH_INFO_ICALL_ADDR: {
5893 char *s = get_debug_sym (ji->data.method, "", cache);
5895 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5899 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5900 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5908 return sanitize_symbol (acfg, debug_sym);
5912 * Calls made from AOTed code are routed through a table of jumps similar to the
5913 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5914 * control to the AOT runtime through a trampoline.
5917 emit_plt (MonoAotCompile *acfg)
5923 sprintf (symbol, "plt");
5925 emit_section_change (acfg, ".text", 0);
5926 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5927 emit_label (acfg, symbol);
5928 emit_label (acfg, acfg->plt_symbol);
5930 for (i = 0; i < acfg->plt_offset; ++i) {
5931 char *debug_sym = NULL;
5932 MonoPltEntry *plt_entry = NULL;
5936 * The first plt entry is unused.
5940 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5942 debug_sym = plt_entry->debug_sym;
5944 if (acfg->thumb_mixed && !plt_entry->jit_used)
5945 /* Emit only a thumb version */
5948 /* Skip plt entries not actually called */
5949 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5952 if (acfg->llvm && !acfg->thumb_mixed) {
5953 emit_label (acfg, plt_entry->llvm_symbol);
5955 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5956 #if defined(TARGET_MACH)
5957 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5963 if (acfg->need_no_dead_strip) {
5964 emit_unset_mode (acfg);
5965 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5967 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5968 emit_label (acfg, debug_sym);
5971 emit_label (acfg, plt_entry->symbol);
5973 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
5976 emit_symbol_size (acfg, debug_sym, ".");
5979 if (acfg->thumb_mixed) {
5980 /* Make sure the ARM symbols don't alias the thumb ones */
5981 emit_zero_bytes (acfg, 16);
5984 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5987 for (i = 0; i < acfg->plt_offset; ++i) {
5988 char *debug_sym = NULL;
5989 MonoPltEntry *plt_entry = NULL;
5994 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5996 /* Skip plt entries not actually called by LLVM code */
5997 if (!plt_entry->llvm_used)
6000 if (acfg->aot_opts.write_symbols) {
6001 if (plt_entry->debug_sym)
6002 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6006 #if defined(TARGET_MACH)
6007 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6008 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6010 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6011 emit_label (acfg, debug_sym);
6013 fprintf (acfg->fp, "\n.thumb_func\n");
6015 emit_label (acfg, plt_entry->llvm_symbol);
6018 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6020 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6023 emit_symbol_size (acfg, debug_sym, ".");
6029 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6031 sprintf (symbol, "plt_end");
6032 emit_label (acfg, symbol);
6036 * emit_trampoline_full:
6038 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6039 * create_jit_info_for_trampoline ().
6041 static G_GNUC_UNUSED void
6042 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6044 char start_symbol [256];
6045 char end_symbol [256];
6047 guint32 buf_size, info_offset;
6048 MonoJumpInfo *patch_info;
6061 code_size = info->code_size;
6063 unwind_ops = info->unwind_ops;
6065 #ifdef __native_client_codegen__
6066 mono_nacl_fix_patches (code, ji);
6071 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6073 emit_section_change (acfg, ".text", 0);
6074 emit_global (acfg, start_symbol, TRUE);
6075 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6076 emit_label (acfg, start_symbol);
6078 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6079 emit_label (acfg, symbol);
6082 * The code should access everything through the GOT, so we pass
6085 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6087 emit_symbol_size (acfg, start_symbol, ".");
6090 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6091 emit_label (acfg, end_symbol);
6096 /* Sort relocations */
6097 patches = g_ptr_array_new ();
6098 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6099 if (patch_info->type != MONO_PATCH_INFO_NONE)
6100 g_ptr_array_add (patches, patch_info);
6101 g_ptr_array_sort (patches, compare_patches);
6103 buf_size = patches->len * 128 + 128;
6104 buf = g_malloc (buf_size);
6107 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6108 g_assert (p - buf < buf_size);
6110 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6112 info_offset = add_to_blob (acfg, buf, p - buf);
6114 emit_section_change (acfg, RODATA_SECT, 0);
6115 emit_global (acfg, symbol, FALSE);
6116 emit_label (acfg, symbol);
6118 emit_int32 (acfg, info_offset);
6122 guint32 encoded_len;
6126 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6128 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6129 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6132 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6133 emit_int32 (acfg, uw_offset);
6136 /* Emit debug info */
6140 sprintf (symbol, "%s", name);
6141 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6144 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6148 static G_GNUC_UNUSED void
6149 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6151 emit_trampoline_full (acfg, got_offset, info, FALSE);
6155 emit_trampolines (MonoAotCompile *acfg)
6158 char end_symbol [256];
6159 int i, tramp_got_offset;
6160 MonoAotTrampoline ntype;
6161 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6165 if (!mono_aot_mode_is_full (&acfg->aot_opts))
6168 g_assert (acfg->image->assembly);
6170 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6171 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6172 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6173 MonoTrampInfo *info;
6176 * Emit the generic trampolines.
6178 * We could save some code by treating the generic trampolines as a wrapper
6179 * method, but that approach has its own complexities, so we choose the simpler
6182 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6183 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6184 #ifdef DISABLE_REMOTING
6185 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6188 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6189 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6192 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6193 emit_trampoline (acfg, acfg->got_offset, info);
6196 mono_arch_get_nullified_class_init_trampoline (&info);
6197 emit_trampoline (acfg, acfg->got_offset, info);
6198 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6199 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6200 emit_trampoline (acfg, acfg->got_offset, info);
6201 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6202 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6203 emit_trampoline (acfg, acfg->got_offset, info);
6205 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6206 emit_trampoline (acfg, acfg->got_offset, info);
6209 /* Emit the exception related code pieces */
6210 mono_arch_get_restore_context (&info, TRUE);
6211 emit_trampoline (acfg, acfg->got_offset, info);
6212 mono_arch_get_call_filter (&info, TRUE);
6213 emit_trampoline (acfg, acfg->got_offset, info);
6214 mono_arch_get_throw_exception (&info, TRUE);
6215 emit_trampoline (acfg, acfg->got_offset, info);
6216 mono_arch_get_rethrow_exception (&info, TRUE);
6217 emit_trampoline (acfg, acfg->got_offset, info);
6218 mono_arch_get_throw_corlib_exception (&info, TRUE);
6219 emit_trampoline (acfg, acfg->got_offset, info);
6221 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6222 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6223 emit_trampoline (acfg, acfg->got_offset, info);
6224 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6225 emit_trampoline (acfg, acfg->got_offset, info);
6228 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6229 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6231 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6233 /* Create a separate out trampoline for more information in stack traces */
6234 info->name = g_strdup ("gsharedvt_out_trampoline");
6235 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6239 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6241 GSList *l = mono_arch_get_trampolines (TRUE);
6244 MonoTrampInfo *info = l->data;
6246 emit_trampoline (acfg, acfg->got_offset, info);
6252 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6255 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6256 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6257 emit_trampoline (acfg, acfg->got_offset, info);
6259 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6260 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6261 emit_trampoline (acfg, acfg->got_offset, info);
6264 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6265 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6266 emit_trampoline (acfg, acfg->got_offset, info);
6272 /* delegate_invoke_impl trampolines */
6273 l = mono_arch_get_delegate_invoke_impls ();
6275 MonoTrampInfo *info = l->data;
6277 emit_trampoline (acfg, acfg->got_offset, info);
6282 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6284 /* Emit trampolines which are numerous */
6287 * These include the following:
6288 * - specific trampolines
6289 * - static rgctx invoke trampolines
6291 * These trampolines have the same code, they are parameterized by GOT
6293 * They are defined in this file, in the arch_... routines instead of
6294 * in tramp-<ARCH>.c, since it is easier to do it this way.
6298 * When running in aot-only mode, we can't create specific trampolines at
6299 * runtime, so we create a few, and save them in the AOT file.
6300 * Normal trampolines embed their argument as a literal inside the
6301 * trampoline code, we can't do that here, so instead we embed an offset
6302 * which needs to be added to the trampoline address to get the address of
6303 * the GOT slot which contains the argument value.
6304 * The generated trampolines jump to the generic trampolines using another
6305 * GOT slot, which will be setup by the AOT loader to point to the
6306 * generic trampoline code of the given type.
6310 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6314 emit_section_change (acfg, ".text", 0);
6316 tramp_got_offset = acfg->got_offset;
6318 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6320 case MONO_AOT_TRAMP_SPECIFIC:
6321 sprintf (symbol, "specific_trampolines");
6323 case MONO_AOT_TRAMP_STATIC_RGCTX:
6324 sprintf (symbol, "static_rgctx_trampolines");
6326 case MONO_AOT_TRAMP_IMT_THUNK:
6327 sprintf (symbol, "imt_thunks");
6329 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6330 sprintf (symbol, "gsharedvt_arg_trampolines");
6333 g_assert_not_reached ();
6336 sprintf (end_symbol, "%s_e", symbol);
6338 if (acfg->aot_opts.write_symbols)
6339 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6341 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6342 emit_label (acfg, symbol);
6344 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6346 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6350 case MONO_AOT_TRAMP_SPECIFIC:
6351 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6352 tramp_got_offset += 2;
6354 case MONO_AOT_TRAMP_STATIC_RGCTX:
6355 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6356 tramp_got_offset += 2;
6358 case MONO_AOT_TRAMP_IMT_THUNK:
6359 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6360 tramp_got_offset += 1;
6362 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6363 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6364 tramp_got_offset += 2;
6367 g_assert_not_reached ();
6369 #ifdef __native_client_codegen__
6370 /* align to avoid 32-byte boundary crossings */
6371 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6374 if (!acfg->trampoline_size [ntype]) {
6375 g_assert (tramp_size);
6376 acfg->trampoline_size [ntype] = tramp_size;
6380 emit_label (acfg, end_symbol);
6381 emit_int32 (acfg, 0);
6384 arch_emit_specific_trampoline_pages (acfg);
6386 /* Reserve some entries at the end of the GOT for our use */
6387 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6390 acfg->got_offset += acfg->num_trampoline_got_entries;
6394 str_begins_with (const char *str1, const char *str2)
6396 int len = strlen (str2);
6397 return strncmp (str1, str2, len) == 0;
6401 mono_aot_readonly_field_override (MonoClassField *field)
6404 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6405 char *p = rdv->name;
6407 len = strlen (field->parent->name_space);
6408 if (strncmp (p, field->parent->name_space, len))
6413 len = strlen (field->parent->name);
6414 if (strncmp (p, field->parent->name, len))
6419 if (strcmp (p, field->name))
6421 switch (rdv->type) {
6423 return &rdv->value.i1;
6425 return &rdv->value.i2;
6427 return &rdv->value.i4;
6436 add_readonly_value (MonoAotOptions *opts, const char *val)
6441 /* the format of val is:
6442 * namespace.typename.fieldname=type/value
6443 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6445 fval = strrchr (val, '/');
6447 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6450 tval = strrchr (val, '=');
6452 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6455 rdv = g_new0 (ReadOnlyValue, 1);
6456 rdv->name = g_malloc0 (tval - val + 1);
6457 memcpy (rdv->name, val, tval - val);
6460 if (strncmp (tval, "i1", 2) == 0) {
6461 rdv->value.i1 = atoi (fval);
6462 rdv->type = MONO_TYPE_I1;
6463 } else if (strncmp (tval, "i2", 2) == 0) {
6464 rdv->value.i2 = atoi (fval);
6465 rdv->type = MONO_TYPE_I2;
6466 } else if (strncmp (tval, "i4", 2) == 0) {
6467 rdv->value.i4 = atoi (fval);
6468 rdv->type = MONO_TYPE_I4;
6470 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6473 rdv->next = readonly_values;
6474 readonly_values = rdv;
6478 clean_path (gchar * path)
6483 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6486 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6493 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6495 gchar **args, **ptr;
6497 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6498 for (ptr = args; ptr && *ptr; ptr ++) {
6499 const char *arg = *ptr;
6501 if (str_begins_with (arg, "outfile=")) {
6502 opts->outfile = g_strdup (arg + strlen ("outfile="));
6503 } else if (str_begins_with (arg, "llvm-outfile=")) {
6504 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6505 } else if (str_begins_with (arg, "temp-path=")) {
6506 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6507 } else if (str_begins_with (arg, "save-temps")) {
6508 opts->save_temps = TRUE;
6509 } else if (str_begins_with (arg, "keep-temps")) {
6510 opts->save_temps = TRUE;
6511 } else if (str_begins_with (arg, "write-symbols")) {
6512 opts->write_symbols = TRUE;
6513 } else if (str_begins_with (arg, "no-write-symbols")) {
6514 opts->write_symbols = FALSE;
6515 } else if (str_begins_with (arg, "metadata-only")) {
6516 opts->metadata_only = TRUE;
6517 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6518 opts->bind_to_runtime_version = TRUE;
6519 } else if (str_begins_with (arg, "full")) {
6520 opts->mode = MONO_AOT_MODE_FULL;
6521 } else if (str_begins_with (arg, "hybrid")) {
6522 opts->mode = MONO_AOT_MODE_HYBRID;
6523 } else if (str_begins_with (arg, "threads=")) {
6524 opts->nthreads = atoi (arg + strlen ("threads="));
6525 } else if (str_begins_with (arg, "static")) {
6526 opts->static_link = TRUE;
6527 opts->no_dlsym = TRUE;
6528 } else if (str_begins_with (arg, "asmonly")) {
6529 opts->asm_only = TRUE;
6530 } else if (str_begins_with (arg, "asmwriter")) {
6531 opts->asm_writer = TRUE;
6532 } else if (str_begins_with (arg, "nodebug")) {
6533 opts->nodebug = TRUE;
6534 } else if (str_begins_with (arg, "dwarfdebug")) {
6535 opts->dwarf_debug = TRUE;
6536 } else if (str_begins_with (arg, "nopagetrampolines")) {
6537 opts->use_trampolines_page = FALSE;
6538 } else if (str_begins_with (arg, "ntrampolines=")) {
6539 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6540 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6541 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6542 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6543 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6544 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6545 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6546 } else if (str_begins_with (arg, "autoreg")) {
6547 opts->autoreg = TRUE;
6548 } else if (str_begins_with (arg, "tool-prefix=")) {
6549 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6550 } else if (str_begins_with (arg, "ld-flags=")) {
6551 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6552 } else if (str_begins_with (arg, "soft-debug")) {
6553 opts->soft_debug = TRUE;
6554 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6555 opts->gen_seq_points_file = TRUE;
6556 } else if (str_begins_with (arg, "direct-pinvoke")) {
6557 opts->direct_pinvoke = TRUE;
6558 } else if (str_begins_with (arg, "direct-icalls")) {
6559 opts->direct_icalls = TRUE;
6560 } else if (str_begins_with (arg, "no-direct-calls")) {
6561 opts->no_direct_calls = TRUE;
6562 } else if (str_begins_with (arg, "print-skipped")) {
6563 opts->print_skipped_methods = TRUE;
6564 } else if (str_begins_with (arg, "stats")) {
6566 } else if (str_begins_with (arg, "no-instances")) {
6567 opts->no_instances = TRUE;
6568 } else if (str_begins_with (arg, "log-generics")) {
6569 opts->log_generics = TRUE;
6570 } else if (str_begins_with (arg, "log-instances=")) {
6571 opts->log_instances = TRUE;
6572 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6573 } else if (str_begins_with (arg, "log-instances")) {
6574 opts->log_instances = TRUE;
6575 } else if (str_begins_with (arg, "internal-logfile=")) {
6576 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6577 } else if (str_begins_with (arg, "mtriple=")) {
6578 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6579 } else if (str_begins_with (arg, "llvm-path=")) {
6580 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6581 } else if (!strcmp (arg, "llvm")) {
6583 } else if (str_begins_with (arg, "readonly-value=")) {
6584 add_readonly_value (opts, arg + strlen ("readonly-value="));
6585 } else if (str_begins_with (arg, "info")) {
6586 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6588 } else if (str_begins_with (arg, "gc-maps")) {
6589 mini_gc_enable_gc_maps_for_aot ();
6590 } else if (str_begins_with (arg, "dump")) {
6591 opts->dump_json = TRUE;
6592 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6593 printf ("Supported options for --aot:\n");
6594 printf (" outfile=\n");
6595 printf (" llvm-outfile=\n");
6596 printf (" llvm-path=\n");
6597 printf (" temp-path=\n");
6598 printf (" save-temps\n");
6599 printf (" keep-temps\n");
6600 printf (" write-symbols\n");
6601 printf (" metadata-only\n");
6602 printf (" bind-to-runtime-version\n");
6604 printf (" threads=\n");
6605 printf (" static\n");
6606 printf (" asmonly\n");
6607 printf (" asmwriter\n");
6608 printf (" nodebug\n");
6609 printf (" dwarfdebug\n");
6610 printf (" ntrampolines=\n");
6611 printf (" nrgctx-trampolines=\n");
6612 printf (" nimt-trampolines=\n");
6613 printf (" ngsharedvt-trampolines=\n");
6614 printf (" autoreg\n");
6615 printf (" tool-prefix=\n");
6616 printf (" readonly-value=\n");
6617 printf (" soft-debug\n");
6618 printf (" gen-seq-points-file\n");
6619 printf (" gc-maps\n");
6620 printf (" print-skipped\n");
6621 printf (" no-instances\n");
6622 printf (" stats\n");
6625 printf (" help/?\n");
6628 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6633 if (opts->use_trampolines_page) {
6634 opts->ntrampolines = 0;
6635 opts->nrgctx_trampolines = 0;
6636 opts->nimt_trampolines = 0;
6637 opts->ngsharedvt_arg_trampolines = 0;
6643 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6645 MonoMethod *method = (MonoMethod*)key;
6646 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6647 MonoAotCompile *acfg = user_data;
6648 MonoJumpInfoToken *new_ji;
6650 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6651 new_ji->image = ji->image;
6652 new_ji->token = ji->token;
6653 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6657 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6659 if (klass->type_token)
6661 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6664 return can_encode_class (acfg, klass->element_class);
6669 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6671 if (method->wrapper_type) {
6672 switch (method->wrapper_type) {
6673 case MONO_WRAPPER_NONE:
6674 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6675 case MONO_WRAPPER_XDOMAIN_INVOKE:
6676 case MONO_WRAPPER_STFLD:
6677 case MONO_WRAPPER_LDFLD:
6678 case MONO_WRAPPER_LDFLDA:
6679 case MONO_WRAPPER_LDFLD_REMOTE:
6680 case MONO_WRAPPER_STFLD_REMOTE:
6681 case MONO_WRAPPER_STELEMREF:
6682 case MONO_WRAPPER_ISINST:
6683 case MONO_WRAPPER_PROXY_ISINST:
6684 case MONO_WRAPPER_ALLOC:
6685 case MONO_WRAPPER_REMOTING_INVOKE:
6686 case MONO_WRAPPER_UNKNOWN:
6687 case MONO_WRAPPER_WRITE_BARRIER:
6688 case MONO_WRAPPER_DELEGATE_INVOKE:
6689 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6690 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6691 case MONO_WRAPPER_SYNCHRONIZED:
6693 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6694 case MONO_WRAPPER_CASTCLASS: {
6695 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6704 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6708 if (!method->token) {
6709 /* The method is part of a constructed type like Int[,].Set (). */
6710 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6711 if (method->klass->rank)
6721 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6723 switch (patch_info->type) {
6724 case MONO_PATCH_INFO_METHOD:
6725 case MONO_PATCH_INFO_METHODCONST:
6726 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6727 MonoMethod *method = patch_info->data.method;
6729 return can_encode_method (acfg, method);
6731 case MONO_PATCH_INFO_VTABLE:
6732 case MONO_PATCH_INFO_CLASS_INIT:
6733 case MONO_PATCH_INFO_CLASS:
6734 case MONO_PATCH_INFO_IID:
6735 case MONO_PATCH_INFO_ADJUSTED_IID:
6736 if (!can_encode_class (acfg, patch_info->data.klass)) {
6737 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6741 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6742 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6743 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6748 case MONO_PATCH_INFO_RGCTX_FETCH: {
6749 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6751 if (!can_encode_method (acfg, entry->method))
6753 if (!can_encode_patch (acfg, entry->data))
6767 * AOT compile a given method.
6768 * This function might be called by multiple threads, so it must be thread-safe.
6771 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6774 MonoJumpInfo *patch_info;
6777 MonoMethod *wrapped;
6780 if (acfg->aot_opts.metadata_only)
6783 mono_acfg_lock (acfg);
6784 index = get_method_index (acfg, method);
6785 mono_acfg_unlock (acfg);
6787 /* fixme: maybe we can also precompile wrapper methods */
6788 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6789 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6790 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6791 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6795 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6798 wrapped = mono_marshal_method_from_wrapper (method);
6799 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6800 // FIXME: The wrapper should be generic too, but it is not
6803 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6806 InterlockedIncrement (&acfg->stats.mcount);
6809 if (method->is_generic || method->klass->generic_container) {
6810 InterlockedIncrement (&acfg->stats.genericcount);
6815 //acfg->aot_opts.print_skipped_methods = TRUE;
6818 * Since these methods are the only ones which are compiled with
6819 * AOT support, and they are not used by runtime startup/shutdown code,
6820 * the runtime will not see AOT methods during AOT compilation,so it
6821 * does not need to support them by creating a fake GOT etc.
6823 flags = JIT_FLAG_AOT;
6824 if (mono_aot_mode_is_full (&acfg->aot_opts))
6825 flags |= JIT_FLAG_FULL_AOT;
6827 flags |= JIT_FLAG_LLVM;
6828 if (acfg->aot_opts.no_direct_calls)
6829 flags |= JIT_FLAG_NO_DIRECT_ICALLS;
6830 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6831 mono_loader_clear_error ();
6833 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6834 if (acfg->aot_opts.print_skipped_methods)
6835 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6836 InterlockedIncrement (&acfg->stats.genericcount);
6839 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6840 if (acfg->aot_opts.print_skipped_methods)
6841 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6842 /* Let the exception happen at runtime */
6846 if (cfg->disable_aot) {
6847 if (acfg->aot_opts.print_skipped_methods)
6848 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6849 InterlockedIncrement (&acfg->stats.ocount);
6850 mono_destroy_compile (cfg);
6853 cfg->method_index = index;
6855 /* Nullify patches which need no aot processing */
6856 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6857 switch (patch_info->type) {
6858 case MONO_PATCH_INFO_LABEL:
6859 case MONO_PATCH_INFO_BB:
6860 patch_info->type = MONO_PATCH_INFO_NONE;
6867 /* Collect method->token associations from the cfg */
6868 mono_acfg_lock (acfg);
6869 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6870 mono_acfg_unlock (acfg);
6871 g_hash_table_destroy (cfg->token_info_hash);
6872 cfg->token_info_hash = NULL;
6875 * Check for absolute addresses.
6878 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6879 switch (patch_info->type) {
6880 case MONO_PATCH_INFO_ABS:
6881 /* unable to handle this */
6890 if (acfg->aot_opts.print_skipped_methods)
6891 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6892 InterlockedIncrement (&acfg->stats.abscount);
6893 mono_destroy_compile (cfg);
6897 /* Lock for the rest of the code */
6898 mono_acfg_lock (acfg);
6901 * Check for methods/klasses we can't encode.
6904 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6905 if (!can_encode_patch (acfg, patch_info))
6910 if (acfg->aot_opts.print_skipped_methods)
6911 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6912 acfg->stats.ocount++;
6913 mono_destroy_compile (cfg);
6914 mono_acfg_unlock (acfg);
6918 if (method->is_inflated && acfg->aot_opts.log_instances) {
6919 if (acfg->instances_logfile)
6920 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6922 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6925 /* Adds generic instances referenced by this method */
6927 * The depth is used to avoid infinite loops when generic virtual recursion is
6930 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6931 if (!acfg->aot_opts.no_instances && depth < 32) {
6932 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6933 switch (patch_info->type) {
6934 case MONO_PATCH_INFO_METHOD: {
6935 MonoMethod *m = patch_info->data.method;
6936 if (m->is_inflated) {
6937 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6938 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6939 !method_has_type_vars (m)) {
6940 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6941 if (mono_aot_mode_is_full (&acfg->aot_opts))
6942 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6944 add_extra_method_with_depth (acfg, m, depth + 1);
6945 add_types_from_method_header (acfg, m);
6948 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6950 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
6951 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
6953 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
6954 add_extra_method_with_depth (acfg, m, depth + 1);
6958 case MONO_PATCH_INFO_VTABLE: {
6959 MonoClass *klass = patch_info->data.klass;
6961 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6962 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6965 case MONO_PATCH_INFO_SFLDA: {
6966 MonoClass *klass = patch_info->data.field->parent;
6968 /* The .cctor needs to run at runtime. */
6969 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6970 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6979 /* Determine whenever the method has GOT slots */
6980 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6981 switch (patch_info->type) {
6982 case MONO_PATCH_INFO_GOT_OFFSET:
6983 case MONO_PATCH_INFO_NONE:
6984 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6985 case MONO_PATCH_INFO_GC_NURSERY_START:
6987 case MONO_PATCH_INFO_IMAGE:
6988 /* The assembly is stored in GOT slot 0 */
6989 if (patch_info->data.image != acfg->image)
6990 cfg->has_got_slots = TRUE;
6993 if (!is_plt_patch (patch_info))
6994 cfg->has_got_slots = TRUE;
6999 if (!cfg->has_got_slots)
7000 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7003 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7005 /* Make a copy of the patch info which is in the mempool */
7007 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7009 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7010 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7013 patches = new_patch_info;
7015 patches_end->next = new_patch_info;
7016 patches_end = new_patch_info;
7018 cfg->patch_info = patches;
7020 /* Make a copy of the unwind info */
7022 GSList *l, *unwind_ops;
7026 for (l = cfg->unwind_ops; l; l = l->next) {
7027 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7028 memcpy (op, l->data, sizeof (MonoUnwindOp));
7029 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7031 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7033 /* Make a copy of the argument/local info */
7035 MonoInst **args, **locals;
7036 MonoMethodSignature *sig;
7037 MonoMethodHeader *header;
7040 sig = mono_method_signature (method);
7041 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7042 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7043 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7044 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7048 header = mono_method_get_header (method);
7049 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7050 for (i = 0; i < header->num_locals; ++i) {
7051 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7052 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7054 cfg->locals = locals;
7057 /* Free some fields used by cfg to conserve memory */
7058 mono_mempool_destroy (cfg->mempool);
7059 cfg->mempool = NULL;
7060 g_free (cfg->varinfo);
7061 cfg->varinfo = NULL;
7065 mono_regstate_free (cfg->rs);
7069 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7071 while (index >= acfg->cfgs_size) {
7072 MonoCompile **new_cfgs;
7075 new_size = acfg->cfgs_size * 2;
7076 new_cfgs = g_new0 (MonoCompile*, new_size);
7077 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7078 g_free (acfg->cfgs);
7079 acfg->cfgs = new_cfgs;
7080 acfg->cfgs_size = new_size;
7082 acfg->cfgs [index] = cfg;
7084 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7087 if (cfg->orig_method->wrapper_type)
7088 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7091 mono_acfg_unlock (acfg);
7093 InterlockedIncrement (&acfg->stats.ccount);
7097 compile_thread_main (gpointer *user_data)
7099 MonoDomain *domain = user_data [0];
7100 MonoAotCompile *acfg = user_data [1];
7101 GPtrArray *methods = user_data [2];
7104 mono_thread_attach (domain);
7106 for (i = 0; i < methods->len; ++i)
7107 compile_method (acfg, g_ptr_array_index (methods, i));
7111 load_profile_files (MonoAotCompile *acfg)
7115 int file_index, res, method_index, i;
7118 GList *unordered, *l;
7123 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7125 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7130 infile = fopen (tmp, "r");
7133 printf ("Using profile data file '%s'\n", tmp);
7138 res = fscanf (infile, "%32s\n", ver);
7139 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7140 printf ("Profile file has wrong version or invalid.\n");
7147 MonoMethodDesc *desc;
7150 if (fgets (name, 1023, infile) == NULL)
7153 /* Kill the newline */
7154 if (strlen (name) > 0)
7155 name [strlen (name) - 1] = '\0';
7157 desc = mono_method_desc_new (name, TRUE);
7159 method = mono_method_desc_search_in_image (desc, acfg->image);
7161 if (method && mono_method_get_token (method)) {
7162 token = mono_method_get_token (method);
7163 method_index = mono_metadata_token_index (token) - 1;
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 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7175 //printf ("No method found matching '%s'.\n", name);
7181 /* Add missing methods */
7183 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7185 for (i = 0; i < acfg->method_order->len; ++i) {
7186 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7192 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7194 unordered = g_list_reverse (unordered);
7195 for (l = unordered; l; l = l->next)
7196 g_ptr_array_add (acfg->method_order, l->data);
7199 /* Used by the LLVM backend */
7201 mono_aot_get_got_offset (MonoJumpInfo *ji)
7203 return get_got_offset (llvm_acfg, TRUE, ji);
7207 mono_aot_get_method_name (MonoCompile *cfg)
7209 if (llvm_acfg->aot_opts.static_link)
7210 /* Include the assembly name too to avoid duplicate symbol errors */
7211 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7213 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7217 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7219 return is_direct_callable (llvm_acfg, NULL, patch_info);
7223 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7225 MonoPltEntry *plt_entry;
7227 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7228 plt_entry->llvm_used = FALSE;
7232 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7234 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7235 MonoPltEntry *plt_entry;
7236 const char *sym = NULL;
7239 ji->data.target = data;
7241 if (!can_encode_patch (llvm_acfg, ji))
7244 if (llvm_acfg->aot_opts.direct_icalls) {
7245 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7246 /* Call to a C function implementing a jit icall */
7247 sym = mono_lookup_jit_icall_symbol (data);
7248 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7249 MonoMethod *method = (gpointer)data;
7250 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7251 sym = mono_lookup_icall_symbol (method);
7254 return g_strdup (sym);
7257 plt_entry = get_plt_entry (llvm_acfg, ji);
7258 plt_entry->llvm_used = TRUE;
7260 #if defined(TARGET_MACH)
7261 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7263 return g_strdup_printf (plt_entry->llvm_symbol);
7268 mono_aot_get_method_index (MonoMethod *method)
7270 g_assert (llvm_acfg);
7271 return get_method_index (llvm_acfg, method);
7275 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7279 mono_acfg_lock (llvm_acfg);
7280 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7281 mono_acfg_unlock (llvm_acfg);
7287 execute_system (const char * command)
7292 // We need an extra set of quotes around the whole command to properly handle commands
7293 // with spaces since internally the command is called through "cmd /c.
7294 command = g_strdup_printf ("\"%s\"", command);
7296 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7297 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7298 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7299 status = _wsystem (wstr);
7304 status = system (command);
7315 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7319 emit_llvm_file (MonoAotCompile *acfg)
7321 char *command, *opts, *tempbc, *output_fname;
7323 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7324 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7328 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7329 * a lot of time, and doesn't seem to save much space.
7330 * The following optimizations cannot be enabled:
7332 * - 'jump-threading' changes our blockaddress references to int constants.
7333 * - 'basiccg' fails because it contains:
7334 * if (CS && !isa<IntrinsicInst>(II)) {
7335 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7336 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7337 * The opt list below was produced by taking the output of:
7338 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7339 * then removing tailcallelim + the global opts.
7340 * strip-dead-prototypes deletes unused intrinsics definitions.
7342 opts = g_strdup ("-instcombine -simplifycfg");
7343 //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");
7344 /* The dse pass is disabled because of #13734 and #17616 */
7346 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7347 * // If we have no DataLayout information around, then the size of the store
7348 * // is inferrable from the pointee type. If they are the same type, then
7349 * // we know that the store is safe.
7350 * if (AA.getDataLayout() == 0 &&
7351 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7352 * return OverwriteComplete;
7353 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7355 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");
7357 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7358 aot_printf (acfg, "Executing opt: %s\n", command);
7359 if (execute_system (command) != 0)
7364 if (!acfg->llc_args)
7365 acfg->llc_args = g_string_new ("");
7367 /* Verbose asm slows down llc greatly */
7368 g_string_append (acfg->llc_args, " -asm-verbose=false");
7370 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7372 if (acfg->aot_opts.mtriple)
7373 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7375 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7377 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7378 /* ios requires PIC code now */
7379 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7381 if (llvm_acfg->aot_opts.static_link)
7382 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7384 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7386 unlink (acfg->tmpfname);
7388 if (acfg->llvm_owriter) {
7389 /* Emit an object file directly */
7390 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7391 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7393 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7395 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7396 g_free (output_fname);
7398 aot_printf (acfg, "Executing llc: %s\n", command);
7400 if (execute_system (command) != 0)
7407 emit_code (MonoAotCompile *acfg)
7409 int oindex, i, prev_index;
7412 #if defined(TARGET_POWERPC64)
7413 sprintf (symbol, ".Lgot_addr");
7414 emit_section_change (acfg, ".text", 0);
7415 emit_alignment (acfg, 8);
7416 emit_label (acfg, symbol);
7417 emit_pointer (acfg, acfg->got_symbol);
7421 * This global symbol is used to compute the address of each method using the
7422 * code_offsets array. It is also used to compute the memory ranges occupied by
7423 * AOT code, so it must be equal to the address of the first emitted method.
7425 emit_section_change (acfg, ".text", 0);
7426 emit_alignment_code (acfg, 8);
7428 for (i = 0; i < acfg->nmethods; ++i) {
7429 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7430 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7435 if (!acfg->methods_symbol) {
7436 sprintf (symbol, "methods");
7437 emit_label (acfg, symbol);
7438 acfg->methods_symbol = g_strdup (symbol);
7440 emit_label (acfg, "jit_code_start");
7443 * Emit some padding so the local symbol for the first method doesn't have the
7444 * same address as 'methods'.
7446 #if defined(__default_codegen__)
7447 emit_padding (acfg, 16);
7448 #elif defined(__native_client_codegen__)
7450 const int kPaddingSize = 16;
7451 guint8 pad_buffer[kPaddingSize];
7452 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7453 emit_bytes (acfg, pad_buffer, kPaddingSize);
7457 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7461 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7463 cfg = acfg->cfgs [i];
7468 method = cfg->orig_method;
7470 /* Emit unbox trampoline */
7471 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7472 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7474 emit_section_change (acfg, ".text", 0);
7475 #ifdef __native_client_codegen__
7476 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7479 if (acfg->thumb_mixed && cfg->compile_llvm) {
7480 emit_set_thumb_mode (acfg);
7481 fprintf (acfg->fp, "\n.thumb_func\n");
7484 emit_label (acfg, symbol);
7486 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7488 if (acfg->thumb_mixed && cfg->compile_llvm)
7489 emit_set_arm_mode (acfg);
7492 if (cfg->compile_llvm)
7493 acfg->stats.llvm_count ++;
7495 emit_method_code (acfg, cfg);
7498 emit_section_change (acfg, ".text", 0);
7499 emit_alignment_code (acfg, 8);
7500 emit_label (acfg, "jit_code_end");
7502 /* To distinguish it from the next symbol */
7503 emit_padding (acfg, 4);
7506 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7507 * from optimizing them away, since it doesn't see that code_offsets references them.
7508 * JITted methods don't need this since they are referenced using assembler local
7510 * FIXME: This is why write-symbols doesn't work on OSX ?
7512 if (acfg->llvm && acfg->need_no_dead_strip) {
7513 fprintf (acfg->fp, "\n");
7514 for (i = 0; i < acfg->nmethods; ++i) {
7515 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7516 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7521 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7522 * This is PIE code, and the linker can update it if needed.
7524 sprintf (symbol, "method_addresses");
7525 emit_section_change (acfg, ".text", 1);
7526 emit_alignment_code (acfg, 8);
7527 emit_label (acfg, symbol);
7528 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7529 emit_unset_mode (acfg);
7530 if (acfg->need_no_dead_strip)
7531 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7533 for (i = 0; i < acfg->nmethods; ++i) {
7534 #ifdef MONO_ARCH_AOT_SUPPORTED
7538 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7540 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7544 sprintf (symbol, "method_addresses_end");
7545 emit_label (acfg, symbol);
7548 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7549 sprintf (symbol, "unbox_trampolines");
7550 emit_section_change (acfg, RODATA_SECT, 0);
7551 emit_alignment (acfg, 8);
7552 emit_label (acfg, symbol);
7555 for (i = 0; i < acfg->nmethods; ++i) {
7560 cfg = acfg->cfgs [i];
7564 method = cfg->orig_method;
7566 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7567 index = get_method_index (acfg, method);
7569 emit_int32 (acfg, index);
7570 /* Make sure the table is sorted by index */
7571 g_assert (index > prev_index);
7575 sprintf (symbol, "unbox_trampolines_end");
7576 emit_label (acfg, symbol);
7577 emit_int32 (acfg, 0);
7579 /* Emit a separate table with the trampoline addresses/offsets */
7580 sprintf (symbol, "unbox_trampoline_addresses");
7581 emit_section_change (acfg, ".text", 0);
7582 emit_alignment_code (acfg, 8);
7583 emit_label (acfg, symbol);
7585 for (i = 0; i < acfg->nmethods; ++i) {
7590 cfg = acfg->cfgs [i];
7594 method = cfg->orig_method;
7596 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7597 #ifdef MONO_ARCH_AOT_SUPPORTED
7600 index = get_method_index (acfg, method);
7601 sprintf (symbol, "ut_%d", index);
7603 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7607 emit_int32 (acfg, 0);
7611 emit_info (MonoAotCompile *acfg)
7617 offsets = g_new0 (gint32, acfg->nmethods);
7619 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7620 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7622 if (acfg->cfgs [i]) {
7623 emit_method_info (acfg, acfg->cfgs [i]);
7624 offsets [i] = acfg->cfgs [i]->method_info_offset;
7630 sprintf (symbol, "method_info_offsets");
7631 emit_section_change (acfg, RODATA_SECT, 1);
7632 emit_alignment (acfg, 8);
7633 emit_label (acfg, symbol);
7635 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7640 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7642 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7643 #define mix(a,b,c) { \
7644 a -= c; a ^= rot(c, 4); c += b; \
7645 b -= a; b ^= rot(a, 6); a += c; \
7646 c -= b; c ^= rot(b, 8); b += a; \
7647 a -= c; a ^= rot(c,16); c += b; \
7648 b -= a; b ^= rot(a,19); a += c; \
7649 c -= b; c ^= rot(b, 4); b += a; \
7651 #define final(a,b,c) { \
7652 c ^= b; c -= rot(b,14); \
7653 a ^= c; a -= rot(c,11); \
7654 b ^= a; b -= rot(a,25); \
7655 c ^= b; c -= rot(b,16); \
7656 a ^= c; a -= rot(c,4); \
7657 b ^= a; b -= rot(a,14); \
7658 c ^= b; c -= rot(b,24); \
7662 mono_aot_type_hash (MonoType *t1)
7664 guint hash = t1->type;
7666 hash |= t1->byref << 6; /* do not collide with t1->type values */
7668 case MONO_TYPE_VALUETYPE:
7669 case MONO_TYPE_CLASS:
7670 case MONO_TYPE_SZARRAY:
7671 /* check if the distribution is good enough */
7672 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7674 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7675 case MONO_TYPE_ARRAY:
7676 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7677 case MONO_TYPE_GENERICINST:
7678 return ((hash << 5) - hash) ^ 0;
7685 * mono_aot_method_hash:
7687 * Return a hash code for methods which only depends on metadata.
7690 mono_aot_method_hash (MonoMethod *method)
7692 MonoMethodSignature *sig;
7696 guint32 *hashes_start, *hashes;
7698 MonoGenericInst *class_ginst = NULL;
7699 MonoGenericInst *ginst = NULL;
7701 /* Similar to the hash in mono_method_get_imt_slot () */
7703 sig = mono_method_signature (method);
7705 if (method->klass->generic_class)
7706 class_ginst = method->klass->generic_class->context.class_inst;
7707 if (method->is_inflated)
7708 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7710 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7711 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7712 hashes = hashes_start;
7714 /* Some wrappers are assigned to random classes */
7715 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7716 klass = method->klass;
7718 klass = mono_defaults.object_class;
7720 if (!method->wrapper_type) {
7723 if (klass->generic_class)
7724 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7726 full_name = mono_type_full_name (&klass->byval_arg);
7728 hashes [0] = mono_metadata_str_hash (full_name);
7732 hashes [0] = mono_metadata_str_hash (klass->name);
7733 hashes [1] = mono_metadata_str_hash (klass->name_space);
7735 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7736 /* The method name includes a stringified pointer */
7739 hashes [2] = mono_metadata_str_hash (method->name);
7740 hashes [3] = method->wrapper_type;
7741 hashes [4] = mono_aot_type_hash (sig->ret);
7743 for (i = 0; i < sig->param_count; i++) {
7744 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7747 for (i = 0; i < class_ginst->type_argc; ++i)
7748 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7751 for (i = 0; i < ginst->type_argc; ++i)
7752 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7754 g_assert (hindex == hashes_count);
7756 /* Setup internal state */
7757 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7759 /* Handle most of the hashes */
7760 while (hashes_count > 3) {
7769 /* Handle the last 3 hashes (all the case statements fall through) */
7770 switch (hashes_count) {
7771 case 3 : c += hashes [2];
7772 case 2 : b += hashes [1];
7773 case 1 : a += hashes [0];
7775 case 0: /* nothing left to add */
7779 free (hashes_start);
7788 * mono_aot_get_array_helper_from_wrapper;
7790 * Get the helper method in Array called by an array wrapper method.
7793 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7797 MonoGenericContext ctx;
7798 MonoType *args [16];
7799 char *mname, *iname, *s, *s2, *helper_name = NULL;
7801 prefix = "System.Collections.Generic";
7802 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7803 s2 = strstr (s, "`1.");
7809 //printf ("X: %s %s\n", iname, mname);
7811 if (!strcmp (iname, "IList"))
7812 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7814 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7815 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7817 g_free (helper_name);
7820 if (m->is_generic) {
7822 memset (&ctx, 0, sizeof (ctx));
7823 args [0] = &method->klass->element_class->byval_arg;
7824 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7825 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7826 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7832 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7834 typedef struct HashEntry {
7835 guint32 key, value, index;
7836 struct HashEntry *next;
7840 * emit_extra_methods:
7842 * Emit methods which are not in the METHOD table, like wrappers.
7845 emit_extra_methods (MonoAotCompile *acfg)
7847 int i, table_size, buf_size;
7850 guint32 *info_offsets;
7853 HashEntry *entry, *new_entry;
7854 int nmethods, max_chain_length;
7857 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7859 /* Emit method info */
7861 for (i = 0; i < acfg->extra_methods->len; ++i) {
7862 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7863 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7869 p = buf = g_malloc (buf_size);
7873 method = cfg->method_to_register;
7875 encode_method_ref (acfg, method, p, &p);
7877 g_assert ((p - buf) < buf_size);
7879 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7884 * Construct a chained hash table for mapping indexes in extra_method_info to
7887 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7888 table = g_ptr_array_sized_new (table_size);
7889 for (i = 0; i < table_size; ++i)
7890 g_ptr_array_add (table, NULL);
7891 chain_lengths = g_new0 (int, table_size);
7892 max_chain_length = 0;
7893 for (i = 0; i < acfg->extra_methods->len; ++i) {
7894 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7895 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7901 key = info_offsets [i];
7902 value = get_method_index (acfg, method);
7904 hash = mono_aot_method_hash (method) % table_size;
7905 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
7907 chain_lengths [hash] ++;
7908 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7910 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7911 new_entry->key = key;
7912 new_entry->value = value;
7914 entry = g_ptr_array_index (table, hash);
7915 if (entry == NULL) {
7916 new_entry->index = hash;
7917 g_ptr_array_index (table, hash) = new_entry;
7920 entry = entry->next;
7922 entry->next = new_entry;
7923 new_entry->index = table->len;
7924 g_ptr_array_add (table, new_entry);
7928 //printf ("MAX: %d\n", max_chain_length);
7930 /* Emit the table */
7931 sprintf (symbol, "extra_method_table");
7932 emit_section_change (acfg, RODATA_SECT, 0);
7933 emit_alignment (acfg, 8);
7934 emit_label (acfg, symbol);
7936 emit_int32 (acfg, table_size);
7937 for (i = 0; i < table->len; ++i) {
7938 HashEntry *entry = g_ptr_array_index (table, i);
7940 if (entry == NULL) {
7941 emit_int32 (acfg, 0);
7942 emit_int32 (acfg, 0);
7943 emit_int32 (acfg, 0);
7945 //g_assert (entry->key > 0);
7946 emit_int32 (acfg, entry->key);
7947 emit_int32 (acfg, entry->value);
7949 emit_int32 (acfg, entry->next->index);
7951 emit_int32 (acfg, 0);
7956 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7957 * This is used by mono_aot_find_jit_info ().
7959 sprintf (symbol, "extra_method_info_offsets");
7960 emit_section_change (acfg, RODATA_SECT, 0);
7961 emit_alignment (acfg, 8);
7962 emit_label (acfg, symbol);
7964 emit_int32 (acfg, acfg->extra_methods->len);
7965 for (i = 0; i < acfg->extra_methods->len; ++i) {
7966 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7968 emit_int32 (acfg, get_method_index (acfg, method));
7969 emit_int32 (acfg, info_offsets [i]);
7974 emit_exception_info (MonoAotCompile *acfg)
7979 SeqPointData sp_data;
7980 gboolean seq_points_to_file = FALSE;
7982 offsets = g_new0 (gint32, acfg->nmethods);
7983 for (i = 0; i < acfg->nmethods; ++i) {
7984 if (acfg->cfgs [i]) {
7985 MonoCompile *cfg = acfg->cfgs [i];
7987 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
7988 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
7989 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
7990 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
7991 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
7993 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
7994 offsets [i] = cfg->ex_info_offset;
7996 if (method_seq_points_to_file) {
7997 if (!seq_points_to_file) {
7998 mono_seq_point_data_init (&sp_data, acfg->nmethods);
7999 seq_points_to_file = TRUE;
8001 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8008 if (seq_points_to_file) {
8009 char *seq_points_aot_file;
8010 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8011 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8012 mono_seq_point_data_free (&sp_data);
8013 g_free (seq_points_aot_file);
8016 sprintf (symbol, "ex_info_offsets");
8017 emit_section_change (acfg, RODATA_SECT, 1);
8018 emit_alignment (acfg, 8);
8019 emit_label (acfg, symbol);
8021 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
8026 emit_unwind_info (MonoAotCompile *acfg)
8032 * The unwind info contains a lot of duplicates so we emit each unique
8033 * entry once, and only store the offset from the start of the table in the
8037 sprintf (symbol, "unwind_info");
8038 emit_section_change (acfg, RODATA_SECT, 1);
8039 emit_alignment (acfg, 8);
8040 emit_label (acfg, symbol);
8042 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8043 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8044 guint8 *unwind_info;
8045 guint32 unwind_info_len;
8049 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8052 encode_value (unwind_info_len, p, &p);
8053 emit_bytes (acfg, buf, p - buf);
8054 emit_bytes (acfg, unwind_info, unwind_info_len);
8056 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8061 emit_class_info (MonoAotCompile *acfg)
8067 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8068 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8069 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8071 sprintf (symbol, "class_info_offsets");
8072 emit_section_change (acfg, RODATA_SECT, 1);
8073 emit_alignment (acfg, 8);
8074 emit_label (acfg, symbol);
8076 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8080 typedef struct ClassNameTableEntry {
8081 guint32 token, index;
8082 struct ClassNameTableEntry *next;
8083 } ClassNameTableEntry;
8086 emit_class_name_table (MonoAotCompile *acfg)
8089 guint32 token, hash;
8094 ClassNameTableEntry *entry, *new_entry;
8097 * Construct a chained hash table for mapping class names to typedef tokens.
8099 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8100 table = g_ptr_array_sized_new (table_size);
8101 for (i = 0; i < table_size; ++i)
8102 g_ptr_array_add (table, NULL);
8103 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8105 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8106 klass = mono_class_get_checked (acfg->image, token, &error);
8108 mono_error_cleanup (&error);
8111 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8112 hash = mono_metadata_str_hash (full_name) % table_size;
8115 /* FIXME: Allocate from the mempool */
8116 new_entry = g_new0 (ClassNameTableEntry, 1);
8117 new_entry->token = token;
8119 entry = g_ptr_array_index (table, hash);
8120 if (entry == NULL) {
8121 new_entry->index = hash;
8122 g_ptr_array_index (table, hash) = new_entry;
8125 entry = entry->next;
8127 entry->next = new_entry;
8128 new_entry->index = table->len;
8129 g_ptr_array_add (table, new_entry);
8133 /* Emit the table */
8134 sprintf (symbol, "class_name_table");
8135 emit_section_change (acfg, RODATA_SECT, 0);
8136 emit_alignment (acfg, 8);
8137 emit_label (acfg, symbol);
8139 /* FIXME: Optimize memory usage */
8140 g_assert (table_size < 65000);
8141 emit_int16 (acfg, table_size);
8142 g_assert (table->len < 65000);
8143 for (i = 0; i < table->len; ++i) {
8144 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8146 if (entry == NULL) {
8147 emit_int16 (acfg, 0);
8148 emit_int16 (acfg, 0);
8150 emit_int16 (acfg, mono_metadata_token_index (entry->token));
8152 emit_int16 (acfg, entry->next->index);
8154 emit_int16 (acfg, 0);
8160 emit_image_table (MonoAotCompile *acfg)
8166 * The image table is small but referenced in a lot of places.
8167 * So we emit it at once, and reference its elements by an index.
8170 sprintf (symbol, "image_table");
8171 emit_section_change (acfg, RODATA_SECT, 1);
8172 emit_alignment (acfg, 8);
8173 emit_label (acfg, symbol);
8175 emit_int32 (acfg, acfg->image_table->len);
8176 for (i = 0; i < acfg->image_table->len; i++) {
8177 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8178 MonoAssemblyName *aname = &image->assembly->aname;
8180 /* FIXME: Support multi-module assemblies */
8181 g_assert (image->assembly->image == image);
8183 emit_string (acfg, image->assembly_name);
8184 emit_string (acfg, image->guid);
8185 emit_string (acfg, aname->culture ? aname->culture : "");
8186 emit_string (acfg, (const char*)aname->public_key_token);
8188 emit_alignment (acfg, 8);
8189 emit_int32 (acfg, aname->flags);
8190 emit_int32 (acfg, aname->major);
8191 emit_int32 (acfg, aname->minor);
8192 emit_int32 (acfg, aname->build);
8193 emit_int32 (acfg, aname->revision);
8198 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8201 int i, first_plt_got_patch = 0, buf_size;
8203 guint32 *got_info_offsets;
8204 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8206 /* Add the patches needed by the PLT to the GOT */
8208 acfg->plt_got_offset_base = acfg->got_offset;
8209 first_plt_got_patch = info->got_patches->len;
8210 for (i = 1; i < acfg->plt_offset; ++i) {
8211 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8213 g_ptr_array_add (info->got_patches, plt_entry->ji);
8215 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8218 acfg->got_offset += acfg->plt_offset;
8223 * - optimize offsets table.
8224 * - reduce number of exported symbols.
8225 * - emit info for a klass only once.
8226 * - determine when a method uses a GOT slot which is guaranteed to be already
8228 * - clean up and document the code.
8229 * - use String.Empty in class libs.
8232 /* Encode info required to decode shared GOT entries */
8233 buf_size = info->got_patches->len * 128;
8234 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8235 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8237 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8239 if (acfg->plt_offset)
8240 acfg->plt_got_info_offsets [0] = 0;
8242 for (i = 0; i < info->got_patches->len; ++i) {
8243 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8248 encode_value (ji->type, p, &p);
8250 encode_patch (acfg, ji, p, &p);
8251 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8252 g_assert (p - buf <= buf_size);
8253 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8255 if (!llvm && i >= first_plt_got_patch)
8256 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8257 acfg->stats.got_info_size += p - buf;
8260 /* Emit got_info_offsets table */
8262 sprintf (symbol, "llvm_got_info_offsets");
8264 sprintf (symbol, "got_info_offsets");
8265 emit_section_change (acfg, RODATA_SECT, 1);
8266 emit_alignment (acfg, 8);
8267 emit_label (acfg, symbol);
8269 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8270 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8274 emit_got (MonoAotCompile *acfg)
8278 /* Don't make GOT global so accesses to it don't need relocations */
8279 sprintf (symbol, "%s", acfg->got_symbol);
8280 emit_section_change (acfg, ".bss", 0);
8281 emit_alignment (acfg, 8);
8282 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8283 emit_label (acfg, symbol);
8284 if (acfg->got_offset > 0)
8285 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8287 sprintf (symbol, "got_end");
8288 emit_label (acfg, symbol);
8291 typedef struct GlobalsTableEntry {
8292 guint32 value, index;
8293 struct GlobalsTableEntry *next;
8294 } GlobalsTableEntry;
8297 emit_globals (MonoAotCompile *acfg)
8303 GlobalsTableEntry *entry, *new_entry;
8305 if (!acfg->aot_opts.static_link)
8309 * When static linking, we emit a table containing our globals.
8313 * Construct a chained hash table for mapping global names to their index in
8314 * the globals table.
8316 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8317 table = g_ptr_array_sized_new (table_size);
8318 for (i = 0; i < table_size; ++i)
8319 g_ptr_array_add (table, NULL);
8320 for (i = 0; i < acfg->globals->len; ++i) {
8321 char *name = g_ptr_array_index (acfg->globals, i);
8323 hash = mono_metadata_str_hash (name) % table_size;
8325 /* FIXME: Allocate from the mempool */
8326 new_entry = g_new0 (GlobalsTableEntry, 1);
8327 new_entry->value = i;
8329 entry = g_ptr_array_index (table, hash);
8330 if (entry == NULL) {
8331 new_entry->index = hash;
8332 g_ptr_array_index (table, hash) = new_entry;
8335 entry = entry->next;
8337 entry->next = new_entry;
8338 new_entry->index = table->len;
8339 g_ptr_array_add (table, new_entry);
8343 /* Emit the table */
8344 sprintf (symbol, ".Lglobals_hash");
8345 emit_section_change (acfg, RODATA_SECT, 0);
8346 emit_alignment (acfg, 8);
8347 emit_label (acfg, symbol);
8349 /* FIXME: Optimize memory usage */
8350 g_assert (table_size < 65000);
8351 emit_int16 (acfg, table_size);
8352 for (i = 0; i < table->len; ++i) {
8353 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8355 if (entry == NULL) {
8356 emit_int16 (acfg, 0);
8357 emit_int16 (acfg, 0);
8359 emit_int16 (acfg, entry->value + 1);
8361 emit_int16 (acfg, entry->next->index);
8363 emit_int16 (acfg, 0);
8367 /* Emit the names */
8368 for (i = 0; i < acfg->globals->len; ++i) {
8369 char *name = g_ptr_array_index (acfg->globals, i);
8371 sprintf (symbol, "name_%d", i);
8372 emit_section_change (acfg, RODATA_SECT, 1);
8374 emit_alignment (acfg, 4);
8376 emit_label (acfg, symbol);
8377 emit_string (acfg, name);
8380 /* Emit the globals table */
8381 sprintf (symbol, "globals");
8382 emit_section_change (acfg, ".data", 0);
8383 /* This is not a global, since it is accessed by the init function */
8384 emit_alignment (acfg, 8);
8385 emit_label (acfg, symbol);
8387 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8388 emit_pointer (acfg, symbol);
8390 for (i = 0; i < acfg->globals->len; ++i) {
8391 char *name = g_ptr_array_index (acfg->globals, i);
8393 sprintf (symbol, "name_%d", i);
8394 emit_pointer (acfg, symbol);
8396 g_assert (strlen (name) < sizeof (symbol));
8397 sprintf (symbol, "%s", name);
8398 emit_pointer (acfg, symbol);
8400 /* Null terminate the table */
8401 emit_int32 (acfg, 0);
8402 emit_int32 (acfg, 0);
8406 emit_autoreg (MonoAotCompile *acfg)
8411 * Emit a function into the .ctor section which will be called by the ELF
8412 * loader to register this module with the runtime.
8414 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8417 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8419 arch_emit_autoreg (acfg, symbol);
8425 emit_mem_end (MonoAotCompile *acfg)
8429 sprintf (symbol, "mem_end");
8430 emit_section_change (acfg, ".text", 1);
8431 emit_alignment_code (acfg, 8);
8432 emit_label (acfg, symbol);
8436 * Emit a structure containing all the information not stored elsewhere.
8439 emit_file_info (MonoAotCompile *acfg)
8444 const char *gc_name;
8447 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8449 if (acfg->aot_opts.bind_to_runtime_version) {
8450 build_info = mono_get_runtime_build_info ();
8451 emit_string_symbol (acfg, "runtime_version", build_info);
8452 g_free (build_info);
8454 emit_string_symbol (acfg, "runtime_version", "");
8457 /* Emit a string holding the assembly name */
8458 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8461 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8464 gc_name = mono_gc_get_gc_name ();
8465 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8467 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8468 emit_section_change (acfg, ".data", 0);
8469 emit_alignment (acfg, 8);
8470 emit_label (acfg, symbol);
8471 if (!acfg->aot_opts.static_link)
8472 emit_global (acfg, symbol, FALSE);
8474 /* The data emitted here must match MonoAotFileInfo. */
8476 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8477 emit_int32 (acfg, 0);
8480 * We emit pointers to our data structures instead of emitting global symbols which
8481 * point to them, to reduce the number of globals, and because using globals leads to
8482 * various problems (i.e. arm/thumb).
8484 emit_pointer (acfg, acfg->got_symbol);
8486 emit_pointer (acfg, acfg->llvm_got_symbol);
8488 emit_pointer (acfg, NULL);
8489 emit_pointer (acfg, acfg->methods_symbol);
8490 emit_pointer (acfg, "jit_code_start");
8491 emit_pointer (acfg, "jit_code_end");
8494 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8496 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8498 emit_pointer (acfg, NULL);
8500 emit_pointer (acfg, "blob");
8501 emit_pointer (acfg, "class_name_table");
8502 emit_pointer (acfg, "class_info_offsets");
8503 emit_pointer (acfg, "method_info_offsets");
8504 emit_pointer (acfg, "ex_info_offsets");
8505 emit_pointer (acfg, "method_addresses");
8506 emit_pointer (acfg, "extra_method_info_offsets");
8507 emit_pointer (acfg, "extra_method_table");
8508 emit_pointer (acfg, "got_info_offsets");
8510 emit_pointer (acfg, "llvm_got_info_offsets");
8512 emit_pointer (acfg, NULL);
8513 emit_pointer (acfg, "unwind_info");
8514 emit_pointer (acfg, "mem_end");
8515 emit_pointer (acfg, "image_table");
8516 emit_pointer (acfg, "plt");
8517 emit_pointer (acfg, "plt_end");
8518 emit_pointer (acfg, "assembly_guid");
8519 emit_pointer (acfg, "runtime_version");
8520 if (acfg->num_trampoline_got_entries) {
8521 emit_pointer (acfg, "specific_trampolines");
8522 emit_pointer (acfg, "static_rgctx_trampolines");
8523 emit_pointer (acfg, "imt_thunks");
8524 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8526 emit_pointer (acfg, NULL);
8527 emit_pointer (acfg, NULL);
8528 emit_pointer (acfg, NULL);
8529 emit_pointer (acfg, NULL);
8531 if (acfg->aot_opts.static_link) {
8532 emit_pointer (acfg, "globals");
8534 emit_pointer (acfg, NULL);
8536 emit_pointer (acfg, "assembly_name");
8537 emit_pointer (acfg, "unbox_trampolines");
8538 emit_pointer (acfg, "unbox_trampolines_end");
8539 emit_pointer (acfg, "unbox_trampoline_addresses");
8541 emit_int32 (acfg, acfg->plt_got_offset_base);
8542 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8543 emit_int32 (acfg, acfg->plt_offset);
8544 emit_int32 (acfg, acfg->nmethods);
8545 emit_int32 (acfg, acfg->flags);
8546 emit_int32 (acfg, acfg->opts);
8547 emit_int32 (acfg, acfg->simd_opts);
8548 emit_int32 (acfg, gc_name_offset);
8550 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8551 emit_int32 (acfg, acfg->num_trampolines [i]);
8552 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8553 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8554 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8555 emit_int32 (acfg, acfg->trampoline_size [i]);
8556 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8558 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8563 memset (&t, 0, sizeof (MonoType));
8564 t.type = MONO_TYPE_R8;
8565 mono_type_size (&t, &align);
8566 emit_int32 (acfg, align);
8568 memset (&t, 0, sizeof (MonoType));
8569 t.type = MONO_TYPE_I8;
8570 mono_type_size (&t, &align);
8572 emit_int32 (acfg, align);
8575 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8576 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8578 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8579 emit_int32 (acfg, acfg->tramp_page_size);
8580 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8581 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8583 if (acfg->aot_opts.static_link) {
8587 * Emit a global symbol which can be passed by an embedding app to
8588 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8591 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8593 /* Get rid of characters which cannot occur in symbols */
8595 for (p = symbol; *p; ++p) {
8596 if (!(isalnum (*p) || *p == '_'))
8599 acfg->static_linking_symbol = g_strdup (symbol);
8600 emit_global_inner (acfg, symbol, FALSE);
8601 emit_alignment (acfg, sizeof (gpointer));
8602 emit_label (acfg, symbol);
8603 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8608 emit_blob (MonoAotCompile *acfg)
8612 sprintf (symbol, "blob");
8613 emit_section_change (acfg, RODATA_SECT, 1);
8614 emit_alignment (acfg, 8);
8615 emit_label (acfg, symbol);
8617 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8621 emit_objc_selectors (MonoAotCompile *acfg)
8626 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8631 * cat > foo.m << EOF
8634 * return @selector(print:);
8639 mono_img_writer_emit_unset_mode (acfg->w);
8640 g_assert (acfg->fp);
8641 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8642 fprintf (acfg->fp, ".align 3\n");
8643 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8644 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8645 emit_label (acfg, symbol);
8646 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8647 emit_pointer (acfg, symbol);
8650 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8651 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8652 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8653 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8656 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8657 fprintf (acfg->fp, ".align 3\n");
8658 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8659 fprintf (acfg->fp, ".long 0\n");
8660 fprintf (acfg->fp, ".long 16\n");
8664 emit_dwarf_info (MonoAotCompile *acfg)
8666 #ifdef EMIT_DWARF_INFO
8670 /* DIEs for methods */
8671 for (i = 0; i < acfg->nmethods; ++i) {
8672 MonoCompile *cfg = acfg->cfgs [i];
8677 // FIXME: LLVM doesn't define .Lme_...
8678 if (cfg->compile_llvm)
8681 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8683 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 ()));
8689 collect_methods (MonoAotCompile *acfg)
8692 MonoImage *image = acfg->image;
8694 /* Collect methods */
8695 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8698 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8700 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8703 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8704 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8705 mono_error_cleanup (&error);
8709 /* Load all methods eagerly to skip the slower lazy loading code */
8710 mono_class_setup_methods (method->klass);
8712 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8713 /* Compile the wrapper instead */
8714 /* We do this here instead of add_wrappers () because it is easy to do it here */
8715 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8719 /* FIXME: Some mscorlib methods don't have debug info */
8721 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8722 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8723 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8724 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8725 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8726 if (!mono_debug_lookup_method (method)) {
8727 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8734 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8735 add_method_with_index (acfg, method, i, FALSE);
8736 acfg->method_index ++;
8739 /* gsharedvt methods */
8740 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8743 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8745 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8748 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8749 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8752 if (strcmp (method->name, "gshared2"))
8756 if (!strstr (method->klass->image->name, "mini"))
8759 if (method->is_generic || method->klass->generic_container) {
8760 MonoMethod *gshared;
8762 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8763 add_extra_method (acfg, gshared);
8767 add_generic_instances (acfg);
8769 if (mono_aot_mode_is_full (&acfg->aot_opts))
8770 add_wrappers (acfg);
8775 compile_methods (MonoAotCompile *acfg)
8779 if (acfg->aot_opts.nthreads > 0) {
8784 gpointer *user_data;
8785 MonoMethod **methods;
8787 methods_len = acfg->methods->len;
8789 len = acfg->methods->len / acfg->aot_opts.nthreads;
8792 * Partition the list of methods into fragments, and hand it to threads to
8795 threads = g_ptr_array_new ();
8796 /* Make a copy since acfg->methods is modified by compile_method () */
8797 methods = g_new0 (MonoMethod*, methods_len);
8798 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8799 for (i = 0; i < methods_len; ++i)
8800 methods [i] = g_ptr_array_index (acfg->methods, i);
8802 while (i < methods_len) {
8803 frag = g_ptr_array_new ();
8804 for (j = 0; j < len; ++j) {
8805 if (i < methods_len) {
8806 g_ptr_array_add (frag, methods [i]);
8811 user_data = g_new0 (gpointer, 3);
8812 user_data [0] = mono_domain_get ();
8813 user_data [1] = acfg;
8814 user_data [2] = frag;
8816 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8817 g_ptr_array_add (threads, handle);
8821 for (i = 0; i < threads->len; ++i) {
8822 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8828 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8829 for (i = methods_len; i < acfg->methods->len; ++i) {
8830 /* This can new methods to acfg->methods */
8831 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8836 compile_asm (MonoAotCompile *acfg)
8838 char *command, *objfile;
8839 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8840 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8841 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
8843 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8844 #define AS_OPTIONS "--64"
8845 #elif defined(TARGET_POWERPC64)
8846 #define AS_OPTIONS "-a64 -mppc64"
8847 #define LD_OPTIONS "-m elf64ppc"
8848 #elif defined(sparc) && SIZEOF_VOID_P == 8
8849 #define AS_OPTIONS "-xarch=v9"
8850 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8851 #define AS_OPTIONS "-arch i386"
8853 #define AS_OPTIONS ""
8856 #ifdef __native_client_codegen__
8857 #if defined(TARGET_AMD64)
8858 #define AS_NAME "nacl64-as"
8860 #define AS_NAME "nacl-as"
8862 #elif defined(TARGET_OSX)
8863 #define AS_NAME "clang"
8865 #define AS_NAME "as"
8869 #define LD_OPTIONS ""
8873 #define LD_NAME "ld -shared -G"
8874 #elif defined(__ppc__) && defined(TARGET_MACH)
8875 #define LD_NAME "gcc -dynamiclib"
8876 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8877 #define LD_NAME "clang --shared"
8878 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
8879 #define LD_NAME "gcc -shared --dll"
8880 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8881 #define LD_NAME "clang -m32 -dynamiclib"
8882 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
8883 #define LD_NAME "gcc --shared"
8886 if (acfg->aot_opts.asm_only) {
8887 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8888 if (acfg->aot_opts.static_link)
8889 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8891 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8895 if (acfg->aot_opts.static_link) {
8896 if (acfg->aot_opts.outfile)
8897 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8899 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8901 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8905 g_string_append (acfg->as_args, "-c -x assembler");
8908 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);
8909 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8910 if (execute_system (command) != 0) {
8916 if (acfg->llvm && !acfg->llvm_owriter) {
8917 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);
8918 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8919 if (execute_system (command) != 0) {
8928 if (acfg->aot_opts.static_link) {
8929 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8930 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8935 if (acfg->aot_opts.outfile)
8936 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8938 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8940 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8943 llvm_ofile = g_strdup (acfg->llvm_ofile);
8945 llvm_ofile = g_strdup ("");
8948 /* replace the ; flags separators with spaces */
8949 g_strdelimit (ld_flags, ";", ' ');
8952 command = g_strdup_printf ("%s -o %s %s %s.o %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
8954 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
8955 acfg->tmpfname, ld_flags);
8957 aot_printf (acfg, "Executing the native linker: %s\n", command);
8958 if (execute_system (command) != 0) {
8959 g_free (tmp_outfile_name);
8960 g_free (outfile_name);
8969 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8970 printf ("Stripping the binary: %s\n", com);
8971 execute_system (com);
8974 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8976 * gas generates 'mapping symbols' each time code and data is mixed, which
8977 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8979 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8980 aot_printf (acfg, "Stripping the binary: %s\n", command);
8981 if (execute_system (command) != 0) {
8982 g_free (tmp_outfile_name);
8983 g_free (outfile_name);
8990 rename (tmp_outfile_name, outfile_name);
8992 #if defined(TARGET_MACH)
8993 command = g_strdup_printf ("dsymutil %s", outfile_name);
8994 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8995 if (execute_system (command) != 0) {
9000 if (!acfg->aot_opts.save_temps)
9003 g_free (tmp_outfile_name);
9004 g_free (outfile_name);
9007 if (acfg->aot_opts.save_temps)
9008 aot_printf (acfg, "Retained input file.\n");
9010 unlink (acfg->tmpfname);
9015 static void init_got_info (GotInfo *info)
9019 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9020 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9021 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9022 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9023 info->got_patches = g_ptr_array_new ();
9026 static MonoAotCompile*
9027 acfg_create (MonoAssembly *ass, guint32 opts)
9029 MonoImage *image = ass->image;
9030 MonoAotCompile *acfg;
9032 acfg = g_new0 (MonoAotCompile, 1);
9033 acfg->methods = g_ptr_array_new ();
9034 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9035 acfg->method_depth = g_hash_table_new (NULL, NULL);
9036 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9037 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9038 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9039 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9040 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9041 acfg->image_hash = g_hash_table_new (NULL, NULL);
9042 acfg->image_table = g_ptr_array_new ();
9043 acfg->globals = g_ptr_array_new ();
9044 acfg->image = image;
9046 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9047 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9048 acfg->mempool = mono_mempool_new ();
9049 acfg->extra_methods = g_ptr_array_new ();
9050 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9051 acfg->unwind_ops = g_ptr_array_new ();
9052 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9053 acfg->method_order = g_ptr_array_new ();
9054 acfg->export_names = g_hash_table_new (NULL, NULL);
9055 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9056 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9057 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9058 mono_mutex_init_recursive (&acfg->mutex);
9060 init_got_info (&acfg->got_info);
9061 init_got_info (&acfg->llvm_got_info);
9067 got_info_free (GotInfo *info)
9071 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9072 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9073 g_free (info->patch_to_got_offset_by_type);
9074 g_hash_table_destroy (info->patch_to_got_offset);
9075 g_ptr_array_free (info->got_patches, TRUE);
9079 acfg_free (MonoAotCompile *acfg)
9083 mono_img_writer_destroy (acfg->w);
9084 for (i = 0; i < acfg->nmethods; ++i)
9086 g_free (acfg->cfgs [i]);
9087 g_free (acfg->cfgs);
9088 g_free (acfg->static_linking_symbol);
9089 g_free (acfg->got_symbol);
9090 g_free (acfg->plt_symbol);
9091 g_ptr_array_free (acfg->methods, TRUE);
9092 g_ptr_array_free (acfg->image_table, TRUE);
9093 g_ptr_array_free (acfg->globals, TRUE);
9094 g_ptr_array_free (acfg->unwind_ops, TRUE);
9095 g_hash_table_destroy (acfg->method_indexes);
9096 g_hash_table_destroy (acfg->method_depth);
9097 g_hash_table_destroy (acfg->plt_offset_to_entry);
9098 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9099 if (acfg->patch_to_plt_entry [i])
9100 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9102 g_free (acfg->patch_to_plt_entry);
9103 g_hash_table_destroy (acfg->method_to_cfg);
9104 g_hash_table_destroy (acfg->token_info_hash);
9105 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9106 g_hash_table_destroy (acfg->image_hash);
9107 g_hash_table_destroy (acfg->unwind_info_offsets);
9108 g_hash_table_destroy (acfg->method_label_hash);
9109 g_hash_table_destroy (acfg->export_names);
9110 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9111 g_hash_table_destroy (acfg->klass_blob_hash);
9112 g_hash_table_destroy (acfg->method_blob_hash);
9113 got_info_free (&acfg->got_info);
9114 got_info_free (&acfg->llvm_got_info);
9115 mono_mempool_destroy (acfg->mempool);
9119 #define WRAPPER(e,n) n,
9120 static const char* const
9121 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9122 #include "mono/metadata/wrapper-types.h"
9126 static G_GNUC_UNUSED const char*
9127 get_wrapper_type_name (int type)
9129 return wrapper_type_names [type];
9135 static void aot_dump (MonoAotCompile *acfg)
9141 mono_json_writer_init (&writer);
9143 mono_json_writer_object_begin(&writer);
9146 mono_json_writer_indent (&writer);
9147 mono_json_writer_object_key(&writer, "methods");
9148 mono_json_writer_array_begin (&writer);
9151 for (i = 0; i < acfg->nmethods; ++i) {
9156 cfg = acfg->cfgs [i];
9160 method = cfg->orig_method;
9162 mono_json_writer_indent (&writer);
9163 mono_json_writer_object_begin(&writer);
9165 mono_json_writer_indent (&writer);
9166 mono_json_writer_object_key(&writer, "name");
9167 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9169 mono_json_writer_indent (&writer);
9170 mono_json_writer_object_key(&writer, "signature");
9171 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9172 /*signature=*/TRUE));
9174 mono_json_writer_indent (&writer);
9175 mono_json_writer_object_key(&writer, "code_size");
9176 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9178 klass = method->klass;
9180 mono_json_writer_indent (&writer);
9181 mono_json_writer_object_key(&writer, "class");
9182 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9184 mono_json_writer_indent (&writer);
9185 mono_json_writer_object_key(&writer, "namespace");
9186 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9188 mono_json_writer_indent (&writer);
9189 mono_json_writer_object_key(&writer, "wrapper_type");
9190 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9192 mono_json_writer_indent_pop (&writer);
9193 mono_json_writer_indent (&writer);
9194 mono_json_writer_object_end (&writer);
9195 mono_json_writer_printf (&writer, ",\n");
9198 mono_json_writer_indent_pop (&writer);
9199 mono_json_writer_indent (&writer);
9200 mono_json_writer_array_end (&writer);
9201 mono_json_writer_printf (&writer, ",\n");
9205 mono_json_writer_indent_push (&writer);
9206 mono_json_writer_indent (&writer);
9207 mono_json_writer_object_key(&writer, "plt");
9208 mono_json_writer_array_begin (&writer);
9210 for (i = 0; i < acfg->plt_offset; ++i) {
9211 MonoPltEntry *plt_entry = NULL;
9216 * The first plt entry is unused.
9220 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9223 mono_json_writer_indent (&writer);
9224 mono_json_writer_printf (&writer, "{ ");
9225 mono_json_writer_object_key(&writer, "symbol");
9226 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9229 mono_json_writer_indent_pop (&writer);
9230 mono_json_writer_indent (&writer);
9231 mono_json_writer_array_end (&writer);
9232 mono_json_writer_printf (&writer, ",\n");
9237 mono_json_writer_indent_push (&writer);
9238 mono_json_writer_indent (&writer);
9239 mono_json_writer_object_key(&writer, "got");
9240 mono_json_writer_array_begin (&writer);
9242 mono_json_writer_indent_push (&writer);
9243 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9244 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9246 mono_json_writer_indent (&writer);
9247 mono_json_writer_printf (&writer, "{ ");
9248 mono_json_writer_object_key(&writer, "patch_name");
9249 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9252 mono_json_writer_indent_pop (&writer);
9253 mono_json_writer_indent (&writer);
9254 mono_json_writer_array_end (&writer);
9255 mono_json_writer_printf (&writer, ",\n");
9258 mono_json_writer_indent_pop (&writer);
9259 mono_json_writer_indent (&writer);
9260 mono_json_writer_object_end (&writer);
9262 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9263 dumpfile = fopen (dumpname, "w+");
9266 fprintf (dumpfile, "%s", writer.text->str);
9269 mono_json_writer_destroy (&writer);
9273 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9275 MonoImage *image = ass->image;
9278 MonoAotCompile *acfg;
9279 char *outfile_name, *tmp_outfile_name, *p;
9280 char llvm_stats_msg [256];
9284 acfg = acfg_create (ass, opts);
9286 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9287 acfg->aot_opts.write_symbols = TRUE;
9288 acfg->aot_opts.ntrampolines = 1024;
9289 acfg->aot_opts.nrgctx_trampolines = 1024;
9290 acfg->aot_opts.nimt_trampolines = 128;
9291 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9292 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9293 acfg->aot_opts.llvm_path = g_strdup ("");
9295 acfg->aot_opts.use_trampolines_page = TRUE;
9298 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9300 if (acfg->aot_opts.logfile) {
9301 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9304 if (acfg->aot_opts.static_link)
9305 acfg->aot_opts.autoreg = TRUE;
9307 //acfg->aot_opts.print_skipped_methods = TRUE;
9309 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9310 if (opts & MONO_OPT_GSHAREDVT) {
9311 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9316 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9318 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9319 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9320 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9325 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9326 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9330 if (acfg->aot_opts.static_link)
9331 acfg->aot_opts.asm_writer = TRUE;
9333 if (acfg->aot_opts.soft_debug) {
9334 MonoDebugOptions *opt = mini_get_debug_options ();
9336 opt->mdb_optimizations = TRUE;
9337 opt->gen_sdb_seq_points = TRUE;
9339 if (!mono_debug_enabled ()) {
9340 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9343 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9346 if (mono_use_llvm || acfg->aot_opts.llvm) {
9348 acfg->aot_opts.asm_writer = TRUE;
9349 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9351 if (acfg->aot_opts.soft_debug) {
9352 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9358 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9359 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9364 * Emit all LLVM code into a separate assembly/object file and link with it
9367 if (!acfg->aot_opts.asm_only) {
9368 acfg->llvm_owriter = TRUE;
9369 } else if (acfg->aot_opts.llvm_outfile) {
9370 int len = strlen (acfg->aot_opts.llvm_outfile);
9372 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
9373 acfg->llvm_owriter = TRUE;
9377 if (mono_aot_mode_is_full (&acfg->aot_opts))
9378 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9380 if (acfg->aot_opts.instances_logfile_path) {
9381 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9382 if (!acfg->instances_logfile) {
9383 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9388 load_profile_files (acfg);
9390 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9391 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9392 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9394 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9395 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9396 if (acfg->opts & MONO_OPT_GSHAREDVT)
9397 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9400 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9404 if (acfg->llvm && acfg->thumb_mixed)
9405 acfg->flags |= MONO_AOT_FILE_FLAG_LLVM_THUMB;
9407 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9408 /* Get rid of characters which cannot occur in symbols */
9409 for (p = acfg->assembly_name_sym; *p; ++p) {
9410 if (!(isalnum (*p) || *p == '_'))
9414 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9415 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9416 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9418 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9420 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9421 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9424 acfg->method_index = 1;
9426 if (mono_aot_mode_is_full (&acfg->aot_opts))
9427 mono_set_partial_sharing_supported (TRUE);
9429 res = collect_methods (acfg);
9433 acfg->cfgs_size = acfg->methods->len + 32;
9434 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9436 /* PLT offset 0 is reserved for the PLT trampoline */
9437 acfg->plt_offset = 1;
9442 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, TRUE, TRUE);
9446 /* GOT offset 0 is reserved for the address of the current assembly */
9450 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9451 ji->type = MONO_PATCH_INFO_IMAGE;
9452 ji->data.image = acfg->image;
9454 get_got_offset (acfg, FALSE, ji);
9455 get_got_offset (acfg, TRUE, ji);
9457 /* Slot 1 is reserved for the mscorlib got addr */
9458 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9459 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9460 get_got_offset (acfg, FALSE, ji);
9461 get_got_offset (acfg, TRUE, ji);
9463 /* This is very common */
9464 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9465 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9466 get_got_offset (acfg, FALSE, ji);
9467 get_got_offset (acfg, TRUE, ji);
9469 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9470 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9471 get_got_offset (acfg, FALSE, ji);
9472 get_got_offset (acfg, TRUE, ji);
9474 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9475 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9476 get_got_offset (acfg, FALSE, ji);
9477 get_got_offset (acfg, TRUE, ji);
9482 compile_methods (acfg);
9486 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9494 if (acfg->aot_opts.asm_only) {
9495 if (acfg->aot_opts.outfile) {
9496 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9497 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9499 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9500 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9502 g_assert (acfg->aot_opts.llvm_outfile);
9503 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9504 if (acfg->llvm_owriter)
9505 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
9507 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9509 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
9510 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9511 acfg->llvm_sfile = g_strdup ("temp-llvm.s");
9512 acfg->llvm_ofile = g_strdup ("temp-llvm.o");
9515 res = emit_llvm_file (acfg);
9521 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && mono_bin_writer_supported ()) {
9522 if (acfg->aot_opts.outfile)
9523 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9525 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9528 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9529 * it might be in another file system so the rename () won't work.
9531 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9533 acfg->fp = fopen (tmp_outfile_name, "w");
9535 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9539 acfg->w = mono_img_writer_create (acfg->fp, TRUE);
9540 acfg->use_bin_writer = TRUE;
9542 if (acfg->aot_opts.asm_only) {
9543 if (acfg->aot_opts.outfile)
9544 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9546 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9547 acfg->fp = fopen (acfg->tmpfname, "w+");
9549 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9550 acfg->fp = fdopen (i, "w+");
9552 if (acfg->fp == 0) {
9553 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9556 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9558 tmp_outfile_name = NULL;
9559 outfile_name = NULL;
9562 /* Compute symbols for methods */
9563 for (i = 0; i < acfg->nmethods; ++i) {
9564 if (acfg->cfgs [i]) {
9565 MonoCompile *cfg = acfg->cfgs [i];
9566 int method_index = get_method_index (acfg, cfg->orig_method);
9568 if (COMPILE_LLVM (cfg))
9569 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9570 else if (acfg->global_symbols || acfg->llvm)
9571 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9573 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9574 cfg->asm_debug_symbol = cfg->asm_symbol;
9578 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9580 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9581 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9584 //acfg->gas_line_numbers = TRUE;
9587 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9588 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9589 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9592 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9595 mono_img_writer_emit_start (acfg->w);
9598 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9604 emit_extra_methods (acfg);
9606 emit_trampolines (acfg);
9608 emit_class_name_table (acfg);
9610 emit_got_info (acfg, FALSE);
9612 emit_got_info (acfg, TRUE);
9614 emit_exception_info (acfg);
9616 emit_unwind_info (acfg);
9618 emit_class_info (acfg);
9622 emit_image_table (acfg);
9626 emit_file_info (acfg);
9630 emit_objc_selectors (acfg);
9632 emit_globals (acfg);
9634 emit_autoreg (acfg);
9637 emit_dwarf_info (acfg);
9638 mono_dwarf_writer_close (acfg->dwarf);
9641 emit_mem_end (acfg);
9643 if (acfg->need_pt_gnu_stack) {
9644 /* This is required so the .so doesn't have an executable stack */
9645 /* The bin writer already emits this */
9646 if (!acfg->use_bin_writer)
9647 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9652 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9655 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9657 strcpy (llvm_stats_msg, "");
9659 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;
9661 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",
9662 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9663 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9664 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9665 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9666 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9667 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,
9668 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9669 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9670 (int)(acfg->got_offset * sizeof (gpointer)));
9671 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9672 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9674 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9675 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9676 if (acfg->stats.genericcount)
9677 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9678 if (acfg->stats.abscount)
9679 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9680 if (acfg->stats.lmfcount)
9681 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9682 if (acfg->stats.ocount)
9683 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9686 res = mono_img_writer_emit_writeout (acfg->w);
9691 if (acfg->use_bin_writer) {
9692 int err = rename (tmp_outfile_name, outfile_name);
9695 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9699 res = compile_asm (acfg);
9706 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9708 if (acfg->aot_opts.stats) {
9711 aot_printf (acfg, "GOT slot distribution:\n");
9712 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9713 if (acfg->stats.got_slot_types [i])
9714 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]);
9717 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);
9719 if (acfg->aot_opts.dump_json)
9732 mono_aot_readonly_field_override (MonoClassField *field)
9738 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)