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;
218 char *llvm_got_symbol;
220 char *llvm_eh_frame_symbol;
221 GHashTable *method_label_hash;
222 const char *temp_prefix;
223 const char *user_symbol_prefix;
224 const char *llvm_label_prefix;
225 const char *inst_directive;
227 guint32 label_generator;
229 gboolean has_jitted_code;
230 MonoAotFileFlags flags;
231 MonoDynamicStream blob;
232 MonoClass **typespec_classes;
235 char *assembly_name_sym;
236 GHashTable *plt_entry_debug_sym_cache;
237 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
238 GHashTable *ginst_hash;
239 GHashTable *dwarf_ln_filenames;
240 gboolean global_symbols;
241 int objc_selector_index, objc_selector_index_2;
242 GPtrArray *objc_selectors;
243 GHashTable *objc_selector_to_index;
245 FILE *instances_logfile;
250 char *symbol, *llvm_symbol, *debug_sym;
252 gboolean jit_used, llvm_used;
255 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
256 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
258 /* This points to the current acfg in LLVM mode */
259 static MonoAotCompile *llvm_acfg;
261 #ifdef HAVE_ARRAY_ELEM_INIT
262 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
263 #define MSGSTRFIELD1(line) str##line
264 static const struct msgstr_t {
265 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
266 #include "patch-info.h"
269 #define PATCH_INFO(a,b) b,
270 #include "patch-info.h"
273 static const gint16 opidx [] = {
274 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
275 #include "patch-info.h"
279 static G_GNUC_UNUSED const char*
280 get_patch_name (int info)
282 return (const char*)&opstr + opidx [info];
286 #define PATCH_INFO(a,b) b,
287 static const char* const
288 patch_types [MONO_PATCH_INFO_NUM + 1] = {
289 #include "patch-info.h"
293 static G_GNUC_UNUSED const char*
294 get_patch_name (int info)
296 return patch_types [info];
302 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
305 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
311 output = acfg->logfile;
315 va_start (args, format);
316 vfprintf (output, format, args);
321 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
327 output = acfg->logfile;
331 va_start (args, format);
332 vfprintf (output, format, args);
337 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
342 if (mono_error_ok (error))
346 output = acfg->logfile;
350 va_start (args, format);
351 vfprintf (output, format, args);
353 mono_error_cleanup (error);
355 g_error ("FullAOT cannot continue if there are loader errors");
358 /* Wrappers around the image writer functions */
361 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
363 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
367 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
369 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
373 emit_label (MonoAotCompile *acfg, const char *name)
375 mono_img_writer_emit_label (acfg->w, name);
379 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
381 mono_img_writer_emit_bytes (acfg->w, buf, size);
385 emit_string (MonoAotCompile *acfg, const char *value)
387 mono_img_writer_emit_string (acfg->w, value);
391 emit_line (MonoAotCompile *acfg)
393 mono_img_writer_emit_line (acfg->w);
397 emit_alignment (MonoAotCompile *acfg, int size)
399 mono_img_writer_emit_alignment (acfg->w, size);
403 emit_alignment_code (MonoAotCompile *acfg, int size)
405 if (acfg->align_pad_value)
406 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
408 mono_img_writer_emit_alignment (acfg->w, size);
412 emit_padding (MonoAotCompile *acfg, int size)
417 if (acfg->align_pad_value) {
418 for (i = 0; i < 16; ++i)
419 buf [i] = acfg->align_pad_value;
421 memset (buf, 0, sizeof (buf));
424 for (i = 0; i < size; i += 16) {
426 emit_bytes (acfg, buf, size - i);
428 emit_bytes (acfg, buf, 16);
433 emit_pointer (MonoAotCompile *acfg, const char *target)
435 mono_img_writer_emit_pointer (acfg->w, target);
439 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
441 if (prefix [0] != '\0') {
442 char *s = g_strdup_printf ("%s%s", prefix, target);
443 mono_img_writer_emit_pointer (acfg->w, s);
446 mono_img_writer_emit_pointer (acfg->w, target);
451 emit_int16 (MonoAotCompile *acfg, int value)
453 mono_img_writer_emit_int16 (acfg->w, value);
457 emit_int32 (MonoAotCompile *acfg, int value)
459 mono_img_writer_emit_int32 (acfg->w, value);
463 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
465 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
469 emit_zero_bytes (MonoAotCompile *acfg, int num)
471 mono_img_writer_emit_zero_bytes (acfg->w, num);
475 emit_byte (MonoAotCompile *acfg, guint8 val)
477 mono_img_writer_emit_byte (acfg->w, val);
480 #ifdef __native_client_codegen__
482 emit_nacl_call_alignment (MonoAotCompile *acfg)
484 mono_img_writer_emit_nacl_call_alignment (acfg->w);
488 static G_GNUC_UNUSED void
489 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
491 mono_img_writer_emit_global (acfg->w, name, func);
495 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
497 if (acfg->aot_opts.no_dlsym) {
498 g_ptr_array_add (acfg->globals, g_strdup (name));
499 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
501 mono_img_writer_emit_global (acfg->w, name, func);
506 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
508 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
511 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
513 emit_info_symbol (MonoAotCompile *acfg, const char *name)
518 emit_label (acfg, name);
519 /* LLVM generated code references this */
520 sprintf (symbol, "%s%s", acfg->user_symbol_prefix, name);
521 emit_label (acfg, symbol);
522 emit_global (acfg, symbol, FALSE);
524 emit_label (acfg, name);
529 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
532 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
536 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
538 /* On apple, all symbols need to be aligned to avoid warnings from ld */
539 emit_alignment (acfg, 4);
541 mono_img_writer_emit_label (acfg->w, name);
542 mono_img_writer_emit_string (acfg->w, value);
545 static G_GNUC_UNUSED void
546 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
549 guint8 b = value & 0x7f;
551 if (value != 0) /* more bytes to come */
557 static G_GNUC_UNUSED void
558 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
561 gboolean negative = (value < 0);
568 /* the following is unnecessary if the
569 * implementation of >>= uses an arithmetic rather
570 * than logical shift for a signed left operand
574 value |= - ((gint64)1 <<(size - 7));
575 /* sign bit of byte is second high order bit (0x40) */
576 if ((value == 0 && !(byte & 0x40)) ||
577 (value == -1 && (byte & 0x40)))
581 emit_byte (acfg, byte);
585 static G_GNUC_UNUSED void
586 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
591 guint8 b = value & 0x7f;
593 if (value != 0) /* more bytes to come */
601 static G_GNUC_UNUSED void
602 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
605 gboolean negative = (value < 0);
613 /* the following is unnecessary if the
614 * implementation of >>= uses an arithmetic rather
615 * than logical shift for a signed left operand
619 value |= - (1 <<(size - 7));
620 /* sign bit of byte is second high order bit (0x40) */
621 if ((value == 0 && !(byte & 0x40)) ||
622 (value == -1 && (byte & 0x40)))
633 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
636 buf [0] = (val >> 0) & 0xff;
637 buf [1] = (val >> 8) & 0xff;
638 buf [2] = (val >> 16) & 0xff;
639 buf [3] = (val >> 24) & 0xff;
645 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
647 buf [0] = (val >> 0) & 0xff;
648 buf [1] = (val >> 8) & 0xff;
654 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
656 int len = strlen (s);
658 memcpy (buf, s, len + 1);
659 *endbuf = buf + len + 1;
663 emit_unset_mode (MonoAotCompile *acfg)
665 mono_img_writer_emit_unset_mode (acfg->w);
668 static G_GNUC_UNUSED void
669 emit_set_thumb_mode (MonoAotCompile *acfg)
671 emit_unset_mode (acfg);
672 fprintf (acfg->fp, ".code 16\n");
675 static G_GNUC_UNUSED void
676 emit_set_arm_mode (MonoAotCompile *acfg)
678 emit_unset_mode (acfg);
679 fprintf (acfg->fp, ".code 32\n");
683 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
688 g_assert (size % 4 == 0);
689 emit_unset_mode (acfg);
690 for (i = 0; i < size; i += 4)
691 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
693 emit_bytes (acfg, buf, size);
697 /* ARCHITECTURE SPECIFIC CODE */
699 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
700 #define EMIT_DWARF_INFO 1
703 #if defined(TARGET_ARM)
704 #define AOT_FUNC_ALIGNMENT 4
706 #define AOT_FUNC_ALIGNMENT 16
708 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
709 #undef AOT_FUNC_ALIGNMENT
710 #define AOT_FUNC_ALIGNMENT 32
713 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
714 #define PPC_LD_OP "ld"
715 #define PPC_LDX_OP "ldx"
717 #define PPC_LD_OP "lwz"
718 #define PPC_LDX_OP "lwzx"
722 #define AOT_TARGET_STR "AMD64"
727 #define AOT_TARGET_STR "ARM (MACH)"
729 #define AOT_TARGET_STR "ARM (!MACH)"
735 #define AOT_TARGET_STR "ARM64 (MACH)"
737 #define AOT_TARGET_STR "ARM64 (!MACH)"
741 #ifdef TARGET_POWERPC64
742 #ifdef __mono_ilp32__
743 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
745 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
748 #ifdef TARGET_POWERPC
749 #ifdef __mono_ilp32__
750 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
752 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
759 #define AOT_TARGET_STR "X86 (WIN32)"
760 #elif defined(__native_client_codegen__)
761 #define AOT_TARGET_STR "X86 (native client codegen)"
763 #define AOT_TARGET_STR "X86 (!native client codegen)"
767 #ifndef AOT_TARGET_STR
768 #define AOT_TARGET_STR ""
772 arch_init (MonoAotCompile *acfg)
774 acfg->llc_args = g_string_new ("");
775 acfg->as_args = g_string_new ("");
778 * The prefix LLVM likes to put in front of symbol names on darwin.
779 * The mach-os specs require this for globals, but LLVM puts them in front of all
780 * symbols. We need to handle this, since we need to refer to LLVM generated
783 acfg->llvm_label_prefix = "";
784 acfg->user_symbol_prefix = "";
786 #if defined(TARGET_X86)
787 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
790 #if defined(TARGET_AMD64)
791 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
793 acfg->align_pad_value = 0x90;
797 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
798 g_string_append (acfg->llc_args, "-mattr=+v6");
801 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
802 g_string_append (acfg->as_args, " -mfpu=vfp3");
804 g_string_append (acfg->llc_args, " -soft-float");
807 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
808 acfg->thumb_mixed = TRUE;
810 if (acfg->aot_opts.mtriple)
811 mono_arch_set_target (acfg->aot_opts.mtriple);
815 acfg->inst_directive = ".inst";
816 if (acfg->aot_opts.mtriple)
817 mono_arch_set_target (acfg->aot_opts.mtriple);
821 acfg->user_symbol_prefix = "_";
822 acfg->llvm_label_prefix = "_";
823 acfg->inst_directive = ".word";
824 acfg->need_no_dead_strip = TRUE;
825 acfg->aot_opts.gnu_asm = TRUE;
828 #if defined(__linux__) && !defined(TARGET_ARM)
829 acfg->need_pt_gnu_stack = TRUE;
833 acfg->global_symbols = TRUE;
839 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
843 #ifdef MONO_ARCH_AOT_SUPPORTED
845 * arch_emit_direct_call:
847 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
851 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
853 #if defined(TARGET_X86) || defined(TARGET_AMD64)
854 /* Need to make sure this is exactly 5 bytes long */
855 if (!acfg->use_bin_writer) {
856 emit_unset_mode (acfg);
857 fprintf (acfg->fp, "call %s\n", target);
859 emit_byte (acfg, '\xe8');
860 emit_symbol_diff (acfg, target, ".", -4);
863 #elif defined(TARGET_ARM)
864 if (acfg->use_bin_writer) {
871 mono_img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
872 emit_bytes (acfg, buf, 4);
874 emit_unset_mode (acfg);
876 fprintf (acfg->fp, "blx %s\n", target);
878 fprintf (acfg->fp, "bl %s\n", target);
881 #elif defined(TARGET_ARM64)
882 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
883 #elif defined(TARGET_POWERPC)
884 if (acfg->use_bin_writer) {
885 g_assert_not_reached ();
887 emit_unset_mode (acfg);
888 fprintf (acfg->fp, "bl %s\n", target);
892 g_assert_not_reached ();
899 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
901 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
902 * in in the 2. slot of every GOT, and require every method to place the GOT
903 * address in r30, even when it doesn't access the GOT otherwise. This way,
904 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
909 * PPC64 uses function descriptors which greatly complicate all code, since
910 * these are used very inconsistently in the runtime. Some functions like
911 * mono_compile_method () return ftn descriptors, while others like the
912 * trampoline creation functions do not.
913 * We assume that all GOT slots contain function descriptors, and create
914 * descriptors in aot-runtime.c when needed.
915 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
916 * from function descriptors, we could do the same, but it would require
917 * rewriting all the ppc/aot code to handle function descriptors properly.
918 * So instead, we use the same approach as on PPC32.
919 * This is a horrible mess, but fixing it would probably lead to an even bigger
925 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
928 #ifdef MONO_ARCH_AOT_SUPPORTED
930 * arch_emit_got_offset:
932 * The memory pointed to by CODE should hold native code for computing the GOT
933 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
934 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
937 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
939 #if defined(TARGET_POWERPC64)
940 g_assert (!acfg->use_bin_writer);
941 emit_unset_mode (acfg);
943 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
944 * unsupported relocations. So we store the got address into the .Lgot_addr
945 * symbol which is in the text segment, compute its address, and load it.
947 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
948 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
949 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
950 fprintf (acfg->fp, "add 30, 30, 0\n");
951 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
952 acfg->label_generator ++;
954 #elif defined(TARGET_POWERPC)
955 g_assert (!acfg->use_bin_writer);
956 emit_unset_mode (acfg);
957 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
958 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
959 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
960 acfg->label_generator ++;
963 guint32 offset = mono_arch_get_patch_offset (code);
964 emit_bytes (acfg, code, offset);
965 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
967 *code_size = offset + 4;
972 * arch_emit_got_access:
974 * The memory pointed to by CODE should hold native code for loading a GOT
975 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
976 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
979 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
982 /* mov reg, got+offset(%rip) */
984 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
988 /* Decode reg, see amd64_mov_reg_membase () */
989 rex_r = code [0] & AMD64_REX_R;
990 g_assert (code [0] == 0x49 + rex_r);
991 g_assert (code [1] == 0x8b);
992 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
994 emit_unset_mode (acfg);
995 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
998 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
999 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1000 *code_size = mono_arch_get_patch_offset (code) + 4;
1002 #elif defined(TARGET_X86)
1003 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1004 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1005 *code_size = mono_arch_get_patch_offset (code) + 4;
1006 #elif defined(TARGET_ARM)
1007 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1008 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1009 *code_size = mono_arch_get_patch_offset (code) + 4;
1010 #elif defined(TARGET_ARM64)
1011 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1012 arm64_emit_got_access (acfg, code, got_slot, code_size);
1013 #elif defined(TARGET_POWERPC)
1018 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1020 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1021 g_assert (code - buf == 8);
1022 emit_bytes (acfg, buf, code - buf);
1023 *code_size = code - buf;
1026 g_assert_not_reached ();
1032 #ifdef MONO_ARCH_AOT_SUPPORTED
1034 * arch_emit_objc_selector_ref:
1036 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1039 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1041 #if defined(TARGET_ARM)
1044 int lindex = acfg->objc_selector_index_2 ++;
1046 /* Emit ldr.imm/b */
1047 emit_bytes (acfg, code, 8);
1049 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1050 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1052 emit_label (acfg, symbol1);
1053 mono_img_writer_emit_unset_mode (acfg->w);
1054 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1057 #elif defined(TARGET_ARM64)
1058 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1060 g_assert_not_reached ();
1066 * arch_emit_plt_entry:
1068 * Emit code for the PLT entry.
1069 * The plt entry should look like this:
1070 * <indirect jump to GOT_SYMBOL + OFFSET>
1071 * <INFO_OFFSET embedded into the instruction stream>
1074 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1076 #if defined(TARGET_X86)
1077 #if defined(__default_codegen__)
1078 /* jmp *<offset>(%ebx) */
1079 emit_byte (acfg, 0xff);
1080 emit_byte (acfg, 0xa3);
1081 emit_int32 (acfg, offset);
1082 /* Used by mono_aot_get_plt_info_offset */
1083 emit_int32 (acfg, info_offset);
1084 #elif defined(__native_client_codegen__)
1085 const guint8 kSizeOfNaClJmp = 11;
1086 guint8 bytes[kSizeOfNaClJmp];
1087 guint8 *pbytes = &bytes[0];
1089 x86_jump_membase32 (pbytes, X86_EBX, offset);
1090 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1091 /* four bytes of data, used by mono_arch_patch_plt_entry */
1092 /* For Native Client, make this work with data embedded in push. */
1093 emit_byte (acfg, 0x68); /* hide data in a push */
1094 emit_int32 (acfg, info_offset);
1095 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1096 #endif /*__native_client_codegen__*/
1097 #elif defined(TARGET_AMD64)
1098 #if defined(__default_codegen__)
1099 if (acfg->use_bin_writer) {
1100 emit_byte (acfg, '\xff');
1101 emit_byte (acfg, '\x25');
1102 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1104 emit_unset_mode (acfg);
1105 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1107 /* Used by mono_aot_get_plt_info_offset */
1108 emit_int32 (acfg, info_offset);
1109 acfg->stats.plt_size += 10;
1110 #elif defined(__native_client_codegen__)
1112 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1113 guint8 *code = buf_aligned;
1115 /* mov <OFFSET>(%rip), %r11d */
1116 emit_byte (acfg, '\x45');
1117 emit_byte (acfg, '\x8b');
1118 emit_byte (acfg, '\x1d');
1119 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1121 amd64_jump_reg (code, AMD64_R11);
1122 /* This should be constant for the plt patch */
1123 g_assert ((size_t)(code-buf_aligned) == 10);
1124 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1126 /* Hide data in a push imm32 so it passes validation */
1127 emit_byte (acfg, 0x68); /* push */
1128 emit_int32 (acfg, info_offset);
1129 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1130 #endif /*__native_client_codegen__*/
1131 #elif defined(TARGET_ARM)
1136 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1137 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1138 emit_bytes (acfg, buf, code - buf);
1139 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1140 /* Used by mono_aot_get_plt_info_offset */
1141 emit_int32 (acfg, info_offset);
1142 #elif defined(TARGET_ARM64)
1143 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1144 #elif defined(TARGET_POWERPC)
1145 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1146 g_assert (!acfg->use_bin_writer);
1147 emit_unset_mode (acfg);
1148 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1149 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1150 fprintf (acfg->fp, "add 11, 11, 30\n");
1151 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1152 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1153 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1154 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1156 fprintf (acfg->fp, "mtctr 11\n");
1157 fprintf (acfg->fp, "bctr\n");
1158 emit_int32 (acfg, info_offset);
1160 g_assert_not_reached ();
1165 * arch_emit_llvm_plt_entry:
1167 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1168 * This is only needed on arm to handle thumb interop.
1171 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1173 #if defined(TARGET_ARM)
1174 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1175 /* The caller already transitioned to thumb */
1176 /* The code below should be 12 bytes long */
1177 /* clang has trouble encoding these instructions, so emit the binary */
1179 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1180 /* thumb can't encode ld pc, [pc, ip] */
1181 fprintf (acfg->fp, "add ip, pc, ip\n");
1182 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1183 fprintf (acfg->fp, "bx ip\n");
1185 emit_set_thumb_mode (acfg);
1186 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1187 fprintf (acfg->fp, ".2byte 0x44fc\n");
1188 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1189 fprintf (acfg->fp, ".2byte 0x4760\n");
1190 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1191 emit_int32 (acfg, info_offset);
1192 emit_unset_mode (acfg);
1193 emit_set_arm_mode (acfg);
1195 g_assert_not_reached ();
1200 * arch_emit_specific_trampoline_pages:
1202 * Emits a page full of trampolines: each trampoline uses its own address to
1203 * lookup both the generic trampoline code and the data argument.
1204 * This page can be remapped in process multiple times so we can get an
1205 * unlimited number of trampolines.
1206 * Specifically this implementation uses the following trick: two memory pages
1207 * are allocated, with the first containing the data and the second containing the trampolines.
1208 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1209 * implementation does all the lifting.
1210 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1211 * on the arm 32 bit system.
1214 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1216 #if defined(TARGET_ARM)
1219 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1221 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1222 #define COMMON_TRAMP_SIZE 16
1223 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1224 int imm8, rot_amount;
1227 if (!acfg->aot_opts.use_trampolines_page)
1230 acfg->tramp_page_size = pagesize;
1232 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1233 emit_alignment (acfg, pagesize);
1234 emit_global (acfg, symbol, TRUE);
1235 emit_label (acfg, symbol);
1237 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1239 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1240 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1241 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1242 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1244 g_assert (code - buf == COMMON_TRAMP_SIZE);
1247 emit_bytes (acfg, buf, code - buf);
1249 for (i = 0; i < count; ++i) {
1251 ARM_PUSH (code, 0x5fff);
1253 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1254 g_assert (code - buf == 8);
1255 emit_bytes (acfg, buf, code - buf);
1258 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1259 * the instruction pointer address, so the generic trampoline at the start of the page
1260 * subtracts 4096 to get to the data page and loads the values
1261 * We again fit the generic trampiline in 16 bytes.
1263 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1264 emit_global (acfg, symbol, TRUE);
1265 emit_label (acfg, symbol);
1267 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1268 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1269 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1270 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1272 g_assert (code - buf == COMMON_TRAMP_SIZE);
1275 emit_bytes (acfg, buf, code - buf);
1277 for (i = 0; i < count; ++i) {
1279 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1281 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1282 g_assert (code - buf == 8);
1283 emit_bytes (acfg, buf, code - buf);
1287 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1289 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1290 emit_global (acfg, symbol, TRUE);
1291 emit_label (acfg, symbol);
1293 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1294 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1295 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1296 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1297 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1298 g_assert (code - buf == COMMON_TRAMP_SIZE);
1300 emit_bytes (acfg, buf, code - buf);
1302 for (i = 0; i < count; ++i) {
1304 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1306 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1307 g_assert (code - buf == 8);
1308 emit_bytes (acfg, buf, code - buf);
1311 /* now the imt trampolines: each specific trampolines puts in the ip register
1312 * the instruction pointer address, so the generic trampoline at the start of the page
1313 * subtracts 4096 to get to the data page and loads the values
1314 * We again fit the generic trampiline in 16 bytes.
1316 #define IMT_TRAMP_SIZE 72
1317 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1318 emit_global (acfg, symbol, TRUE);
1319 emit_label (acfg, symbol);
1321 /* Need at least two free registers, plus a slot for storing the pc */
1322 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1324 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1325 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1326 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1328 /* The IMT method is in v5, r0 has the imt array address */
1331 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1332 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1333 imt_found_check = code;
1334 ARM_B_COND (code, ARMCOND_EQ, 0);
1336 /* End-of-loop check */
1337 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1338 loop_end_check = code;
1339 ARM_B_COND (code, ARMCOND_EQ, 0);
1342 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1343 loop_branch_back = code;
1345 arm_patch (loop_branch_back, loop_start);
1348 arm_patch (imt_found_check, code);
1349 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1350 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1351 /* Save it to the third stack slot */
1352 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1353 /* Restore the registers and branch */
1354 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1357 arm_patch (loop_end_check, code);
1358 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1359 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1360 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1364 g_assert (code - buf == IMT_TRAMP_SIZE);
1365 emit_bytes (acfg, buf, code - buf);
1367 for (i = 0; i < count; ++i) {
1369 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1371 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1372 g_assert (code - buf == 8);
1373 emit_bytes (acfg, buf, code - buf);
1376 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1377 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1378 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1379 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1380 #elif defined(TARGET_ARM64)
1381 arm64_emit_specific_trampoline_pages (acfg);
1386 * arch_emit_specific_trampoline:
1388 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1389 * two GOT slots which contain the generic trampoline address and the trampoline
1390 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1393 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1396 * The trampolines created here are variations of the specific
1397 * trampolines created in mono_arch_create_specific_trampoline (). The
1399 * - the generic trampoline address is taken from a got slot.
1400 * - the offset of the got slot where the trampoline argument is stored
1401 * is embedded in the instruction stream, and the generic trampoline
1402 * can load the argument by loading the offset, adding it to the
1403 * address of the trampoline to get the address of the got slot, and
1404 * loading the argument from there.
1405 * - all the trampolines should be of the same length.
1407 #if defined(TARGET_AMD64)
1408 #if defined(__default_codegen__)
1409 /* This should be exactly 8 bytes long */
1411 /* call *<offset>(%rip) */
1413 emit_unset_mode (acfg);
1414 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1415 emit_zero_bytes (acfg, 2);
1417 emit_byte (acfg, '\x41');
1418 emit_byte (acfg, '\xff');
1419 emit_byte (acfg, '\x15');
1420 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1421 emit_zero_bytes (acfg, 1);
1423 #elif defined(__native_client_codegen__)
1425 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1426 guint8 *code = buf_aligned;
1431 /* Emit this call in 'code' so we can find out how long it is. */
1432 amd64_call_reg (code, AMD64_R11);
1433 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1434 call_len = code - call_start;
1436 /* The tramp_size is twice the NaCl alignment because it starts with */
1437 /* a call which needs to be aligned to the end of the boundary. */
1438 *tramp_size = kNaClAlignment*2;
1440 /* Emit nops to align call site below which is 7 bytes plus */
1441 /* the length of the call sequence emitted above. */
1442 /* Note: this requires the specific trampoline starts on a */
1443 /* kNaclAlignedment aligned address, which it does because */
1444 /* it's its own function that is aligned. */
1445 guint8 nop_buf[256];
1446 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1447 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1448 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1450 /* The trampoline is stored at the offset'th pointer, the -4 is */
1451 /* present because RIP relative addressing starts at the end of */
1452 /* the current instruction, while the label "." is relative to */
1453 /* the beginning of the current asm location, which in this case */
1454 /* is not the mov instruction, but the offset itself, due to the */
1455 /* way the bytes and ints are emitted here. */
1456 got_offset = (offset * sizeof(gpointer)) - 4;
1458 /* mov <OFFSET>(%rip), %r11d */
1459 emit_byte (acfg, '\x45');
1460 emit_byte (acfg, '\x8b');
1461 emit_byte (acfg, '\x1d');
1462 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1465 emit_bytes (acfg, call_start, call_len);
1467 /* The arg is stored at the offset+1 pointer, relative to beginning */
1468 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1469 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1471 /* We can't emit this data directly, hide in a "push imm32" */
1472 emit_byte (acfg, '\x68'); /* push */
1473 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1474 emit_alignment (acfg, kNaClAlignment);
1475 #endif /*__native_client_codegen__*/
1476 #elif defined(TARGET_ARM)
1480 /* This should be exactly 20 bytes long */
1483 ARM_PUSH (code, 0x5fff);
1484 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1485 /* Load the value from the GOT */
1486 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1488 ARM_BLX_REG (code, ARMREG_R1);
1490 g_assert (code - buf == 16);
1493 emit_bytes (acfg, buf, code - buf);
1495 * Only one offset is needed, since the second one would be equal to the
1498 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1499 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1500 #elif defined(TARGET_ARM64)
1501 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1502 #elif defined(TARGET_POWERPC)
1509 g_assert (!acfg->use_bin_writer);
1512 * PPC has no ip relative addressing, so we need to compute the address
1513 * of the mscorlib got. That is slow and complex, so instead, we store it
1514 * in the second got slot of every aot image. The caller already computed
1515 * the address of its got and placed it into r30.
1517 emit_unset_mode (acfg);
1518 /* Load mscorlib got address */
1519 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1520 /* Load generic trampoline address */
1521 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1522 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1523 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1524 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1525 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1527 fprintf (acfg->fp, "mtctr 11\n");
1528 /* Load trampoline argument */
1529 /* On ppc, we pass it normally to the generic trampoline */
1530 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1531 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1532 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1533 /* Branch to generic trampoline */
1534 fprintf (acfg->fp, "bctr\n");
1536 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1537 *tramp_size = 10 * 4;
1539 *tramp_size = 9 * 4;
1541 #elif defined(TARGET_X86)
1545 /* Similar to the PPC code above */
1547 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1549 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1550 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1551 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1552 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1553 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1558 /* Load mscorlib got address */
1559 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1560 /* Push trampoline argument */
1561 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1562 /* Load generic trampoline address */
1563 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1564 /* Branch to generic trampoline */
1565 x86_jump_reg (code, X86_ECX);
1567 #ifdef __native_client_codegen__
1569 /* emit nops to next 32 byte alignment */
1570 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1571 while (code < (buf + a)) x86_nop(code);
1574 emit_bytes (acfg, buf, code - buf);
1576 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1577 g_assert (code - buf == *tramp_size);
1579 g_assert_not_reached ();
1584 * arch_emit_unbox_trampoline:
1586 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1587 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1590 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1592 #if defined(TARGET_AMD64)
1597 this_reg = mono_arch_get_this_arg_reg (NULL);
1599 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1601 emit_bytes (acfg, buf, code - buf);
1604 emit_unset_mode (acfg);
1605 fprintf (acfg->fp, "jmp %s\n", call_target);
1607 emit_byte (acfg, '\xe9');
1608 emit_symbol_diff (acfg, call_target, ".", -4);
1610 #elif defined(TARGET_X86)
1617 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1619 emit_bytes (acfg, buf, code - buf);
1622 emit_byte (acfg, '\xe9');
1623 emit_symbol_diff (acfg, call_target, ".", -4);
1624 #elif defined(TARGET_ARM)
1628 if (acfg->thumb_mixed && cfg->compile_llvm) {
1629 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1630 fprintf (acfg->fp, "b %s\n", call_target);
1631 fprintf (acfg->fp, ".arm\n");
1632 fprintf (acfg->fp, ".align 2\n");
1638 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1640 emit_bytes (acfg, buf, code - buf);
1641 /* jump to method */
1642 if (acfg->use_bin_writer) {
1649 mono_img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1650 emit_bytes (acfg, buf, 4);
1652 if (acfg->thumb_mixed && cfg->compile_llvm)
1653 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1655 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1657 #elif defined(TARGET_ARM64)
1658 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1659 #elif defined(TARGET_POWERPC)
1662 g_assert (!acfg->use_bin_writer);
1664 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1665 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1667 g_assert_not_reached ();
1672 * arch_emit_static_rgctx_trampoline:
1674 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1675 * two GOT slots which contain the rgctx argument, and the method to jump to.
1676 * TRAMP_SIZE is set to the size of the emitted trampoline.
1677 * These kinds of trampolines cannot be enumerated statically, since there could
1678 * be one trampoline per method instantiation, so we emit the same code for all
1679 * trampolines, and parameterize them using two GOT slots.
1682 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1684 #if defined(TARGET_AMD64)
1685 #if defined(__default_codegen__)
1686 /* This should be exactly 13 bytes long */
1690 emit_unset_mode (acfg);
1691 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1692 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1694 /* mov <OFFSET>(%rip), %r10 */
1695 emit_byte (acfg, '\x4d');
1696 emit_byte (acfg, '\x8b');
1697 emit_byte (acfg, '\x15');
1698 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1700 /* jmp *<offset>(%rip) */
1701 emit_byte (acfg, '\xff');
1702 emit_byte (acfg, '\x25');
1703 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1705 #elif defined(__native_client_codegen__)
1707 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1708 guint8 *code = buf_aligned;
1710 /* mov <OFFSET>(%rip), %r10d */
1711 emit_byte (acfg, '\x45');
1712 emit_byte (acfg, '\x8b');
1713 emit_byte (acfg, '\x15');
1714 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1716 /* mov <OFFSET>(%rip), %r11d */
1717 emit_byte (acfg, '\x45');
1718 emit_byte (acfg, '\x8b');
1719 emit_byte (acfg, '\x1d');
1720 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1723 amd64_jump_reg (code, AMD64_R11);
1724 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1726 emit_alignment (acfg, kNaClAlignment);
1727 *tramp_size = kNaClAlignment;
1728 #endif /*__native_client_codegen__*/
1730 #elif defined(TARGET_ARM)
1734 /* This should be exactly 24 bytes long */
1737 /* Load rgctx value */
1738 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1739 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1740 /* Load branch addr + branch */
1741 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1742 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1744 g_assert (code - buf == 16);
1747 emit_bytes (acfg, buf, code - buf);
1748 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1749 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1750 #elif defined(TARGET_ARM64)
1751 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1752 #elif defined(TARGET_POWERPC)
1759 g_assert (!acfg->use_bin_writer);
1762 * PPC has no ip relative addressing, so we need to compute the address
1763 * of the mscorlib got. That is slow and complex, so instead, we store it
1764 * in the second got slot of every aot image. The caller already computed
1765 * the address of its got and placed it into r30.
1767 emit_unset_mode (acfg);
1768 /* Load mscorlib got address */
1769 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1771 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1772 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1773 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1774 /* Load target address */
1775 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1776 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1777 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1778 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1779 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1780 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1782 fprintf (acfg->fp, "mtctr 11\n");
1783 /* Branch to the target address */
1784 fprintf (acfg->fp, "bctr\n");
1786 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1787 *tramp_size = 11 * 4;
1789 *tramp_size = 9 * 4;
1792 #elif defined(TARGET_X86)
1796 /* Similar to the PPC code above */
1798 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1801 /* Load mscorlib got address */
1802 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1804 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1805 /* Branch to the target address */
1806 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1808 #ifdef __native_client_codegen__
1810 /* emit nops to next 32 byte alignment */
1811 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1812 while (code < (buf + a)) x86_nop(code);
1816 emit_bytes (acfg, buf, code - buf);
1818 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1819 g_assert (code - buf == *tramp_size);
1821 g_assert_not_reached ();
1826 * arch_emit_imt_thunk:
1828 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1829 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1830 * key is the IMT key, and ptr holds the address of a memory location holding
1831 * the address to branch to if the IMT arg matches the key. The array is
1832 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1834 * TRAMP_SIZE is set to the size of the emitted trampoline.
1837 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1839 #if defined(TARGET_AMD64)
1841 #if defined(__native_client_codegen__)
1844 guint8 *labels [16];
1846 guint8 *mov_buf_ptr = mov_buf;
1848 const int kSizeOfMove = 7;
1849 #if defined(__default_codegen__)
1850 code = buf = g_malloc (256);
1851 #elif defined(__native_client_codegen__)
1852 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1853 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1854 /* The RIP relative move below is emitted first */
1859 /* FIXME: Optimize this, i.e. use binary search etc. */
1860 /* Maybe move the body into a separate function (slower, but much smaller) */
1862 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1865 emit_unset_mode (acfg);
1866 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1870 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1872 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1875 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1877 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1880 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1881 amd64_jump_code (code, labels [0]);
1884 mono_amd64_patch (labels [2], code);
1885 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1886 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1889 mono_amd64_patch (labels [1], code);
1890 /* Load fail tramp */
1891 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1892 /* Check if there is a fail tramp */
1893 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1895 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1896 /* Jump to fail tramp */
1897 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1900 mono_amd64_patch (labels [3], code);
1901 x86_breakpoint (code);
1904 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1905 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1906 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1907 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1908 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1909 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1911 emit_bytes (acfg, buf, code - buf);
1913 *tramp_size = code - buf + kSizeOfMove;
1914 #if defined(__native_client_codegen__)
1915 /* The tramp will be padded to the next kNaClAlignment bundle. */
1916 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1919 #if defined(__default_codegen__)
1921 #elif defined(__native_client_codegen__)
1925 #elif defined(TARGET_X86)
1927 #ifdef __native_client_codegen__
1930 guint8 *labels [16];
1932 #if defined(__default_codegen__)
1933 code = buf = g_malloc (256);
1934 #elif defined(__native_client_codegen__)
1935 buf_alloc = g_malloc (256 + kNaClAlignment);
1936 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1939 /* Allocate a temporary stack slot */
1940 x86_push_reg (code, X86_EAX);
1942 x86_push_reg (code, X86_EAX);
1944 /* Load mscorlib got address */
1945 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1947 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1950 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1952 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1955 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1957 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1960 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1961 x86_jump_code (code, labels [0]);
1964 mono_x86_patch (labels [2], code);
1965 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1966 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1967 /* Save the target address to the temporary stack location */
1968 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1970 x86_pop_reg (code, X86_EAX);
1971 /* Jump to the target address */
1975 mono_x86_patch (labels [1], code);
1976 /* Load fail tramp */
1977 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1978 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1980 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1981 /* Jump to fail tramp */
1982 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1983 x86_pop_reg (code, X86_EAX);
1987 mono_x86_patch (labels [3], code);
1988 x86_breakpoint (code);
1990 #ifdef __native_client_codegen__
1992 /* emit nops to next 32 byte alignment */
1993 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1994 while (code < (buf + a)) x86_nop(code);
1997 emit_bytes (acfg, buf, code - buf);
1999 *tramp_size = code - buf;
2001 #if defined(__default_codegen__)
2003 #elif defined(__native_client_codegen__)
2007 #elif defined(TARGET_ARM)
2009 guint8 *code, *code2, *labels [16];
2013 /* The IMT method is in v5 */
2015 /* Need at least two free registers, plus a slot for storing the pc */
2016 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2018 /* Load the parameter from the GOT */
2019 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2020 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2023 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2024 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2026 ARM_B_COND (code, ARMCOND_EQ, 0);
2028 /* End-of-loop check */
2029 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2031 ARM_B_COND (code, ARMCOND_EQ, 0);
2034 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2037 arm_patch (labels [4], labels [1]);
2040 arm_patch (labels [2], code);
2041 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2042 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2043 /* Save it to the third stack slot */
2044 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2045 /* Restore the registers and branch */
2046 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2049 arm_patch (labels [3], code);
2050 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2051 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2052 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2056 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2058 emit_bytes (acfg, buf, code - buf);
2059 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2061 *tramp_size = code - buf + 4;
2062 #elif defined(TARGET_ARM64)
2063 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2064 #elif defined(TARGET_POWERPC)
2066 guint8 *code, *labels [16];
2070 /* Load the mscorlib got address */
2071 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2072 /* Load the parameter from the GOT */
2073 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2074 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2076 /* Load and check key */
2078 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2079 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2081 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2083 /* End-of-loop check */
2084 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2086 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2089 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2092 mono_ppc_patch (labels [4], labels [1]);
2095 mono_ppc_patch (labels [2], code);
2096 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2097 /* r12 now contains the value of the vtable slot */
2098 /* this is not a function descriptor on ppc64 */
2099 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2100 ppc_mtctr (code, ppc_r12);
2101 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2104 mono_ppc_patch (labels [3], code);
2108 *tramp_size = code - buf;
2110 emit_bytes (acfg, buf, code - buf);
2112 g_assert_not_reached ();
2117 * arch_emit_gsharedvt_arg_trampoline:
2119 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2120 * two GOT slots which contain the argument, and the code to jump to.
2121 * TRAMP_SIZE is set to the size of the emitted trampoline.
2122 * These kinds of trampolines cannot be enumerated statically, since there could
2123 * be one trampoline per method instantiation, so we emit the same code for all
2124 * trampolines, and parameterize them using two GOT slots.
2127 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2129 #if defined(TARGET_X86)
2133 /* Similar to the PPC code above */
2135 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2138 /* Load mscorlib got address */
2139 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2141 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2142 /* Branch to the target address */
2143 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2145 #ifdef __native_client_codegen__
2147 /* emit nops to next 32 byte alignment */
2148 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2149 while (code < (buf + a)) x86_nop(code);
2153 emit_bytes (acfg, buf, code - buf);
2155 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2156 g_assert (code - buf == *tramp_size);
2157 #elif defined(TARGET_ARM)
2161 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2162 /* Similar to arch_emit_specific_trampoline () */
2165 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2166 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2167 /* Load the arg value from the GOT */
2168 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2169 /* Load the addr from the GOT */
2170 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2172 ARM_BX (code, ARMREG_R1);
2174 g_assert (code - buf == 20);
2177 emit_bytes (acfg, buf, code - buf);
2178 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2179 #elif defined(TARGET_ARM64)
2180 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2182 g_assert_not_reached ();
2187 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2189 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2190 /* Based on code generated by gcc */
2191 emit_unset_mode (acfg);
2194 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2195 ".section .ctors,\"aw\",@progbits\n"
2199 ".section .opd,\"aw\"\n"
2202 ".long .%s,.TOC.@tocbase32\n"
2205 ".type .%s,@function\n"
2207 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2209 ".section .ctors,\"aw\",@progbits\n"
2213 ".section .opd,\"aw\"\n"
2216 ".long .%1$s,.TOC.@tocbase32\n"
2217 ".size %1$s,.-%1$s\n"
2219 ".type .%1$s,@function\n"
2221 ".%1$s:\n", symbol);
2232 "lis 3, .Lglobals@h\n"
2233 "ori 3, 3, .Lglobals@l\n"
2234 "bl .mono_aot_register_module\n"
2242 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2244 ".size .%s,.-.%s\n", symbol, symbol);
2247 ".size .%1$s,.-.%1$s\n", symbol);
2253 /* END OF ARCH SPECIFIC CODE */
2256 mono_get_field_token (MonoClassField *field)
2258 MonoClass *klass = field->parent;
2261 for (i = 0; i < klass->field.count; ++i) {
2262 if (field == &klass->fields [i])
2263 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2266 g_assert_not_reached ();
2271 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2275 //printf ("ENCODE: %d 0x%x.\n", value, value);
2278 * Same encoding as the one used in the metadata, extended to handle values
2279 * greater than 0x1fffffff.
2281 if ((value >= 0) && (value <= 127))
2283 else if ((value >= 0) && (value <= 16383)) {
2284 p [0] = 0x80 | (value >> 8);
2285 p [1] = value & 0xff;
2287 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2288 p [0] = (value >> 24) | 0xc0;
2289 p [1] = (value >> 16) & 0xff;
2290 p [2] = (value >> 8) & 0xff;
2291 p [3] = value & 0xff;
2296 p [1] = (value >> 24) & 0xff;
2297 p [2] = (value >> 16) & 0xff;
2298 p [3] = (value >> 8) & 0xff;
2299 p [4] = value & 0xff;
2307 stream_init (MonoDynamicStream *sh)
2310 sh->alloc_size = 4096;
2311 sh->data = g_malloc (4096);
2313 /* So offsets are > 0 */
2319 make_room_in_stream (MonoDynamicStream *stream, int size)
2321 if (size <= stream->alloc_size)
2324 while (stream->alloc_size <= size) {
2325 if (stream->alloc_size < 4096)
2326 stream->alloc_size = 4096;
2328 stream->alloc_size *= 2;
2331 stream->data = g_realloc (stream->data, stream->alloc_size);
2335 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2339 make_room_in_stream (stream, stream->index + len);
2340 memcpy (stream->data + stream->index, data, len);
2341 idx = stream->index;
2342 stream->index += len;
2349 * Add data to the binary blob inside the aot image. Returns the offset inside the
2350 * blob where the data was stored.
2353 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2355 if (acfg->blob.alloc_size == 0)
2356 stream_init (&acfg->blob);
2358 return add_stream_data (&acfg->blob, (char*)data, data_len);
2362 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2367 if (acfg->blob.alloc_size == 0)
2368 stream_init (&acfg->blob);
2370 count = acfg->blob.index % align;
2372 /* we assume the stream data will be aligned */
2374 add_stream_data (&acfg->blob, buf, 4 - count);
2376 return add_stream_data (&acfg->blob, (char*)data, data_len);
2380 * emit_offset_table:
2382 * Emit a table of increasing offsets in a compact form using differential encoding.
2383 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2384 * group size, the more compact the table becomes, but the slower it becomes to compute
2385 * a given entry. Returns the size of the table.
2388 emit_offset_table (MonoAotCompile *acfg, const char *symbol, int noffsets, int group_size, gint32 *offsets)
2390 gint32 current_offset;
2391 int i, buf_size, ngroups, index_entry_size;
2393 guint8 *data_p, *data_buf;
2394 guint32 *index_offsets;
2396 ngroups = (noffsets + (group_size - 1)) / group_size;
2398 index_offsets = g_new0 (guint32, ngroups);
2400 buf_size = noffsets * 4;
2401 p = buf = g_malloc0 (buf_size);
2404 for (i = 0; i < noffsets; ++i) {
2405 //printf ("D: %d -> %d\n", i, offsets [i]);
2406 if ((i % group_size) == 0) {
2407 index_offsets [i / group_size] = p - buf;
2408 /* Emit the full value for these entries */
2409 encode_value (offsets [i], p, &p);
2411 /* The offsets are allowed to be non-increasing */
2412 //g_assert (offsets [i] >= current_offset);
2413 encode_value (offsets [i] - current_offset, p, &p);
2415 current_offset = offsets [i];
2420 if (ngroups && index_offsets [ngroups - 1] < 65000)
2421 index_entry_size = 2;
2423 index_entry_size = 4;
2425 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2426 p = buf = g_malloc0 (buf_size);
2428 /* Emit the header */
2429 encode_int (noffsets, p, &p);
2430 encode_int (group_size, p, &p);
2431 encode_int (ngroups, p, &p);
2432 encode_int (index_entry_size, p, &p);
2434 /* Emit the index */
2435 for (i = 0; i < ngroups; ++i) {
2436 if (index_entry_size == 2)
2437 encode_int16 (index_offsets [i], p, &p);
2439 encode_int (index_offsets [i], p, &p);
2442 memcpy (p, data_buf, data_p - data_buf);
2443 p += data_p - data_buf;
2445 g_assert (p - buf <= buf_size);
2448 mono_llvm_emit_aot_data (symbol, buf, p - buf);
2450 emit_section_change (acfg, RODATA_SECT, 1);
2451 emit_alignment (acfg, 8);
2452 emit_label (acfg, symbol);
2453 emit_bytes (acfg, buf, p - buf);
2459 return (int)(p - buf);
2463 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2467 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2471 index = g_hash_table_size (cfg->image_hash);
2472 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2473 g_ptr_array_add (cfg->image_table, image);
2479 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2482 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2484 /* FIXME: Search referenced images as well */
2485 if (!acfg->typespec_classes) {
2486 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2487 for (i = 0; i < len; ++i) {
2489 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2490 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2493 for (i = 0; i < len; ++i) {
2494 if (acfg->typespec_classes [i] == klass)
2499 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2505 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2508 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2511 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2514 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2517 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2522 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2526 if (klass->generic_class) {
2528 g_assert (klass->type_token);
2530 /* Find a typespec for a class if possible */
2531 token = find_typespec_for_class (acfg, klass);
2533 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2534 encode_value (token, p, &p);
2536 MonoClass *gclass = klass->generic_class->container_class;
2537 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2538 static int count = 0;
2541 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2542 encode_klass_ref (acfg, gclass, p, &p);
2543 encode_ginst (acfg, inst, p, &p);
2547 } else if (klass->type_token) {
2548 int iindex = get_image_index (acfg, klass->image);
2550 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2552 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2553 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2555 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2556 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2557 encode_value (get_image_index (acfg, klass->image), p, &p);
2559 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2560 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2561 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2563 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2564 encode_value (klass->byval_arg.type, p, &p);
2565 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2567 encode_value (container ? 1 : 0, p, &p);
2569 encode_value (container->is_method, p, &p);
2570 g_assert (!par->gshared_constraint);
2571 if (container->is_method)
2572 encode_method_ref (acfg, container->owner.method, p, &p);
2574 encode_klass_ref (acfg, container->owner.klass, p, &p);
2576 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2577 if (par->gshared_constraint) {
2580 encode_type (acfg, par->gshared_constraint, p, &p);
2582 name = mono_generic_param_name (par);
2584 int len = strlen (name);
2586 encode_value (len, p, &p);
2587 memcpy (p, name, len);
2590 encode_value (0, p, &p);
2594 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2595 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2596 encode_type (acfg, &klass->byval_arg, p, &p);
2599 g_assert (klass->rank > 0);
2600 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2601 encode_value (klass->rank, p, &p);
2602 encode_klass_ref (acfg, klass->element_class, p, &p);
2610 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2611 * standard metadata encoding.
2614 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2616 gboolean shared = FALSE;
2619 * The encoding of generic instances is large so emit them only once.
2621 if (klass->generic_class) {
2623 g_assert (klass->type_token);
2625 /* Find a typespec for a class if possible */
2626 token = find_typespec_for_class (acfg, klass);
2629 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2634 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2638 buf2 = g_malloc (1024);
2641 encode_klass_ref_inner (acfg, klass, p, &p);
2642 g_assert (p - buf2 < 1024);
2644 offset = add_to_blob (acfg, buf2, p - buf2);
2647 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2653 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2654 encode_value (offset, p, &p);
2659 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2663 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2665 guint32 token = mono_get_field_token (field);
2668 encode_klass_ref (cfg, field->parent, p, &p);
2669 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2670 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2675 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2680 encode_value (inst->type_argc, p, &p);
2681 for (i = 0; i < inst->type_argc; ++i)
2682 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2687 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2690 MonoGenericInst *inst;
2692 inst = context->class_inst;
2694 g_assert (inst->type_argc);
2695 encode_ginst (acfg, inst, p, &p);
2697 encode_value (0, p, &p);
2699 inst = context->method_inst;
2701 g_assert (inst->type_argc);
2702 encode_ginst (acfg, inst, p, &p);
2704 encode_value (0, p, &p);
2710 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2714 g_assert (t->num_mods == 0);
2715 /* t->attrs can be ignored */
2716 //g_assert (t->attrs == 0);
2719 *p = MONO_TYPE_PINNED;
2723 *p = MONO_TYPE_BYREF;
2731 case MONO_TYPE_VOID:
2732 case MONO_TYPE_BOOLEAN:
2733 case MONO_TYPE_CHAR:
2746 case MONO_TYPE_STRING:
2747 case MONO_TYPE_OBJECT:
2748 case MONO_TYPE_TYPEDBYREF:
2750 case MONO_TYPE_VALUETYPE:
2751 case MONO_TYPE_CLASS:
2752 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2754 case MONO_TYPE_SZARRAY:
2755 encode_klass_ref (acfg, t->data.klass, p, &p);
2758 encode_type (acfg, t->data.type, p, &p);
2760 case MONO_TYPE_GENERICINST: {
2761 MonoClass *gclass = t->data.generic_class->container_class;
2762 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2764 encode_klass_ref (acfg, gclass, p, &p);
2765 encode_ginst (acfg, inst, p, &p);
2768 case MONO_TYPE_ARRAY: {
2769 MonoArrayType *array = t->data.array;
2772 encode_klass_ref (acfg, array->eklass, p, &p);
2773 encode_value (array->rank, p, &p);
2774 encode_value (array->numsizes, p, &p);
2775 for (i = 0; i < array->numsizes; ++i)
2776 encode_value (array->sizes [i], p, &p);
2777 encode_value (array->numlobounds, p, &p);
2778 for (i = 0; i < array->numlobounds; ++i)
2779 encode_value (array->lobounds [i], p, &p);
2783 case MONO_TYPE_MVAR:
2784 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2787 g_assert_not_reached ();
2794 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2800 /* Similar to the metadata encoding */
2801 if (sig->generic_param_count)
2805 if (sig->explicit_this)
2807 flags |= (sig->call_convention & 0x0F);
2811 if (sig->generic_param_count)
2812 encode_value (sig->generic_param_count, p, &p);
2813 encode_value (sig->param_count, p, &p);
2815 encode_type (acfg, sig->ret, p, &p);
2816 for (i = 0; i < sig->param_count; ++i) {
2817 if (sig->sentinelpos == i) {
2818 *p = MONO_TYPE_SENTINEL;
2821 encode_type (acfg, sig->params [i], p, &p);
2827 #define MAX_IMAGE_INDEX 250
2830 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2832 guint32 image_index = get_image_index (acfg, method->klass->image);
2833 guint32 token = method->token;
2834 MonoJumpInfoToken *ji;
2838 * The encoding for most methods is as follows:
2839 * - image index encoded as a leb128
2840 * - token index encoded as a leb128
2841 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2842 * types of method encodings.
2845 /* Mark methods which can't use aot trampolines because they need the further
2846 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2848 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2849 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2850 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2852 if (method->wrapper_type) {
2853 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2855 encode_value (method->wrapper_type, p, &p);
2857 switch (method->wrapper_type) {
2858 case MONO_WRAPPER_REMOTING_INVOKE:
2859 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2860 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2863 m = mono_marshal_method_from_wrapper (method);
2865 encode_method_ref (acfg, m, p, &p);
2868 case MONO_WRAPPER_PROXY_ISINST:
2869 case MONO_WRAPPER_LDFLD:
2870 case MONO_WRAPPER_LDFLDA:
2871 case MONO_WRAPPER_STFLD:
2872 case MONO_WRAPPER_ISINST: {
2873 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2876 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2879 case MONO_WRAPPER_LDFLD_REMOTE:
2880 case MONO_WRAPPER_STFLD_REMOTE:
2882 case MONO_WRAPPER_ALLOC: {
2883 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2885 /* The GC name is saved once in MonoAotFileInfo */
2886 g_assert (info->alloc_type != -1);
2887 encode_value (info->alloc_type, p, &p);
2890 case MONO_WRAPPER_WRITE_BARRIER:
2892 case MONO_WRAPPER_STELEMREF: {
2893 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2896 encode_value (info->subtype, p, &p);
2897 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2898 encode_value (info->d.virtual_stelemref.kind, p, &p);
2901 case MONO_WRAPPER_UNKNOWN: {
2902 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2905 encode_value (info->subtype, p, &p);
2906 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2907 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2908 encode_klass_ref (acfg, method->klass, p, &p);
2909 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2910 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2911 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2912 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2915 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2916 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2919 encode_value (info->subtype, p, &p);
2920 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2921 strcpy ((char*)p, method->name);
2922 p += strlen (method->name) + 1;
2923 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2924 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2926 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2927 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2931 case MONO_WRAPPER_SYNCHRONIZED: {
2934 m = mono_marshal_method_from_wrapper (method);
2936 g_assert (m != method);
2937 encode_method_ref (acfg, m, p, &p);
2940 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2941 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2944 encode_value (info->subtype, p, &p);
2946 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2947 encode_value (info->d.element_addr.rank, p, &p);
2948 encode_value (info->d.element_addr.elem_size, p, &p);
2949 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2950 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2952 g_assert_not_reached ();
2956 case MONO_WRAPPER_CASTCLASS: {
2957 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2960 encode_value (info->subtype, p, &p);
2963 case MONO_WRAPPER_RUNTIME_INVOKE: {
2964 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2967 encode_value (info->subtype, p, &p);
2968 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2969 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2970 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2971 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2974 case MONO_WRAPPER_DELEGATE_INVOKE:
2975 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2976 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2977 if (method->is_inflated) {
2978 /* These wrappers are identified by their class */
2979 encode_value (1, p, &p);
2980 encode_klass_ref (acfg, method->klass, p, &p);
2982 MonoMethodSignature *sig = mono_method_signature (method);
2983 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2985 encode_value (0, p, &p);
2986 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2987 encode_value (info ? info->subtype : 0, p, &p);
2988 encode_signature (acfg, sig, p, &p);
2992 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2993 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2996 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2997 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3001 g_assert_not_reached ();
3003 } else if (mono_method_signature (method)->is_inflated) {
3005 * This is a generic method, find the original token which referenced it and
3007 * Obtain the token from information recorded by the JIT.
3009 ji = g_hash_table_lookup (acfg->token_info_hash, method);
3011 image_index = get_image_index (acfg, ji->image);
3012 g_assert (image_index < MAX_IMAGE_INDEX);
3015 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3016 encode_value (image_index, p, &p);
3017 encode_value (token, p, &p);
3019 MonoMethod *declaring;
3020 MonoGenericContext *context = mono_method_get_context (method);
3022 g_assert (method->is_inflated);
3023 declaring = ((MonoMethodInflated*)method)->declaring;
3026 * This might be a non-generic method of a generic instance, which
3027 * doesn't have a token since the reference is generated by the JIT
3028 * like Nullable:Box/Unbox, or by generic sharing.
3030 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3031 /* Encode the klass */
3032 encode_klass_ref (acfg, method->klass, p, &p);
3033 /* Encode the method */
3034 image_index = get_image_index (acfg, method->klass->image);
3035 g_assert (image_index < MAX_IMAGE_INDEX);
3036 g_assert (declaring->token);
3037 token = declaring->token;
3038 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3039 encode_value (image_index, p, &p);
3040 encode_value (token, p, &p);
3041 encode_generic_context (acfg, context, p, &p);
3043 } else if (token == 0) {
3044 /* This might be a method of a constructed type like int[,].Set */
3045 /* Obtain the token from information recorded by the JIT */
3046 ji = g_hash_table_lookup (acfg->token_info_hash, method);
3048 image_index = get_image_index (acfg, ji->image);
3049 g_assert (image_index < MAX_IMAGE_INDEX);
3052 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3053 encode_value (image_index, p, &p);
3054 encode_value (token, p, &p);
3057 g_assert (method->klass->rank);
3059 /* Encode directly */
3060 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3061 encode_klass_ref (acfg, method->klass, p, &p);
3062 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3063 encode_value (0, p, &p);
3064 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3065 encode_value (1, p, &p);
3066 else if (!strcmp (method->name, "Get"))
3067 encode_value (2, p, &p);
3068 else if (!strcmp (method->name, "Address"))
3069 encode_value (3, p, &p);
3070 else if (!strcmp (method->name, "Set"))
3071 encode_value (4, p, &p);
3073 g_assert_not_reached ();
3076 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3078 if (image_index >= MONO_AOT_METHODREF_MIN) {
3079 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3080 encode_value (image_index, p, &p);
3081 encode_value (mono_metadata_token_index (token), p, &p);
3083 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3090 compare_patches (gconstpointer a, gconstpointer b)
3094 i = (*(MonoJumpInfo**)a)->ip.i;
3095 j = (*(MonoJumpInfo**)b)->ip.i;
3106 static G_GNUC_UNUSED char*
3107 patch_to_string (MonoJumpInfo *patch_info)
3111 str = g_string_new ("");
3113 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3115 switch (patch_info->type) {
3116 case MONO_PATCH_INFO_VTABLE:
3117 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3122 g_string_append_printf (str, ")");
3123 return g_string_free (str, FALSE);
3129 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3132 static inline gboolean
3133 is_plt_patch (MonoJumpInfo *patch_info)
3135 switch (patch_info->type) {
3136 case MONO_PATCH_INFO_METHOD:
3137 case MONO_PATCH_INFO_INTERNAL_METHOD:
3138 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3139 case MONO_PATCH_INFO_ICALL_ADDR:
3140 case MONO_PATCH_INFO_CLASS_INIT:
3141 case MONO_PATCH_INFO_RGCTX_FETCH:
3142 case MONO_PATCH_INFO_MONITOR_ENTER:
3143 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3144 case MONO_PATCH_INFO_MONITOR_EXIT:
3145 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3155 * Return the symbol identifying the plt entry PLT_OFFSET.
3158 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3162 * The Apple linker reorganizes object files, so it doesn't like branches to local
3163 * labels, since those have no relocations.
3165 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3167 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3174 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3176 static MonoPltEntry*
3177 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3180 gboolean synchronized = FALSE;
3181 static int synchronized_symbol_idx;
3183 if (!is_plt_patch (patch_info))
3186 if (!acfg->patch_to_plt_entry [patch_info->type])
3187 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3188 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3190 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3192 * Allocate a separate PLT slot for each such patch, since some plt
3193 * entries will refer to the method itself, and some will refer to the
3197 synchronized = TRUE;
3201 MonoJumpInfo *new_ji;
3203 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3205 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3206 res->plt_offset = acfg->plt_offset;
3208 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3209 if (acfg->aot_opts.write_symbols)
3210 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3212 /* Avoid duplicate symbols because we don't cache */
3213 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3215 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3216 synchronized_symbol_idx ++;
3219 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3221 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3223 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3225 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3227 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3228 //mono_print_ji (patch_info); printf ("\n");
3229 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3231 acfg->plt_offset ++;
3240 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3241 * JI could be found if it exists, otherwise allocates a new one.
3244 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3247 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3249 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3251 return got_offset - 1;
3254 got_offset = acfg->llvm_got_offset;
3255 acfg->llvm_got_offset ++;
3257 got_offset = acfg->got_offset;
3258 acfg->got_offset ++;
3261 acfg->stats.got_slots ++;
3262 acfg->stats.got_slot_types [ji->type] ++;
3264 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3265 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3266 g_ptr_array_add (info->got_patches, ji);
3271 /* Add a method to the list of methods which need to be emitted */
3273 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3276 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3277 g_ptr_array_add (acfg->methods, method);
3278 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3279 acfg->nmethods = acfg->methods->len + 1;
3282 if (method->wrapper_type || extra)
3283 g_ptr_array_add (acfg->extra_methods, method);
3287 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3289 /* One instantiation with valuetypes is generated for each async method */
3290 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3297 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3299 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3307 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3311 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3315 index = acfg->method_index;
3316 add_method_with_index (acfg, method, index, extra);
3318 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3320 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3322 acfg->method_index ++;
3328 add_method (MonoAotCompile *acfg, MonoMethod *method)
3330 return add_method_full (acfg, method, FALSE, 0);
3334 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3336 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3337 method = mini_get_shared_method (method);
3338 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3339 /* Use the gsharedvt version */
3342 if (acfg->aot_opts.log_generics)
3343 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3345 add_method_full (acfg, method, TRUE, depth);
3349 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3351 add_extra_method_with_depth (acfg, method, 0);
3355 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3357 MonoAotCompile *acfg = user_data;
3358 MonoJitICallInfo *callinfo = value;
3359 MonoMethod *wrapper;
3365 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3366 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3369 add_method (acfg, wrapper);
3373 get_runtime_invoke_sig (MonoMethodSignature *sig)
3375 MonoMethodBuilder *mb;
3378 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3379 m = mono_mb_create_method (mb, sig, 16);
3380 return mono_marshal_get_runtime_invoke (m, FALSE);
3384 can_marshal_struct (MonoClass *klass)
3386 MonoClassField *field;
3387 gboolean can_marshal = TRUE;
3388 gpointer iter = NULL;
3389 MonoMarshalType *info;
3392 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3395 info = mono_marshal_load_type_info (klass);
3397 /* Only allow a few field types to avoid asserts in the marshalling code */
3398 while ((field = mono_class_get_fields (klass, &iter))) {
3399 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3402 switch (field->type->type) {
3407 case MONO_TYPE_BOOLEAN:
3410 case MONO_TYPE_CHAR:
3418 case MONO_TYPE_STRING:
3420 case MONO_TYPE_VALUETYPE:
3421 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3422 can_marshal = FALSE;
3424 case MONO_TYPE_SZARRAY: {
3425 gboolean has_mspec = FALSE;
3428 for (i = 0; i < info->num_fields; ++i) {
3429 if (info->fields [i].field == field && info->fields [i].mspec)
3434 can_marshal = FALSE;
3438 can_marshal = FALSE;
3444 /* Its hard to compute whenever these can be marshalled or not */
3445 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3452 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3454 /* Create a vtype instantiation */
3455 MonoGenericContext shared_context;
3457 MonoGenericInst *inst;
3458 MonoGenericContainer *container;
3459 MonoClass **constraints;
3462 memset (ctx, 0, sizeof (MonoGenericContext));
3464 if (method->klass->generic_container) {
3465 shared_context = method->klass->generic_container->context;
3466 inst = shared_context.class_inst;
3468 args = g_new0 (MonoType*, inst->type_argc);
3469 for (i = 0; i < inst->type_argc; ++i) {
3470 args [i] = &mono_defaults.int_class->byval_arg;
3472 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3474 if (method->is_generic) {
3475 container = mono_method_get_generic_container (method);
3476 shared_context = container->context;
3477 inst = shared_context.method_inst;
3479 args = g_new0 (MonoType*, inst->type_argc);
3480 for (i = 0; i < container->type_argc; ++i) {
3481 MonoGenericParamInfo *info = &container->type_params [i].info;
3482 gboolean ref_only = FALSE;
3484 if (info && info->constraints) {
3485 constraints = info->constraints;
3487 while (*constraints) {
3488 MonoClass *cklass = *constraints;
3489 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3490 /* Inflaring the method with our vtype would not be valid */
3497 args [i] = &mono_defaults.object_class->byval_arg;
3499 args [i] = &mono_defaults.int_class->byval_arg;
3501 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3506 add_wrappers (MonoAotCompile *acfg)
3508 MonoMethod *method, *m;
3510 MonoMethodSignature *sig, *csig;
3514 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3515 * so there is only one wrapper of a given type, or inlining their contents into their
3518 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3521 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3522 gboolean skip = FALSE;
3524 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3525 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3527 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3528 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3529 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3532 /* Skip methods which can not be handled by get_runtime_invoke () */
3533 sig = mono_method_signature (method);
3536 if ((sig->ret->type == MONO_TYPE_PTR) ||
3537 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3539 if (mono_class_is_open_constructed_type (sig->ret))
3542 for (j = 0; j < sig->param_count; j++) {
3543 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3545 if (mono_class_is_open_constructed_type (sig->params [j]))
3549 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3550 if (!mono_class_is_contextbound (method->klass)) {
3551 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3552 gboolean has_nullable = FALSE;
3554 for (j = 0; j < sig->param_count; j++) {
3555 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3556 has_nullable = TRUE;
3559 if (info && !has_nullable) {
3560 /* Supported by the dynamic runtime-invoke wrapper */
3564 mono_arch_dyn_call_free (info);
3569 //printf ("%s\n", mono_method_full_name (method, TRUE));
3570 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3574 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3577 /* Runtime invoke wrappers */
3579 /* void runtime-invoke () [.cctor] */
3580 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3581 csig->ret = &mono_defaults.void_class->byval_arg;
3582 add_method (acfg, get_runtime_invoke_sig (csig));
3584 /* void runtime-invoke () [Finalize] */
3585 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3587 csig->ret = &mono_defaults.void_class->byval_arg;
3588 add_method (acfg, get_runtime_invoke_sig (csig));
3590 /* void runtime-invoke (string) [exception ctor] */
3591 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3593 csig->ret = &mono_defaults.void_class->byval_arg;
3594 csig->params [0] = &mono_defaults.string_class->byval_arg;
3595 add_method (acfg, get_runtime_invoke_sig (csig));
3597 /* void runtime-invoke (string, string) [exception ctor] */
3598 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3600 csig->ret = &mono_defaults.void_class->byval_arg;
3601 csig->params [0] = &mono_defaults.string_class->byval_arg;
3602 csig->params [1] = &mono_defaults.string_class->byval_arg;
3603 add_method (acfg, get_runtime_invoke_sig (csig));
3605 /* string runtime-invoke () [Exception.ToString ()] */
3606 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3608 csig->ret = &mono_defaults.string_class->byval_arg;
3609 add_method (acfg, get_runtime_invoke_sig (csig));
3611 /* void runtime-invoke (string, Exception) [exception ctor] */
3612 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3614 csig->ret = &mono_defaults.void_class->byval_arg;
3615 csig->params [0] = &mono_defaults.string_class->byval_arg;
3616 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3617 add_method (acfg, get_runtime_invoke_sig (csig));
3619 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3620 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3622 csig->ret = &(mono_class_from_name (
3623 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3624 csig->params [0] = &mono_defaults.string_class->byval_arg;
3625 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3626 add_method (acfg, get_runtime_invoke_sig (csig));
3628 /* runtime-invoke used by finalizers */
3629 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3631 /* This is used by mono_runtime_capture_context () */
3632 method = mono_get_context_capture_method ();
3634 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3636 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3637 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3641 add_method (acfg, mono_marshal_get_stelemref ());
3643 if (MONO_ARCH_HAVE_TLS_GET) {
3644 /* Managed Allocators */
3645 nallocators = mono_gc_get_managed_allocator_types ();
3646 for (i = 0; i < nallocators; ++i) {
3647 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3649 add_method (acfg, m);
3651 for (i = 0; i < nallocators; ++i) {
3652 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3654 add_method (acfg, m);
3658 /* write barriers */
3659 if (mono_gc_is_moving ()) {
3660 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3661 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3664 /* Stelemref wrappers */
3666 MonoMethod **wrappers;
3669 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3670 for (i = 0; i < nwrappers; ++i)
3671 add_method (acfg, wrappers [i]);
3675 /* castclass_with_check wrapper */
3676 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3677 /* isinst_with_check wrapper */
3678 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3680 /* JIT icall wrappers */
3681 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3682 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3686 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3687 * we use the original method instead at runtime.
3688 * Since full-aot doesn't support remoting, this is not a problem.
3691 /* remoting-invoke wrappers */
3692 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3693 MonoMethodSignature *sig;
3695 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3696 method = mono_get_method (acfg->image, token, NULL);
3698 sig = mono_method_signature (method);
3700 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3701 m = mono_marshal_get_remoting_invoke_with_check (method);
3703 add_method (acfg, m);
3708 /* delegate-invoke wrappers */
3709 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3712 MonoCustomAttrInfo *cattr;
3714 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3715 klass = mono_class_get_checked (acfg->image, token, &error);
3718 mono_error_cleanup (&error);
3722 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3725 if (!klass->generic_container) {
3726 method = mono_get_delegate_invoke (klass);
3728 m = mono_marshal_get_delegate_invoke (method, NULL);
3730 add_method (acfg, m);
3732 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3734 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3736 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3738 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3740 cattr = mono_custom_attrs_from_class (klass);
3745 for (j = 0; j < cattr->num_attrs; ++j)
3746 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3748 if (j < cattr->num_attrs) {
3750 MonoMethod *wrapper;
3751 MonoMethod *del_invoke;
3753 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3754 invoke = mono_get_delegate_invoke (klass);
3755 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3756 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3757 add_method (acfg, wrapper);
3758 add_method (acfg, del_invoke);
3761 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3763 MonoGenericContext ctx;
3764 MonoMethod *inst, *gshared;
3767 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3770 method = mono_get_delegate_invoke (klass);
3771 create_gsharedvt_inst (acfg, method, &ctx);
3773 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3774 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3776 m = mono_marshal_get_delegate_invoke (inst, NULL);
3777 g_assert (m->is_inflated);
3779 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3780 add_extra_method (acfg, gshared);
3783 method = mono_get_delegate_begin_invoke (klass);
3784 create_gsharedvt_inst (acfg, method, &ctx);
3786 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3787 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3789 m = mono_marshal_get_delegate_begin_invoke (inst);
3790 g_assert (m->is_inflated);
3792 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3793 add_extra_method (acfg, gshared);
3796 method = mono_get_delegate_end_invoke (klass);
3797 create_gsharedvt_inst (acfg, method, &ctx);
3799 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3800 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3802 m = mono_marshal_get_delegate_end_invoke (inst);
3803 g_assert (m->is_inflated);
3805 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3806 add_extra_method (acfg, gshared);
3811 /* array access wrappers */
3812 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3816 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3817 klass = mono_class_get_checked (acfg->image, token, &error);
3820 mono_error_cleanup (&error);
3824 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3825 MonoMethod *m, *wrapper;
3827 /* Add runtime-invoke wrappers too */
3829 m = mono_class_get_method_from_name (klass, "Get", -1);
3831 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3832 add_extra_method (acfg, wrapper);
3833 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3835 m = mono_class_get_method_from_name (klass, "Set", -1);
3837 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3838 add_extra_method (acfg, wrapper);
3839 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3843 /* Synchronized wrappers */
3844 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3846 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3847 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3848 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3850 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3851 if (method->is_generic) {
3853 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3855 MonoGenericContext ctx;
3856 MonoMethod *inst, *gshared, *m;
3859 * Create a generic wrapper for a generic instance, and AOT that.
3861 create_gsharedvt_inst (acfg, method, &ctx);
3862 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3863 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3864 m = mono_marshal_get_synchronized_wrapper (inst);
3865 g_assert (m->is_inflated);
3866 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3867 add_method (acfg, gshared);
3869 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3874 /* pinvoke wrappers */
3875 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3878 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3880 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3881 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3883 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3884 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3885 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3889 /* native-to-managed wrappers */
3890 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3893 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3894 MonoCustomAttrInfo *cattr;
3897 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3898 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3901 * Only generate native-to-managed wrappers for methods which have an
3902 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3903 * name to avoid defining a new assembly to contain it.
3905 cattr = mono_custom_attrs_from_method (method);
3908 for (j = 0; j < cattr->num_attrs; ++j)
3909 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3911 if (j < cattr->num_attrs) {
3912 MonoCustomAttrEntry *e = &cattr->attrs [j];
3913 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3914 const char *p = (const char*)e->data;
3916 int slen, num_named, named_type;
3920 char *export_name = NULL;
3921 MonoMethod *wrapper;
3923 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3924 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3925 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3926 mono_method_full_name (method, TRUE));
3930 g_assert (sig->param_count == 1);
3931 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3934 * Decode the cattr manually since we can't create objects
3935 * during aot compilation.
3941 /* From load_cattr_value () in reflection.c */
3942 slen = mono_metadata_decode_value (p, &p);
3943 n = g_memdup (p, slen + 1);
3945 t = mono_reflection_type_from_name (n, acfg->image);
3949 klass = mono_class_from_mono_type (t);
3950 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3954 num_named = read16 (p);
3957 g_assert (num_named < 2);
3958 if (num_named == 1) {
3962 /* parse ExportSymbol attribute */
3964 named_type = *named;
3966 /* data_type = *named; */
3969 name_len = mono_metadata_decode_blob_size (named, &named);
3970 name = g_malloc (name_len + 1);
3971 memcpy (name, named, name_len);
3972 name [name_len] = 0;
3975 g_assert (named_type == 0x54);
3976 g_assert (!strcmp (name, "ExportSymbol"));
3978 /* load_cattr_value (), string case */
3979 g_assert (*named != (char)0xff);
3980 slen = mono_metadata_decode_value (named, &named);
3981 export_name = g_malloc (slen + 1);
3982 memcpy (export_name, named, slen);
3983 export_name [slen] = 0;
3987 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3988 add_method (acfg, wrapper);
3990 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3994 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3995 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3996 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4000 /* StructureToPtr/PtrToStructure wrappers */
4001 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4005 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4006 klass = mono_class_get_checked (acfg->image, token, &error);
4009 mono_error_cleanup (&error);
4013 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4014 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4015 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4016 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4022 has_type_vars (MonoClass *klass)
4024 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4027 return has_type_vars (klass->element_class);
4028 if (klass->generic_class) {
4029 MonoGenericContext *context = &klass->generic_class->context;
4030 if (context->class_inst) {
4033 for (i = 0; i < context->class_inst->type_argc; ++i)
4034 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4038 if (klass->generic_container)
4044 is_vt_inst (MonoGenericInst *inst)
4048 for (i = 0; i < inst->type_argc; ++i) {
4049 MonoType *t = inst->type_argv [i];
4050 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4057 method_has_type_vars (MonoMethod *method)
4059 if (has_type_vars (method->klass))
4062 if (method->is_inflated) {
4063 MonoGenericContext *context = mono_method_get_context (method);
4064 if (context->method_inst) {
4067 for (i = 0; i < context->method_inst->type_argc; ++i)
4068 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4076 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4078 return opts->mode == MONO_AOT_MODE_FULL;
4081 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4084 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4086 /* This might lead to a huge code blowup so only do it if neccesary */
4087 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4090 add_generic_class_with_depth (acfg, klass, 0, ref);
4094 check_type_depth (MonoType *t, int depth)
4102 case MONO_TYPE_GENERICINST: {
4103 MonoGenericClass *gklass = t->data.generic_class;
4104 MonoGenericInst *ginst = gklass->context.class_inst;
4107 for (i = 0; i < ginst->type_argc; ++i) {
4108 if (check_type_depth (ginst->type_argv [i], depth + 1))
4122 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4125 * add_generic_class:
4127 * Add all methods of a generic class.
4130 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4133 MonoClassField *field;
4135 gboolean use_gsharedvt = FALSE;
4137 if (!acfg->ginst_hash)
4138 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4140 mono_class_init (klass);
4142 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4145 if (has_type_vars (klass))
4148 if (!klass->generic_class && !klass->rank)
4151 if (klass->exception_type)
4154 if (!acfg->ginst_hash)
4155 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4157 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4160 if (check_type_depth (&klass->byval_arg, 0))
4163 if (acfg->aot_opts.log_generics)
4164 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4166 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4169 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4170 * Enable this only for some classes since gsharedvt might not support all methods.
4172 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) &&
4173 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4174 use_gsharedvt = TRUE;
4177 while ((method = mono_class_get_methods (klass, &iter))) {
4178 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4180 * This is partial sharing, and we can't handle it yet
4185 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4187 add_types_from_method_header (acfg, method);
4191 if (method->is_generic)
4196 * FIXME: Instances which are referenced by these methods are not added,
4197 * for example Array.Resize<int> for List<int>.Add ().
4199 add_extra_method_with_depth (acfg, method, depth + 1);
4203 while ((field = mono_class_get_fields (klass, &iter))) {
4204 if (field->type->type == MONO_TYPE_GENERICINST)
4205 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4208 if (klass->delegate) {
4209 method = mono_get_delegate_invoke (klass);
4211 method = mono_marshal_get_delegate_invoke (method, NULL);
4213 if (acfg->aot_opts.log_generics)
4214 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4216 add_method (acfg, method);
4219 /* Add superclasses */
4221 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4224 * For ICollection<T>, add instances of the helper methods
4225 * in Array, since a T[] could be cast to ICollection<T>.
4227 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4228 (!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"))) {
4229 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4230 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4234 if (!strcmp (klass->name, "IEnumerator`1"))
4235 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4237 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4239 /* Add the T[]/InternalEnumerator class */
4240 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4244 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4245 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4249 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4250 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4254 while ((method = mono_class_get_methods (array_class, &iter))) {
4255 if (strstr (method->name, name_prefix)) {
4256 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4258 add_extra_method_with_depth (acfg, m, depth);
4262 g_free (name_prefix);
4265 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4266 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4267 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4268 MonoClass *icomparable, *gcomparer;
4269 MonoGenericContext ctx;
4270 MonoType *args [16];
4272 memset (&ctx, 0, sizeof (ctx));
4274 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4275 g_assert (icomparable);
4276 args [0] = &tclass->byval_arg;
4277 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4279 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4280 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4281 g_assert (gcomparer);
4282 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4286 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4287 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4288 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4289 MonoClass *iface, *gcomparer;
4290 MonoGenericContext ctx;
4291 MonoType *args [16];
4293 memset (&ctx, 0, sizeof (ctx));
4295 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4297 args [0] = &tclass->byval_arg;
4298 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4300 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4301 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4302 g_assert (gcomparer);
4303 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4307 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4308 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4309 MonoClass *enum_comparer;
4310 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4311 MonoGenericContext ctx;
4312 MonoType *args [16];
4314 if (mono_class_is_enum (tclass)) {
4315 memset (&ctx, 0, sizeof (ctx));
4316 args [0] = &tclass->byval_arg;
4317 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4319 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4320 g_assert (enum_comparer);
4321 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4325 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4326 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4327 MonoClass *comparer;
4328 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4329 MonoGenericContext ctx;
4330 MonoType *args [16];
4332 if (mono_class_is_enum (tclass)) {
4333 memset (&ctx, 0, sizeof (ctx));
4334 args [0] = &tclass->byval_arg;
4335 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4337 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4338 g_assert (comparer);
4339 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4345 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4348 MonoGenericContext ctx;
4349 MonoType *args [16];
4351 if (acfg->aot_opts.no_instances)
4354 memset (&ctx, 0, sizeof (ctx));
4356 for (i = 0; i < ninsts; ++i) {
4357 args [0] = insts [i];
4358 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4359 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4364 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4366 MonoMethodHeader *header;
4367 MonoMethodSignature *sig;
4370 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4372 sig = mono_method_signature (method);
4375 for (j = 0; j < sig->param_count; ++j)
4376 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4377 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4380 header = mono_method_get_header (method);
4383 for (j = 0; j < header->num_locals; ++j)
4384 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4385 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4387 mono_loader_clear_error ();
4392 * add_generic_instances:
4394 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4397 add_generic_instances (MonoAotCompile *acfg)
4402 MonoGenericContext *context;
4404 if (acfg->aot_opts.no_instances)
4407 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4409 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4410 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4413 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4414 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4415 mono_error_cleanup (&error);
4419 if (method->klass->image != acfg->image)
4422 context = mono_method_get_context (method);
4424 if (context && ((context->class_inst && context->class_inst->is_open)))
4428 * For open methods, create an instantiation which can be passed to the JIT.
4429 * FIXME: Handle class_inst as well.
4431 if (context && context->method_inst && context->method_inst->is_open) {
4433 MonoGenericContext shared_context;
4434 MonoGenericInst *inst;
4435 MonoType **type_argv;
4437 MonoMethod *declaring_method;
4438 gboolean supported = TRUE;
4440 /* Check that the context doesn't contain open constructed types */
4441 if (context->class_inst) {
4442 inst = context->class_inst;
4443 for (i = 0; i < inst->type_argc; ++i) {
4444 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)
4446 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4450 if (context->method_inst) {
4451 inst = context->method_inst;
4452 for (i = 0; i < inst->type_argc; ++i) {
4453 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)
4455 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4463 memset (&shared_context, 0, sizeof (MonoGenericContext));
4465 inst = context->class_inst;
4467 type_argv = g_new0 (MonoType*, inst->type_argc);
4468 for (i = 0; i < inst->type_argc; ++i) {
4469 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)
4470 type_argv [i] = &mono_defaults.object_class->byval_arg;
4472 type_argv [i] = inst->type_argv [i];
4475 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4479 inst = context->method_inst;
4481 type_argv = g_new0 (MonoType*, inst->type_argc);
4482 for (i = 0; i < inst->type_argc; ++i) {
4483 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)
4484 type_argv [i] = &mono_defaults.object_class->byval_arg;
4486 type_argv [i] = inst->type_argv [i];
4489 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4493 if (method->is_generic || method->klass->generic_container)
4494 declaring_method = method;
4496 declaring_method = mono_method_get_declaring_generic_method (method);
4498 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4499 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4503 * If the method is fully sharable, it was already added in place of its
4504 * generic definition.
4506 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4510 * FIXME: Partially shared methods are not shared here, so we end up with
4511 * many identical methods.
4513 add_extra_method (acfg, method);
4516 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4520 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4522 klass = mono_class_get_checked (acfg->image, token, &error);
4523 if (!klass || klass->rank) {
4524 mono_error_cleanup (&error);
4528 add_generic_class (acfg, klass, FALSE, "typespec");
4531 /* Add types of args/locals */
4532 for (i = 0; i < acfg->methods->len; ++i) {
4533 method = g_ptr_array_index (acfg->methods, i);
4534 add_types_from_method_header (acfg, method);
4537 if (acfg->image == mono_defaults.corlib) {
4539 MonoType *insts [256];
4542 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4543 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4544 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4545 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4546 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4547 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4548 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4549 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4550 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4551 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4552 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4553 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4555 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4556 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4558 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4559 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4561 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4563 /* Add instances of the array generic interfaces for primitive types */
4564 /* This will add instances of the InternalArray_ helper methods in Array too */
4565 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4567 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4568 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4570 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4571 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4573 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4576 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4577 * used for all instances of GetGenericValueImpl by the AOT runtime.
4580 MonoGenericContext ctx;
4581 MonoType *args [16];
4582 MonoMethod *get_method;
4583 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4585 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4589 memset (&ctx, 0, sizeof (ctx));
4590 args [0] = &mono_defaults.object_class->byval_arg;
4591 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4592 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4593 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4597 /* Same for CompareExchange<T>/Exchange<T> */
4599 MonoGenericContext ctx;
4600 MonoType *args [16];
4602 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4603 gpointer iter = NULL;
4605 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4606 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4608 memset (&ctx, 0, sizeof (ctx));
4609 args [0] = &mono_defaults.object_class->byval_arg;
4610 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4611 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4612 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4617 /* Same for Volatile.Read/Write<T> */
4619 MonoGenericContext ctx;
4620 MonoType *args [16];
4622 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4623 gpointer iter = NULL;
4625 if (volatile_klass) {
4626 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4627 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4629 memset (&ctx, 0, sizeof (ctx));
4630 args [0] = &mono_defaults.object_class->byval_arg;
4631 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4632 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4633 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4642 * is_direct_callable:
4644 * Return whenever the method identified by JI is directly callable without
4645 * going through the PLT.
4648 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4650 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4651 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4653 gboolean direct_callable = TRUE;
4655 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4656 direct_callable = FALSE;
4657 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4658 // FIXME: Maybe call the wrapper directly ?
4659 direct_callable = FALSE;
4661 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4662 /* Disable this so all calls go through load_method (), see the
4663 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4664 * mono_debugger_agent_init ().
4666 direct_callable = FALSE;
4669 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4670 /* sgen does some initialization when the allocator method is created */
4671 direct_callable = FALSE;
4672 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4673 /* we don't know at compile time whether sgen is concurrent or not */
4674 direct_callable = FALSE;
4676 if (direct_callable)
4679 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4680 if (acfg->aot_opts.direct_pinvoke)
4682 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4683 if (acfg->aot_opts.direct_icalls)
4691 #ifdef MONO_ARCH_AOT_SUPPORTED
4693 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4695 MonoImage *image = method->klass->image;
4696 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4697 MonoTableInfo *tables = image->tables;
4698 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4699 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4700 guint32 im_cols [MONO_IMPLMAP_SIZE];
4703 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4707 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4710 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4712 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4715 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4717 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4724 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4726 if (a->native_offset == b->native_offset)
4727 return a->il_offset - b->il_offset;
4729 return a->native_offset - b->native_offset;
4733 * compute_line_numbers:
4735 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4738 static MonoDebugSourceLocation**
4739 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4741 MonoDebugMethodInfo *minfo;
4742 MonoDebugLineNumberEntry *ln_array;
4743 MonoDebugSourceLocation *loc;
4744 int i, prev_line, prev_il_offset;
4745 int *native_to_il_offset = NULL;
4746 MonoDebugSourceLocation **res;
4749 minfo = mono_debug_lookup_method (method);
4752 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4753 if (debug_info->code_size != code_size)
4756 g_assert (code_size);
4758 /* Compute the native->IL offset mapping */
4760 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4761 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4763 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4765 native_to_il_offset = g_new0 (int, code_size + 1);
4767 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4769 MonoDebugLineNumberEntry *lne = &ln_array [i];
4772 for (j = 0; j < lne->native_offset; ++j)
4773 native_to_il_offset [j] = -1;
4776 if (i < debug_info->num_line_numbers - 1) {
4777 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4779 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4780 native_to_il_offset [j] = lne->il_offset;
4782 for (j = lne->native_offset; j < code_size; ++j)
4783 native_to_il_offset [j] = lne->il_offset;
4788 /* Compute the native->line number mapping */
4789 res = g_new0 (MonoDebugSourceLocation*, code_size);
4790 prev_il_offset = -1;
4793 for (i = 0; i < code_size; ++i) {
4794 int il_offset = native_to_il_offset [i];
4796 if (il_offset == -1 || il_offset == prev_il_offset)
4798 prev_il_offset = il_offset;
4799 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4800 if (!(loc && loc->source_file))
4802 if (loc->row == prev_line) {
4803 mono_debug_symfile_free_location (loc);
4806 prev_line = loc->row;
4807 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4809 /* This will cover the prolog too */
4819 get_file_index (MonoAotCompile *acfg, const char *source_file)
4823 // FIXME: Free these
4824 if (!acfg->dwarf_ln_filenames)
4825 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4826 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4828 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4829 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4830 emit_unset_mode (acfg);
4831 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4843 * emit_and_reloc_code:
4845 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4846 * is true, calls are made through the GOT too. This is used for emitting trampolines
4847 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4848 * since trampolines are needed to make PTL work.
4851 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4853 int i, pindex, start_index;
4855 MonoJumpInfo *patch_info;
4856 MonoDebugSourceLocation **locs = NULL;
4858 #ifdef MONO_ARCH_AOT_SUPPORTED
4859 gboolean direct_call, external_call;
4861 const char *direct_call_target = 0;
4862 const char *direct_pinvoke;
4865 if (acfg->gas_line_numbers && method && debug_info) {
4866 locs = compute_line_numbers (method, code_len, debug_info);
4868 int findex = get_file_index (acfg, "<unknown>");
4869 emit_unset_mode (acfg);
4870 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4874 /* Collect and sort relocations */
4875 patches = g_ptr_array_new ();
4876 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4877 g_ptr_array_add (patches, patch_info);
4878 g_ptr_array_sort (patches, compare_patches);
4881 for (i = 0; i < code_len; i += INST_LEN) {
4883 for (pindex = start_index; pindex < patches->len; ++pindex) {
4884 patch_info = g_ptr_array_index (patches, pindex);
4885 if (patch_info->ip.i >= i)
4889 if (locs && locs [i]) {
4890 MonoDebugSourceLocation *loc = locs [i];
4893 findex = get_file_index (acfg, loc->source_file);
4894 emit_unset_mode (acfg);
4895 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4896 mono_debug_symfile_free_location (loc);
4900 #ifdef MONO_ARCH_AOT_SUPPORTED
4901 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4902 start_index = pindex;
4904 switch (patch_info->type) {
4905 case MONO_PATCH_INFO_NONE:
4907 case MONO_PATCH_INFO_GOT_OFFSET: {
4910 arch_emit_got_offset (acfg, code + i, &code_size);
4911 i += code_size - INST_LEN;
4913 patch_info->type = MONO_PATCH_INFO_NONE;
4916 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4917 int code_size, index;
4918 char *selector = (void*)patch_info->data.target;
4920 if (!acfg->objc_selector_to_index)
4921 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4922 if (!acfg->objc_selectors)
4923 acfg->objc_selectors = g_ptr_array_new ();
4924 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4928 index = acfg->objc_selector_index;
4929 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4930 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4931 acfg->objc_selector_index ++;
4934 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4935 i += code_size - INST_LEN;
4937 patch_info->type = MONO_PATCH_INFO_NONE;
4942 * If this patch is a call, try emitting a direct call instead of
4943 * through a PLT entry. This is possible if the called method is in
4944 * the same assembly and requires no initialization.
4946 direct_call = FALSE;
4947 external_call = FALSE;
4948 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4949 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4950 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4951 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4953 direct_call_target = callee_cfg->asm_symbol;
4954 patch_info->type = MONO_PATCH_INFO_NONE;
4955 acfg->stats.direct_calls ++;
4958 acfg->stats.all_calls ++;
4959 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4960 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4961 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4962 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4964 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4965 if (direct_pinvoke) {
4967 g_assert (strlen (direct_pinvoke) < 1000);
4968 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4971 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4972 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4973 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4974 /* Call to a C function implementing a jit icall */
4976 external_call = TRUE;
4977 g_assert (strlen (sym) < 1000);
4978 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4980 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4981 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4982 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4983 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4984 /* Call to a jit icall without a wrapper */
4986 external_call = TRUE;
4987 g_assert (strlen (sym) < 1000);
4988 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4993 patch_info->type = MONO_PATCH_INFO_NONE;
4994 acfg->stats.direct_calls ++;
4997 if (!got_only && !direct_call) {
4998 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5000 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5002 direct_call_target = plt_entry->symbol;
5004 /* Nullify the patch */
5005 patch_info->type = MONO_PATCH_INFO_NONE;
5006 plt_entry->jit_used = TRUE;
5013 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5014 i += call_size - INST_LEN;
5018 got_slot = get_got_offset (acfg, FALSE, patch_info);
5020 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5021 i += code_size - INST_LEN;
5027 #endif /* MONO_ARCH_AOT_SUPPORTED */
5030 /* Find next patch */
5032 for (pindex = start_index; pindex < patches->len; ++pindex) {
5033 patch_info = g_ptr_array_index (patches, pindex);
5034 if (patch_info->ip.i >= i)
5038 /* Try to emit multiple bytes at once */
5039 if (pindex < patches->len && patch_info->ip.i > i) {
5042 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5043 if (locs && locs [limit])
5047 emit_code_bytes (acfg, code + i, limit - i);
5048 i = limit - INST_LEN;
5050 emit_code_bytes (acfg, code + i, INST_LEN);
5061 * Return a modified version of S which only includes characters permissible in symbols.
5064 sanitize_symbol (MonoAotCompile *acfg, char *s)
5066 gboolean process = FALSE;
5075 for (i = 0; i < len; ++i)
5076 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5081 gs = g_string_sized_new (len);
5082 for (i = 0; i < len; ++i) {
5084 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5085 g_string_append_c (gs, c);
5086 } else if (c > 0x7f) {
5087 /* multi-byte utf8 */
5088 g_string_append_printf (gs, "_0x%x", c);
5091 while (c >> 6 == 0x2) {
5092 g_string_append_printf (gs, "%x", c);
5096 g_string_append_printf (gs, "_");
5099 g_string_append_c (gs, '_');
5103 res = mono_mempool_strdup (acfg->mempool, gs->str);
5104 g_string_free (gs, TRUE);
5109 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5111 char *name1, *name2, *cached;
5112 int i, j, len, count;
5113 MonoMethod *cached_method;
5115 name1 = mono_method_full_name (method, TRUE);
5118 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5119 if ((!prefix || !*prefix) && name1 [0] == 'L')
5123 len = strlen (name1);
5124 name2 = malloc (strlen (prefix) + len + 16);
5125 memcpy (name2, prefix, strlen (prefix));
5126 j = strlen (prefix);
5127 for (i = 0; i < len; ++i) {
5128 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5130 } else if (isalnum (name1 [i])) {
5131 name2 [j ++] = name1 [i];
5132 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5134 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5137 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5147 cached_method = g_hash_table_lookup (cache, name2);
5148 if (!(cached_method && cached_method != method))
5150 sprintf (name2 + j, "_%d", count);
5154 cached = g_strdup (name2);
5155 g_hash_table_insert (cache, cached, method);
5161 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5166 char *debug_sym = NULL;
5167 char *symbol = NULL;
5168 int func_alignment = AOT_FUNC_ALIGNMENT;
5171 method = cfg->orig_method;
5172 code = cfg->native_code;
5174 method_index = get_method_index (acfg, method);
5175 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5177 /* Make the labels local */
5178 emit_section_change (acfg, ".text", 0);
5179 emit_alignment_code (acfg, func_alignment);
5181 if (acfg->global_symbols && acfg->need_no_dead_strip)
5182 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5184 emit_label (acfg, cfg->asm_symbol);
5186 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5188 * Write a C style symbol for every method, this has two uses:
5189 * - it works on platforms where the dwarf debugging info is not
5191 * - it allows the setting of breakpoints of aot-ed methods.
5193 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5194 cfg->asm_debug_symbol = g_strdup (debug_sym);
5196 if (acfg->need_no_dead_strip)
5197 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5198 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5199 emit_label (acfg, debug_sym);
5202 export_name = g_hash_table_lookup (acfg->export_names, method);
5204 /* Emit a global symbol for the method */
5205 emit_global_inner (acfg, export_name, TRUE);
5206 emit_label (acfg, export_name);
5209 if (cfg->verbose_level > 0)
5210 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5212 acfg->stats.code_size += cfg->code_len;
5214 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5216 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 ()));
5220 if (acfg->aot_opts.write_symbols) {
5222 emit_symbol_size (acfg, debug_sym, ".");
5224 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5228 emit_label (acfg, symbol);
5235 * Encode PATCH_INFO into its disk representation.
5238 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5242 switch (patch_info->type) {
5243 case MONO_PATCH_INFO_NONE:
5245 case MONO_PATCH_INFO_IMAGE:
5246 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5248 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5249 case MONO_PATCH_INFO_JIT_TLS_ID:
5250 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5251 case MONO_PATCH_INFO_GC_NURSERY_START:
5253 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5254 encode_value (patch_info->data.index, p, &p);
5256 case MONO_PATCH_INFO_METHOD_REL:
5257 encode_value ((gint)patch_info->data.offset, p, &p);
5259 case MONO_PATCH_INFO_SWITCH: {
5260 gpointer *table = (gpointer *)patch_info->data.table->table;
5263 encode_value (patch_info->data.table->table_size, p, &p);
5264 for (k = 0; k < patch_info->data.table->table_size; k++)
5265 encode_value ((int)(gssize)table [k], p, &p);
5268 case MONO_PATCH_INFO_METHODCONST:
5269 case MONO_PATCH_INFO_METHOD:
5270 case MONO_PATCH_INFO_METHOD_JUMP:
5271 case MONO_PATCH_INFO_ICALL_ADDR:
5272 case MONO_PATCH_INFO_METHOD_RGCTX:
5273 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5274 encode_method_ref (acfg, patch_info->data.method, p, &p);
5276 case MONO_PATCH_INFO_INTERNAL_METHOD:
5277 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5278 guint32 len = strlen (patch_info->data.name);
5280 encode_value (len, p, &p);
5282 memcpy (p, patch_info->data.name, len);
5287 case MONO_PATCH_INFO_LDSTR: {
5288 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5289 guint32 token = patch_info->data.token->token;
5290 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5291 encode_value (image_index, p, &p);
5292 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5295 case MONO_PATCH_INFO_RVA:
5296 case MONO_PATCH_INFO_DECLSEC:
5297 case MONO_PATCH_INFO_LDTOKEN:
5298 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5299 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5300 encode_value (patch_info->data.token->token, p, &p);
5301 encode_value (patch_info->data.token->has_context, p, &p);
5302 if (patch_info->data.token->has_context)
5303 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5305 case MONO_PATCH_INFO_EXC_NAME: {
5306 MonoClass *ex_class;
5309 mono_class_from_name (mono_defaults.exception_class->image,
5310 "System", patch_info->data.target);
5311 g_assert (ex_class);
5312 encode_klass_ref (acfg, ex_class, p, &p);
5315 case MONO_PATCH_INFO_R4:
5316 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5318 case MONO_PATCH_INFO_R8:
5319 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5320 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5322 case MONO_PATCH_INFO_VTABLE:
5323 case MONO_PATCH_INFO_CLASS:
5324 case MONO_PATCH_INFO_IID:
5325 case MONO_PATCH_INFO_ADJUSTED_IID:
5326 case MONO_PATCH_INFO_CLASS_INIT:
5327 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5329 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5330 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5331 if (patch_info->data.del_tramp->method) {
5332 encode_value (1, p, &p);
5333 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5335 encode_value (0, p, &p);
5337 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5339 case MONO_PATCH_INFO_FIELD:
5340 case MONO_PATCH_INFO_SFLDA:
5341 encode_field_info (acfg, patch_info->data.field, p, &p);
5343 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5345 case MONO_PATCH_INFO_RGCTX_FETCH: {
5346 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5351 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5352 * reference the same method, so encode the method only once.
5354 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5356 buf2 = g_malloc (1024);
5359 encode_method_ref (acfg, entry->method, p2, &p2);
5360 g_assert (p2 - buf2 < 1024);
5362 offset = add_to_blob (acfg, buf2, p2 - buf2);
5365 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5370 encode_value (offset, p, &p);
5371 g_assert ((int)entry->info_type < 256);
5372 g_assert (entry->data->type < 256);
5373 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5374 encode_patch (acfg, entry->data, p, &p);
5377 case MONO_PATCH_INFO_MONITOR_ENTER:
5378 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5379 case MONO_PATCH_INFO_MONITOR_EXIT:
5380 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5382 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5383 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5384 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5386 case MONO_PATCH_INFO_SIGNATURE:
5387 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5389 case MONO_PATCH_INFO_TLS_OFFSET:
5390 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5392 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5393 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5394 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5396 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5397 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5400 encode_method_ref (acfg, info->method, p, &p);
5401 encode_value (info->num_entries, p, &p);
5402 for (i = 0; i < info->num_entries; ++i) {
5403 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5405 encode_value (template->info_type, p, &p);
5406 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5407 case MONO_PATCH_INFO_CLASS:
5408 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5410 case MONO_PATCH_INFO_FIELD:
5411 encode_field_info (acfg, template->data, p, &p);
5414 g_assert_not_reached ();
5420 case MONO_PATCH_INFO_LDSTR_LIT: {
5421 const char *s = patch_info->data.target;
5422 int len = strlen (s);
5424 encode_value (len, p, &p);
5425 memcpy (p, s, len + 1);
5429 case MONO_PATCH_INFO_VIRT_METHOD:
5430 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5431 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5433 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5436 g_warning ("unable to handle jump info %d", patch_info->type);
5437 g_assert_not_reached ();
5444 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5447 guint32 pindex, offset;
5448 MonoJumpInfo *patch_info;
5450 encode_value (n_patches, p, &p);
5452 for (pindex = 0; pindex < patches->len; ++pindex) {
5453 patch_info = g_ptr_array_index (patches, pindex);
5455 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5459 offset = get_got_offset (acfg, llvm, patch_info);
5460 encode_value (offset, p, &p);
5467 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5470 int pindex, buf_size, n_patches;
5472 MonoJumpInfo *patch_info;
5473 guint32 method_index;
5475 guint32 first_got_offset;
5477 method = cfg->orig_method;
5479 method_index = get_method_index (acfg, method);
5481 /* Sort relocations */
5482 patches = g_ptr_array_new ();
5483 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5484 g_ptr_array_add (patches, patch_info);
5485 g_ptr_array_sort (patches, compare_patches);
5487 first_got_offset = acfg->cfgs [method_index]->got_offset;
5489 /**********************/
5490 /* Encode method info */
5491 /**********************/
5493 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5494 p = buf = g_malloc (buf_size);
5496 if (mono_class_get_cctor (method->klass))
5497 encode_klass_ref (acfg, method->klass, p, &p);
5499 /* Not needed when loading the method */
5500 encode_value (0, p, &p);
5502 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5505 for (pindex = 0; pindex < patches->len; ++pindex) {
5506 patch_info = g_ptr_array_index (patches, pindex);
5508 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5509 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5510 patch_info->type = MONO_PATCH_INFO_NONE;
5515 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5516 /* Stored in a GOT slot initialized at module load time */
5517 patch_info->type = MONO_PATCH_INFO_NONE;
5521 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5522 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START) {
5523 /* Stored in a GOT slot initialized at module load time */
5524 patch_info->type = MONO_PATCH_INFO_NONE;
5528 if (is_plt_patch (patch_info)) {
5529 /* Calls are made through the PLT */
5530 patch_info->type = MONO_PATCH_INFO_NONE;
5538 g_assert (cfg->has_got_slots);
5540 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5542 acfg->stats.info_size += p - buf;
5544 g_assert (p - buf < buf_size);
5546 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5551 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5553 guint32 cache_index;
5556 /* Reuse the unwind module to canonize and store unwind info entries */
5557 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5559 /* Use +/- 1 to distinguish 0s from missing entries */
5560 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5568 * It would be easier to use assembler symbols, but the caller needs an
5571 offset = acfg->unwind_info_offset;
5572 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5573 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5576 encode_value (encoded_len, p, &p);
5578 acfg->unwind_info_offset += encoded_len + (p - buf);
5584 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5587 guint32 debug_info_size, seq_points_size;
5589 MonoMethodHeader *header;
5590 guint8 *p, *buf, *debug_info;
5591 MonoJitInfo *jinfo = cfg->jit_info;
5593 gboolean use_unwind_ops = FALSE;
5594 MonoSeqPointInfo *seq_points;
5596 code = cfg->native_code;
5597 header = cfg->header;
5599 if (!acfg->aot_opts.nodebug) {
5600 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5603 debug_info_size = 0;
5606 seq_points = cfg->seq_point_info;
5607 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5609 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5611 p = buf = g_malloc (buf_size);
5613 use_unwind_ops = cfg->unwind_ops != NULL;
5615 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);
5617 encode_value (flags, p, &p);
5619 if (use_unwind_ops) {
5620 guint32 encoded_len;
5622 guint32 unwind_desc;
5624 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5626 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5627 encode_value (unwind_desc, p, &p);
5629 encode_value (jinfo->unwind_info, p, &p);
5632 /*Encode the number of holes before the number of clauses to make decoding easier*/
5633 if (jinfo->has_try_block_holes) {
5634 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5635 encode_value (table->num_holes, p, &p);
5638 if (jinfo->has_arch_eh_info) {
5640 * In AOT mode, the code length is calculated from the address of the previous method,
5641 * which could include alignment padding, so calculating the start of the epilog as
5642 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5644 encode_value (jinfo->code_size, p, &p);
5647 /* Exception table */
5648 if (cfg->compile_llvm) {
5650 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5651 * since the information is only available to llc. Instead, we let llc save the data
5652 * into the LSDA, and read it from there at runtime.
5654 /* The assembly might be CIL stripped so emit the data ourselves */
5655 if (header->num_clauses)
5656 encode_value (header->num_clauses, p, &p);
5658 for (k = 0; k < header->num_clauses; ++k) {
5659 MonoExceptionClause *clause;
5661 clause = &header->clauses [k];
5663 encode_value (clause->flags, p, &p);
5664 if (clause->data.catch_class) {
5665 encode_value (1, p, &p);
5666 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5668 encode_value (0, p, &p);
5671 /* Emit a list of nesting clauses */
5672 for (i = 0; i < header->num_clauses; ++i) {
5674 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5676 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5678 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5679 encode_value (i, p, &p);
5681 encode_value (-1, p, &p);
5684 if (jinfo->num_clauses)
5685 encode_value (jinfo->num_clauses, p, &p);
5687 for (k = 0; k < jinfo->num_clauses; ++k) {
5688 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5690 encode_value (ei->flags, p, &p);
5691 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5692 /* Not used for catch clauses */
5693 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5694 encode_value (ei->exvar_offset, p, &p);
5696 encode_value (ei->exvar_offset, p, &p);
5699 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5700 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5702 if (ei->data.catch_class) {
5706 buf2 = g_malloc (4096);
5708 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5710 g_assert (len < 4096);
5711 encode_value (len, p, &p);
5712 memcpy (p, buf2, len);
5716 encode_value (0, p, &p);
5720 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5721 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5722 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5726 if (jinfo->has_try_block_holes) {
5727 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5728 for (i = 0; i < table->num_holes; ++i) {
5729 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5730 encode_value (hole->clause, p, &p);
5731 encode_value (hole->length, p, &p);
5732 encode_value (hole->offset, p, &p);
5736 if (jinfo->has_arch_eh_info) {
5737 MonoArchEHJitInfo *eh_info;
5739 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5740 encode_value (eh_info->stack_size, p, &p);
5741 encode_value (eh_info->epilog_size, p, &p);
5744 if (jinfo->has_generic_jit_info) {
5745 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5746 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5750 encode_value (gi->nlocs, p, &p);
5752 for (i = 0; i < gi->nlocs; ++i) {
5753 MonoDwarfLocListEntry *entry = &gi->locations [i];
5755 encode_value (entry->is_reg ? 1 : 0, p, &p);
5756 encode_value (entry->reg, p, &p);
5758 encode_value (entry->offset, p, &p);
5760 g_assert (entry->from == 0);
5762 encode_value (entry->from, p, &p);
5763 encode_value (entry->to, p, &p);
5766 if (!cfg->compile_llvm) {
5767 encode_value (gi->has_this ? 1 : 0, p, &p);
5768 encode_value (gi->this_reg, p, &p);
5769 encode_value (gi->this_offset, p, &p);
5774 * Need to encode jinfo->method too, since it is not equal to 'method'
5775 * when using generic sharing.
5777 buf2 = g_malloc (4096);
5779 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5781 g_assert (len < 4096);
5782 encode_value (len, p, &p);
5783 memcpy (p, buf2, len);
5787 if (gsctx && gsctx->is_gsharedvt) {
5788 encode_value (1, p, &p);
5790 encode_value (0, p, &p);
5794 if (seq_points_size)
5795 p += mono_seq_point_info_write (seq_points, p);
5797 g_assert (debug_info_size < buf_size);
5799 encode_value (debug_info_size, p, &p);
5800 if (debug_info_size) {
5801 memcpy (p, debug_info, debug_info_size);
5802 p += debug_info_size;
5803 g_free (debug_info);
5808 encode_value (cfg->gc_map_size, p, &p);
5809 /* The GC map requires 4 bytes of alignment */
5810 while ((gsize)p % 4)
5812 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5813 p += cfg->gc_map_size;
5816 acfg->stats.ex_info_size += p - buf;
5818 g_assert (p - buf < buf_size);
5821 /* The GC Map requires 4 byte alignment */
5822 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5827 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5830 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5832 int i, buf_size, res;
5833 gboolean no_special_static, cant_encode;
5834 gpointer iter = NULL;
5837 mono_error_cleanup (&error);
5841 p = buf = g_malloc (buf_size);
5843 /* Mark as unusable */
5844 encode_value (-1, p, &p);
5846 res = add_to_blob (acfg, buf, p - buf);
5852 buf_size = 10240 + (klass->vtable_size * 16);
5853 p = buf = g_malloc (buf_size);
5857 mono_class_init (klass);
5859 mono_class_get_nested_types (klass, &iter);
5860 g_assert (klass->nested_classes_inited);
5862 mono_class_setup_vtable (klass);
5865 * Emit all the information which is required for creating vtables so
5866 * the runtime does not need to create the MonoMethod structures which
5867 * take up a lot of space.
5870 no_special_static = !mono_class_has_special_static_fields (klass);
5872 /* Check whenever we have enough info to encode the vtable */
5873 cant_encode = FALSE;
5874 for (i = 0; i < klass->vtable_size; ++i) {
5875 MonoMethod *cm = klass->vtable [i];
5877 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5881 mono_class_has_finalizer (klass);
5883 if (klass->generic_container || cant_encode) {
5884 encode_value (-1, p, &p);
5886 encode_value (klass->vtable_size, p, &p);
5887 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);
5888 if (klass->has_cctor)
5889 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5890 if (klass->has_finalize)
5891 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5893 encode_value (klass->instance_size, p, &p);
5894 encode_value (mono_class_data_size (klass), p, &p);
5895 encode_value (klass->packing_size, p, &p);
5896 encode_value (klass->min_align, p, &p);
5898 for (i = 0; i < klass->vtable_size; ++i) {
5899 MonoMethod *cm = klass->vtable [i];
5902 encode_method_ref (acfg, cm, p, &p);
5904 encode_value (0, p, &p);
5908 acfg->stats.class_info_size += p - buf;
5910 g_assert (p - buf < buf_size);
5911 res = add_to_blob (acfg, buf, p - buf);
5918 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5920 char *debug_sym = NULL;
5924 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5925 /* Need to add a prefix to create unique symbols */
5926 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5928 prefix = g_strdup ("plt_");
5932 case MONO_PATCH_INFO_METHOD:
5933 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5935 case MONO_PATCH_INFO_INTERNAL_METHOD:
5936 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5938 case MONO_PATCH_INFO_CLASS_INIT:
5939 s = mono_type_get_name (&ji->data.klass->byval_arg);
5940 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5943 case MONO_PATCH_INFO_RGCTX_FETCH:
5944 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5946 case MONO_PATCH_INFO_ICALL_ADDR: {
5947 char *s = get_debug_sym (ji->data.method, "", cache);
5949 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5953 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5954 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5962 return sanitize_symbol (acfg, debug_sym);
5966 * Calls made from AOTed code are routed through a table of jumps similar to the
5967 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5968 * control to the AOT runtime through a trampoline.
5971 emit_plt (MonoAotCompile *acfg)
5977 sprintf (symbol, "plt");
5979 emit_section_change (acfg, ".text", 0);
5980 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5981 emit_info_symbol (acfg, symbol);
5982 emit_label (acfg, acfg->plt_symbol);
5984 for (i = 0; i < acfg->plt_offset; ++i) {
5985 char *debug_sym = NULL;
5986 MonoPltEntry *plt_entry = NULL;
5990 * The first plt entry is unused.
5994 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5996 debug_sym = plt_entry->debug_sym;
5998 if (acfg->thumb_mixed && !plt_entry->jit_used)
5999 /* Emit only a thumb version */
6002 /* Skip plt entries not actually called */
6003 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6006 if (acfg->llvm && !acfg->thumb_mixed) {
6007 emit_label (acfg, plt_entry->llvm_symbol);
6009 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6010 #if defined(TARGET_MACH)
6011 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6017 if (acfg->need_no_dead_strip) {
6018 emit_unset_mode (acfg);
6019 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6021 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6022 emit_label (acfg, debug_sym);
6025 emit_label (acfg, plt_entry->symbol);
6027 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6030 emit_symbol_size (acfg, debug_sym, ".");
6033 if (acfg->thumb_mixed) {
6034 /* Make sure the ARM symbols don't alias the thumb ones */
6035 emit_zero_bytes (acfg, 16);
6038 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6041 for (i = 0; i < acfg->plt_offset; ++i) {
6042 char *debug_sym = NULL;
6043 MonoPltEntry *plt_entry = NULL;
6048 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6050 /* Skip plt entries not actually called by LLVM code */
6051 if (!plt_entry->llvm_used)
6054 if (acfg->aot_opts.write_symbols) {
6055 if (plt_entry->debug_sym)
6056 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6060 #if defined(TARGET_MACH)
6061 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6062 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6064 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6065 emit_label (acfg, debug_sym);
6067 fprintf (acfg->fp, "\n.thumb_func\n");
6069 emit_label (acfg, plt_entry->llvm_symbol);
6072 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6074 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6077 emit_symbol_size (acfg, debug_sym, ".");
6083 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6085 sprintf (symbol, "plt_end");
6086 emit_info_symbol (acfg, symbol);
6090 * emit_trampoline_full:
6092 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6093 * create_jit_info_for_trampoline ().
6095 static G_GNUC_UNUSED void
6096 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6098 char start_symbol [256];
6099 char end_symbol [256];
6101 guint32 buf_size, info_offset;
6102 MonoJumpInfo *patch_info;
6115 code_size = info->code_size;
6117 unwind_ops = info->unwind_ops;
6119 #ifdef __native_client_codegen__
6120 mono_nacl_fix_patches (code, ji);
6125 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6127 emit_section_change (acfg, ".text", 0);
6128 emit_global (acfg, start_symbol, TRUE);
6129 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6130 emit_label (acfg, start_symbol);
6132 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6133 emit_label (acfg, symbol);
6136 * The code should access everything through the GOT, so we pass
6139 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6141 emit_symbol_size (acfg, start_symbol, ".");
6144 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6145 emit_label (acfg, end_symbol);
6150 /* Sort relocations */
6151 patches = g_ptr_array_new ();
6152 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6153 if (patch_info->type != MONO_PATCH_INFO_NONE)
6154 g_ptr_array_add (patches, patch_info);
6155 g_ptr_array_sort (patches, compare_patches);
6157 buf_size = patches->len * 128 + 128;
6158 buf = g_malloc (buf_size);
6161 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6162 g_assert (p - buf < buf_size);
6164 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6166 info_offset = add_to_blob (acfg, buf, p - buf);
6168 emit_section_change (acfg, RODATA_SECT, 0);
6169 emit_global (acfg, symbol, FALSE);
6170 emit_label (acfg, symbol);
6172 emit_int32 (acfg, info_offset);
6176 guint32 encoded_len;
6180 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6182 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6183 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6186 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6187 emit_int32 (acfg, uw_offset);
6190 /* Emit debug info */
6194 sprintf (symbol, "%s", name);
6195 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6198 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6202 static G_GNUC_UNUSED void
6203 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6205 emit_trampoline_full (acfg, got_offset, info, FALSE);
6209 emit_trampolines (MonoAotCompile *acfg)
6212 char end_symbol [256];
6213 int i, tramp_got_offset;
6214 MonoAotTrampoline ntype;
6215 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6219 if (!mono_aot_mode_is_full (&acfg->aot_opts))
6222 g_assert (acfg->image->assembly);
6224 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6225 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6226 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6227 MonoTrampInfo *info;
6230 * Emit the generic trampolines.
6232 * We could save some code by treating the generic trampolines as a wrapper
6233 * method, but that approach has its own complexities, so we choose the simpler
6236 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6237 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6238 #ifdef DISABLE_REMOTING
6239 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6242 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6243 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6246 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6247 emit_trampoline (acfg, acfg->got_offset, info);
6250 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6251 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6252 emit_trampoline (acfg, acfg->got_offset, info);
6253 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6254 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6255 emit_trampoline (acfg, acfg->got_offset, info);
6257 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6258 emit_trampoline (acfg, acfg->got_offset, info);
6261 /* Emit the exception related code pieces */
6262 mono_arch_get_restore_context (&info, TRUE);
6263 emit_trampoline (acfg, acfg->got_offset, info);
6264 mono_arch_get_call_filter (&info, TRUE);
6265 emit_trampoline (acfg, acfg->got_offset, info);
6266 mono_arch_get_throw_exception (&info, TRUE);
6267 emit_trampoline (acfg, acfg->got_offset, info);
6268 mono_arch_get_rethrow_exception (&info, TRUE);
6269 emit_trampoline (acfg, acfg->got_offset, info);
6270 mono_arch_get_throw_corlib_exception (&info, TRUE);
6271 emit_trampoline (acfg, acfg->got_offset, info);
6273 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6274 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6275 emit_trampoline (acfg, acfg->got_offset, info);
6276 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6277 emit_trampoline (acfg, acfg->got_offset, info);
6280 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6281 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6283 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6285 /* Create a separate out trampoline for more information in stack traces */
6286 info->name = g_strdup ("gsharedvt_out_trampoline");
6287 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6291 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6293 GSList *l = mono_arch_get_trampolines (TRUE);
6296 MonoTrampInfo *info = l->data;
6298 emit_trampoline (acfg, acfg->got_offset, info);
6304 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6307 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6308 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6309 emit_trampoline (acfg, acfg->got_offset, info);
6311 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6312 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6313 emit_trampoline (acfg, acfg->got_offset, info);
6316 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6317 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6318 emit_trampoline (acfg, acfg->got_offset, info);
6324 /* delegate_invoke_impl trampolines */
6325 l = mono_arch_get_delegate_invoke_impls ();
6327 MonoTrampInfo *info = l->data;
6329 emit_trampoline (acfg, acfg->got_offset, info);
6334 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6336 /* Emit trampolines which are numerous */
6339 * These include the following:
6340 * - specific trampolines
6341 * - static rgctx invoke trampolines
6343 * These trampolines have the same code, they are parameterized by GOT
6345 * They are defined in this file, in the arch_... routines instead of
6346 * in tramp-<ARCH>.c, since it is easier to do it this way.
6350 * When running in aot-only mode, we can't create specific trampolines at
6351 * runtime, so we create a few, and save them in the AOT file.
6352 * Normal trampolines embed their argument as a literal inside the
6353 * trampoline code, we can't do that here, so instead we embed an offset
6354 * which needs to be added to the trampoline address to get the address of
6355 * the GOT slot which contains the argument value.
6356 * The generated trampolines jump to the generic trampolines using another
6357 * GOT slot, which will be setup by the AOT loader to point to the
6358 * generic trampoline code of the given type.
6362 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6366 emit_section_change (acfg, ".text", 0);
6368 tramp_got_offset = acfg->got_offset;
6370 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6372 case MONO_AOT_TRAMP_SPECIFIC:
6373 sprintf (symbol, "specific_trampolines");
6375 case MONO_AOT_TRAMP_STATIC_RGCTX:
6376 sprintf (symbol, "static_rgctx_trampolines");
6378 case MONO_AOT_TRAMP_IMT_THUNK:
6379 sprintf (symbol, "imt_thunks");
6381 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6382 sprintf (symbol, "gsharedvt_arg_trampolines");
6385 g_assert_not_reached ();
6388 sprintf (end_symbol, "%s_e", symbol);
6390 if (acfg->aot_opts.write_symbols)
6391 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6393 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6394 emit_info_symbol (acfg, symbol);
6396 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6398 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6402 case MONO_AOT_TRAMP_SPECIFIC:
6403 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6404 tramp_got_offset += 2;
6406 case MONO_AOT_TRAMP_STATIC_RGCTX:
6407 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6408 tramp_got_offset += 2;
6410 case MONO_AOT_TRAMP_IMT_THUNK:
6411 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6412 tramp_got_offset += 1;
6414 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6415 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6416 tramp_got_offset += 2;
6419 g_assert_not_reached ();
6421 #ifdef __native_client_codegen__
6422 /* align to avoid 32-byte boundary crossings */
6423 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6426 if (!acfg->trampoline_size [ntype]) {
6427 g_assert (tramp_size);
6428 acfg->trampoline_size [ntype] = tramp_size;
6432 emit_label (acfg, end_symbol);
6433 emit_int32 (acfg, 0);
6436 arch_emit_specific_trampoline_pages (acfg);
6438 /* Reserve some entries at the end of the GOT for our use */
6439 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6442 acfg->got_offset += acfg->num_trampoline_got_entries;
6446 str_begins_with (const char *str1, const char *str2)
6448 int len = strlen (str2);
6449 return strncmp (str1, str2, len) == 0;
6453 mono_aot_readonly_field_override (MonoClassField *field)
6456 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6457 char *p = rdv->name;
6459 len = strlen (field->parent->name_space);
6460 if (strncmp (p, field->parent->name_space, len))
6465 len = strlen (field->parent->name);
6466 if (strncmp (p, field->parent->name, len))
6471 if (strcmp (p, field->name))
6473 switch (rdv->type) {
6475 return &rdv->value.i1;
6477 return &rdv->value.i2;
6479 return &rdv->value.i4;
6488 add_readonly_value (MonoAotOptions *opts, const char *val)
6493 /* the format of val is:
6494 * namespace.typename.fieldname=type/value
6495 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6497 fval = strrchr (val, '/');
6499 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6502 tval = strrchr (val, '=');
6504 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6507 rdv = g_new0 (ReadOnlyValue, 1);
6508 rdv->name = g_malloc0 (tval - val + 1);
6509 memcpy (rdv->name, val, tval - val);
6512 if (strncmp (tval, "i1", 2) == 0) {
6513 rdv->value.i1 = atoi (fval);
6514 rdv->type = MONO_TYPE_I1;
6515 } else if (strncmp (tval, "i2", 2) == 0) {
6516 rdv->value.i2 = atoi (fval);
6517 rdv->type = MONO_TYPE_I2;
6518 } else if (strncmp (tval, "i4", 2) == 0) {
6519 rdv->value.i4 = atoi (fval);
6520 rdv->type = MONO_TYPE_I4;
6522 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6525 rdv->next = readonly_values;
6526 readonly_values = rdv;
6530 clean_path (gchar * path)
6535 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6538 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6545 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6547 gchar **args, **ptr;
6549 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6550 for (ptr = args; ptr && *ptr; ptr ++) {
6551 const char *arg = *ptr;
6553 if (str_begins_with (arg, "outfile=")) {
6554 opts->outfile = g_strdup (arg + strlen ("outfile="));
6555 } else if (str_begins_with (arg, "llvm-outfile=")) {
6556 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6557 } else if (str_begins_with (arg, "temp-path=")) {
6558 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6559 } else if (str_begins_with (arg, "save-temps")) {
6560 opts->save_temps = TRUE;
6561 } else if (str_begins_with (arg, "keep-temps")) {
6562 opts->save_temps = TRUE;
6563 } else if (str_begins_with (arg, "write-symbols")) {
6564 opts->write_symbols = TRUE;
6565 } else if (str_begins_with (arg, "no-write-symbols")) {
6566 opts->write_symbols = FALSE;
6567 } else if (str_begins_with (arg, "metadata-only")) {
6568 opts->metadata_only = TRUE;
6569 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6570 opts->bind_to_runtime_version = TRUE;
6571 } else if (str_begins_with (arg, "full")) {
6572 opts->mode = MONO_AOT_MODE_FULL;
6573 } else if (str_begins_with (arg, "hybrid")) {
6574 opts->mode = MONO_AOT_MODE_HYBRID;
6575 } else if (str_begins_with (arg, "threads=")) {
6576 opts->nthreads = atoi (arg + strlen ("threads="));
6577 } else if (str_begins_with (arg, "static")) {
6578 opts->static_link = TRUE;
6579 opts->no_dlsym = TRUE;
6580 } else if (str_begins_with (arg, "asmonly")) {
6581 opts->asm_only = TRUE;
6582 } else if (str_begins_with (arg, "asmwriter")) {
6583 opts->asm_writer = TRUE;
6584 } else if (str_begins_with (arg, "nodebug")) {
6585 opts->nodebug = TRUE;
6586 } else if (str_begins_with (arg, "dwarfdebug")) {
6587 opts->dwarf_debug = TRUE;
6588 } else if (str_begins_with (arg, "nopagetrampolines")) {
6589 opts->use_trampolines_page = FALSE;
6590 } else if (str_begins_with (arg, "ntrampolines=")) {
6591 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6592 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6593 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6594 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6595 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6596 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6597 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6598 } else if (str_begins_with (arg, "autoreg")) {
6599 opts->autoreg = TRUE;
6600 } else if (str_begins_with (arg, "tool-prefix=")) {
6601 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6602 } else if (str_begins_with (arg, "ld-flags=")) {
6603 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6604 } else if (str_begins_with (arg, "soft-debug")) {
6605 opts->soft_debug = TRUE;
6606 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6607 opts->gen_seq_points_file = TRUE;
6608 } else if (str_begins_with (arg, "direct-pinvoke")) {
6609 opts->direct_pinvoke = TRUE;
6610 } else if (str_begins_with (arg, "direct-icalls")) {
6611 opts->direct_icalls = TRUE;
6612 } else if (str_begins_with (arg, "no-direct-calls")) {
6613 opts->no_direct_calls = TRUE;
6614 } else if (str_begins_with (arg, "print-skipped")) {
6615 opts->print_skipped_methods = TRUE;
6616 } else if (str_begins_with (arg, "stats")) {
6618 } else if (str_begins_with (arg, "no-instances")) {
6619 opts->no_instances = TRUE;
6620 } else if (str_begins_with (arg, "log-generics")) {
6621 opts->log_generics = TRUE;
6622 } else if (str_begins_with (arg, "log-instances=")) {
6623 opts->log_instances = TRUE;
6624 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6625 } else if (str_begins_with (arg, "log-instances")) {
6626 opts->log_instances = TRUE;
6627 } else if (str_begins_with (arg, "internal-logfile=")) {
6628 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6629 } else if (str_begins_with (arg, "mtriple=")) {
6630 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6631 } else if (str_begins_with (arg, "llvm-path=")) {
6632 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6633 } else if (!strcmp (arg, "llvm")) {
6635 } else if (str_begins_with (arg, "readonly-value=")) {
6636 add_readonly_value (opts, arg + strlen ("readonly-value="));
6637 } else if (str_begins_with (arg, "info")) {
6638 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6640 } else if (str_begins_with (arg, "gc-maps")) {
6641 mini_gc_enable_gc_maps_for_aot ();
6642 } else if (str_begins_with (arg, "dump")) {
6643 opts->dump_json = TRUE;
6644 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6645 printf ("Supported options for --aot:\n");
6646 printf (" outfile=\n");
6647 printf (" llvm-outfile=\n");
6648 printf (" llvm-path=\n");
6649 printf (" temp-path=\n");
6650 printf (" save-temps\n");
6651 printf (" keep-temps\n");
6652 printf (" write-symbols\n");
6653 printf (" metadata-only\n");
6654 printf (" bind-to-runtime-version\n");
6656 printf (" threads=\n");
6657 printf (" static\n");
6658 printf (" asmonly\n");
6659 printf (" asmwriter\n");
6660 printf (" nodebug\n");
6661 printf (" dwarfdebug\n");
6662 printf (" ntrampolines=\n");
6663 printf (" nrgctx-trampolines=\n");
6664 printf (" nimt-trampolines=\n");
6665 printf (" ngsharedvt-trampolines=\n");
6666 printf (" autoreg\n");
6667 printf (" tool-prefix=\n");
6668 printf (" readonly-value=\n");
6669 printf (" soft-debug\n");
6670 printf (" gen-seq-points-file\n");
6671 printf (" gc-maps\n");
6672 printf (" print-skipped\n");
6673 printf (" no-instances\n");
6674 printf (" stats\n");
6677 printf (" help/?\n");
6680 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6685 if (opts->use_trampolines_page) {
6686 opts->ntrampolines = 0;
6687 opts->nrgctx_trampolines = 0;
6688 opts->nimt_trampolines = 0;
6689 opts->ngsharedvt_arg_trampolines = 0;
6695 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6697 MonoMethod *method = (MonoMethod*)key;
6698 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6699 MonoAotCompile *acfg = user_data;
6700 MonoJumpInfoToken *new_ji;
6702 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6703 new_ji->image = ji->image;
6704 new_ji->token = ji->token;
6705 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6709 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6711 if (klass->type_token)
6713 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6716 return can_encode_class (acfg, klass->element_class);
6721 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6723 if (method->wrapper_type) {
6724 switch (method->wrapper_type) {
6725 case MONO_WRAPPER_NONE:
6726 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6727 case MONO_WRAPPER_XDOMAIN_INVOKE:
6728 case MONO_WRAPPER_STFLD:
6729 case MONO_WRAPPER_LDFLD:
6730 case MONO_WRAPPER_LDFLDA:
6731 case MONO_WRAPPER_LDFLD_REMOTE:
6732 case MONO_WRAPPER_STFLD_REMOTE:
6733 case MONO_WRAPPER_STELEMREF:
6734 case MONO_WRAPPER_ISINST:
6735 case MONO_WRAPPER_PROXY_ISINST:
6736 case MONO_WRAPPER_ALLOC:
6737 case MONO_WRAPPER_REMOTING_INVOKE:
6738 case MONO_WRAPPER_UNKNOWN:
6739 case MONO_WRAPPER_WRITE_BARRIER:
6740 case MONO_WRAPPER_DELEGATE_INVOKE:
6741 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6742 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6743 case MONO_WRAPPER_SYNCHRONIZED:
6745 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6746 case MONO_WRAPPER_CASTCLASS: {
6747 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6756 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6760 if (!method->token) {
6761 /* The method is part of a constructed type like Int[,].Set (). */
6762 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6763 if (method->klass->rank)
6773 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6775 switch (patch_info->type) {
6776 case MONO_PATCH_INFO_METHOD:
6777 case MONO_PATCH_INFO_METHODCONST:
6778 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6779 MonoMethod *method = patch_info->data.method;
6781 return can_encode_method (acfg, method);
6783 case MONO_PATCH_INFO_VTABLE:
6784 case MONO_PATCH_INFO_CLASS_INIT:
6785 case MONO_PATCH_INFO_CLASS:
6786 case MONO_PATCH_INFO_IID:
6787 case MONO_PATCH_INFO_ADJUSTED_IID:
6788 if (!can_encode_class (acfg, patch_info->data.klass)) {
6789 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6793 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6794 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6795 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6800 case MONO_PATCH_INFO_RGCTX_FETCH: {
6801 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6803 if (!can_encode_method (acfg, entry->method))
6805 if (!can_encode_patch (acfg, entry->data))
6819 * AOT compile a given method.
6820 * This function might be called by multiple threads, so it must be thread-safe.
6823 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6826 MonoJumpInfo *patch_info;
6829 MonoMethod *wrapped;
6832 if (acfg->aot_opts.metadata_only)
6835 mono_acfg_lock (acfg);
6836 index = get_method_index (acfg, method);
6837 mono_acfg_unlock (acfg);
6839 /* fixme: maybe we can also precompile wrapper methods */
6840 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6841 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6842 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6843 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6847 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6850 wrapped = mono_marshal_method_from_wrapper (method);
6851 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6852 // FIXME: The wrapper should be generic too, but it is not
6855 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6858 InterlockedIncrement (&acfg->stats.mcount);
6861 if (method->is_generic || method->klass->generic_container) {
6862 InterlockedIncrement (&acfg->stats.genericcount);
6867 //acfg->aot_opts.print_skipped_methods = TRUE;
6870 * Since these methods are the only ones which are compiled with
6871 * AOT support, and they are not used by runtime startup/shutdown code,
6872 * the runtime will not see AOT methods during AOT compilation,so it
6873 * does not need to support them by creating a fake GOT etc.
6875 flags = JIT_FLAG_AOT;
6876 if (mono_aot_mode_is_full (&acfg->aot_opts))
6877 flags |= JIT_FLAG_FULL_AOT;
6879 flags |= JIT_FLAG_LLVM;
6880 if (acfg->aot_opts.no_direct_calls)
6881 flags |= JIT_FLAG_NO_DIRECT_ICALLS;
6882 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
6883 mono_loader_clear_error ();
6885 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6886 if (acfg->aot_opts.print_skipped_methods)
6887 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6888 InterlockedIncrement (&acfg->stats.genericcount);
6891 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6892 if (acfg->aot_opts.print_skipped_methods)
6893 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6894 /* Let the exception happen at runtime */
6898 if (cfg->disable_aot) {
6899 if (acfg->aot_opts.print_skipped_methods)
6900 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6901 InterlockedIncrement (&acfg->stats.ocount);
6902 mono_destroy_compile (cfg);
6905 cfg->method_index = index;
6907 /* Nullify patches which need no aot processing */
6908 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6909 switch (patch_info->type) {
6910 case MONO_PATCH_INFO_LABEL:
6911 case MONO_PATCH_INFO_BB:
6912 patch_info->type = MONO_PATCH_INFO_NONE;
6919 /* Collect method->token associations from the cfg */
6920 mono_acfg_lock (acfg);
6921 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6922 mono_acfg_unlock (acfg);
6923 g_hash_table_destroy (cfg->token_info_hash);
6924 cfg->token_info_hash = NULL;
6927 * Check for absolute addresses.
6930 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6931 switch (patch_info->type) {
6932 case MONO_PATCH_INFO_ABS:
6933 /* unable to handle this */
6942 if (acfg->aot_opts.print_skipped_methods)
6943 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6944 InterlockedIncrement (&acfg->stats.abscount);
6945 mono_destroy_compile (cfg);
6949 /* Lock for the rest of the code */
6950 mono_acfg_lock (acfg);
6953 * Check for methods/klasses we can't encode.
6956 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6957 if (!can_encode_patch (acfg, patch_info))
6962 if (acfg->aot_opts.print_skipped_methods)
6963 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6964 acfg->stats.ocount++;
6965 mono_destroy_compile (cfg);
6966 mono_acfg_unlock (acfg);
6970 if (!cfg->compile_llvm)
6971 acfg->has_jitted_code = TRUE;
6973 if (method->is_inflated && acfg->aot_opts.log_instances) {
6974 if (acfg->instances_logfile)
6975 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6977 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6980 /* Adds generic instances referenced by this method */
6982 * The depth is used to avoid infinite loops when generic virtual recursion is
6985 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6986 if (!acfg->aot_opts.no_instances && depth < 32) {
6987 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6988 switch (patch_info->type) {
6989 case MONO_PATCH_INFO_RGCTX_FETCH:
6990 case MONO_PATCH_INFO_METHOD: {
6991 MonoMethod *m = NULL;
6993 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH) {
6994 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
6996 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
6997 m = e->data->data.method;
6999 m = patch_info->data.method;
7004 if (m->is_inflated) {
7005 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7006 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7007 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7008 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7009 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7010 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7012 add_extra_method_with_depth (acfg, m, depth + 1);
7013 add_types_from_method_header (acfg, m);
7016 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7018 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7019 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7021 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7022 add_extra_method_with_depth (acfg, m, depth + 1);
7026 case MONO_PATCH_INFO_VTABLE: {
7027 MonoClass *klass = patch_info->data.klass;
7029 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7030 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7033 case MONO_PATCH_INFO_SFLDA: {
7034 MonoClass *klass = patch_info->data.field->parent;
7036 /* The .cctor needs to run at runtime. */
7037 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7038 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7047 /* Determine whenever the method has GOT slots */
7048 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7049 switch (patch_info->type) {
7050 case MONO_PATCH_INFO_GOT_OFFSET:
7051 case MONO_PATCH_INFO_NONE:
7052 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7053 case MONO_PATCH_INFO_GC_NURSERY_START:
7055 case MONO_PATCH_INFO_IMAGE:
7056 /* The assembly is stored in GOT slot 0 */
7057 if (patch_info->data.image != acfg->image)
7058 cfg->has_got_slots = TRUE;
7061 if (!is_plt_patch (patch_info))
7062 cfg->has_got_slots = TRUE;
7067 if (!cfg->has_got_slots)
7068 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7071 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7073 /* Make a copy of the patch info which is in the mempool */
7075 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7077 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7078 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7081 patches = new_patch_info;
7083 patches_end->next = new_patch_info;
7084 patches_end = new_patch_info;
7086 cfg->patch_info = patches;
7088 /* Make a copy of the unwind info */
7090 GSList *l, *unwind_ops;
7094 for (l = cfg->unwind_ops; l; l = l->next) {
7095 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7096 memcpy (op, l->data, sizeof (MonoUnwindOp));
7097 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7099 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7101 /* Make a copy of the argument/local info */
7103 MonoInst **args, **locals;
7104 MonoMethodSignature *sig;
7105 MonoMethodHeader *header;
7108 sig = mono_method_signature (method);
7109 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7110 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7111 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7112 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7116 header = mono_method_get_header (method);
7117 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7118 for (i = 0; i < header->num_locals; ++i) {
7119 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7120 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7122 cfg->locals = locals;
7125 /* Free some fields used by cfg to conserve memory */
7126 mono_mempool_destroy (cfg->mempool);
7127 cfg->mempool = NULL;
7128 g_free (cfg->varinfo);
7129 cfg->varinfo = NULL;
7133 mono_regstate_free (cfg->rs);
7137 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7139 while (index >= acfg->cfgs_size) {
7140 MonoCompile **new_cfgs;
7143 new_size = acfg->cfgs_size * 2;
7144 new_cfgs = g_new0 (MonoCompile*, new_size);
7145 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7146 g_free (acfg->cfgs);
7147 acfg->cfgs = new_cfgs;
7148 acfg->cfgs_size = new_size;
7150 acfg->cfgs [index] = cfg;
7152 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7155 if (cfg->orig_method->wrapper_type)
7156 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7159 mono_acfg_unlock (acfg);
7161 InterlockedIncrement (&acfg->stats.ccount);
7165 compile_thread_main (gpointer *user_data)
7167 MonoDomain *domain = user_data [0];
7168 MonoAotCompile *acfg = user_data [1];
7169 GPtrArray *methods = user_data [2];
7172 mono_thread_attach (domain);
7174 for (i = 0; i < methods->len; ++i)
7175 compile_method (acfg, g_ptr_array_index (methods, i));
7179 load_profile_files (MonoAotCompile *acfg)
7183 int file_index, res, method_index, i;
7186 GList *unordered, *l;
7191 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7193 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7198 infile = fopen (tmp, "r");
7201 printf ("Using profile data file '%s'\n", tmp);
7206 res = fscanf (infile, "%32s\n", ver);
7207 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7208 printf ("Profile file has wrong version or invalid.\n");
7215 MonoMethodDesc *desc;
7218 if (fgets (name, 1023, infile) == NULL)
7221 /* Kill the newline */
7222 if (strlen (name) > 0)
7223 name [strlen (name) - 1] = '\0';
7225 desc = mono_method_desc_new (name, TRUE);
7227 method = mono_method_desc_search_in_image (desc, acfg->image);
7229 if (method && mono_method_get_token (method)) {
7230 token = mono_method_get_token (method);
7231 method_index = mono_metadata_token_index (token) - 1;
7234 for (i = 0; i < acfg->method_order->len; ++i) {
7235 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7241 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7243 //printf ("No method found matching '%s'.\n", name);
7249 /* Add missing methods */
7251 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7253 for (i = 0; i < acfg->method_order->len; ++i) {
7254 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7260 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7262 unordered = g_list_reverse (unordered);
7263 for (l = unordered; l; l = l->next)
7264 g_ptr_array_add (acfg->method_order, l->data);
7267 /* Used by the LLVM backend */
7269 mono_aot_get_got_offset (MonoJumpInfo *ji)
7271 return get_got_offset (llvm_acfg, TRUE, ji);
7275 mono_aot_get_method_name (MonoCompile *cfg)
7277 if (llvm_acfg->aot_opts.static_link)
7278 /* Include the assembly name too to avoid duplicate symbol errors */
7279 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7281 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7285 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7287 return is_direct_callable (llvm_acfg, NULL, patch_info);
7291 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7293 MonoPltEntry *plt_entry;
7295 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7296 plt_entry->llvm_used = FALSE;
7300 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7302 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7303 MonoPltEntry *plt_entry;
7304 const char *sym = NULL;
7307 ji->data.target = data;
7309 if (!can_encode_patch (llvm_acfg, ji))
7312 if (llvm_acfg->aot_opts.direct_icalls) {
7313 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7314 /* Call to a C function implementing a jit icall */
7315 sym = mono_lookup_jit_icall_symbol (data);
7316 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7317 MonoMethod *method = (gpointer)data;
7318 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7319 sym = mono_lookup_icall_symbol (method);
7322 return g_strdup (sym);
7325 plt_entry = get_plt_entry (llvm_acfg, ji);
7326 plt_entry->llvm_used = TRUE;
7328 #if defined(TARGET_MACH)
7329 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7331 return g_strdup_printf (plt_entry->llvm_symbol);
7336 mono_aot_get_method_index (MonoMethod *method)
7338 g_assert (llvm_acfg);
7339 return get_method_index (llvm_acfg, method);
7343 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7347 mono_acfg_lock (llvm_acfg);
7348 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7349 mono_acfg_unlock (llvm_acfg);
7355 execute_system (const char * command)
7360 // We need an extra set of quotes around the whole command to properly handle commands
7361 // with spaces since internally the command is called through "cmd /c.
7362 command = g_strdup_printf ("\"%s\"", command);
7364 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7365 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7366 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7367 status = _wsystem (wstr);
7371 #elif defined (HAVE_SYSTEM)
7372 status = system (command);
7374 g_assert_not_reached ();
7385 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7389 emit_llvm_file (MonoAotCompile *acfg)
7391 char *command, *opts, *tempbc, *output_fname;
7393 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7394 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7398 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7399 * a lot of time, and doesn't seem to save much space.
7400 * The following optimizations cannot be enabled:
7402 * - 'jump-threading' changes our blockaddress references to int constants.
7403 * - 'basiccg' fails because it contains:
7404 * if (CS && !isa<IntrinsicInst>(II)) {
7405 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7406 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7407 * The opt list below was produced by taking the output of:
7408 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7409 * then removing tailcallelim + the global opts.
7410 * strip-dead-prototypes deletes unused intrinsics definitions.
7412 opts = g_strdup ("-instcombine -simplifycfg");
7413 //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");
7414 /* The dse pass is disabled because of #13734 and #17616 */
7416 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7417 * // If we have no DataLayout information around, then the size of the store
7418 * // is inferrable from the pointee type. If they are the same type, then
7419 * // we know that the store is safe.
7420 * if (AA.getDataLayout() == 0 &&
7421 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7422 * return OverwriteComplete;
7423 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7425 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");
7427 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7428 aot_printf (acfg, "Executing opt: %s\n", command);
7429 if (execute_system (command) != 0)
7434 if (!acfg->llc_args)
7435 acfg->llc_args = g_string_new ("");
7437 /* Verbose asm slows down llc greatly */
7438 g_string_append (acfg->llc_args, " -asm-verbose=false");
7440 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7442 if (acfg->aot_opts.mtriple)
7443 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7445 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
7447 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7448 /* ios requires PIC code now */
7449 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7451 if (llvm_acfg->aot_opts.static_link)
7452 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7454 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7457 if (acfg->llvm_owriter) {
7458 /* Emit an object file directly */
7459 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7460 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7462 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7464 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7465 g_free (output_fname);
7467 aot_printf (acfg, "Executing llc: %s\n", command);
7469 if (execute_system (command) != 0)
7476 emit_code (MonoAotCompile *acfg)
7478 int oindex, i, prev_index;
7481 #if defined(TARGET_POWERPC64)
7482 sprintf (symbol, ".Lgot_addr");
7483 emit_section_change (acfg, ".text", 0);
7484 emit_alignment (acfg, 8);
7485 emit_label (acfg, symbol);
7486 emit_pointer (acfg, acfg->got_symbol);
7490 * This global symbol is used to compute the address of each method using the
7491 * code_offsets array. It is also used to compute the memory ranges occupied by
7492 * AOT code, so it must be equal to the address of the first emitted method.
7494 emit_section_change (acfg, ".text", 0);
7495 emit_alignment_code (acfg, 8);
7496 emit_info_symbol (acfg, "jit_code_start");
7499 * Emit some padding so the local symbol for the first method doesn't have the
7500 * same address as 'methods'.
7502 #if defined(__default_codegen__)
7503 emit_padding (acfg, 16);
7504 #elif defined(__native_client_codegen__)
7506 const int kPaddingSize = 16;
7507 guint8 pad_buffer[kPaddingSize];
7508 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7509 emit_bytes (acfg, pad_buffer, kPaddingSize);
7513 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7517 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7519 cfg = acfg->cfgs [i];
7524 method = cfg->orig_method;
7526 /* Emit unbox trampoline */
7527 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7528 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7530 emit_section_change (acfg, ".text", 0);
7531 #ifdef __native_client_codegen__
7532 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7535 if (acfg->thumb_mixed && cfg->compile_llvm) {
7536 emit_set_thumb_mode (acfg);
7537 fprintf (acfg->fp, "\n.thumb_func\n");
7540 emit_label (acfg, symbol);
7542 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7544 if (acfg->thumb_mixed && cfg->compile_llvm)
7545 emit_set_arm_mode (acfg);
7548 if (cfg->compile_llvm)
7549 acfg->stats.llvm_count ++;
7551 emit_method_code (acfg, cfg);
7554 emit_section_change (acfg, ".text", 0);
7555 emit_alignment_code (acfg, 8);
7556 emit_info_symbol (acfg, "jit_code_end");
7558 /* To distinguish it from the next symbol */
7559 emit_padding (acfg, 4);
7562 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7563 * from optimizing them away, since it doesn't see that code_offsets references them.
7564 * JITted methods don't need this since they are referenced using assembler local
7566 * FIXME: This is why write-symbols doesn't work on OSX ?
7568 if (acfg->llvm && acfg->need_no_dead_strip) {
7569 fprintf (acfg->fp, "\n");
7570 for (i = 0; i < acfg->nmethods; ++i) {
7571 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7572 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7577 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7578 * This is PIE code, and the linker can update it if needed.
7580 sprintf (symbol, "method_addresses");
7581 emit_section_change (acfg, ".text", 1);
7582 emit_alignment_code (acfg, 8);
7583 emit_info_symbol (acfg, symbol);
7584 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7585 emit_unset_mode (acfg);
7586 if (acfg->need_no_dead_strip)
7587 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7589 for (i = 0; i < acfg->nmethods; ++i) {
7590 #ifdef MONO_ARCH_AOT_SUPPORTED
7594 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7596 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7600 sprintf (symbol, "method_addresses_end");
7601 emit_label (acfg, symbol);
7604 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7605 sprintf (symbol, "unbox_trampolines");
7606 emit_section_change (acfg, RODATA_SECT, 0);
7607 emit_alignment (acfg, 8);
7608 emit_info_symbol (acfg, symbol);
7611 for (i = 0; i < acfg->nmethods; ++i) {
7616 cfg = acfg->cfgs [i];
7620 method = cfg->orig_method;
7622 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7623 index = get_method_index (acfg, method);
7625 emit_int32 (acfg, index);
7626 /* Make sure the table is sorted by index */
7627 g_assert (index > prev_index);
7631 sprintf (symbol, "unbox_trampolines_end");
7632 emit_info_symbol (acfg, symbol);
7633 emit_int32 (acfg, 0);
7635 /* Emit a separate table with the trampoline addresses/offsets */
7636 sprintf (symbol, "unbox_trampoline_addresses");
7637 emit_section_change (acfg, ".text", 0);
7638 emit_alignment_code (acfg, 8);
7639 emit_info_symbol (acfg, symbol);
7641 for (i = 0; i < acfg->nmethods; ++i) {
7646 cfg = acfg->cfgs [i];
7650 method = cfg->orig_method;
7652 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7653 #ifdef MONO_ARCH_AOT_SUPPORTED
7656 index = get_method_index (acfg, method);
7657 sprintf (symbol, "ut_%d", index);
7659 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7663 emit_int32 (acfg, 0);
7667 emit_info (MonoAotCompile *acfg)
7672 offsets = g_new0 (gint32, acfg->nmethods);
7674 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7675 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7677 if (acfg->cfgs [i]) {
7678 emit_method_info (acfg, acfg->cfgs [i]);
7679 offsets [i] = acfg->cfgs [i]->method_info_offset;
7685 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", acfg->nmethods, 10, offsets);
7690 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7692 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7693 #define mix(a,b,c) { \
7694 a -= c; a ^= rot(c, 4); c += b; \
7695 b -= a; b ^= rot(a, 6); a += c; \
7696 c -= b; c ^= rot(b, 8); b += a; \
7697 a -= c; a ^= rot(c,16); c += b; \
7698 b -= a; b ^= rot(a,19); a += c; \
7699 c -= b; c ^= rot(b, 4); b += a; \
7701 #define final(a,b,c) { \
7702 c ^= b; c -= rot(b,14); \
7703 a ^= c; a -= rot(c,11); \
7704 b ^= a; b -= rot(a,25); \
7705 c ^= b; c -= rot(b,16); \
7706 a ^= c; a -= rot(c,4); \
7707 b ^= a; b -= rot(a,14); \
7708 c ^= b; c -= rot(b,24); \
7712 mono_aot_type_hash (MonoType *t1)
7714 guint hash = t1->type;
7716 hash |= t1->byref << 6; /* do not collide with t1->type values */
7718 case MONO_TYPE_VALUETYPE:
7719 case MONO_TYPE_CLASS:
7720 case MONO_TYPE_SZARRAY:
7721 /* check if the distribution is good enough */
7722 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7724 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7725 case MONO_TYPE_ARRAY:
7726 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7727 case MONO_TYPE_GENERICINST:
7728 return ((hash << 5) - hash) ^ 0;
7735 * mono_aot_method_hash:
7737 * Return a hash code for methods which only depends on metadata.
7740 mono_aot_method_hash (MonoMethod *method)
7742 MonoMethodSignature *sig;
7746 guint32 *hashes_start, *hashes;
7748 MonoGenericInst *class_ginst = NULL;
7749 MonoGenericInst *ginst = NULL;
7751 /* Similar to the hash in mono_method_get_imt_slot () */
7753 sig = mono_method_signature (method);
7755 if (method->klass->generic_class)
7756 class_ginst = method->klass->generic_class->context.class_inst;
7757 if (method->is_inflated)
7758 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7760 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7761 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7762 hashes = hashes_start;
7764 /* Some wrappers are assigned to random classes */
7765 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7766 klass = method->klass;
7768 klass = mono_defaults.object_class;
7770 if (!method->wrapper_type) {
7773 if (klass->generic_class)
7774 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7776 full_name = mono_type_full_name (&klass->byval_arg);
7778 hashes [0] = mono_metadata_str_hash (full_name);
7782 hashes [0] = mono_metadata_str_hash (klass->name);
7783 hashes [1] = mono_metadata_str_hash (klass->name_space);
7785 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7786 /* The method name includes a stringified pointer */
7789 hashes [2] = mono_metadata_str_hash (method->name);
7790 hashes [3] = method->wrapper_type;
7791 hashes [4] = mono_aot_type_hash (sig->ret);
7793 for (i = 0; i < sig->param_count; i++) {
7794 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7797 for (i = 0; i < class_ginst->type_argc; ++i)
7798 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7801 for (i = 0; i < ginst->type_argc; ++i)
7802 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7804 g_assert (hindex == hashes_count);
7806 /* Setup internal state */
7807 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7809 /* Handle most of the hashes */
7810 while (hashes_count > 3) {
7819 /* Handle the last 3 hashes (all the case statements fall through) */
7820 switch (hashes_count) {
7821 case 3 : c += hashes [2];
7822 case 2 : b += hashes [1];
7823 case 1 : a += hashes [0];
7825 case 0: /* nothing left to add */
7829 free (hashes_start);
7838 * mono_aot_get_array_helper_from_wrapper;
7840 * Get the helper method in Array called by an array wrapper method.
7843 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7847 MonoGenericContext ctx;
7848 MonoType *args [16];
7849 char *mname, *iname, *s, *s2, *helper_name = NULL;
7851 prefix = "System.Collections.Generic";
7852 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7853 s2 = strstr (s, "`1.");
7859 //printf ("X: %s %s\n", iname, mname);
7861 if (!strcmp (iname, "IList"))
7862 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7864 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7865 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7867 g_free (helper_name);
7870 if (m->is_generic) {
7872 memset (&ctx, 0, sizeof (ctx));
7873 args [0] = &method->klass->element_class->byval_arg;
7874 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7875 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7876 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7882 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7884 typedef struct HashEntry {
7885 guint32 key, value, index;
7886 struct HashEntry *next;
7890 * emit_extra_methods:
7892 * Emit methods which are not in the METHOD table, like wrappers.
7895 emit_extra_methods (MonoAotCompile *acfg)
7897 int i, table_size, buf_size;
7900 guint32 *info_offsets;
7903 HashEntry *entry, *new_entry;
7904 int nmethods, max_chain_length;
7907 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7909 /* Emit method info */
7911 for (i = 0; i < acfg->extra_methods->len; ++i) {
7912 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7913 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7919 p = buf = g_malloc (buf_size);
7923 method = cfg->method_to_register;
7925 encode_method_ref (acfg, method, p, &p);
7927 g_assert ((p - buf) < buf_size);
7929 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7934 * Construct a chained hash table for mapping indexes in extra_method_info to
7937 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7938 table = g_ptr_array_sized_new (table_size);
7939 for (i = 0; i < table_size; ++i)
7940 g_ptr_array_add (table, NULL);
7941 chain_lengths = g_new0 (int, table_size);
7942 max_chain_length = 0;
7943 for (i = 0; i < acfg->extra_methods->len; ++i) {
7944 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7945 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7951 key = info_offsets [i];
7952 value = get_method_index (acfg, method);
7954 hash = mono_aot_method_hash (method) % table_size;
7955 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
7957 chain_lengths [hash] ++;
7958 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7960 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7961 new_entry->key = key;
7962 new_entry->value = value;
7964 entry = g_ptr_array_index (table, hash);
7965 if (entry == NULL) {
7966 new_entry->index = hash;
7967 g_ptr_array_index (table, hash) = new_entry;
7970 entry = entry->next;
7972 entry->next = new_entry;
7973 new_entry->index = table->len;
7974 g_ptr_array_add (table, new_entry);
7978 //printf ("MAX: %d\n", max_chain_length);
7980 buf_size = table->len * 12 + 4;
7981 p = buf = g_malloc (buf_size);
7982 encode_int (table_size, p, &p);
7984 for (i = 0; i < table->len; ++i) {
7985 HashEntry *entry = g_ptr_array_index (table, i);
7987 if (entry == NULL) {
7988 encode_int (0, p, &p);
7989 encode_int (0, p, &p);
7990 encode_int (0, p, &p);
7992 //g_assert (entry->key > 0);
7993 encode_int (entry->key, p, &p);
7994 encode_int (entry->value, p, &p);
7996 encode_int (entry->next->index, p, &p);
7998 encode_int (0, p, &p);
8001 g_assert (p - buf <= buf_size);
8003 /* Emit the table */
8005 mono_llvm_emit_aot_data ("extra_method_table", buf, p - buf);
8007 sprintf (symbol, "extra_method_table");
8008 emit_section_change (acfg, RODATA_SECT, 0);
8009 emit_alignment (acfg, 8);
8010 emit_label (acfg, symbol);
8011 emit_bytes (acfg, buf, p - buf);
8015 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8016 * This is used by mono_aot_find_jit_info ().
8018 buf_size = acfg->extra_methods->len * 8 + 4;
8019 p = buf = g_malloc (buf_size);
8020 encode_int (acfg->extra_methods->len, p, &p);
8021 for (i = 0; i < acfg->extra_methods->len; ++i) {
8022 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
8024 encode_int (get_method_index (acfg, method), p, &p);
8025 encode_int (info_offsets [i], p, &p);
8028 mono_llvm_emit_aot_data ("extra_method_info_offsets", buf, p - buf);
8030 sprintf (symbol, "extra_method_info_offsets");
8031 emit_section_change (acfg, RODATA_SECT, 0);
8032 emit_alignment (acfg, 8);
8033 emit_label (acfg, symbol);
8034 emit_bytes (acfg, buf, p - buf);
8039 emit_exception_info (MonoAotCompile *acfg)
8043 SeqPointData sp_data;
8044 gboolean seq_points_to_file = FALSE;
8046 offsets = g_new0 (gint32, acfg->nmethods);
8047 for (i = 0; i < acfg->nmethods; ++i) {
8048 if (acfg->cfgs [i]) {
8049 MonoCompile *cfg = acfg->cfgs [i];
8051 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8052 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8053 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8054 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8055 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8057 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8058 offsets [i] = cfg->ex_info_offset;
8060 if (method_seq_points_to_file) {
8061 if (!seq_points_to_file) {
8062 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8063 seq_points_to_file = TRUE;
8065 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8072 if (seq_points_to_file) {
8073 char *seq_points_aot_file;
8074 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8075 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8076 mono_seq_point_data_free (&sp_data);
8077 g_free (seq_points_aot_file);
8080 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", acfg->nmethods, 10, offsets);
8085 emit_unwind_info (MonoAotCompile *acfg)
8091 * The unwind info contains a lot of duplicates so we emit each unique
8092 * entry once, and only store the offset from the start of the table in the
8096 sprintf (symbol, "unwind_info");
8097 emit_section_change (acfg, RODATA_SECT, 1);
8098 emit_alignment (acfg, 8);
8099 emit_info_symbol (acfg, symbol);
8101 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8102 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8103 guint8 *unwind_info;
8104 guint32 unwind_info_len;
8108 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8111 encode_value (unwind_info_len, p, &p);
8112 emit_bytes (acfg, buf, p - buf);
8113 emit_bytes (acfg, unwind_info, unwind_info_len);
8115 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8120 emit_class_info (MonoAotCompile *acfg)
8125 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8126 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8127 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8129 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8133 typedef struct ClassNameTableEntry {
8134 guint32 token, index;
8135 struct ClassNameTableEntry *next;
8136 } ClassNameTableEntry;
8139 emit_class_name_table (MonoAotCompile *acfg)
8141 int i, table_size, buf_size;
8142 guint32 token, hash;
8148 ClassNameTableEntry *entry, *new_entry;
8151 * Construct a chained hash table for mapping class names to typedef tokens.
8153 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8154 table = g_ptr_array_sized_new (table_size);
8155 for (i = 0; i < table_size; ++i)
8156 g_ptr_array_add (table, NULL);
8157 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8159 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8160 klass = mono_class_get_checked (acfg->image, token, &error);
8162 mono_error_cleanup (&error);
8165 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8166 hash = mono_metadata_str_hash (full_name) % table_size;
8169 /* FIXME: Allocate from the mempool */
8170 new_entry = g_new0 (ClassNameTableEntry, 1);
8171 new_entry->token = token;
8173 entry = g_ptr_array_index (table, hash);
8174 if (entry == NULL) {
8175 new_entry->index = hash;
8176 g_ptr_array_index (table, hash) = new_entry;
8179 entry = entry->next;
8181 entry->next = new_entry;
8182 new_entry->index = table->len;
8183 g_ptr_array_add (table, new_entry);
8187 /* Emit the table */
8188 buf_size = table->len * 4 + 4;
8189 p = buf = g_malloc0 (buf_size);
8191 /* FIXME: Optimize memory usage */
8192 g_assert (table_size < 65000);
8193 encode_int16 (table_size, p, &p);
8194 g_assert (table->len < 65000);
8195 for (i = 0; i < table->len; ++i) {
8196 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8198 if (entry == NULL) {
8199 encode_int16 (0, p, &p);
8200 encode_int16 (0, p, &p);
8202 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8204 encode_int16 (entry->next->index, p, &p);
8206 encode_int16 (0, p, &p);
8209 g_assert (p - buf <= buf_size);
8212 mono_llvm_emit_aot_data ("class_name_table", buf, p - buf);
8214 sprintf (symbol, "class_name_table");
8215 emit_section_change (acfg, RODATA_SECT, 0);
8216 emit_alignment (acfg, 8);
8217 emit_label (acfg, symbol);
8218 emit_bytes (acfg, buf, p - buf);
8223 emit_image_table (MonoAotCompile *acfg)
8230 * The image table is small but referenced in a lot of places.
8231 * So we emit it at once, and reference its elements by an index.
8233 buf_size = acfg->image_table->len * 28 + 4;
8234 for (i = 0; i < acfg->image_table->len; i++) {
8235 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8236 MonoAssemblyName *aname = &image->assembly->aname;
8238 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8241 buf = p = g_malloc0 (buf_size);
8242 encode_int (acfg->image_table->len, p, &p);
8243 for (i = 0; i < acfg->image_table->len; i++) {
8244 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8245 MonoAssemblyName *aname = &image->assembly->aname;
8247 /* FIXME: Support multi-module assemblies */
8248 g_assert (image->assembly->image == image);
8250 encode_string (image->assembly_name, p, &p);
8251 encode_string (image->guid, p, &p);
8252 encode_string (aname->culture ? aname->culture : "", p, &p);
8253 encode_string ((const char*)aname->public_key_token, p, &p);
8255 while (GPOINTER_TO_UINT (p) % 8 != 0)
8258 encode_int (aname->flags, p, &p);
8259 encode_int (aname->major, p, &p);
8260 encode_int (aname->minor, p, &p);
8261 encode_int (aname->build, p, &p);
8262 encode_int (aname->revision, p, &p);
8264 g_assert (p - buf <= buf_size);
8267 mono_llvm_emit_aot_data ("image_table", buf, p - buf);
8269 sprintf (symbol, "image_table");
8270 emit_section_change (acfg, RODATA_SECT, 1);
8271 emit_alignment (acfg, 8);
8272 emit_label (acfg, symbol);
8273 emit_bytes (acfg, buf, p - buf);
8280 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8282 int i, first_plt_got_patch = 0, buf_size;
8284 guint32 *got_info_offsets;
8285 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8287 /* Add the patches needed by the PLT to the GOT */
8289 acfg->plt_got_offset_base = acfg->got_offset;
8290 first_plt_got_patch = info->got_patches->len;
8291 for (i = 1; i < acfg->plt_offset; ++i) {
8292 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8294 g_ptr_array_add (info->got_patches, plt_entry->ji);
8296 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8299 acfg->got_offset += acfg->plt_offset;
8304 * - optimize offsets table.
8305 * - reduce number of exported symbols.
8306 * - emit info for a klass only once.
8307 * - determine when a method uses a GOT slot which is guaranteed to be already
8309 * - clean up and document the code.
8310 * - use String.Empty in class libs.
8313 /* Encode info required to decode shared GOT entries */
8314 buf_size = info->got_patches->len * 128;
8315 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8316 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8318 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8320 if (acfg->plt_offset)
8321 acfg->plt_got_info_offsets [0] = 0;
8323 for (i = 0; i < info->got_patches->len; ++i) {
8324 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8329 encode_value (ji->type, p, &p);
8331 encode_patch (acfg, ji, p, &p);
8332 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8333 g_assert (p - buf <= buf_size);
8334 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8336 if (!llvm && i >= first_plt_got_patch)
8337 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8338 acfg->stats.got_info_size += p - buf;
8341 /* Emit got_info_offsets table */
8343 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8344 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8348 emit_got (MonoAotCompile *acfg)
8352 /* Don't make GOT global so accesses to it don't need relocations */
8353 sprintf (symbol, "%s", acfg->got_symbol);
8354 emit_section_change (acfg, ".bss", 0);
8355 emit_alignment (acfg, 8);
8356 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8357 emit_label (acfg, symbol);
8359 emit_info_symbol (acfg, "jit_got");
8360 if (acfg->got_offset > 0)
8361 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8363 sprintf (symbol, "got_end");
8364 emit_label (acfg, symbol);
8367 typedef struct GlobalsTableEntry {
8368 guint32 value, index;
8369 struct GlobalsTableEntry *next;
8370 } GlobalsTableEntry;
8373 emit_globals (MonoAotCompile *acfg)
8379 GlobalsTableEntry *entry, *new_entry;
8381 if (!acfg->aot_opts.static_link)
8385 * When static linking, we emit a table containing our globals.
8389 * Construct a chained hash table for mapping global names to their index in
8390 * the globals table.
8392 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8393 table = g_ptr_array_sized_new (table_size);
8394 for (i = 0; i < table_size; ++i)
8395 g_ptr_array_add (table, NULL);
8396 for (i = 0; i < acfg->globals->len; ++i) {
8397 char *name = g_ptr_array_index (acfg->globals, i);
8399 hash = mono_metadata_str_hash (name) % table_size;
8401 /* FIXME: Allocate from the mempool */
8402 new_entry = g_new0 (GlobalsTableEntry, 1);
8403 new_entry->value = i;
8405 entry = g_ptr_array_index (table, hash);
8406 if (entry == NULL) {
8407 new_entry->index = hash;
8408 g_ptr_array_index (table, hash) = new_entry;
8411 entry = entry->next;
8413 entry->next = new_entry;
8414 new_entry->index = table->len;
8415 g_ptr_array_add (table, new_entry);
8419 /* Emit the table */
8420 sprintf (symbol, ".Lglobals_hash");
8421 emit_section_change (acfg, RODATA_SECT, 0);
8422 emit_alignment (acfg, 8);
8423 emit_label (acfg, symbol);
8425 /* FIXME: Optimize memory usage */
8426 g_assert (table_size < 65000);
8427 emit_int16 (acfg, table_size);
8428 for (i = 0; i < table->len; ++i) {
8429 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8431 if (entry == NULL) {
8432 emit_int16 (acfg, 0);
8433 emit_int16 (acfg, 0);
8435 emit_int16 (acfg, entry->value + 1);
8437 emit_int16 (acfg, entry->next->index);
8439 emit_int16 (acfg, 0);
8443 /* Emit the names */
8444 for (i = 0; i < acfg->globals->len; ++i) {
8445 char *name = g_ptr_array_index (acfg->globals, i);
8447 sprintf (symbol, "name_%d", i);
8448 emit_section_change (acfg, RODATA_SECT, 1);
8450 emit_alignment (acfg, 4);
8452 emit_label (acfg, symbol);
8453 emit_string (acfg, name);
8456 /* Emit the globals table */
8457 sprintf (symbol, "globals");
8458 emit_section_change (acfg, ".data", 0);
8459 /* This is not a global, since it is accessed by the init function */
8460 emit_alignment (acfg, 8);
8461 emit_label (acfg, symbol);
8463 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8464 emit_pointer (acfg, symbol);
8466 for (i = 0; i < acfg->globals->len; ++i) {
8467 char *name = g_ptr_array_index (acfg->globals, i);
8469 sprintf (symbol, "name_%d", i);
8470 emit_pointer (acfg, symbol);
8472 g_assert (strlen (name) < sizeof (symbol));
8473 sprintf (symbol, "%s", name);
8474 emit_pointer (acfg, symbol);
8476 /* Null terminate the table */
8477 emit_int32 (acfg, 0);
8478 emit_int32 (acfg, 0);
8482 emit_autoreg (MonoAotCompile *acfg)
8487 * Emit a function into the .ctor section which will be called by the ELF
8488 * loader to register this module with the runtime.
8490 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8493 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8495 arch_emit_autoreg (acfg, symbol);
8501 emit_mem_end (MonoAotCompile *acfg)
8505 sprintf (symbol, "mem_end");
8506 emit_section_change (acfg, ".text", 1);
8507 emit_alignment_code (acfg, 8);
8508 emit_label (acfg, symbol);
8512 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info, int gc_name_offset)
8516 info->version = MONO_AOT_FILE_VERSION;
8517 info->plt_got_offset_base = acfg->plt_got_offset_base;
8518 info->got_size = acfg->got_offset * sizeof (gpointer);
8519 info->plt_size = acfg->plt_offset;
8520 info->nmethods = acfg->nmethods;
8521 info->flags = acfg->flags;
8522 info->opts = acfg->opts;
8523 info->simd_opts = acfg->simd_opts;
8524 info->gc_name_index = gc_name_offset;
8525 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8526 info->num_trampolines [i] = acfg->num_trampolines [i];
8527 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8528 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
8529 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8530 info->trampoline_size [i] = acfg->trampoline_size [i];
8531 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
8533 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8538 memset (&t, 0, sizeof (MonoType));
8539 t.type = MONO_TYPE_R8;
8540 mono_type_size (&t, &align);
8541 info->double_align = align;
8543 memset (&t, 0, sizeof (MonoType));
8544 t.type = MONO_TYPE_I8;
8545 mono_type_size (&t, &align);
8546 info->long_align = align;
8549 info->double_align = MONO_ABI_ALIGNOF (double);
8550 info->long_align = MONO_ABI_ALIGNOF (gint64);
8552 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
8553 info->tramp_page_size = acfg->tramp_page_size;
8554 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8555 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
8559 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
8563 const char **symbols;
8565 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8567 symbols [sindex ++] = acfg->got_symbol;
8569 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
8570 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
8572 symbols [sindex ++] = NULL;
8573 symbols [sindex ++] = NULL;
8575 symbols [sindex ++] = "jit_code_start";
8576 symbols [sindex ++] = "jit_code_end";
8577 symbols [sindex ++] = "method_addresses";
8578 symbols [sindex ++] = "blob";
8579 symbols [sindex ++] = "class_name_table";
8580 symbols [sindex ++] = "class_info_offsets";
8581 symbols [sindex ++] = "method_info_offsets";
8582 symbols [sindex ++] = "ex_info_offsets";
8583 symbols [sindex ++] = "extra_method_info_offsets";
8584 symbols [sindex ++] = "extra_method_table";
8585 symbols [sindex ++] = "got_info_offsets";
8587 symbols [sindex ++] = "llvm_got_info_offsets";
8589 symbols [sindex ++] = NULL;
8590 symbols [sindex ++] = "mem_end";
8591 symbols [sindex ++] = "image_table";
8592 symbols [sindex ++] = "assembly_guid";
8593 symbols [sindex ++] = "runtime_version";
8594 if (acfg->num_trampoline_got_entries) {
8595 symbols [sindex ++] = "specific_trampolines";
8596 symbols [sindex ++] = "static_rgctx_trampolines";
8597 symbols [sindex ++] = "imt_thunks";
8598 symbols [sindex ++] = "gsharedvt_arg_trampolines";
8600 symbols [sindex ++] = NULL;
8601 symbols [sindex ++] = NULL;
8602 symbols [sindex ++] = NULL;
8603 symbols [sindex ++] = NULL;
8605 if (acfg->aot_opts.static_link) {
8606 symbols [sindex ++] = "globals";
8608 symbols [sindex ++] = NULL;
8610 symbols [sindex ++] = "assembly_name";
8611 symbols [sindex ++] = "plt";
8612 symbols [sindex ++] = "plt_end";
8613 symbols [sindex ++] = "unwind_info";
8614 symbols [sindex ++] = "unbox_trampolines";
8615 symbols [sindex ++] = "unbox_trampolines_end";
8616 symbols [sindex ++] = "unbox_trampoline_addresses";
8617 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8619 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8620 emit_section_change (acfg, ".data", 0);
8621 emit_alignment (acfg, 8);
8622 emit_label (acfg, symbol);
8623 if (!acfg->aot_opts.static_link)
8624 emit_global (acfg, symbol, FALSE);
8626 /* The data emitted here must match MonoAotFileInfo. */
8628 emit_int32 (acfg, info->version);
8629 emit_int32 (acfg, info->dummy);
8632 * We emit pointers to our data structures instead of emitting global symbols which
8633 * point to them, to reduce the number of globals, and because using globals leads to
8634 * various problems (i.e. arm/thumb).
8636 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
8637 emit_pointer (acfg, symbols [i]);
8639 emit_int32 (acfg, info->plt_got_offset_base);
8640 emit_int32 (acfg, info->got_size);
8641 emit_int32 (acfg, info->plt_size);
8642 emit_int32 (acfg, info->nmethods);
8643 emit_int32 (acfg, info->flags);
8644 emit_int32 (acfg, info->opts);
8645 emit_int32 (acfg, info->simd_opts);
8646 emit_int32 (acfg, info->gc_name_index);
8647 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
8648 emit_int32 (acfg, info->double_align);
8649 emit_int32 (acfg, info->long_align);
8650 emit_int32 (acfg, info->generic_tramp_num);
8651 emit_int32 (acfg, info->tramp_page_size);
8653 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8654 emit_int32 (acfg, info->num_trampolines [i]);
8655 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8656 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
8657 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8658 emit_int32 (acfg, info->trampoline_size [i]);
8659 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8660 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
8662 if (acfg->aot_opts.static_link) {
8666 * Emit a global symbol which can be passed by an embedding app to
8667 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8670 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8672 /* Get rid of characters which cannot occur in symbols */
8674 for (p = symbol; *p; ++p) {
8675 if (!(isalnum (*p) || *p == '_'))
8678 acfg->static_linking_symbol = g_strdup (symbol);
8679 emit_global_inner (acfg, symbol, FALSE);
8680 emit_alignment (acfg, sizeof (gpointer));
8681 emit_label (acfg, symbol);
8682 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8687 * Emit a structure containing all the information not stored elsewhere.
8690 emit_file_info (MonoAotCompile *acfg)
8693 const char *gc_name;
8695 MonoAotFileInfo *info;
8697 if (acfg->aot_opts.bind_to_runtime_version) {
8698 build_info = mono_get_runtime_build_info ();
8699 emit_string_symbol (acfg, "runtime_version", build_info);
8700 g_free (build_info);
8702 emit_string_symbol (acfg, "runtime_version", "");
8705 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8707 /* Emit a string holding the assembly name */
8708 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8711 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8714 gc_name = mono_gc_get_gc_name ();
8715 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8717 info = g_new0 (MonoAotFileInfo, 1);
8718 init_aot_file_info (acfg, info, gc_name_offset);
8721 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
8723 emit_aot_file_info (acfg, info);
8727 emit_blob (MonoAotCompile *acfg)
8732 mono_llvm_emit_aot_data ("blob", (guint8*)acfg->blob.data, acfg->blob.index);
8736 sprintf (symbol, "blob");
8737 emit_section_change (acfg, RODATA_SECT, 1);
8738 emit_alignment (acfg, 8);
8739 emit_label (acfg, symbol);
8741 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8745 emit_objc_selectors (MonoAotCompile *acfg)
8750 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8755 * cat > foo.m << EOF
8758 * return @selector(print:);
8763 mono_img_writer_emit_unset_mode (acfg->w);
8764 g_assert (acfg->fp);
8765 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8766 fprintf (acfg->fp, ".align 3\n");
8767 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8768 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8769 emit_label (acfg, symbol);
8770 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8771 emit_pointer (acfg, symbol);
8774 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8775 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8776 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8777 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8780 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8781 fprintf (acfg->fp, ".align 3\n");
8782 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8783 fprintf (acfg->fp, ".long 0\n");
8784 fprintf (acfg->fp, ".long 16\n");
8788 emit_dwarf_info (MonoAotCompile *acfg)
8790 #ifdef EMIT_DWARF_INFO
8794 /* DIEs for methods */
8795 for (i = 0; i < acfg->nmethods; ++i) {
8796 MonoCompile *cfg = acfg->cfgs [i];
8801 // FIXME: LLVM doesn't define .Lme_...
8802 if (cfg->compile_llvm)
8805 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8807 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 ()));
8813 collect_methods (MonoAotCompile *acfg)
8816 MonoImage *image = acfg->image;
8818 /* Collect methods */
8819 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8822 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8824 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8827 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8828 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8829 mono_error_cleanup (&error);
8833 /* Load all methods eagerly to skip the slower lazy loading code */
8834 mono_class_setup_methods (method->klass);
8836 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8837 /* Compile the wrapper instead */
8838 /* We do this here instead of add_wrappers () because it is easy to do it here */
8839 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8843 /* FIXME: Some mscorlib methods don't have debug info */
8845 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8846 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8847 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8848 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8849 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8850 if (!mono_debug_lookup_method (method)) {
8851 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8858 if (method->is_generic || method->klass->generic_container)
8859 /* Compile the ref shared version instead */
8860 method = mini_get_shared_method (method);
8862 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8863 add_method_with_index (acfg, method, i, FALSE);
8864 acfg->method_index ++;
8867 /* gsharedvt methods */
8868 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8871 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8873 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8876 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8877 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8879 if (method->is_generic || method->klass->generic_container) {
8880 MonoMethod *gshared;
8882 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8883 add_extra_method (acfg, gshared);
8887 add_generic_instances (acfg);
8889 if (mono_aot_mode_is_full (&acfg->aot_opts))
8890 add_wrappers (acfg);
8895 compile_methods (MonoAotCompile *acfg)
8899 if (acfg->aot_opts.nthreads > 0) {
8904 gpointer *user_data;
8905 MonoMethod **methods;
8907 methods_len = acfg->methods->len;
8909 len = acfg->methods->len / acfg->aot_opts.nthreads;
8912 * Partition the list of methods into fragments, and hand it to threads to
8915 threads = g_ptr_array_new ();
8916 /* Make a copy since acfg->methods is modified by compile_method () */
8917 methods = g_new0 (MonoMethod*, methods_len);
8918 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8919 for (i = 0; i < methods_len; ++i)
8920 methods [i] = g_ptr_array_index (acfg->methods, i);
8922 while (i < methods_len) {
8923 frag = g_ptr_array_new ();
8924 for (j = 0; j < len; ++j) {
8925 if (i < methods_len) {
8926 g_ptr_array_add (frag, methods [i]);
8931 user_data = g_new0 (gpointer, 3);
8932 user_data [0] = mono_domain_get ();
8933 user_data [1] = acfg;
8934 user_data [2] = frag;
8936 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8937 g_ptr_array_add (threads, handle);
8941 for (i = 0; i < threads->len; ++i) {
8942 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8948 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8949 for (i = methods_len; i < acfg->methods->len; ++i) {
8950 /* This can new methods to acfg->methods */
8951 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8956 compile_asm (MonoAotCompile *acfg)
8958 char *command, *objfile;
8959 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8960 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8961 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
8963 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8964 #define AS_OPTIONS "--64"
8965 #elif defined(TARGET_POWERPC64)
8966 #define AS_OPTIONS "-a64 -mppc64"
8967 #define LD_OPTIONS "-m elf64ppc"
8968 #elif defined(sparc) && SIZEOF_VOID_P == 8
8969 #define AS_OPTIONS "-xarch=v9"
8970 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8971 #define AS_OPTIONS "-arch i386"
8973 #define AS_OPTIONS ""
8976 #ifdef __native_client_codegen__
8977 #if defined(TARGET_AMD64)
8978 #define AS_NAME "nacl64-as"
8980 #define AS_NAME "nacl-as"
8982 #elif defined(TARGET_OSX)
8983 #define AS_NAME "clang"
8985 #define AS_NAME "as"
8989 #define LD_OPTIONS ""
8993 #define LD_NAME "ld -shared -G"
8994 #elif defined(__ppc__) && defined(TARGET_MACH)
8995 #define LD_NAME "gcc -dynamiclib"
8996 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8997 #define LD_NAME "clang --shared"
8998 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
8999 #define LD_NAME "gcc -shared --dll"
9000 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9001 #define LD_NAME "clang -m32 -dynamiclib"
9002 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9003 #define LD_NAME "gcc --shared"
9006 if (acfg->aot_opts.asm_only) {
9007 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9008 if (acfg->aot_opts.static_link)
9009 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9011 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9015 if (acfg->aot_opts.static_link) {
9016 if (acfg->aot_opts.outfile)
9017 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9019 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9021 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9025 g_string_append (acfg->as_args, "-c -x assembler");
9028 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);
9029 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9030 if (execute_system (command) != 0) {
9036 if (acfg->llvm && !acfg->llvm_owriter) {
9037 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);
9038 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9039 if (execute_system (command) != 0) {
9048 if (acfg->aot_opts.static_link) {
9049 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9050 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9055 if (acfg->aot_opts.outfile)
9056 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9058 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9060 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9063 llvm_ofile = g_strdup (acfg->llvm_ofile);
9065 llvm_ofile = g_strdup ("");
9068 /* replace the ; flags separators with spaces */
9069 g_strdelimit (ld_flags, ";", ' ');
9072 command = g_strdup_printf ("%s -o %s %s %s.o %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
9074 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
9075 acfg->tmpfname, ld_flags);
9077 aot_printf (acfg, "Executing the native linker: %s\n", command);
9078 if (execute_system (command) != 0) {
9079 g_free (tmp_outfile_name);
9080 g_free (outfile_name);
9089 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9090 printf ("Stripping the binary: %s\n", com);
9091 execute_system (com);
9094 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9096 * gas generates 'mapping symbols' each time code and data is mixed, which
9097 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9099 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9100 aot_printf (acfg, "Stripping the binary: %s\n", command);
9101 if (execute_system (command) != 0) {
9102 g_free (tmp_outfile_name);
9103 g_free (outfile_name);
9110 rename (tmp_outfile_name, outfile_name);
9112 #if defined(TARGET_MACH)
9113 command = g_strdup_printf ("dsymutil %s", outfile_name);
9114 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9115 if (execute_system (command) != 0) {
9120 if (!acfg->aot_opts.save_temps)
9123 g_free (tmp_outfile_name);
9124 g_free (outfile_name);
9127 if (acfg->aot_opts.save_temps)
9128 aot_printf (acfg, "Retained input file.\n");
9130 unlink (acfg->tmpfname);
9135 static void init_got_info (GotInfo *info)
9139 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9140 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9141 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9142 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9143 info->got_patches = g_ptr_array_new ();
9146 static MonoAotCompile*
9147 acfg_create (MonoAssembly *ass, guint32 opts)
9149 MonoImage *image = ass->image;
9150 MonoAotCompile *acfg;
9152 acfg = g_new0 (MonoAotCompile, 1);
9153 acfg->methods = g_ptr_array_new ();
9154 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9155 acfg->method_depth = g_hash_table_new (NULL, NULL);
9156 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9157 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9158 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9159 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9160 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9161 acfg->image_hash = g_hash_table_new (NULL, NULL);
9162 acfg->image_table = g_ptr_array_new ();
9163 acfg->globals = g_ptr_array_new ();
9164 acfg->image = image;
9166 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9167 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9168 acfg->mempool = mono_mempool_new ();
9169 acfg->extra_methods = g_ptr_array_new ();
9170 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9171 acfg->unwind_ops = g_ptr_array_new ();
9172 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9173 acfg->method_order = g_ptr_array_new ();
9174 acfg->export_names = g_hash_table_new (NULL, NULL);
9175 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9176 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9177 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9178 mono_mutex_init_recursive (&acfg->mutex);
9180 init_got_info (&acfg->got_info);
9181 init_got_info (&acfg->llvm_got_info);
9187 got_info_free (GotInfo *info)
9191 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9192 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9193 g_free (info->patch_to_got_offset_by_type);
9194 g_hash_table_destroy (info->patch_to_got_offset);
9195 g_ptr_array_free (info->got_patches, TRUE);
9199 acfg_free (MonoAotCompile *acfg)
9203 mono_img_writer_destroy (acfg->w);
9204 for (i = 0; i < acfg->nmethods; ++i)
9206 g_free (acfg->cfgs [i]);
9207 g_free (acfg->cfgs);
9208 g_free (acfg->static_linking_symbol);
9209 g_free (acfg->got_symbol);
9210 g_free (acfg->plt_symbol);
9211 g_ptr_array_free (acfg->methods, TRUE);
9212 g_ptr_array_free (acfg->image_table, TRUE);
9213 g_ptr_array_free (acfg->globals, TRUE);
9214 g_ptr_array_free (acfg->unwind_ops, TRUE);
9215 g_hash_table_destroy (acfg->method_indexes);
9216 g_hash_table_destroy (acfg->method_depth);
9217 g_hash_table_destroy (acfg->plt_offset_to_entry);
9218 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9219 if (acfg->patch_to_plt_entry [i])
9220 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9222 g_free (acfg->patch_to_plt_entry);
9223 g_hash_table_destroy (acfg->method_to_cfg);
9224 g_hash_table_destroy (acfg->token_info_hash);
9225 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9226 g_hash_table_destroy (acfg->image_hash);
9227 g_hash_table_destroy (acfg->unwind_info_offsets);
9228 g_hash_table_destroy (acfg->method_label_hash);
9229 g_hash_table_destroy (acfg->export_names);
9230 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9231 g_hash_table_destroy (acfg->klass_blob_hash);
9232 g_hash_table_destroy (acfg->method_blob_hash);
9233 got_info_free (&acfg->got_info);
9234 got_info_free (&acfg->llvm_got_info);
9235 mono_mempool_destroy (acfg->mempool);
9239 #define WRAPPER(e,n) n,
9240 static const char* const
9241 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9242 #include "mono/metadata/wrapper-types.h"
9246 static G_GNUC_UNUSED const char*
9247 get_wrapper_type_name (int type)
9249 return wrapper_type_names [type];
9255 static void aot_dump (MonoAotCompile *acfg)
9261 mono_json_writer_init (&writer);
9263 mono_json_writer_object_begin(&writer);
9266 mono_json_writer_indent (&writer);
9267 mono_json_writer_object_key(&writer, "methods");
9268 mono_json_writer_array_begin (&writer);
9271 for (i = 0; i < acfg->nmethods; ++i) {
9276 cfg = acfg->cfgs [i];
9280 method = cfg->orig_method;
9282 mono_json_writer_indent (&writer);
9283 mono_json_writer_object_begin(&writer);
9285 mono_json_writer_indent (&writer);
9286 mono_json_writer_object_key(&writer, "name");
9287 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9289 mono_json_writer_indent (&writer);
9290 mono_json_writer_object_key(&writer, "signature");
9291 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9292 /*signature=*/TRUE));
9294 mono_json_writer_indent (&writer);
9295 mono_json_writer_object_key(&writer, "code_size");
9296 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9298 klass = method->klass;
9300 mono_json_writer_indent (&writer);
9301 mono_json_writer_object_key(&writer, "class");
9302 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9304 mono_json_writer_indent (&writer);
9305 mono_json_writer_object_key(&writer, "namespace");
9306 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9308 mono_json_writer_indent (&writer);
9309 mono_json_writer_object_key(&writer, "wrapper_type");
9310 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9312 mono_json_writer_indent_pop (&writer);
9313 mono_json_writer_indent (&writer);
9314 mono_json_writer_object_end (&writer);
9315 mono_json_writer_printf (&writer, ",\n");
9318 mono_json_writer_indent_pop (&writer);
9319 mono_json_writer_indent (&writer);
9320 mono_json_writer_array_end (&writer);
9321 mono_json_writer_printf (&writer, ",\n");
9325 mono_json_writer_indent_push (&writer);
9326 mono_json_writer_indent (&writer);
9327 mono_json_writer_object_key(&writer, "plt");
9328 mono_json_writer_array_begin (&writer);
9330 for (i = 0; i < acfg->plt_offset; ++i) {
9331 MonoPltEntry *plt_entry = NULL;
9336 * The first plt entry is unused.
9340 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9343 mono_json_writer_indent (&writer);
9344 mono_json_writer_printf (&writer, "{ ");
9345 mono_json_writer_object_key(&writer, "symbol");
9346 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9349 mono_json_writer_indent_pop (&writer);
9350 mono_json_writer_indent (&writer);
9351 mono_json_writer_array_end (&writer);
9352 mono_json_writer_printf (&writer, ",\n");
9357 mono_json_writer_indent_push (&writer);
9358 mono_json_writer_indent (&writer);
9359 mono_json_writer_object_key(&writer, "got");
9360 mono_json_writer_array_begin (&writer);
9362 mono_json_writer_indent_push (&writer);
9363 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9364 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9366 mono_json_writer_indent (&writer);
9367 mono_json_writer_printf (&writer, "{ ");
9368 mono_json_writer_object_key(&writer, "patch_name");
9369 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9372 mono_json_writer_indent_pop (&writer);
9373 mono_json_writer_indent (&writer);
9374 mono_json_writer_array_end (&writer);
9375 mono_json_writer_printf (&writer, ",\n");
9378 mono_json_writer_indent_pop (&writer);
9379 mono_json_writer_indent (&writer);
9380 mono_json_writer_object_end (&writer);
9382 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9383 dumpfile = fopen (dumpname, "w+");
9386 fprintf (dumpfile, "%s", writer.text->str);
9389 mono_json_writer_destroy (&writer);
9393 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9395 MonoImage *image = ass->image;
9398 MonoAotCompile *acfg;
9399 char *outfile_name, *tmp_outfile_name, *p;
9400 char llvm_stats_msg [256];
9404 acfg = acfg_create (ass, opts);
9406 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9407 acfg->aot_opts.write_symbols = TRUE;
9408 acfg->aot_opts.ntrampolines = 1024;
9409 acfg->aot_opts.nrgctx_trampolines = 1024;
9410 acfg->aot_opts.nimt_trampolines = 128;
9411 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9412 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9413 acfg->aot_opts.llvm_path = g_strdup ("");
9414 acfg->aot_opts.temp_path = g_strdup ("");
9416 acfg->aot_opts.use_trampolines_page = TRUE;
9419 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9421 if (acfg->aot_opts.logfile) {
9422 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9425 if (acfg->aot_opts.static_link)
9426 acfg->aot_opts.autoreg = TRUE;
9428 //acfg->aot_opts.print_skipped_methods = TRUE;
9430 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9431 if (opts & MONO_OPT_GSHAREDVT) {
9432 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9437 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9439 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9440 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9441 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9446 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9447 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9451 if (acfg->aot_opts.static_link)
9452 acfg->aot_opts.asm_writer = TRUE;
9454 if (acfg->aot_opts.soft_debug) {
9455 MonoDebugOptions *opt = mini_get_debug_options ();
9457 opt->mdb_optimizations = TRUE;
9458 opt->gen_sdb_seq_points = TRUE;
9460 if (!mono_debug_enabled ()) {
9461 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9464 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9467 if (mono_use_llvm || acfg->aot_opts.llvm) {
9469 acfg->aot_opts.asm_writer = TRUE;
9470 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9472 if (acfg->aot_opts.soft_debug) {
9473 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9479 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9480 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9485 * Emit all LLVM code into a separate assembly/object file and link with it
9488 if (!acfg->aot_opts.asm_only) {
9489 acfg->llvm_owriter = TRUE;
9490 } else if (acfg->aot_opts.llvm_outfile) {
9491 int len = strlen (acfg->aot_opts.llvm_outfile);
9493 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
9494 acfg->llvm_owriter = TRUE;
9498 if (mono_aot_mode_is_full (&acfg->aot_opts))
9499 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9501 if (acfg->aot_opts.instances_logfile_path) {
9502 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9503 if (!acfg->instances_logfile) {
9504 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9509 load_profile_files (acfg);
9511 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9512 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9513 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9515 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9516 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9517 if (acfg->opts & MONO_OPT_GSHAREDVT)
9518 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9521 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9525 if (acfg->llvm && acfg->thumb_mixed)
9526 acfg->flags |= MONO_AOT_FILE_FLAG_LLVM_THUMB;
9528 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9529 /* Get rid of characters which cannot occur in symbols */
9530 for (p = acfg->assembly_name_sym; *p; ++p) {
9531 if (!(isalnum (*p) || *p == '_'))
9535 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
9536 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
9537 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
9539 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
9540 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
9543 acfg->method_index = 1;
9545 if (mono_aot_mode_is_full (&acfg->aot_opts))
9546 mono_set_partial_sharing_supported (TRUE);
9548 res = collect_methods (acfg);
9552 acfg->cfgs_size = acfg->methods->len + 32;
9553 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9555 /* PLT offset 0 is reserved for the PLT trampoline */
9556 acfg->plt_offset = 1;
9561 mono_llvm_create_aot_module (acfg->global_prefix, TRUE);
9565 /* GOT offset 0 is reserved for the address of the current assembly */
9569 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9570 ji->type = MONO_PATCH_INFO_IMAGE;
9571 ji->data.image = acfg->image;
9573 get_got_offset (acfg, FALSE, ji);
9574 get_got_offset (acfg, TRUE, ji);
9576 /* Slot 1 is reserved for the mscorlib got addr */
9577 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9578 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9579 get_got_offset (acfg, FALSE, ji);
9580 get_got_offset (acfg, TRUE, ji);
9582 /* This is very common */
9583 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9584 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9585 get_got_offset (acfg, FALSE, ji);
9586 get_got_offset (acfg, TRUE, ji);
9588 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9589 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9590 get_got_offset (acfg, FALSE, ji);
9591 get_got_offset (acfg, TRUE, ji);
9593 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9594 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9595 get_got_offset (acfg, FALSE, ji);
9596 get_got_offset (acfg, TRUE, ji);
9601 compile_methods (acfg);
9605 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9611 if (acfg->aot_opts.asm_only) {
9612 if (acfg->aot_opts.outfile) {
9613 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9614 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9616 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9617 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9619 g_assert (acfg->aot_opts.llvm_outfile);
9620 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9621 if (acfg->llvm_owriter)
9622 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
9624 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9626 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
9627 g_strdup_printf ("%s", "temp") :
9628 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
9630 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9631 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
9632 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
9637 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && mono_bin_writer_supported ()) {
9638 if (acfg->aot_opts.outfile)
9639 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9641 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9644 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9645 * it might be in another file system so the rename () won't work.
9647 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9649 acfg->fp = fopen (tmp_outfile_name, "w");
9651 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9655 acfg->w = mono_img_writer_create (acfg->fp, TRUE);
9656 acfg->use_bin_writer = TRUE;
9658 if (acfg->aot_opts.asm_only) {
9659 if (acfg->aot_opts.outfile)
9660 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9662 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9663 acfg->fp = fopen (acfg->tmpfname, "w+");
9665 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9666 acfg->fp = fdopen (i, "w+");
9668 if (acfg->fp == 0) {
9669 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9672 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9674 tmp_outfile_name = NULL;
9675 outfile_name = NULL;
9678 /* Compute symbols for methods */
9679 for (i = 0; i < acfg->nmethods; ++i) {
9680 if (acfg->cfgs [i]) {
9681 MonoCompile *cfg = acfg->cfgs [i];
9682 int method_index = get_method_index (acfg, cfg->orig_method);
9684 if (COMPILE_LLVM (cfg))
9685 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9686 else if (acfg->global_symbols || acfg->llvm)
9687 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9689 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9690 cfg->asm_debug_symbol = cfg->asm_symbol;
9694 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9696 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9697 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9700 //acfg->gas_line_numbers = TRUE;
9703 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
9704 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9705 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9708 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9711 mono_img_writer_emit_start (acfg->w);
9714 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9720 emit_extra_methods (acfg);
9722 emit_trampolines (acfg);
9724 emit_class_name_table (acfg);
9726 emit_got_info (acfg, FALSE);
9728 emit_got_info (acfg, TRUE);
9730 emit_exception_info (acfg);
9732 emit_unwind_info (acfg);
9734 emit_class_info (acfg);
9738 emit_image_table (acfg);
9742 emit_file_info (acfg);
9746 emit_objc_selectors (acfg);
9748 emit_globals (acfg);
9750 emit_autoreg (acfg);
9753 emit_dwarf_info (acfg);
9754 mono_dwarf_writer_close (acfg->dwarf);
9757 emit_mem_end (acfg);
9759 if (acfg->need_pt_gnu_stack) {
9760 /* This is required so the .so doesn't have an executable stack */
9761 /* The bin writer already emits this */
9762 if (!acfg->use_bin_writer)
9763 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9770 res = emit_llvm_file (acfg);
9778 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9781 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9783 strcpy (llvm_stats_msg, "");
9785 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;
9787 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",
9788 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9789 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9790 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9791 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9792 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9793 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,
9794 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9795 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9796 (int)(acfg->got_offset * sizeof (gpointer)));
9797 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9798 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9800 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9801 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9802 if (acfg->stats.genericcount)
9803 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9804 if (acfg->stats.abscount)
9805 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9806 if (acfg->stats.lmfcount)
9807 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9808 if (acfg->stats.ocount)
9809 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9812 res = mono_img_writer_emit_writeout (acfg->w);
9817 if (acfg->use_bin_writer) {
9818 int err = rename (tmp_outfile_name, outfile_name);
9821 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9825 res = compile_asm (acfg);
9832 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9834 if (acfg->aot_opts.stats) {
9837 aot_printf (acfg, "GOT slot distribution:\n");
9838 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9839 if (acfg->stats.got_slot_types [i])
9840 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]);
9843 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);
9845 if (acfg->aot_opts.dump_json)
9858 mono_aot_readonly_field_override (MonoClassField *field)
9864 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)