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%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
521 emit_label (acfg, symbol);
522 emit_global_inner (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_RGCTX_FETCH:
3141 case MONO_PATCH_INFO_MONITOR_ENTER:
3142 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3143 case MONO_PATCH_INFO_MONITOR_EXIT:
3144 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3154 * Return the symbol identifying the plt entry PLT_OFFSET.
3157 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3161 * The Apple linker reorganizes object files, so it doesn't like branches to local
3162 * labels, since those have no relocations.
3164 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3166 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3173 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3175 static MonoPltEntry*
3176 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3179 gboolean synchronized = FALSE;
3180 static int synchronized_symbol_idx;
3182 if (!is_plt_patch (patch_info))
3185 if (!acfg->patch_to_plt_entry [patch_info->type])
3186 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3187 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3189 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3191 * Allocate a separate PLT slot for each such patch, since some plt
3192 * entries will refer to the method itself, and some will refer to the
3196 synchronized = TRUE;
3200 MonoJumpInfo *new_ji;
3202 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3204 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3205 res->plt_offset = acfg->plt_offset;
3207 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3208 if (acfg->aot_opts.write_symbols)
3209 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3211 /* Avoid duplicate symbols because we don't cache */
3212 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3214 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3215 synchronized_symbol_idx ++;
3218 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3220 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3222 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3224 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3226 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3227 //mono_print_ji (patch_info); printf ("\n");
3228 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3230 acfg->plt_offset ++;
3239 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3240 * JI could be found if it exists, otherwise allocates a new one.
3243 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3246 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3248 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3250 return got_offset - 1;
3253 got_offset = acfg->llvm_got_offset;
3254 acfg->llvm_got_offset ++;
3256 got_offset = acfg->got_offset;
3257 acfg->got_offset ++;
3260 acfg->stats.got_slots ++;
3261 acfg->stats.got_slot_types [ji->type] ++;
3263 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3264 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3265 g_ptr_array_add (info->got_patches, ji);
3270 /* Add a method to the list of methods which need to be emitted */
3272 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3275 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3276 g_ptr_array_add (acfg->methods, method);
3277 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3278 acfg->nmethods = acfg->methods->len + 1;
3281 if (method->wrapper_type || extra)
3282 g_ptr_array_add (acfg->extra_methods, method);
3286 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3288 /* One instantiation with valuetypes is generated for each async method */
3289 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3296 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3298 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3306 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3310 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3314 index = acfg->method_index;
3315 add_method_with_index (acfg, method, index, extra);
3317 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3319 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3321 acfg->method_index ++;
3327 add_method (MonoAotCompile *acfg, MonoMethod *method)
3329 return add_method_full (acfg, method, FALSE, 0);
3333 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3335 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3336 method = mini_get_shared_method (method);
3337 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3338 /* Use the gsharedvt version */
3339 method = mini_get_shared_method_full (method, TRUE, TRUE);
3341 if (acfg->aot_opts.log_generics)
3342 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3344 add_method_full (acfg, method, TRUE, depth);
3348 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3350 add_extra_method_with_depth (acfg, method, 0);
3354 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3356 MonoAotCompile *acfg = user_data;
3357 MonoJitICallInfo *callinfo = value;
3358 MonoMethod *wrapper;
3364 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3365 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3368 add_method (acfg, wrapper);
3372 get_runtime_invoke_sig (MonoMethodSignature *sig)
3374 MonoMethodBuilder *mb;
3377 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3378 m = mono_mb_create_method (mb, sig, 16);
3379 return mono_marshal_get_runtime_invoke (m, FALSE);
3383 can_marshal_struct (MonoClass *klass)
3385 MonoClassField *field;
3386 gboolean can_marshal = TRUE;
3387 gpointer iter = NULL;
3388 MonoMarshalType *info;
3391 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3394 info = mono_marshal_load_type_info (klass);
3396 /* Only allow a few field types to avoid asserts in the marshalling code */
3397 while ((field = mono_class_get_fields (klass, &iter))) {
3398 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3401 switch (field->type->type) {
3406 case MONO_TYPE_BOOLEAN:
3409 case MONO_TYPE_CHAR:
3417 case MONO_TYPE_STRING:
3419 case MONO_TYPE_VALUETYPE:
3420 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3421 can_marshal = FALSE;
3423 case MONO_TYPE_SZARRAY: {
3424 gboolean has_mspec = FALSE;
3427 for (i = 0; i < info->num_fields; ++i) {
3428 if (info->fields [i].field == field && info->fields [i].mspec)
3433 can_marshal = FALSE;
3437 can_marshal = FALSE;
3443 /* Its hard to compute whenever these can be marshalled or not */
3444 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3451 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3453 /* Create a vtype instantiation */
3454 MonoGenericContext shared_context;
3456 MonoGenericInst *inst;
3457 MonoGenericContainer *container;
3458 MonoClass **constraints;
3461 memset (ctx, 0, sizeof (MonoGenericContext));
3463 if (method->klass->generic_container) {
3464 shared_context = method->klass->generic_container->context;
3465 inst = shared_context.class_inst;
3467 args = g_new0 (MonoType*, inst->type_argc);
3468 for (i = 0; i < inst->type_argc; ++i) {
3469 args [i] = &mono_defaults.int_class->byval_arg;
3471 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3473 if (method->is_generic) {
3474 container = mono_method_get_generic_container (method);
3475 shared_context = container->context;
3476 inst = shared_context.method_inst;
3478 args = g_new0 (MonoType*, inst->type_argc);
3479 for (i = 0; i < container->type_argc; ++i) {
3480 MonoGenericParamInfo *info = &container->type_params [i].info;
3481 gboolean ref_only = FALSE;
3483 if (info && info->constraints) {
3484 constraints = info->constraints;
3486 while (*constraints) {
3487 MonoClass *cklass = *constraints;
3488 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3489 /* Inflaring the method with our vtype would not be valid */
3496 args [i] = &mono_defaults.object_class->byval_arg;
3498 args [i] = &mono_defaults.int_class->byval_arg;
3500 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3505 add_wrappers (MonoAotCompile *acfg)
3507 MonoMethod *method, *m;
3509 MonoMethodSignature *sig, *csig;
3513 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3514 * so there is only one wrapper of a given type, or inlining their contents into their
3517 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3520 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3521 gboolean skip = FALSE;
3523 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3524 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3526 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3527 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3528 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3531 /* Skip methods which can not be handled by get_runtime_invoke () */
3532 sig = mono_method_signature (method);
3535 if ((sig->ret->type == MONO_TYPE_PTR) ||
3536 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3538 if (mono_class_is_open_constructed_type (sig->ret))
3541 for (j = 0; j < sig->param_count; j++) {
3542 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3544 if (mono_class_is_open_constructed_type (sig->params [j]))
3548 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3549 if (!mono_class_is_contextbound (method->klass)) {
3550 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3551 gboolean has_nullable = FALSE;
3553 for (j = 0; j < sig->param_count; j++) {
3554 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3555 has_nullable = TRUE;
3558 if (info && !has_nullable) {
3559 /* Supported by the dynamic runtime-invoke wrapper */
3563 mono_arch_dyn_call_free (info);
3568 //printf ("%s\n", mono_method_full_name (method, TRUE));
3569 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3573 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3576 /* Runtime invoke wrappers */
3578 /* void runtime-invoke () [.cctor] */
3579 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3580 csig->ret = &mono_defaults.void_class->byval_arg;
3581 add_method (acfg, get_runtime_invoke_sig (csig));
3583 /* void runtime-invoke () [Finalize] */
3584 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3586 csig->ret = &mono_defaults.void_class->byval_arg;
3587 add_method (acfg, get_runtime_invoke_sig (csig));
3589 /* void runtime-invoke (string) [exception ctor] */
3590 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3592 csig->ret = &mono_defaults.void_class->byval_arg;
3593 csig->params [0] = &mono_defaults.string_class->byval_arg;
3594 add_method (acfg, get_runtime_invoke_sig (csig));
3596 /* void runtime-invoke (string, string) [exception ctor] */
3597 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3599 csig->ret = &mono_defaults.void_class->byval_arg;
3600 csig->params [0] = &mono_defaults.string_class->byval_arg;
3601 csig->params [1] = &mono_defaults.string_class->byval_arg;
3602 add_method (acfg, get_runtime_invoke_sig (csig));
3604 /* string runtime-invoke () [Exception.ToString ()] */
3605 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3607 csig->ret = &mono_defaults.string_class->byval_arg;
3608 add_method (acfg, get_runtime_invoke_sig (csig));
3610 /* void runtime-invoke (string, Exception) [exception ctor] */
3611 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3613 csig->ret = &mono_defaults.void_class->byval_arg;
3614 csig->params [0] = &mono_defaults.string_class->byval_arg;
3615 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3616 add_method (acfg, get_runtime_invoke_sig (csig));
3618 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3619 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3621 csig->ret = &(mono_class_from_name (
3622 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3623 csig->params [0] = &mono_defaults.string_class->byval_arg;
3624 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3625 add_method (acfg, get_runtime_invoke_sig (csig));
3627 /* runtime-invoke used by finalizers */
3628 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3630 /* This is used by mono_runtime_capture_context () */
3631 method = mono_get_context_capture_method ();
3633 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3635 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3636 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3640 add_method (acfg, mono_marshal_get_stelemref ());
3642 if (MONO_ARCH_HAVE_TLS_GET) {
3643 /* Managed Allocators */
3644 nallocators = mono_gc_get_managed_allocator_types ();
3645 for (i = 0; i < nallocators; ++i) {
3646 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3648 add_method (acfg, m);
3650 for (i = 0; i < nallocators; ++i) {
3651 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3653 add_method (acfg, m);
3657 /* write barriers */
3658 if (mono_gc_is_moving ()) {
3659 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3660 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3663 /* Stelemref wrappers */
3665 MonoMethod **wrappers;
3668 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3669 for (i = 0; i < nwrappers; ++i)
3670 add_method (acfg, wrappers [i]);
3674 /* castclass_with_check wrapper */
3675 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3676 /* isinst_with_check wrapper */
3677 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3679 /* JIT icall wrappers */
3680 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3681 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3685 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3686 * we use the original method instead at runtime.
3687 * Since full-aot doesn't support remoting, this is not a problem.
3690 /* remoting-invoke wrappers */
3691 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3692 MonoMethodSignature *sig;
3694 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3695 method = mono_get_method (acfg->image, token, NULL);
3697 sig = mono_method_signature (method);
3699 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3700 m = mono_marshal_get_remoting_invoke_with_check (method);
3702 add_method (acfg, m);
3707 /* delegate-invoke wrappers */
3708 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3711 MonoCustomAttrInfo *cattr;
3713 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3714 klass = mono_class_get_checked (acfg->image, token, &error);
3717 mono_error_cleanup (&error);
3721 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3724 if (!klass->generic_container) {
3725 method = mono_get_delegate_invoke (klass);
3727 m = mono_marshal_get_delegate_invoke (method, NULL);
3729 add_method (acfg, m);
3731 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3733 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3735 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3737 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3739 cattr = mono_custom_attrs_from_class (klass);
3744 for (j = 0; j < cattr->num_attrs; ++j)
3745 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3747 if (j < cattr->num_attrs) {
3749 MonoMethod *wrapper;
3750 MonoMethod *del_invoke;
3752 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3753 invoke = mono_get_delegate_invoke (klass);
3754 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3755 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3756 add_method (acfg, wrapper);
3757 add_method (acfg, del_invoke);
3760 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3762 MonoGenericContext ctx;
3763 MonoMethod *inst, *gshared;
3766 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3769 method = mono_get_delegate_invoke (klass);
3770 create_gsharedvt_inst (acfg, method, &ctx);
3772 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3773 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3775 m = mono_marshal_get_delegate_invoke (inst, NULL);
3776 g_assert (m->is_inflated);
3778 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3779 add_extra_method (acfg, gshared);
3782 method = mono_get_delegate_begin_invoke (klass);
3783 create_gsharedvt_inst (acfg, method, &ctx);
3785 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3786 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3788 m = mono_marshal_get_delegate_begin_invoke (inst);
3789 g_assert (m->is_inflated);
3791 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3792 add_extra_method (acfg, gshared);
3795 method = mono_get_delegate_end_invoke (klass);
3796 create_gsharedvt_inst (acfg, method, &ctx);
3798 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3799 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3801 m = mono_marshal_get_delegate_end_invoke (inst);
3802 g_assert (m->is_inflated);
3804 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3805 add_extra_method (acfg, gshared);
3810 /* array access wrappers */
3811 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3815 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3816 klass = mono_class_get_checked (acfg->image, token, &error);
3819 mono_error_cleanup (&error);
3823 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3824 MonoMethod *m, *wrapper;
3826 /* Add runtime-invoke wrappers too */
3828 m = mono_class_get_method_from_name (klass, "Get", -1);
3830 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3831 add_extra_method (acfg, wrapper);
3832 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3834 m = mono_class_get_method_from_name (klass, "Set", -1);
3836 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3837 add_extra_method (acfg, wrapper);
3838 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3842 /* Synchronized wrappers */
3843 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3845 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3846 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3847 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3849 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3850 if (method->is_generic) {
3852 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3854 MonoGenericContext ctx;
3855 MonoMethod *inst, *gshared, *m;
3858 * Create a generic wrapper for a generic instance, and AOT that.
3860 create_gsharedvt_inst (acfg, method, &ctx);
3861 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3862 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3863 m = mono_marshal_get_synchronized_wrapper (inst);
3864 g_assert (m->is_inflated);
3865 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3866 add_method (acfg, gshared);
3868 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3873 /* pinvoke wrappers */
3874 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3877 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3879 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3880 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3882 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3883 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3884 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3888 /* native-to-managed wrappers */
3889 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3892 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3893 MonoCustomAttrInfo *cattr;
3896 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3897 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3900 * Only generate native-to-managed wrappers for methods which have an
3901 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3902 * name to avoid defining a new assembly to contain it.
3904 cattr = mono_custom_attrs_from_method (method);
3907 for (j = 0; j < cattr->num_attrs; ++j)
3908 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3910 if (j < cattr->num_attrs) {
3911 MonoCustomAttrEntry *e = &cattr->attrs [j];
3912 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3913 const char *p = (const char*)e->data;
3915 int slen, num_named, named_type;
3919 char *export_name = NULL;
3920 MonoMethod *wrapper;
3922 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3923 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3924 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3925 mono_method_full_name (method, TRUE));
3929 g_assert (sig->param_count == 1);
3930 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3933 * Decode the cattr manually since we can't create objects
3934 * during aot compilation.
3940 /* From load_cattr_value () in reflection.c */
3941 slen = mono_metadata_decode_value (p, &p);
3942 n = g_memdup (p, slen + 1);
3944 t = mono_reflection_type_from_name (n, acfg->image);
3948 klass = mono_class_from_mono_type (t);
3949 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3953 num_named = read16 (p);
3956 g_assert (num_named < 2);
3957 if (num_named == 1) {
3961 /* parse ExportSymbol attribute */
3963 named_type = *named;
3965 /* data_type = *named; */
3968 name_len = mono_metadata_decode_blob_size (named, &named);
3969 name = g_malloc (name_len + 1);
3970 memcpy (name, named, name_len);
3971 name [name_len] = 0;
3974 g_assert (named_type == 0x54);
3975 g_assert (!strcmp (name, "ExportSymbol"));
3977 /* load_cattr_value (), string case */
3978 g_assert (*named != (char)0xff);
3979 slen = mono_metadata_decode_value (named, &named);
3980 export_name = g_malloc (slen + 1);
3981 memcpy (export_name, named, slen);
3982 export_name [slen] = 0;
3986 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3987 add_method (acfg, wrapper);
3989 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3993 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3994 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3995 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3999 /* StructureToPtr/PtrToStructure wrappers */
4000 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4004 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4005 klass = mono_class_get_checked (acfg->image, token, &error);
4008 mono_error_cleanup (&error);
4012 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4013 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4014 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4015 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4021 has_type_vars (MonoClass *klass)
4023 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4026 return has_type_vars (klass->element_class);
4027 if (klass->generic_class) {
4028 MonoGenericContext *context = &klass->generic_class->context;
4029 if (context->class_inst) {
4032 for (i = 0; i < context->class_inst->type_argc; ++i)
4033 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4037 if (klass->generic_container)
4043 is_vt_inst (MonoGenericInst *inst)
4047 for (i = 0; i < inst->type_argc; ++i) {
4048 MonoType *t = inst->type_argv [i];
4049 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4056 method_has_type_vars (MonoMethod *method)
4058 if (has_type_vars (method->klass))
4061 if (method->is_inflated) {
4062 MonoGenericContext *context = mono_method_get_context (method);
4063 if (context->method_inst) {
4066 for (i = 0; i < context->method_inst->type_argc; ++i)
4067 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4075 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4077 return opts->mode == MONO_AOT_MODE_FULL;
4080 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4083 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4085 /* This might lead to a huge code blowup so only do it if neccesary */
4086 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4089 add_generic_class_with_depth (acfg, klass, 0, ref);
4093 check_type_depth (MonoType *t, int depth)
4101 case MONO_TYPE_GENERICINST: {
4102 MonoGenericClass *gklass = t->data.generic_class;
4103 MonoGenericInst *ginst = gklass->context.class_inst;
4106 for (i = 0; i < ginst->type_argc; ++i) {
4107 if (check_type_depth (ginst->type_argv [i], depth + 1))
4121 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4124 * add_generic_class:
4126 * Add all methods of a generic class.
4129 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4132 MonoClassField *field;
4134 gboolean use_gsharedvt = FALSE;
4136 if (!acfg->ginst_hash)
4137 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4139 mono_class_init (klass);
4141 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4144 if (has_type_vars (klass))
4147 if (!klass->generic_class && !klass->rank)
4150 if (klass->exception_type)
4153 if (!acfg->ginst_hash)
4154 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4156 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4159 if (check_type_depth (&klass->byval_arg, 0))
4162 if (acfg->aot_opts.log_generics)
4163 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4165 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4168 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4169 * Enable this only for some classes since gsharedvt might not support all methods.
4171 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) &&
4172 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4173 use_gsharedvt = TRUE;
4176 while ((method = mono_class_get_methods (klass, &iter))) {
4177 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4179 * This is partial sharing, and we can't handle it yet
4184 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4186 add_types_from_method_header (acfg, method);
4190 if (method->is_generic)
4195 * FIXME: Instances which are referenced by these methods are not added,
4196 * for example Array.Resize<int> for List<int>.Add ().
4198 add_extra_method_with_depth (acfg, method, depth + 1);
4202 while ((field = mono_class_get_fields (klass, &iter))) {
4203 if (field->type->type == MONO_TYPE_GENERICINST)
4204 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4207 if (klass->delegate) {
4208 method = mono_get_delegate_invoke (klass);
4210 method = mono_marshal_get_delegate_invoke (method, NULL);
4212 if (acfg->aot_opts.log_generics)
4213 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4215 add_method (acfg, method);
4218 /* Add superclasses */
4220 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4223 * For ICollection<T>, add instances of the helper methods
4224 * in Array, since a T[] could be cast to ICollection<T>.
4226 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4227 (!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"))) {
4228 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4229 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4233 if (!strcmp (klass->name, "IEnumerator`1"))
4234 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4236 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4238 /* Add the T[]/InternalEnumerator class */
4239 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4243 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4244 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4248 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4249 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4253 while ((method = mono_class_get_methods (array_class, &iter))) {
4254 if (strstr (method->name, name_prefix)) {
4255 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4257 add_extra_method_with_depth (acfg, m, depth);
4261 g_free (name_prefix);
4264 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4265 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4266 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4267 MonoClass *icomparable, *gcomparer;
4268 MonoGenericContext ctx;
4269 MonoType *args [16];
4271 memset (&ctx, 0, sizeof (ctx));
4273 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4274 g_assert (icomparable);
4275 args [0] = &tclass->byval_arg;
4276 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4278 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4279 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4280 g_assert (gcomparer);
4281 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4285 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4286 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4287 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4288 MonoClass *iface, *gcomparer;
4289 MonoGenericContext ctx;
4290 MonoType *args [16];
4292 memset (&ctx, 0, sizeof (ctx));
4294 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4296 args [0] = &tclass->byval_arg;
4297 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4299 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4300 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4301 g_assert (gcomparer);
4302 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4306 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4307 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4308 MonoClass *enum_comparer;
4309 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4310 MonoGenericContext ctx;
4311 MonoType *args [16];
4313 if (mono_class_is_enum (tclass)) {
4314 memset (&ctx, 0, sizeof (ctx));
4315 args [0] = &tclass->byval_arg;
4316 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4318 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4319 g_assert (enum_comparer);
4320 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4324 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4325 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4326 MonoClass *comparer;
4327 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4328 MonoGenericContext ctx;
4329 MonoType *args [16];
4331 if (mono_class_is_enum (tclass)) {
4332 memset (&ctx, 0, sizeof (ctx));
4333 args [0] = &tclass->byval_arg;
4334 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4336 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4337 g_assert (comparer);
4338 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4344 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4347 MonoGenericContext ctx;
4348 MonoType *args [16];
4350 if (acfg->aot_opts.no_instances)
4353 memset (&ctx, 0, sizeof (ctx));
4355 for (i = 0; i < ninsts; ++i) {
4356 args [0] = insts [i];
4357 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4358 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4363 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4365 MonoMethodHeader *header;
4366 MonoMethodSignature *sig;
4369 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4371 sig = mono_method_signature (method);
4374 for (j = 0; j < sig->param_count; ++j)
4375 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4376 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4379 header = mono_method_get_header (method);
4382 for (j = 0; j < header->num_locals; ++j)
4383 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4384 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4386 mono_loader_clear_error ();
4391 * add_generic_instances:
4393 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4396 add_generic_instances (MonoAotCompile *acfg)
4401 MonoGenericContext *context;
4403 if (acfg->aot_opts.no_instances)
4406 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4408 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4409 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4412 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4413 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4414 mono_error_cleanup (&error);
4418 if (method->klass->image != acfg->image)
4421 context = mono_method_get_context (method);
4423 if (context && ((context->class_inst && context->class_inst->is_open)))
4427 * For open methods, create an instantiation which can be passed to the JIT.
4428 * FIXME: Handle class_inst as well.
4430 if (context && context->method_inst && context->method_inst->is_open) {
4432 MonoGenericContext shared_context;
4433 MonoGenericInst *inst;
4434 MonoType **type_argv;
4436 MonoMethod *declaring_method;
4437 gboolean supported = TRUE;
4439 /* Check that the context doesn't contain open constructed types */
4440 if (context->class_inst) {
4441 inst = context->class_inst;
4442 for (i = 0; i < inst->type_argc; ++i) {
4443 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)
4445 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4449 if (context->method_inst) {
4450 inst = context->method_inst;
4451 for (i = 0; i < inst->type_argc; ++i) {
4452 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)
4454 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4462 memset (&shared_context, 0, sizeof (MonoGenericContext));
4464 inst = context->class_inst;
4466 type_argv = g_new0 (MonoType*, inst->type_argc);
4467 for (i = 0; i < inst->type_argc; ++i) {
4468 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)
4469 type_argv [i] = &mono_defaults.object_class->byval_arg;
4471 type_argv [i] = inst->type_argv [i];
4474 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4478 inst = context->method_inst;
4480 type_argv = g_new0 (MonoType*, inst->type_argc);
4481 for (i = 0; i < inst->type_argc; ++i) {
4482 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)
4483 type_argv [i] = &mono_defaults.object_class->byval_arg;
4485 type_argv [i] = inst->type_argv [i];
4488 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4492 if (method->is_generic || method->klass->generic_container)
4493 declaring_method = method;
4495 declaring_method = mono_method_get_declaring_generic_method (method);
4497 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4498 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4502 * If the method is fully sharable, it was already added in place of its
4503 * generic definition.
4505 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4509 * FIXME: Partially shared methods are not shared here, so we end up with
4510 * many identical methods.
4512 add_extra_method (acfg, method);
4515 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4519 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4521 klass = mono_class_get_checked (acfg->image, token, &error);
4522 if (!klass || klass->rank) {
4523 mono_error_cleanup (&error);
4527 add_generic_class (acfg, klass, FALSE, "typespec");
4530 /* Add types of args/locals */
4531 for (i = 0; i < acfg->methods->len; ++i) {
4532 method = g_ptr_array_index (acfg->methods, i);
4533 add_types_from_method_header (acfg, method);
4536 if (acfg->image == mono_defaults.corlib) {
4538 MonoType *insts [256];
4541 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4542 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4543 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4544 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4545 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4546 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4547 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4548 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4549 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4550 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4551 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4552 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4554 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4555 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4557 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4558 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4560 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4562 /* Add instances of the array generic interfaces for primitive types */
4563 /* This will add instances of the InternalArray_ helper methods in Array too */
4564 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4566 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4567 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4569 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4570 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4572 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4575 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4576 * used for all instances of GetGenericValueImpl by the AOT runtime.
4579 MonoGenericContext ctx;
4580 MonoType *args [16];
4581 MonoMethod *get_method;
4582 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4584 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4588 memset (&ctx, 0, sizeof (ctx));
4589 args [0] = &mono_defaults.object_class->byval_arg;
4590 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4591 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4592 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4596 /* Same for CompareExchange<T>/Exchange<T> */
4598 MonoGenericContext ctx;
4599 MonoType *args [16];
4601 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4602 gpointer iter = NULL;
4604 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4605 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4607 memset (&ctx, 0, sizeof (ctx));
4608 args [0] = &mono_defaults.object_class->byval_arg;
4609 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4610 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4611 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4616 /* Same for Volatile.Read/Write<T> */
4618 MonoGenericContext ctx;
4619 MonoType *args [16];
4621 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4622 gpointer iter = NULL;
4624 if (volatile_klass) {
4625 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4626 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4628 memset (&ctx, 0, sizeof (ctx));
4629 args [0] = &mono_defaults.object_class->byval_arg;
4630 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4631 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4632 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4641 * is_direct_callable:
4643 * Return whenever the method identified by JI is directly callable without
4644 * going through the PLT.
4647 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4649 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4650 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4652 gboolean direct_callable = TRUE;
4654 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4655 direct_callable = FALSE;
4656 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4657 // FIXME: Maybe call the wrapper directly ?
4658 direct_callable = FALSE;
4660 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4661 /* Disable this so all calls go through load_method (), see the
4662 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4663 * mono_debugger_agent_init ().
4665 direct_callable = FALSE;
4668 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4669 /* sgen does some initialization when the allocator method is created */
4670 direct_callable = FALSE;
4671 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4672 /* we don't know at compile time whether sgen is concurrent or not */
4673 direct_callable = FALSE;
4675 if (direct_callable)
4678 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4679 if (acfg->aot_opts.direct_pinvoke)
4681 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4682 if (acfg->aot_opts.direct_icalls)
4690 #ifdef MONO_ARCH_AOT_SUPPORTED
4692 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4694 MonoImage *image = method->klass->image;
4695 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4696 MonoTableInfo *tables = image->tables;
4697 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4698 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4699 guint32 im_cols [MONO_IMPLMAP_SIZE];
4702 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4706 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4709 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4711 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4714 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4716 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4723 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4725 if (a->native_offset == b->native_offset)
4726 return a->il_offset - b->il_offset;
4728 return a->native_offset - b->native_offset;
4732 * compute_line_numbers:
4734 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4737 static MonoDebugSourceLocation**
4738 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4740 MonoDebugMethodInfo *minfo;
4741 MonoDebugLineNumberEntry *ln_array;
4742 MonoDebugSourceLocation *loc;
4743 int i, prev_line, prev_il_offset;
4744 int *native_to_il_offset = NULL;
4745 MonoDebugSourceLocation **res;
4748 minfo = mono_debug_lookup_method (method);
4751 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4752 if (debug_info->code_size != code_size)
4755 g_assert (code_size);
4757 /* Compute the native->IL offset mapping */
4759 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4760 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4762 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4764 native_to_il_offset = g_new0 (int, code_size + 1);
4766 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4768 MonoDebugLineNumberEntry *lne = &ln_array [i];
4771 for (j = 0; j < lne->native_offset; ++j)
4772 native_to_il_offset [j] = -1;
4775 if (i < debug_info->num_line_numbers - 1) {
4776 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4778 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4779 native_to_il_offset [j] = lne->il_offset;
4781 for (j = lne->native_offset; j < code_size; ++j)
4782 native_to_il_offset [j] = lne->il_offset;
4787 /* Compute the native->line number mapping */
4788 res = g_new0 (MonoDebugSourceLocation*, code_size);
4789 prev_il_offset = -1;
4792 for (i = 0; i < code_size; ++i) {
4793 int il_offset = native_to_il_offset [i];
4795 if (il_offset == -1 || il_offset == prev_il_offset)
4797 prev_il_offset = il_offset;
4798 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4799 if (!(loc && loc->source_file))
4801 if (loc->row == prev_line) {
4802 mono_debug_symfile_free_location (loc);
4805 prev_line = loc->row;
4806 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4808 /* This will cover the prolog too */
4818 get_file_index (MonoAotCompile *acfg, const char *source_file)
4822 // FIXME: Free these
4823 if (!acfg->dwarf_ln_filenames)
4824 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4825 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4827 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4828 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4829 emit_unset_mode (acfg);
4830 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4842 * emit_and_reloc_code:
4844 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4845 * is true, calls are made through the GOT too. This is used for emitting trampolines
4846 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4847 * since trampolines are needed to make PTL work.
4850 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4852 int i, pindex, start_index;
4854 MonoJumpInfo *patch_info;
4855 MonoDebugSourceLocation **locs = NULL;
4857 #ifdef MONO_ARCH_AOT_SUPPORTED
4858 gboolean direct_call, external_call;
4860 const char *direct_call_target = 0;
4861 const char *direct_pinvoke;
4864 if (acfg->gas_line_numbers && method && debug_info) {
4865 locs = compute_line_numbers (method, code_len, debug_info);
4867 int findex = get_file_index (acfg, "<unknown>");
4868 emit_unset_mode (acfg);
4869 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4873 /* Collect and sort relocations */
4874 patches = g_ptr_array_new ();
4875 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4876 g_ptr_array_add (patches, patch_info);
4877 g_ptr_array_sort (patches, compare_patches);
4880 for (i = 0; i < code_len; i += INST_LEN) {
4882 for (pindex = start_index; pindex < patches->len; ++pindex) {
4883 patch_info = g_ptr_array_index (patches, pindex);
4884 if (patch_info->ip.i >= i)
4888 if (locs && locs [i]) {
4889 MonoDebugSourceLocation *loc = locs [i];
4892 findex = get_file_index (acfg, loc->source_file);
4893 emit_unset_mode (acfg);
4894 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4895 mono_debug_symfile_free_location (loc);
4899 #ifdef MONO_ARCH_AOT_SUPPORTED
4900 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4901 start_index = pindex;
4903 switch (patch_info->type) {
4904 case MONO_PATCH_INFO_NONE:
4906 case MONO_PATCH_INFO_GOT_OFFSET: {
4909 arch_emit_got_offset (acfg, code + i, &code_size);
4910 i += code_size - INST_LEN;
4912 patch_info->type = MONO_PATCH_INFO_NONE;
4915 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4916 int code_size, index;
4917 char *selector = (void*)patch_info->data.target;
4919 if (!acfg->objc_selector_to_index)
4920 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4921 if (!acfg->objc_selectors)
4922 acfg->objc_selectors = g_ptr_array_new ();
4923 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4927 index = acfg->objc_selector_index;
4928 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4929 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4930 acfg->objc_selector_index ++;
4933 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4934 i += code_size - INST_LEN;
4936 patch_info->type = MONO_PATCH_INFO_NONE;
4941 * If this patch is a call, try emitting a direct call instead of
4942 * through a PLT entry. This is possible if the called method is in
4943 * the same assembly and requires no initialization.
4945 direct_call = FALSE;
4946 external_call = FALSE;
4947 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4948 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4949 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4950 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4952 direct_call_target = callee_cfg->asm_symbol;
4953 patch_info->type = MONO_PATCH_INFO_NONE;
4954 acfg->stats.direct_calls ++;
4957 acfg->stats.all_calls ++;
4958 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4959 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4960 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4961 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4963 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4964 if (direct_pinvoke) {
4966 g_assert (strlen (direct_pinvoke) < 1000);
4967 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4970 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4971 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4972 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4973 /* Call to a C function implementing a jit icall */
4975 external_call = TRUE;
4976 g_assert (strlen (sym) < 1000);
4977 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4979 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4980 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4981 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4982 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4983 /* Call to a jit icall without a wrapper */
4985 external_call = TRUE;
4986 g_assert (strlen (sym) < 1000);
4987 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4992 patch_info->type = MONO_PATCH_INFO_NONE;
4993 acfg->stats.direct_calls ++;
4996 if (!got_only && !direct_call) {
4997 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4999 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5001 direct_call_target = plt_entry->symbol;
5003 /* Nullify the patch */
5004 patch_info->type = MONO_PATCH_INFO_NONE;
5005 plt_entry->jit_used = TRUE;
5012 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5013 i += call_size - INST_LEN;
5017 got_slot = get_got_offset (acfg, FALSE, patch_info);
5019 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5020 i += code_size - INST_LEN;
5026 #endif /* MONO_ARCH_AOT_SUPPORTED */
5029 /* Find next patch */
5031 for (pindex = start_index; pindex < patches->len; ++pindex) {
5032 patch_info = g_ptr_array_index (patches, pindex);
5033 if (patch_info->ip.i >= i)
5037 /* Try to emit multiple bytes at once */
5038 if (pindex < patches->len && patch_info->ip.i > i) {
5041 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5042 if (locs && locs [limit])
5046 emit_code_bytes (acfg, code + i, limit - i);
5047 i = limit - INST_LEN;
5049 emit_code_bytes (acfg, code + i, INST_LEN);
5060 * Return a modified version of S which only includes characters permissible in symbols.
5063 sanitize_symbol (MonoAotCompile *acfg, char *s)
5065 gboolean process = FALSE;
5074 for (i = 0; i < len; ++i)
5075 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5080 gs = g_string_sized_new (len);
5081 for (i = 0; i < len; ++i) {
5083 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5084 g_string_append_c (gs, c);
5085 } else if (c > 0x7f) {
5086 /* multi-byte utf8 */
5087 g_string_append_printf (gs, "_0x%x", c);
5090 while (c >> 6 == 0x2) {
5091 g_string_append_printf (gs, "%x", c);
5095 g_string_append_printf (gs, "_");
5098 g_string_append_c (gs, '_');
5102 res = mono_mempool_strdup (acfg->mempool, gs->str);
5103 g_string_free (gs, TRUE);
5108 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5110 char *name1, *name2, *cached;
5111 int i, j, len, count;
5112 MonoMethod *cached_method;
5114 name1 = mono_method_full_name (method, TRUE);
5117 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5118 if ((!prefix || !*prefix) && name1 [0] == 'L')
5122 len = strlen (name1);
5123 name2 = malloc (strlen (prefix) + len + 16);
5124 memcpy (name2, prefix, strlen (prefix));
5125 j = strlen (prefix);
5126 for (i = 0; i < len; ++i) {
5127 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5129 } else if (isalnum (name1 [i])) {
5130 name2 [j ++] = name1 [i];
5131 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5133 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5136 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5146 cached_method = g_hash_table_lookup (cache, name2);
5147 if (!(cached_method && cached_method != method))
5149 sprintf (name2 + j, "_%d", count);
5153 cached = g_strdup (name2);
5154 g_hash_table_insert (cache, cached, method);
5160 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5165 char *debug_sym = NULL;
5166 char *symbol = NULL;
5167 int func_alignment = AOT_FUNC_ALIGNMENT;
5170 method = cfg->orig_method;
5171 code = cfg->native_code;
5173 method_index = get_method_index (acfg, method);
5174 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5176 /* Make the labels local */
5177 emit_section_change (acfg, ".text", 0);
5178 emit_alignment_code (acfg, func_alignment);
5180 if (acfg->global_symbols && acfg->need_no_dead_strip)
5181 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5183 emit_label (acfg, cfg->asm_symbol);
5185 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5187 * Write a C style symbol for every method, this has two uses:
5188 * - it works on platforms where the dwarf debugging info is not
5190 * - it allows the setting of breakpoints of aot-ed methods.
5192 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5193 cfg->asm_debug_symbol = g_strdup (debug_sym);
5195 if (acfg->need_no_dead_strip)
5196 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5197 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5198 emit_label (acfg, debug_sym);
5201 export_name = g_hash_table_lookup (acfg->export_names, method);
5203 /* Emit a global symbol for the method */
5204 emit_global_inner (acfg, export_name, TRUE);
5205 emit_label (acfg, export_name);
5208 if (cfg->verbose_level > 0)
5209 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5211 acfg->stats.code_size += cfg->code_len;
5213 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5215 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 ()));
5219 if (acfg->aot_opts.write_symbols) {
5221 emit_symbol_size (acfg, debug_sym, ".");
5223 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5227 emit_label (acfg, symbol);
5234 * Encode PATCH_INFO into its disk representation.
5237 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5241 switch (patch_info->type) {
5242 case MONO_PATCH_INFO_NONE:
5244 case MONO_PATCH_INFO_IMAGE:
5245 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5247 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5248 case MONO_PATCH_INFO_JIT_TLS_ID:
5249 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5250 case MONO_PATCH_INFO_GC_NURSERY_START:
5252 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5253 encode_value (patch_info->data.index, p, &p);
5255 case MONO_PATCH_INFO_METHOD_REL:
5256 encode_value ((gint)patch_info->data.offset, p, &p);
5258 case MONO_PATCH_INFO_SWITCH: {
5259 gpointer *table = (gpointer *)patch_info->data.table->table;
5262 encode_value (patch_info->data.table->table_size, p, &p);
5263 for (k = 0; k < patch_info->data.table->table_size; k++)
5264 encode_value ((int)(gssize)table [k], p, &p);
5267 case MONO_PATCH_INFO_METHODCONST:
5268 case MONO_PATCH_INFO_METHOD:
5269 case MONO_PATCH_INFO_METHOD_JUMP:
5270 case MONO_PATCH_INFO_ICALL_ADDR:
5271 case MONO_PATCH_INFO_METHOD_RGCTX:
5272 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5273 encode_method_ref (acfg, patch_info->data.method, p, &p);
5275 case MONO_PATCH_INFO_INTERNAL_METHOD:
5276 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5277 guint32 len = strlen (patch_info->data.name);
5279 encode_value (len, p, &p);
5281 memcpy (p, patch_info->data.name, len);
5286 case MONO_PATCH_INFO_LDSTR: {
5287 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5288 guint32 token = patch_info->data.token->token;
5289 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5290 encode_value (image_index, p, &p);
5291 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5294 case MONO_PATCH_INFO_RVA:
5295 case MONO_PATCH_INFO_DECLSEC:
5296 case MONO_PATCH_INFO_LDTOKEN:
5297 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5298 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5299 encode_value (patch_info->data.token->token, p, &p);
5300 encode_value (patch_info->data.token->has_context, p, &p);
5301 if (patch_info->data.token->has_context)
5302 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5304 case MONO_PATCH_INFO_EXC_NAME: {
5305 MonoClass *ex_class;
5308 mono_class_from_name (mono_defaults.exception_class->image,
5309 "System", patch_info->data.target);
5310 g_assert (ex_class);
5311 encode_klass_ref (acfg, ex_class, p, &p);
5314 case MONO_PATCH_INFO_R4:
5315 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5317 case MONO_PATCH_INFO_R8:
5318 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5319 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5321 case MONO_PATCH_INFO_VTABLE:
5322 case MONO_PATCH_INFO_CLASS:
5323 case MONO_PATCH_INFO_IID:
5324 case MONO_PATCH_INFO_ADJUSTED_IID:
5325 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5327 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5328 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5329 if (patch_info->data.del_tramp->method) {
5330 encode_value (1, p, &p);
5331 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5333 encode_value (0, p, &p);
5335 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5337 case MONO_PATCH_INFO_FIELD:
5338 case MONO_PATCH_INFO_SFLDA:
5339 encode_field_info (acfg, patch_info->data.field, p, &p);
5341 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5343 case MONO_PATCH_INFO_RGCTX_FETCH: {
5344 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5349 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5350 * reference the same method, so encode the method only once.
5352 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5354 buf2 = g_malloc (1024);
5357 encode_method_ref (acfg, entry->method, p2, &p2);
5358 g_assert (p2 - buf2 < 1024);
5360 offset = add_to_blob (acfg, buf2, p2 - buf2);
5363 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5368 encode_value (offset, p, &p);
5369 g_assert ((int)entry->info_type < 256);
5370 g_assert (entry->data->type < 256);
5371 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5372 encode_patch (acfg, entry->data, p, &p);
5375 case MONO_PATCH_INFO_MONITOR_ENTER:
5376 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5377 case MONO_PATCH_INFO_MONITOR_EXIT:
5378 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5380 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5381 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5382 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5384 case MONO_PATCH_INFO_SIGNATURE:
5385 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5387 case MONO_PATCH_INFO_TLS_OFFSET:
5388 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5390 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5391 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5392 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5394 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5395 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5398 encode_method_ref (acfg, info->method, p, &p);
5399 encode_value (info->num_entries, p, &p);
5400 for (i = 0; i < info->num_entries; ++i) {
5401 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5403 encode_value (template->info_type, p, &p);
5404 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5405 case MONO_PATCH_INFO_CLASS:
5406 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5408 case MONO_PATCH_INFO_FIELD:
5409 encode_field_info (acfg, template->data, p, &p);
5412 g_assert_not_reached ();
5418 case MONO_PATCH_INFO_LDSTR_LIT: {
5419 const char *s = patch_info->data.target;
5420 int len = strlen (s);
5422 encode_value (len, p, &p);
5423 memcpy (p, s, len + 1);
5427 case MONO_PATCH_INFO_VIRT_METHOD:
5428 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5429 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5431 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5434 g_warning ("unable to handle jump info %d", patch_info->type);
5435 g_assert_not_reached ();
5442 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5445 guint32 pindex, offset;
5446 MonoJumpInfo *patch_info;
5448 encode_value (n_patches, p, &p);
5450 for (pindex = 0; pindex < patches->len; ++pindex) {
5451 patch_info = g_ptr_array_index (patches, pindex);
5453 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5457 offset = get_got_offset (acfg, llvm, patch_info);
5458 encode_value (offset, p, &p);
5465 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5468 int pindex, buf_size, n_patches;
5470 MonoJumpInfo *patch_info;
5471 guint32 method_index;
5473 guint32 first_got_offset;
5475 method = cfg->orig_method;
5477 method_index = get_method_index (acfg, method);
5479 /* Sort relocations */
5480 patches = g_ptr_array_new ();
5481 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5482 g_ptr_array_add (patches, patch_info);
5483 g_ptr_array_sort (patches, compare_patches);
5485 first_got_offset = acfg->cfgs [method_index]->got_offset;
5487 /**********************/
5488 /* Encode method info */
5489 /**********************/
5491 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5492 p = buf = g_malloc (buf_size);
5494 if (mono_class_get_cctor (method->klass))
5495 encode_klass_ref (acfg, method->klass, p, &p);
5497 /* Not needed when loading the method */
5498 encode_value (0, p, &p);
5500 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5503 for (pindex = 0; pindex < patches->len; ++pindex) {
5504 patch_info = g_ptr_array_index (patches, pindex);
5506 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5507 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5508 patch_info->type = MONO_PATCH_INFO_NONE;
5513 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5514 /* Stored in a GOT slot initialized at module load time */
5515 patch_info->type = MONO_PATCH_INFO_NONE;
5519 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5520 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START) {
5521 /* Stored in a GOT slot initialized at module load time */
5522 patch_info->type = MONO_PATCH_INFO_NONE;
5526 if (is_plt_patch (patch_info)) {
5527 /* Calls are made through the PLT */
5528 patch_info->type = MONO_PATCH_INFO_NONE;
5536 g_assert (cfg->has_got_slots);
5538 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5540 acfg->stats.info_size += p - buf;
5542 g_assert (p - buf < buf_size);
5544 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5549 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5551 guint32 cache_index;
5554 /* Reuse the unwind module to canonize and store unwind info entries */
5555 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5557 /* Use +/- 1 to distinguish 0s from missing entries */
5558 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5566 * It would be easier to use assembler symbols, but the caller needs an
5569 offset = acfg->unwind_info_offset;
5570 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5571 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5574 encode_value (encoded_len, p, &p);
5576 acfg->unwind_info_offset += encoded_len + (p - buf);
5582 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5585 guint32 debug_info_size, seq_points_size;
5587 MonoMethodHeader *header;
5588 guint8 *p, *buf, *debug_info;
5589 MonoJitInfo *jinfo = cfg->jit_info;
5591 gboolean use_unwind_ops = FALSE;
5592 MonoSeqPointInfo *seq_points;
5594 code = cfg->native_code;
5595 header = cfg->header;
5597 if (!acfg->aot_opts.nodebug) {
5598 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5601 debug_info_size = 0;
5604 seq_points = cfg->seq_point_info;
5605 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5607 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5609 p = buf = g_malloc (buf_size);
5611 use_unwind_ops = cfg->unwind_ops != NULL;
5613 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);
5615 encode_value (flags, p, &p);
5617 if (use_unwind_ops) {
5618 guint32 encoded_len;
5620 guint32 unwind_desc;
5622 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5624 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5625 encode_value (unwind_desc, p, &p);
5627 encode_value (jinfo->unwind_info, p, &p);
5630 /*Encode the number of holes before the number of clauses to make decoding easier*/
5631 if (jinfo->has_try_block_holes) {
5632 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5633 encode_value (table->num_holes, p, &p);
5636 if (jinfo->has_arch_eh_info) {
5638 * In AOT mode, the code length is calculated from the address of the previous method,
5639 * which could include alignment padding, so calculating the start of the epilog as
5640 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5642 encode_value (jinfo->code_size, p, &p);
5645 /* Exception table */
5646 if (cfg->compile_llvm) {
5648 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5649 * since the information is only available to llc. Instead, we let llc save the data
5650 * into the LSDA, and read it from there at runtime.
5652 /* The assembly might be CIL stripped so emit the data ourselves */
5653 if (header->num_clauses)
5654 encode_value (header->num_clauses, p, &p);
5656 for (k = 0; k < header->num_clauses; ++k) {
5657 MonoExceptionClause *clause;
5659 clause = &header->clauses [k];
5661 encode_value (clause->flags, p, &p);
5662 if (clause->data.catch_class) {
5663 encode_value (1, p, &p);
5664 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5666 encode_value (0, p, &p);
5669 /* Emit a list of nesting clauses */
5670 for (i = 0; i < header->num_clauses; ++i) {
5672 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5674 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5676 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5677 encode_value (i, p, &p);
5679 encode_value (-1, p, &p);
5682 if (jinfo->num_clauses)
5683 encode_value (jinfo->num_clauses, p, &p);
5685 for (k = 0; k < jinfo->num_clauses; ++k) {
5686 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5688 encode_value (ei->flags, p, &p);
5689 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5690 /* Not used for catch clauses */
5691 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5692 encode_value (ei->exvar_offset, p, &p);
5694 encode_value (ei->exvar_offset, p, &p);
5697 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5698 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5700 if (ei->data.catch_class) {
5704 buf2 = g_malloc (4096);
5706 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5708 g_assert (len < 4096);
5709 encode_value (len, p, &p);
5710 memcpy (p, buf2, len);
5714 encode_value (0, p, &p);
5718 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5719 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5720 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5724 if (jinfo->has_try_block_holes) {
5725 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5726 for (i = 0; i < table->num_holes; ++i) {
5727 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5728 encode_value (hole->clause, p, &p);
5729 encode_value (hole->length, p, &p);
5730 encode_value (hole->offset, p, &p);
5734 if (jinfo->has_arch_eh_info) {
5735 MonoArchEHJitInfo *eh_info;
5737 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5738 encode_value (eh_info->stack_size, p, &p);
5739 encode_value (eh_info->epilog_size, p, &p);
5742 if (jinfo->has_generic_jit_info) {
5743 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5744 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5748 encode_value (gi->nlocs, p, &p);
5750 for (i = 0; i < gi->nlocs; ++i) {
5751 MonoDwarfLocListEntry *entry = &gi->locations [i];
5753 encode_value (entry->is_reg ? 1 : 0, p, &p);
5754 encode_value (entry->reg, p, &p);
5756 encode_value (entry->offset, p, &p);
5758 g_assert (entry->from == 0);
5760 encode_value (entry->from, p, &p);
5761 encode_value (entry->to, p, &p);
5764 if (!cfg->compile_llvm) {
5765 encode_value (gi->has_this ? 1 : 0, p, &p);
5766 encode_value (gi->this_reg, p, &p);
5767 encode_value (gi->this_offset, p, &p);
5772 * Need to encode jinfo->method too, since it is not equal to 'method'
5773 * when using generic sharing.
5775 buf2 = g_malloc (4096);
5777 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5779 g_assert (len < 4096);
5780 encode_value (len, p, &p);
5781 memcpy (p, buf2, len);
5785 if (gsctx && gsctx->is_gsharedvt) {
5786 encode_value (1, p, &p);
5788 encode_value (0, p, &p);
5792 if (seq_points_size)
5793 p += mono_seq_point_info_write (seq_points, p);
5795 g_assert (debug_info_size < buf_size);
5797 encode_value (debug_info_size, p, &p);
5798 if (debug_info_size) {
5799 memcpy (p, debug_info, debug_info_size);
5800 p += debug_info_size;
5801 g_free (debug_info);
5806 encode_value (cfg->gc_map_size, p, &p);
5807 /* The GC map requires 4 bytes of alignment */
5808 while ((gsize)p % 4)
5810 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5811 p += cfg->gc_map_size;
5814 acfg->stats.ex_info_size += p - buf;
5816 g_assert (p - buf < buf_size);
5819 /* The GC Map requires 4 byte alignment */
5820 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5825 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5828 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5830 int i, buf_size, res;
5831 gboolean no_special_static, cant_encode;
5832 gpointer iter = NULL;
5835 mono_error_cleanup (&error);
5839 p = buf = g_malloc (buf_size);
5841 /* Mark as unusable */
5842 encode_value (-1, p, &p);
5844 res = add_to_blob (acfg, buf, p - buf);
5850 buf_size = 10240 + (klass->vtable_size * 16);
5851 p = buf = g_malloc (buf_size);
5855 mono_class_init (klass);
5857 mono_class_get_nested_types (klass, &iter);
5858 g_assert (klass->nested_classes_inited);
5860 mono_class_setup_vtable (klass);
5863 * Emit all the information which is required for creating vtables so
5864 * the runtime does not need to create the MonoMethod structures which
5865 * take up a lot of space.
5868 no_special_static = !mono_class_has_special_static_fields (klass);
5870 /* Check whenever we have enough info to encode the vtable */
5871 cant_encode = FALSE;
5872 for (i = 0; i < klass->vtable_size; ++i) {
5873 MonoMethod *cm = klass->vtable [i];
5875 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5879 mono_class_has_finalizer (klass);
5881 if (klass->generic_container || cant_encode) {
5882 encode_value (-1, p, &p);
5884 encode_value (klass->vtable_size, p, &p);
5885 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);
5886 if (klass->has_cctor)
5887 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5888 if (klass->has_finalize)
5889 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5891 encode_value (klass->instance_size, p, &p);
5892 encode_value (mono_class_data_size (klass), p, &p);
5893 encode_value (klass->packing_size, p, &p);
5894 encode_value (klass->min_align, p, &p);
5896 for (i = 0; i < klass->vtable_size; ++i) {
5897 MonoMethod *cm = klass->vtable [i];
5900 encode_method_ref (acfg, cm, p, &p);
5902 encode_value (0, p, &p);
5906 acfg->stats.class_info_size += p - buf;
5908 g_assert (p - buf < buf_size);
5909 res = add_to_blob (acfg, buf, p - buf);
5916 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5918 char *debug_sym = NULL;
5921 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5922 /* Need to add a prefix to create unique symbols */
5923 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5925 prefix = g_strdup ("plt_");
5929 case MONO_PATCH_INFO_METHOD:
5930 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5932 case MONO_PATCH_INFO_INTERNAL_METHOD:
5933 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5935 case MONO_PATCH_INFO_RGCTX_FETCH:
5936 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5938 case MONO_PATCH_INFO_ICALL_ADDR: {
5939 char *s = get_debug_sym (ji->data.method, "", cache);
5941 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5945 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5946 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5954 return sanitize_symbol (acfg, debug_sym);
5958 * Calls made from AOTed code are routed through a table of jumps similar to the
5959 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5960 * control to the AOT runtime through a trampoline.
5963 emit_plt (MonoAotCompile *acfg)
5969 sprintf (symbol, "plt");
5971 emit_section_change (acfg, ".text", 0);
5972 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5973 emit_info_symbol (acfg, symbol);
5974 emit_label (acfg, acfg->plt_symbol);
5976 for (i = 0; i < acfg->plt_offset; ++i) {
5977 char *debug_sym = NULL;
5978 MonoPltEntry *plt_entry = NULL;
5982 * The first plt entry is unused.
5986 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5988 debug_sym = plt_entry->debug_sym;
5990 if (acfg->thumb_mixed && !plt_entry->jit_used)
5991 /* Emit only a thumb version */
5994 /* Skip plt entries not actually called */
5995 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5998 if (acfg->llvm && !acfg->thumb_mixed) {
5999 emit_label (acfg, plt_entry->llvm_symbol);
6001 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6002 #if defined(TARGET_MACH)
6003 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6009 if (acfg->need_no_dead_strip) {
6010 emit_unset_mode (acfg);
6011 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6013 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6014 emit_label (acfg, debug_sym);
6017 emit_label (acfg, plt_entry->symbol);
6019 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6022 emit_symbol_size (acfg, debug_sym, ".");
6025 if (acfg->thumb_mixed) {
6026 /* Make sure the ARM symbols don't alias the thumb ones */
6027 emit_zero_bytes (acfg, 16);
6030 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6033 for (i = 0; i < acfg->plt_offset; ++i) {
6034 char *debug_sym = NULL;
6035 MonoPltEntry *plt_entry = NULL;
6040 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6042 /* Skip plt entries not actually called by LLVM code */
6043 if (!plt_entry->llvm_used)
6046 if (acfg->aot_opts.write_symbols) {
6047 if (plt_entry->debug_sym)
6048 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6052 #if defined(TARGET_MACH)
6053 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6054 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6056 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6057 emit_label (acfg, debug_sym);
6059 fprintf (acfg->fp, "\n.thumb_func\n");
6061 emit_label (acfg, plt_entry->llvm_symbol);
6064 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6066 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6069 emit_symbol_size (acfg, debug_sym, ".");
6075 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6077 sprintf (symbol, "plt_end");
6078 emit_info_symbol (acfg, symbol);
6082 * emit_trampoline_full:
6084 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6085 * create_jit_info_for_trampoline ().
6087 static G_GNUC_UNUSED void
6088 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6090 char start_symbol [256];
6091 char end_symbol [256];
6093 guint32 buf_size, info_offset;
6094 MonoJumpInfo *patch_info;
6107 code_size = info->code_size;
6109 unwind_ops = info->unwind_ops;
6111 #ifdef __native_client_codegen__
6112 mono_nacl_fix_patches (code, ji);
6117 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6119 emit_section_change (acfg, ".text", 0);
6120 emit_global (acfg, start_symbol, TRUE);
6121 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6122 emit_label (acfg, start_symbol);
6124 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6125 emit_label (acfg, symbol);
6128 * The code should access everything through the GOT, so we pass
6131 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6133 emit_symbol_size (acfg, start_symbol, ".");
6136 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6137 emit_label (acfg, end_symbol);
6142 /* Sort relocations */
6143 patches = g_ptr_array_new ();
6144 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6145 if (patch_info->type != MONO_PATCH_INFO_NONE)
6146 g_ptr_array_add (patches, patch_info);
6147 g_ptr_array_sort (patches, compare_patches);
6149 buf_size = patches->len * 128 + 128;
6150 buf = g_malloc (buf_size);
6153 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6154 g_assert (p - buf < buf_size);
6156 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6158 info_offset = add_to_blob (acfg, buf, p - buf);
6160 emit_section_change (acfg, RODATA_SECT, 0);
6161 emit_global (acfg, symbol, FALSE);
6162 emit_label (acfg, symbol);
6164 emit_int32 (acfg, info_offset);
6168 guint32 encoded_len;
6172 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6174 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6175 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6178 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6179 emit_int32 (acfg, uw_offset);
6182 /* Emit debug info */
6186 sprintf (symbol, "%s", name);
6187 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6190 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6194 static G_GNUC_UNUSED void
6195 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6197 emit_trampoline_full (acfg, got_offset, info, FALSE);
6201 emit_trampolines (MonoAotCompile *acfg)
6204 char end_symbol [256];
6205 int i, tramp_got_offset;
6206 MonoAotTrampoline ntype;
6207 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6211 if (!mono_aot_mode_is_full (&acfg->aot_opts))
6214 g_assert (acfg->image->assembly);
6216 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6217 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6218 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6219 MonoTrampInfo *info;
6222 * Emit the generic trampolines.
6224 * We could save some code by treating the generic trampolines as a wrapper
6225 * method, but that approach has its own complexities, so we choose the simpler
6228 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6229 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6230 #ifdef DISABLE_REMOTING
6231 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6234 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6235 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6238 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6239 emit_trampoline (acfg, acfg->got_offset, info);
6242 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6243 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6244 emit_trampoline (acfg, acfg->got_offset, info);
6245 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6246 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6247 emit_trampoline (acfg, acfg->got_offset, info);
6249 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6250 emit_trampoline (acfg, acfg->got_offset, info);
6253 /* Emit the exception related code pieces */
6254 mono_arch_get_restore_context (&info, TRUE);
6255 emit_trampoline (acfg, acfg->got_offset, info);
6256 mono_arch_get_call_filter (&info, TRUE);
6257 emit_trampoline (acfg, acfg->got_offset, info);
6258 mono_arch_get_throw_exception (&info, TRUE);
6259 emit_trampoline (acfg, acfg->got_offset, info);
6260 mono_arch_get_rethrow_exception (&info, TRUE);
6261 emit_trampoline (acfg, acfg->got_offset, info);
6262 mono_arch_get_throw_corlib_exception (&info, TRUE);
6263 emit_trampoline (acfg, acfg->got_offset, info);
6265 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6266 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6267 emit_trampoline (acfg, acfg->got_offset, info);
6268 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6269 emit_trampoline (acfg, acfg->got_offset, info);
6272 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6273 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6275 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6277 /* Create a separate out trampoline for more information in stack traces */
6278 info->name = g_strdup ("gsharedvt_out_trampoline");
6279 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6283 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6285 GSList *l = mono_arch_get_trampolines (TRUE);
6288 MonoTrampInfo *info = l->data;
6290 emit_trampoline (acfg, acfg->got_offset, info);
6296 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6299 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6300 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6301 emit_trampoline (acfg, acfg->got_offset, info);
6303 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6304 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6305 emit_trampoline (acfg, acfg->got_offset, info);
6308 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6309 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6310 emit_trampoline (acfg, acfg->got_offset, info);
6316 /* delegate_invoke_impl trampolines */
6317 l = mono_arch_get_delegate_invoke_impls ();
6319 MonoTrampInfo *info = l->data;
6321 emit_trampoline (acfg, acfg->got_offset, info);
6326 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6328 /* Emit trampolines which are numerous */
6331 * These include the following:
6332 * - specific trampolines
6333 * - static rgctx invoke trampolines
6335 * These trampolines have the same code, they are parameterized by GOT
6337 * They are defined in this file, in the arch_... routines instead of
6338 * in tramp-<ARCH>.c, since it is easier to do it this way.
6342 * When running in aot-only mode, we can't create specific trampolines at
6343 * runtime, so we create a few, and save them in the AOT file.
6344 * Normal trampolines embed their argument as a literal inside the
6345 * trampoline code, we can't do that here, so instead we embed an offset
6346 * which needs to be added to the trampoline address to get the address of
6347 * the GOT slot which contains the argument value.
6348 * The generated trampolines jump to the generic trampolines using another
6349 * GOT slot, which will be setup by the AOT loader to point to the
6350 * generic trampoline code of the given type.
6354 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6358 emit_section_change (acfg, ".text", 0);
6360 tramp_got_offset = acfg->got_offset;
6362 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6364 case MONO_AOT_TRAMP_SPECIFIC:
6365 sprintf (symbol, "specific_trampolines");
6367 case MONO_AOT_TRAMP_STATIC_RGCTX:
6368 sprintf (symbol, "static_rgctx_trampolines");
6370 case MONO_AOT_TRAMP_IMT_THUNK:
6371 sprintf (symbol, "imt_thunks");
6373 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6374 sprintf (symbol, "gsharedvt_arg_trampolines");
6377 g_assert_not_reached ();
6380 sprintf (end_symbol, "%s_e", symbol);
6382 if (acfg->aot_opts.write_symbols)
6383 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6385 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6386 emit_info_symbol (acfg, symbol);
6388 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6390 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6394 case MONO_AOT_TRAMP_SPECIFIC:
6395 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6396 tramp_got_offset += 2;
6398 case MONO_AOT_TRAMP_STATIC_RGCTX:
6399 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6400 tramp_got_offset += 2;
6402 case MONO_AOT_TRAMP_IMT_THUNK:
6403 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6404 tramp_got_offset += 1;
6406 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6407 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6408 tramp_got_offset += 2;
6411 g_assert_not_reached ();
6413 #ifdef __native_client_codegen__
6414 /* align to avoid 32-byte boundary crossings */
6415 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6418 if (!acfg->trampoline_size [ntype]) {
6419 g_assert (tramp_size);
6420 acfg->trampoline_size [ntype] = tramp_size;
6424 emit_label (acfg, end_symbol);
6425 emit_int32 (acfg, 0);
6428 arch_emit_specific_trampoline_pages (acfg);
6430 /* Reserve some entries at the end of the GOT for our use */
6431 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6434 acfg->got_offset += acfg->num_trampoline_got_entries;
6438 str_begins_with (const char *str1, const char *str2)
6440 int len = strlen (str2);
6441 return strncmp (str1, str2, len) == 0;
6445 mono_aot_readonly_field_override (MonoClassField *field)
6448 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6449 char *p = rdv->name;
6451 len = strlen (field->parent->name_space);
6452 if (strncmp (p, field->parent->name_space, len))
6457 len = strlen (field->parent->name);
6458 if (strncmp (p, field->parent->name, len))
6463 if (strcmp (p, field->name))
6465 switch (rdv->type) {
6467 return &rdv->value.i1;
6469 return &rdv->value.i2;
6471 return &rdv->value.i4;
6480 add_readonly_value (MonoAotOptions *opts, const char *val)
6485 /* the format of val is:
6486 * namespace.typename.fieldname=type/value
6487 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6489 fval = strrchr (val, '/');
6491 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6494 tval = strrchr (val, '=');
6496 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6499 rdv = g_new0 (ReadOnlyValue, 1);
6500 rdv->name = g_malloc0 (tval - val + 1);
6501 memcpy (rdv->name, val, tval - val);
6504 if (strncmp (tval, "i1", 2) == 0) {
6505 rdv->value.i1 = atoi (fval);
6506 rdv->type = MONO_TYPE_I1;
6507 } else if (strncmp (tval, "i2", 2) == 0) {
6508 rdv->value.i2 = atoi (fval);
6509 rdv->type = MONO_TYPE_I2;
6510 } else if (strncmp (tval, "i4", 2) == 0) {
6511 rdv->value.i4 = atoi (fval);
6512 rdv->type = MONO_TYPE_I4;
6514 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6517 rdv->next = readonly_values;
6518 readonly_values = rdv;
6522 clean_path (gchar * path)
6527 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6530 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6537 mono_aot_split_options (const char *aot_options)
6539 enum MonoAotOptionState {
6540 MONO_AOT_OPTION_STATE_DEFAULT,
6541 MONO_AOT_OPTION_STATE_STRING,
6542 MONO_AOT_OPTION_STATE_ESCAPE,
6545 GPtrArray *args = g_ptr_array_new ();
6546 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6547 gchar const *opt_start = aot_options;
6548 gboolean end_of_string = FALSE;
6551 g_return_val_if_fail (aot_options != NULL, NULL);
6553 while ((cur = *aot_options) != '\0') {
6554 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6559 // If we find a quote, then if we're in the default case then
6560 // it means we've found the start of a string, if not then it
6561 // means we've found the end of the string and should switch
6562 // back to the default case.
6564 case MONO_AOT_OPTION_STATE_DEFAULT:
6565 state = MONO_AOT_OPTION_STATE_STRING;
6567 case MONO_AOT_OPTION_STATE_STRING:
6568 state = MONO_AOT_OPTION_STATE_DEFAULT;
6570 case MONO_AOT_OPTION_STATE_ESCAPE:
6571 g_assert_not_reached ();
6576 // If we've found an escaping operator, then this means we
6577 // should not process the next character if inside a string.
6578 if (state == MONO_AOT_OPTION_STATE_STRING)
6579 state = MONO_AOT_OPTION_STATE_ESCAPE;
6582 // If we're in the default state then this means we've found
6583 // an option, store it for later processing.
6584 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6591 // If the next character is end of string, then process the last option.
6592 if (*(aot_options) == '\0') {
6593 end_of_string = TRUE;
6599 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6600 opt_start = ++aot_options;
6610 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6614 args = mono_aot_split_options (aot_options ? aot_options : "");
6615 for (int i = 0; i < args->len; ++i) {
6616 const char *arg = g_ptr_array_index (args, i);
6618 if (str_begins_with (arg, "outfile=")) {
6619 opts->outfile = g_strdup (arg + strlen ("outfile="));
6620 } else if (str_begins_with (arg, "llvm-outfile=")) {
6621 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6622 } else if (str_begins_with (arg, "temp-path=")) {
6623 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6624 } else if (str_begins_with (arg, "save-temps")) {
6625 opts->save_temps = TRUE;
6626 } else if (str_begins_with (arg, "keep-temps")) {
6627 opts->save_temps = TRUE;
6628 } else if (str_begins_with (arg, "write-symbols")) {
6629 opts->write_symbols = TRUE;
6630 } else if (str_begins_with (arg, "no-write-symbols")) {
6631 opts->write_symbols = FALSE;
6632 } else if (str_begins_with (arg, "metadata-only")) {
6633 opts->metadata_only = TRUE;
6634 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6635 opts->bind_to_runtime_version = TRUE;
6636 } else if (str_begins_with (arg, "full")) {
6637 opts->mode = MONO_AOT_MODE_FULL;
6638 } else if (str_begins_with (arg, "hybrid")) {
6639 opts->mode = MONO_AOT_MODE_HYBRID;
6640 } else if (str_begins_with (arg, "threads=")) {
6641 opts->nthreads = atoi (arg + strlen ("threads="));
6642 } else if (str_begins_with (arg, "static")) {
6643 opts->static_link = TRUE;
6644 opts->no_dlsym = TRUE;
6645 } else if (str_begins_with (arg, "asmonly")) {
6646 opts->asm_only = TRUE;
6647 } else if (str_begins_with (arg, "asmwriter")) {
6648 opts->asm_writer = TRUE;
6649 } else if (str_begins_with (arg, "nodebug")) {
6650 opts->nodebug = TRUE;
6651 } else if (str_begins_with (arg, "dwarfdebug")) {
6652 opts->dwarf_debug = TRUE;
6653 } else if (str_begins_with (arg, "nopagetrampolines")) {
6654 opts->use_trampolines_page = FALSE;
6655 } else if (str_begins_with (arg, "ntrampolines=")) {
6656 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6657 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6658 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6659 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6660 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6661 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6662 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6663 } else if (str_begins_with (arg, "autoreg")) {
6664 opts->autoreg = TRUE;
6665 } else if (str_begins_with (arg, "tool-prefix=")) {
6666 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6667 } else if (str_begins_with (arg, "ld-flags=")) {
6668 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6669 } else if (str_begins_with (arg, "soft-debug")) {
6670 opts->soft_debug = TRUE;
6671 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6672 opts->gen_seq_points_file = TRUE;
6673 } else if (str_begins_with (arg, "direct-pinvoke")) {
6674 opts->direct_pinvoke = TRUE;
6675 } else if (str_begins_with (arg, "direct-icalls")) {
6676 opts->direct_icalls = TRUE;
6677 } else if (str_begins_with (arg, "no-direct-calls")) {
6678 opts->no_direct_calls = TRUE;
6679 } else if (str_begins_with (arg, "print-skipped")) {
6680 opts->print_skipped_methods = TRUE;
6681 } else if (str_begins_with (arg, "stats")) {
6683 } else if (str_begins_with (arg, "no-instances")) {
6684 opts->no_instances = TRUE;
6685 } else if (str_begins_with (arg, "log-generics")) {
6686 opts->log_generics = TRUE;
6687 } else if (str_begins_with (arg, "log-instances=")) {
6688 opts->log_instances = TRUE;
6689 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6690 } else if (str_begins_with (arg, "log-instances")) {
6691 opts->log_instances = TRUE;
6692 } else if (str_begins_with (arg, "internal-logfile=")) {
6693 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6694 } else if (str_begins_with (arg, "mtriple=")) {
6695 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6696 } else if (str_begins_with (arg, "llvm-path=")) {
6697 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6698 } else if (!strcmp (arg, "llvm")) {
6700 } else if (str_begins_with (arg, "readonly-value=")) {
6701 add_readonly_value (opts, arg + strlen ("readonly-value="));
6702 } else if (str_begins_with (arg, "info")) {
6703 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6705 } else if (str_begins_with (arg, "gc-maps")) {
6706 mini_gc_enable_gc_maps_for_aot ();
6707 } else if (str_begins_with (arg, "dump")) {
6708 opts->dump_json = TRUE;
6709 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6710 printf ("Supported options for --aot:\n");
6711 printf (" outfile=\n");
6712 printf (" llvm-outfile=\n");
6713 printf (" llvm-path=\n");
6714 printf (" temp-path=\n");
6715 printf (" save-temps\n");
6716 printf (" keep-temps\n");
6717 printf (" write-symbols\n");
6718 printf (" metadata-only\n");
6719 printf (" bind-to-runtime-version\n");
6721 printf (" threads=\n");
6722 printf (" static\n");
6723 printf (" asmonly\n");
6724 printf (" asmwriter\n");
6725 printf (" nodebug\n");
6726 printf (" dwarfdebug\n");
6727 printf (" ntrampolines=\n");
6728 printf (" nrgctx-trampolines=\n");
6729 printf (" nimt-trampolines=\n");
6730 printf (" ngsharedvt-trampolines=\n");
6731 printf (" autoreg\n");
6732 printf (" tool-prefix=\n");
6733 printf (" readonly-value=\n");
6734 printf (" soft-debug\n");
6735 printf (" gen-seq-points-file\n");
6736 printf (" gc-maps\n");
6737 printf (" print-skipped\n");
6738 printf (" no-instances\n");
6739 printf (" stats\n");
6742 printf (" help/?\n");
6745 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6749 g_free ((gpointer) arg);
6752 if (opts->use_trampolines_page) {
6753 opts->ntrampolines = 0;
6754 opts->nrgctx_trampolines = 0;
6755 opts->nimt_trampolines = 0;
6756 opts->ngsharedvt_arg_trampolines = 0;
6759 g_ptr_array_free (args, /*free_seg=*/TRUE);
6763 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6765 MonoMethod *method = (MonoMethod*)key;
6766 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6767 MonoAotCompile *acfg = user_data;
6768 MonoJumpInfoToken *new_ji;
6770 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6771 new_ji->image = ji->image;
6772 new_ji->token = ji->token;
6773 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6777 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6779 if (klass->type_token)
6781 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6784 return can_encode_class (acfg, klass->element_class);
6789 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6791 if (method->wrapper_type) {
6792 switch (method->wrapper_type) {
6793 case MONO_WRAPPER_NONE:
6794 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6795 case MONO_WRAPPER_XDOMAIN_INVOKE:
6796 case MONO_WRAPPER_STFLD:
6797 case MONO_WRAPPER_LDFLD:
6798 case MONO_WRAPPER_LDFLDA:
6799 case MONO_WRAPPER_LDFLD_REMOTE:
6800 case MONO_WRAPPER_STFLD_REMOTE:
6801 case MONO_WRAPPER_STELEMREF:
6802 case MONO_WRAPPER_ISINST:
6803 case MONO_WRAPPER_PROXY_ISINST:
6804 case MONO_WRAPPER_ALLOC:
6805 case MONO_WRAPPER_REMOTING_INVOKE:
6806 case MONO_WRAPPER_UNKNOWN:
6807 case MONO_WRAPPER_WRITE_BARRIER:
6808 case MONO_WRAPPER_DELEGATE_INVOKE:
6809 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6810 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6811 case MONO_WRAPPER_SYNCHRONIZED:
6813 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6814 case MONO_WRAPPER_CASTCLASS: {
6815 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6824 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6828 if (!method->token) {
6829 /* The method is part of a constructed type like Int[,].Set (). */
6830 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6831 if (method->klass->rank)
6841 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6843 switch (patch_info->type) {
6844 case MONO_PATCH_INFO_METHOD:
6845 case MONO_PATCH_INFO_METHODCONST:
6846 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6847 MonoMethod *method = patch_info->data.method;
6849 return can_encode_method (acfg, method);
6851 case MONO_PATCH_INFO_VTABLE:
6852 case MONO_PATCH_INFO_CLASS:
6853 case MONO_PATCH_INFO_IID:
6854 case MONO_PATCH_INFO_ADJUSTED_IID:
6855 if (!can_encode_class (acfg, patch_info->data.klass)) {
6856 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6860 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6861 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6862 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6867 case MONO_PATCH_INFO_RGCTX_FETCH: {
6868 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6870 if (!can_encode_method (acfg, entry->method))
6872 if (!can_encode_patch (acfg, entry->data))
6886 * AOT compile a given method.
6887 * This function might be called by multiple threads, so it must be thread-safe.
6890 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6893 MonoJumpInfo *patch_info;
6896 MonoMethod *wrapped;
6899 if (acfg->aot_opts.metadata_only)
6902 mono_acfg_lock (acfg);
6903 index = get_method_index (acfg, method);
6904 mono_acfg_unlock (acfg);
6906 /* fixme: maybe we can also precompile wrapper methods */
6907 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6908 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6909 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6910 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6914 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6917 wrapped = mono_marshal_method_from_wrapper (method);
6918 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6919 // FIXME: The wrapper should be generic too, but it is not
6922 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6925 InterlockedIncrement (&acfg->stats.mcount);
6928 if (method->is_generic || method->klass->generic_container) {
6929 InterlockedIncrement (&acfg->stats.genericcount);
6934 //acfg->aot_opts.print_skipped_methods = TRUE;
6937 * Since these methods are the only ones which are compiled with
6938 * AOT support, and they are not used by runtime startup/shutdown code,
6939 * the runtime will not see AOT methods during AOT compilation,so it
6940 * does not need to support them by creating a fake GOT etc.
6942 flags = JIT_FLAG_AOT;
6943 if (mono_aot_mode_is_full (&acfg->aot_opts))
6944 flags |= JIT_FLAG_FULL_AOT;
6946 flags |= JIT_FLAG_LLVM;
6947 if (acfg->aot_opts.no_direct_calls)
6948 flags |= JIT_FLAG_NO_DIRECT_ICALLS;
6949 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
6950 mono_loader_clear_error ();
6952 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6953 if (acfg->aot_opts.print_skipped_methods)
6954 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6955 InterlockedIncrement (&acfg->stats.genericcount);
6958 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6959 if (acfg->aot_opts.print_skipped_methods)
6960 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6961 /* Let the exception happen at runtime */
6965 if (cfg->disable_aot) {
6966 if (acfg->aot_opts.print_skipped_methods)
6967 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6968 InterlockedIncrement (&acfg->stats.ocount);
6969 mono_destroy_compile (cfg);
6972 cfg->method_index = index;
6974 /* Nullify patches which need no aot processing */
6975 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6976 switch (patch_info->type) {
6977 case MONO_PATCH_INFO_LABEL:
6978 case MONO_PATCH_INFO_BB:
6979 patch_info->type = MONO_PATCH_INFO_NONE;
6986 /* Collect method->token associations from the cfg */
6987 mono_acfg_lock (acfg);
6988 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6989 mono_acfg_unlock (acfg);
6990 g_hash_table_destroy (cfg->token_info_hash);
6991 cfg->token_info_hash = NULL;
6994 * Check for absolute addresses.
6997 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6998 switch (patch_info->type) {
6999 case MONO_PATCH_INFO_ABS:
7000 /* unable to handle this */
7009 if (acfg->aot_opts.print_skipped_methods)
7010 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
7011 InterlockedIncrement (&acfg->stats.abscount);
7012 mono_destroy_compile (cfg);
7016 /* Lock for the rest of the code */
7017 mono_acfg_lock (acfg);
7020 * Check for methods/klasses we can't encode.
7023 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7024 if (!can_encode_patch (acfg, patch_info))
7029 if (acfg->aot_opts.print_skipped_methods)
7030 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
7031 acfg->stats.ocount++;
7032 mono_destroy_compile (cfg);
7033 mono_acfg_unlock (acfg);
7037 if (!cfg->compile_llvm)
7038 acfg->has_jitted_code = TRUE;
7040 if (method->is_inflated && acfg->aot_opts.log_instances) {
7041 if (acfg->instances_logfile)
7042 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
7044 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
7047 /* Adds generic instances referenced by this method */
7049 * The depth is used to avoid infinite loops when generic virtual recursion is
7052 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7053 if (!acfg->aot_opts.no_instances && depth < 32) {
7054 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7055 switch (patch_info->type) {
7056 case MONO_PATCH_INFO_RGCTX_FETCH:
7057 case MONO_PATCH_INFO_METHOD: {
7058 MonoMethod *m = NULL;
7060 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH) {
7061 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7063 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7064 m = e->data->data.method;
7066 m = patch_info->data.method;
7071 if (m->is_inflated) {
7072 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7073 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7074 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7075 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7076 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7077 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7079 add_extra_method_with_depth (acfg, m, depth + 1);
7080 add_types_from_method_header (acfg, m);
7083 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7085 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7086 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7088 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7089 add_extra_method_with_depth (acfg, m, depth + 1);
7093 case MONO_PATCH_INFO_VTABLE: {
7094 MonoClass *klass = patch_info->data.klass;
7096 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7097 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7100 case MONO_PATCH_INFO_SFLDA: {
7101 MonoClass *klass = patch_info->data.field->parent;
7103 /* The .cctor needs to run at runtime. */
7104 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7105 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7114 /* Determine whenever the method has GOT slots */
7115 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7116 switch (patch_info->type) {
7117 case MONO_PATCH_INFO_GOT_OFFSET:
7118 case MONO_PATCH_INFO_NONE:
7119 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7120 case MONO_PATCH_INFO_GC_NURSERY_START:
7122 case MONO_PATCH_INFO_IMAGE:
7123 /* The assembly is stored in GOT slot 0 */
7124 if (patch_info->data.image != acfg->image)
7125 cfg->has_got_slots = TRUE;
7128 if (!is_plt_patch (patch_info))
7129 cfg->has_got_slots = TRUE;
7134 if (!cfg->has_got_slots)
7135 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7138 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7140 /* Make a copy of the patch info which is in the mempool */
7142 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7144 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7145 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7148 patches = new_patch_info;
7150 patches_end->next = new_patch_info;
7151 patches_end = new_patch_info;
7153 cfg->patch_info = patches;
7155 /* Make a copy of the unwind info */
7157 GSList *l, *unwind_ops;
7161 for (l = cfg->unwind_ops; l; l = l->next) {
7162 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7163 memcpy (op, l->data, sizeof (MonoUnwindOp));
7164 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7166 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7168 /* Make a copy of the argument/local info */
7170 MonoInst **args, **locals;
7171 MonoMethodSignature *sig;
7172 MonoMethodHeader *header;
7175 sig = mono_method_signature (method);
7176 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7177 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7178 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7179 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7183 header = mono_method_get_header (method);
7184 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7185 for (i = 0; i < header->num_locals; ++i) {
7186 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7187 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7189 cfg->locals = locals;
7192 /* Free some fields used by cfg to conserve memory */
7193 mono_mempool_destroy (cfg->mempool);
7194 cfg->mempool = NULL;
7195 g_free (cfg->varinfo);
7196 cfg->varinfo = NULL;
7200 mono_regstate_free (cfg->rs);
7204 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7206 while (index >= acfg->cfgs_size) {
7207 MonoCompile **new_cfgs;
7210 new_size = acfg->cfgs_size * 2;
7211 new_cfgs = g_new0 (MonoCompile*, new_size);
7212 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7213 g_free (acfg->cfgs);
7214 acfg->cfgs = new_cfgs;
7215 acfg->cfgs_size = new_size;
7217 acfg->cfgs [index] = cfg;
7219 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7222 if (cfg->orig_method->wrapper_type)
7223 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7226 mono_acfg_unlock (acfg);
7228 InterlockedIncrement (&acfg->stats.ccount);
7232 compile_thread_main (gpointer *user_data)
7234 MonoDomain *domain = user_data [0];
7235 MonoAotCompile *acfg = user_data [1];
7236 GPtrArray *methods = user_data [2];
7239 mono_thread_attach (domain);
7241 for (i = 0; i < methods->len; ++i)
7242 compile_method (acfg, g_ptr_array_index (methods, i));
7246 load_profile_files (MonoAotCompile *acfg)
7250 int file_index, res, method_index, i;
7253 GList *unordered, *l;
7258 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7260 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7265 infile = fopen (tmp, "r");
7268 printf ("Using profile data file '%s'\n", tmp);
7273 res = fscanf (infile, "%32s\n", ver);
7274 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7275 printf ("Profile file has wrong version or invalid.\n");
7282 MonoMethodDesc *desc;
7285 if (fgets (name, 1023, infile) == NULL)
7288 /* Kill the newline */
7289 if (strlen (name) > 0)
7290 name [strlen (name) - 1] = '\0';
7292 desc = mono_method_desc_new (name, TRUE);
7294 method = mono_method_desc_search_in_image (desc, acfg->image);
7296 if (method && mono_method_get_token (method)) {
7297 token = mono_method_get_token (method);
7298 method_index = mono_metadata_token_index (token) - 1;
7301 for (i = 0; i < acfg->method_order->len; ++i) {
7302 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7308 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7310 //printf ("No method found matching '%s'.\n", name);
7316 /* Add missing methods */
7318 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7320 for (i = 0; i < acfg->method_order->len; ++i) {
7321 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7327 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7329 unordered = g_list_reverse (unordered);
7330 for (l = unordered; l; l = l->next)
7331 g_ptr_array_add (acfg->method_order, l->data);
7334 /* Used by the LLVM backend */
7336 mono_aot_get_got_offset (MonoJumpInfo *ji)
7338 return get_got_offset (llvm_acfg, TRUE, ji);
7342 mono_aot_get_method_name (MonoCompile *cfg)
7344 if (llvm_acfg->aot_opts.static_link)
7345 /* Include the assembly name too to avoid duplicate symbol errors */
7346 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7348 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7352 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7354 return is_direct_callable (llvm_acfg, NULL, patch_info);
7358 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7360 MonoPltEntry *plt_entry;
7362 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7363 plt_entry->llvm_used = FALSE;
7367 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7369 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7370 MonoPltEntry *plt_entry;
7371 const char *sym = NULL;
7374 ji->data.target = data;
7376 if (!can_encode_patch (llvm_acfg, ji))
7379 if (llvm_acfg->aot_opts.direct_icalls) {
7380 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7381 /* Call to a C function implementing a jit icall */
7382 sym = mono_lookup_jit_icall_symbol (data);
7383 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7384 MonoMethod *method = (gpointer)data;
7385 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7386 sym = mono_lookup_icall_symbol (method);
7389 return g_strdup (sym);
7392 plt_entry = get_plt_entry (llvm_acfg, ji);
7393 plt_entry->llvm_used = TRUE;
7395 #if defined(TARGET_MACH)
7396 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7398 return g_strdup_printf (plt_entry->llvm_symbol);
7403 mono_aot_get_method_index (MonoMethod *method)
7405 g_assert (llvm_acfg);
7406 return get_method_index (llvm_acfg, method);
7410 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7414 mono_acfg_lock (llvm_acfg);
7415 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7416 mono_acfg_unlock (llvm_acfg);
7422 execute_system (const char * command)
7427 // We need an extra set of quotes around the whole command to properly handle commands
7428 // with spaces since internally the command is called through "cmd /c.
7429 command = g_strdup_printf ("\"%s\"", command);
7431 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7432 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7433 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7434 status = _wsystem (wstr);
7438 #elif defined (HAVE_SYSTEM)
7439 status = system (command);
7441 g_assert_not_reached ();
7452 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7456 emit_llvm_file (MonoAotCompile *acfg)
7458 char *command, *opts, *tempbc, *output_fname;
7460 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7461 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7465 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7466 * a lot of time, and doesn't seem to save much space.
7467 * The following optimizations cannot be enabled:
7469 * - 'jump-threading' changes our blockaddress references to int constants.
7470 * - 'basiccg' fails because it contains:
7471 * if (CS && !isa<IntrinsicInst>(II)) {
7472 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7473 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7474 * The opt list below was produced by taking the output of:
7475 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7476 * then removing tailcallelim + the global opts.
7477 * strip-dead-prototypes deletes unused intrinsics definitions.
7479 opts = g_strdup ("-instcombine -simplifycfg");
7480 //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");
7481 /* The dse pass is disabled because of #13734 and #17616 */
7483 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7484 * // If we have no DataLayout information around, then the size of the store
7485 * // is inferrable from the pointee type. If they are the same type, then
7486 * // we know that the store is safe.
7487 * if (AA.getDataLayout() == 0 &&
7488 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7489 * return OverwriteComplete;
7490 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7492 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");
7494 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7495 aot_printf (acfg, "Executing opt: %s\n", command);
7496 if (execute_system (command) != 0)
7501 if (!acfg->llc_args)
7502 acfg->llc_args = g_string_new ("");
7504 /* Verbose asm slows down llc greatly */
7505 g_string_append (acfg->llc_args, " -asm-verbose=false");
7507 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7509 if (acfg->aot_opts.mtriple)
7510 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7512 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
7514 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7515 /* ios requires PIC code now */
7516 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7518 if (llvm_acfg->aot_opts.static_link)
7519 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7521 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7524 if (acfg->llvm_owriter) {
7525 /* Emit an object file directly */
7526 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7527 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7529 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7531 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7532 g_free (output_fname);
7534 aot_printf (acfg, "Executing llc: %s\n", command);
7536 if (execute_system (command) != 0)
7543 emit_code (MonoAotCompile *acfg)
7545 int oindex, i, prev_index;
7548 #if defined(TARGET_POWERPC64)
7549 sprintf (symbol, ".Lgot_addr");
7550 emit_section_change (acfg, ".text", 0);
7551 emit_alignment (acfg, 8);
7552 emit_label (acfg, symbol);
7553 emit_pointer (acfg, acfg->got_symbol);
7557 * This global symbol is used to compute the address of each method using the
7558 * code_offsets array. It is also used to compute the memory ranges occupied by
7559 * AOT code, so it must be equal to the address of the first emitted method.
7561 emit_section_change (acfg, ".text", 0);
7562 emit_alignment_code (acfg, 8);
7563 emit_info_symbol (acfg, "jit_code_start");
7566 * Emit some padding so the local symbol for the first method doesn't have the
7567 * same address as 'methods'.
7569 #if defined(__default_codegen__)
7570 emit_padding (acfg, 16);
7571 #elif defined(__native_client_codegen__)
7573 const int kPaddingSize = 16;
7574 guint8 pad_buffer[kPaddingSize];
7575 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7576 emit_bytes (acfg, pad_buffer, kPaddingSize);
7580 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7584 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7586 cfg = acfg->cfgs [i];
7591 method = cfg->orig_method;
7593 /* Emit unbox trampoline */
7594 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7595 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7597 emit_section_change (acfg, ".text", 0);
7598 #ifdef __native_client_codegen__
7599 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7602 if (acfg->thumb_mixed && cfg->compile_llvm) {
7603 emit_set_thumb_mode (acfg);
7604 fprintf (acfg->fp, "\n.thumb_func\n");
7607 emit_label (acfg, symbol);
7609 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7611 if (acfg->thumb_mixed && cfg->compile_llvm)
7612 emit_set_arm_mode (acfg);
7615 if (cfg->compile_llvm)
7616 acfg->stats.llvm_count ++;
7618 emit_method_code (acfg, cfg);
7621 emit_section_change (acfg, ".text", 0);
7622 emit_alignment_code (acfg, 8);
7623 emit_info_symbol (acfg, "jit_code_end");
7625 /* To distinguish it from the next symbol */
7626 emit_padding (acfg, 4);
7629 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7630 * from optimizing them away, since it doesn't see that code_offsets references them.
7631 * JITted methods don't need this since they are referenced using assembler local
7633 * FIXME: This is why write-symbols doesn't work on OSX ?
7635 if (acfg->llvm && acfg->need_no_dead_strip) {
7636 fprintf (acfg->fp, "\n");
7637 for (i = 0; i < acfg->nmethods; ++i) {
7638 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7639 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7644 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7645 * This is PIE code, and the linker can update it if needed.
7647 sprintf (symbol, "method_addresses");
7648 emit_section_change (acfg, ".text", 1);
7649 emit_alignment_code (acfg, 8);
7650 emit_info_symbol (acfg, symbol);
7651 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7652 emit_unset_mode (acfg);
7653 if (acfg->need_no_dead_strip)
7654 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7656 for (i = 0; i < acfg->nmethods; ++i) {
7657 #ifdef MONO_ARCH_AOT_SUPPORTED
7661 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7663 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7667 sprintf (symbol, "method_addresses_end");
7668 emit_label (acfg, symbol);
7671 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7672 sprintf (symbol, "unbox_trampolines");
7673 emit_section_change (acfg, RODATA_SECT, 0);
7674 emit_alignment (acfg, 8);
7675 emit_info_symbol (acfg, symbol);
7678 for (i = 0; i < acfg->nmethods; ++i) {
7683 cfg = acfg->cfgs [i];
7687 method = cfg->orig_method;
7689 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7690 index = get_method_index (acfg, method);
7692 emit_int32 (acfg, index);
7693 /* Make sure the table is sorted by index */
7694 g_assert (index > prev_index);
7698 sprintf (symbol, "unbox_trampolines_end");
7699 emit_info_symbol (acfg, symbol);
7700 emit_int32 (acfg, 0);
7702 /* Emit a separate table with the trampoline addresses/offsets */
7703 sprintf (symbol, "unbox_trampoline_addresses");
7704 emit_section_change (acfg, ".text", 0);
7705 emit_alignment_code (acfg, 8);
7706 emit_info_symbol (acfg, symbol);
7708 for (i = 0; i < acfg->nmethods; ++i) {
7713 cfg = acfg->cfgs [i];
7717 method = cfg->orig_method;
7719 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
7720 #ifdef MONO_ARCH_AOT_SUPPORTED
7723 index = get_method_index (acfg, method);
7724 sprintf (symbol, "ut_%d", index);
7726 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7730 emit_int32 (acfg, 0);
7734 emit_info (MonoAotCompile *acfg)
7739 offsets = g_new0 (gint32, acfg->nmethods);
7741 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7742 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7744 if (acfg->cfgs [i]) {
7745 emit_method_info (acfg, acfg->cfgs [i]);
7746 offsets [i] = acfg->cfgs [i]->method_info_offset;
7752 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", acfg->nmethods, 10, offsets);
7757 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7759 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7760 #define mix(a,b,c) { \
7761 a -= c; a ^= rot(c, 4); c += b; \
7762 b -= a; b ^= rot(a, 6); a += c; \
7763 c -= b; c ^= rot(b, 8); b += a; \
7764 a -= c; a ^= rot(c,16); c += b; \
7765 b -= a; b ^= rot(a,19); a += c; \
7766 c -= b; c ^= rot(b, 4); b += a; \
7768 #define final(a,b,c) { \
7769 c ^= b; c -= rot(b,14); \
7770 a ^= c; a -= rot(c,11); \
7771 b ^= a; b -= rot(a,25); \
7772 c ^= b; c -= rot(b,16); \
7773 a ^= c; a -= rot(c,4); \
7774 b ^= a; b -= rot(a,14); \
7775 c ^= b; c -= rot(b,24); \
7779 mono_aot_type_hash (MonoType *t1)
7781 guint hash = t1->type;
7783 hash |= t1->byref << 6; /* do not collide with t1->type values */
7785 case MONO_TYPE_VALUETYPE:
7786 case MONO_TYPE_CLASS:
7787 case MONO_TYPE_SZARRAY:
7788 /* check if the distribution is good enough */
7789 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7791 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7792 case MONO_TYPE_ARRAY:
7793 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7794 case MONO_TYPE_GENERICINST:
7795 return ((hash << 5) - hash) ^ 0;
7802 * mono_aot_method_hash:
7804 * Return a hash code for methods which only depends on metadata.
7807 mono_aot_method_hash (MonoMethod *method)
7809 MonoMethodSignature *sig;
7813 guint32 *hashes_start, *hashes;
7815 MonoGenericInst *class_ginst = NULL;
7816 MonoGenericInst *ginst = NULL;
7818 /* Similar to the hash in mono_method_get_imt_slot () */
7820 sig = mono_method_signature (method);
7822 if (method->klass->generic_class)
7823 class_ginst = method->klass->generic_class->context.class_inst;
7824 if (method->is_inflated)
7825 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7827 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7828 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7829 hashes = hashes_start;
7831 /* Some wrappers are assigned to random classes */
7832 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7833 klass = method->klass;
7835 klass = mono_defaults.object_class;
7837 if (!method->wrapper_type) {
7840 if (klass->generic_class)
7841 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7843 full_name = mono_type_full_name (&klass->byval_arg);
7845 hashes [0] = mono_metadata_str_hash (full_name);
7849 hashes [0] = mono_metadata_str_hash (klass->name);
7850 hashes [1] = mono_metadata_str_hash (klass->name_space);
7852 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7853 /* The method name includes a stringified pointer */
7856 hashes [2] = mono_metadata_str_hash (method->name);
7857 hashes [3] = method->wrapper_type;
7858 hashes [4] = mono_aot_type_hash (sig->ret);
7860 for (i = 0; i < sig->param_count; i++) {
7861 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7864 for (i = 0; i < class_ginst->type_argc; ++i)
7865 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7868 for (i = 0; i < ginst->type_argc; ++i)
7869 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7871 g_assert (hindex == hashes_count);
7873 /* Setup internal state */
7874 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7876 /* Handle most of the hashes */
7877 while (hashes_count > 3) {
7886 /* Handle the last 3 hashes (all the case statements fall through) */
7887 switch (hashes_count) {
7888 case 3 : c += hashes [2];
7889 case 2 : b += hashes [1];
7890 case 1 : a += hashes [0];
7892 case 0: /* nothing left to add */
7896 free (hashes_start);
7905 * mono_aot_get_array_helper_from_wrapper;
7907 * Get the helper method in Array called by an array wrapper method.
7910 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7914 MonoGenericContext ctx;
7915 MonoType *args [16];
7916 char *mname, *iname, *s, *s2, *helper_name = NULL;
7918 prefix = "System.Collections.Generic";
7919 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7920 s2 = strstr (s, "`1.");
7926 //printf ("X: %s %s\n", iname, mname);
7928 if (!strcmp (iname, "IList"))
7929 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7931 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7932 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7934 g_free (helper_name);
7937 if (m->is_generic) {
7939 memset (&ctx, 0, sizeof (ctx));
7940 args [0] = &method->klass->element_class->byval_arg;
7941 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7942 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7943 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7949 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7951 typedef struct HashEntry {
7952 guint32 key, value, index;
7953 struct HashEntry *next;
7957 * emit_extra_methods:
7959 * Emit methods which are not in the METHOD table, like wrappers.
7962 emit_extra_methods (MonoAotCompile *acfg)
7964 int i, table_size, buf_size;
7967 guint32 *info_offsets;
7970 HashEntry *entry, *new_entry;
7971 int nmethods, max_chain_length;
7974 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7976 /* Emit method info */
7978 for (i = 0; i < acfg->extra_methods->len; ++i) {
7979 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7980 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7986 p = buf = g_malloc (buf_size);
7990 method = cfg->method_to_register;
7992 encode_method_ref (acfg, method, p, &p);
7994 g_assert ((p - buf) < buf_size);
7996 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8001 * Construct a chained hash table for mapping indexes in extra_method_info to
8004 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8005 table = g_ptr_array_sized_new (table_size);
8006 for (i = 0; i < table_size; ++i)
8007 g_ptr_array_add (table, NULL);
8008 chain_lengths = g_new0 (int, table_size);
8009 max_chain_length = 0;
8010 for (i = 0; i < acfg->extra_methods->len; ++i) {
8011 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
8012 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
8018 key = info_offsets [i];
8019 value = get_method_index (acfg, method);
8021 hash = mono_aot_method_hash (method) % table_size;
8022 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
8024 chain_lengths [hash] ++;
8025 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8027 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8028 new_entry->key = key;
8029 new_entry->value = value;
8031 entry = g_ptr_array_index (table, hash);
8032 if (entry == NULL) {
8033 new_entry->index = hash;
8034 g_ptr_array_index (table, hash) = new_entry;
8037 entry = entry->next;
8039 entry->next = new_entry;
8040 new_entry->index = table->len;
8041 g_ptr_array_add (table, new_entry);
8045 //printf ("MAX: %d\n", max_chain_length);
8047 buf_size = table->len * 12 + 4;
8048 p = buf = g_malloc (buf_size);
8049 encode_int (table_size, p, &p);
8051 for (i = 0; i < table->len; ++i) {
8052 HashEntry *entry = g_ptr_array_index (table, i);
8054 if (entry == NULL) {
8055 encode_int (0, p, &p);
8056 encode_int (0, p, &p);
8057 encode_int (0, p, &p);
8059 //g_assert (entry->key > 0);
8060 encode_int (entry->key, p, &p);
8061 encode_int (entry->value, p, &p);
8063 encode_int (entry->next->index, p, &p);
8065 encode_int (0, p, &p);
8068 g_assert (p - buf <= buf_size);
8070 /* Emit the table */
8072 mono_llvm_emit_aot_data ("extra_method_table", buf, p - buf);
8074 sprintf (symbol, "extra_method_table");
8075 emit_section_change (acfg, RODATA_SECT, 0);
8076 emit_alignment (acfg, 8);
8077 emit_label (acfg, symbol);
8078 emit_bytes (acfg, buf, p - buf);
8082 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8083 * This is used by mono_aot_find_jit_info ().
8085 buf_size = acfg->extra_methods->len * 8 + 4;
8086 p = buf = g_malloc (buf_size);
8087 encode_int (acfg->extra_methods->len, p, &p);
8088 for (i = 0; i < acfg->extra_methods->len; ++i) {
8089 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
8091 encode_int (get_method_index (acfg, method), p, &p);
8092 encode_int (info_offsets [i], p, &p);
8095 mono_llvm_emit_aot_data ("extra_method_info_offsets", buf, p - buf);
8097 sprintf (symbol, "extra_method_info_offsets");
8098 emit_section_change (acfg, RODATA_SECT, 0);
8099 emit_alignment (acfg, 8);
8100 emit_label (acfg, symbol);
8101 emit_bytes (acfg, buf, p - buf);
8106 emit_exception_info (MonoAotCompile *acfg)
8110 SeqPointData sp_data;
8111 gboolean seq_points_to_file = FALSE;
8113 offsets = g_new0 (gint32, acfg->nmethods);
8114 for (i = 0; i < acfg->nmethods; ++i) {
8115 if (acfg->cfgs [i]) {
8116 MonoCompile *cfg = acfg->cfgs [i];
8118 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8119 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8120 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8121 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8122 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8124 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8125 offsets [i] = cfg->ex_info_offset;
8127 if (method_seq_points_to_file) {
8128 if (!seq_points_to_file) {
8129 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8130 seq_points_to_file = TRUE;
8132 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8139 if (seq_points_to_file) {
8140 char *seq_points_aot_file;
8141 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8142 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8143 mono_seq_point_data_free (&sp_data);
8144 g_free (seq_points_aot_file);
8147 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", acfg->nmethods, 10, offsets);
8152 emit_unwind_info (MonoAotCompile *acfg)
8158 * The unwind info contains a lot of duplicates so we emit each unique
8159 * entry once, and only store the offset from the start of the table in the
8163 sprintf (symbol, "unwind_info");
8164 emit_section_change (acfg, RODATA_SECT, 1);
8165 emit_alignment (acfg, 8);
8166 emit_info_symbol (acfg, symbol);
8168 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8169 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8170 guint8 *unwind_info;
8171 guint32 unwind_info_len;
8175 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8178 encode_value (unwind_info_len, p, &p);
8179 emit_bytes (acfg, buf, p - buf);
8180 emit_bytes (acfg, unwind_info, unwind_info_len);
8182 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8187 emit_class_info (MonoAotCompile *acfg)
8192 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8193 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8194 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8196 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8200 typedef struct ClassNameTableEntry {
8201 guint32 token, index;
8202 struct ClassNameTableEntry *next;
8203 } ClassNameTableEntry;
8206 emit_class_name_table (MonoAotCompile *acfg)
8208 int i, table_size, buf_size;
8209 guint32 token, hash;
8215 ClassNameTableEntry *entry, *new_entry;
8218 * Construct a chained hash table for mapping class names to typedef tokens.
8220 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8221 table = g_ptr_array_sized_new (table_size);
8222 for (i = 0; i < table_size; ++i)
8223 g_ptr_array_add (table, NULL);
8224 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8226 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8227 klass = mono_class_get_checked (acfg->image, token, &error);
8229 mono_error_cleanup (&error);
8232 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8233 hash = mono_metadata_str_hash (full_name) % table_size;
8236 /* FIXME: Allocate from the mempool */
8237 new_entry = g_new0 (ClassNameTableEntry, 1);
8238 new_entry->token = token;
8240 entry = g_ptr_array_index (table, hash);
8241 if (entry == NULL) {
8242 new_entry->index = hash;
8243 g_ptr_array_index (table, hash) = new_entry;
8246 entry = entry->next;
8248 entry->next = new_entry;
8249 new_entry->index = table->len;
8250 g_ptr_array_add (table, new_entry);
8254 /* Emit the table */
8255 buf_size = table->len * 4 + 4;
8256 p = buf = g_malloc0 (buf_size);
8258 /* FIXME: Optimize memory usage */
8259 g_assert (table_size < 65000);
8260 encode_int16 (table_size, p, &p);
8261 g_assert (table->len < 65000);
8262 for (i = 0; i < table->len; ++i) {
8263 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8265 if (entry == NULL) {
8266 encode_int16 (0, p, &p);
8267 encode_int16 (0, p, &p);
8269 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8271 encode_int16 (entry->next->index, p, &p);
8273 encode_int16 (0, p, &p);
8276 g_assert (p - buf <= buf_size);
8279 mono_llvm_emit_aot_data ("class_name_table", buf, p - buf);
8281 sprintf (symbol, "class_name_table");
8282 emit_section_change (acfg, RODATA_SECT, 0);
8283 emit_alignment (acfg, 8);
8284 emit_label (acfg, symbol);
8285 emit_bytes (acfg, buf, p - buf);
8290 emit_image_table (MonoAotCompile *acfg)
8297 * The image table is small but referenced in a lot of places.
8298 * So we emit it at once, and reference its elements by an index.
8300 buf_size = acfg->image_table->len * 28 + 4;
8301 for (i = 0; i < acfg->image_table->len; i++) {
8302 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8303 MonoAssemblyName *aname = &image->assembly->aname;
8305 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8308 buf = p = g_malloc0 (buf_size);
8309 encode_int (acfg->image_table->len, p, &p);
8310 for (i = 0; i < acfg->image_table->len; i++) {
8311 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8312 MonoAssemblyName *aname = &image->assembly->aname;
8314 /* FIXME: Support multi-module assemblies */
8315 g_assert (image->assembly->image == image);
8317 encode_string (image->assembly_name, p, &p);
8318 encode_string (image->guid, p, &p);
8319 encode_string (aname->culture ? aname->culture : "", p, &p);
8320 encode_string ((const char*)aname->public_key_token, p, &p);
8322 while (GPOINTER_TO_UINT (p) % 8 != 0)
8325 encode_int (aname->flags, p, &p);
8326 encode_int (aname->major, p, &p);
8327 encode_int (aname->minor, p, &p);
8328 encode_int (aname->build, p, &p);
8329 encode_int (aname->revision, p, &p);
8331 g_assert (p - buf <= buf_size);
8334 mono_llvm_emit_aot_data ("image_table", buf, p - buf);
8336 sprintf (symbol, "image_table");
8337 emit_section_change (acfg, RODATA_SECT, 1);
8338 emit_alignment (acfg, 8);
8339 emit_label (acfg, symbol);
8340 emit_bytes (acfg, buf, p - buf);
8347 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8349 int i, first_plt_got_patch = 0, buf_size;
8351 guint32 *got_info_offsets;
8352 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8354 /* Add the patches needed by the PLT to the GOT */
8356 acfg->plt_got_offset_base = acfg->got_offset;
8357 first_plt_got_patch = info->got_patches->len;
8358 for (i = 1; i < acfg->plt_offset; ++i) {
8359 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8361 g_ptr_array_add (info->got_patches, plt_entry->ji);
8363 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8366 acfg->got_offset += acfg->plt_offset;
8371 * - optimize offsets table.
8372 * - reduce number of exported symbols.
8373 * - emit info for a klass only once.
8374 * - determine when a method uses a GOT slot which is guaranteed to be already
8376 * - clean up and document the code.
8377 * - use String.Empty in class libs.
8380 /* Encode info required to decode shared GOT entries */
8381 buf_size = info->got_patches->len * 128;
8382 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8383 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8385 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8387 if (acfg->plt_offset)
8388 acfg->plt_got_info_offsets [0] = 0;
8390 for (i = 0; i < info->got_patches->len; ++i) {
8391 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8396 encode_value (ji->type, p, &p);
8398 encode_patch (acfg, ji, p, &p);
8399 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8400 g_assert (p - buf <= buf_size);
8401 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8403 if (!llvm && i >= first_plt_got_patch)
8404 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8405 acfg->stats.got_info_size += p - buf;
8408 /* Emit got_info_offsets table */
8410 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8411 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);
8415 emit_got (MonoAotCompile *acfg)
8419 /* Don't make GOT global so accesses to it don't need relocations */
8420 sprintf (symbol, "%s", acfg->got_symbol);
8423 emit_unset_mode (acfg);
8424 fprintf (acfg->fp, ".section __DATA, __bss\n");
8425 emit_alignment (acfg, 8);
8427 emit_info_symbol (acfg, "jit_got");
8428 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8430 emit_section_change (acfg, ".bss", 0);
8431 emit_alignment (acfg, 8);
8432 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8433 emit_label (acfg, symbol);
8435 emit_info_symbol (acfg, "jit_got");
8436 if (acfg->got_offset > 0)
8437 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8440 sprintf (symbol, "got_end");
8441 emit_label (acfg, symbol);
8444 typedef struct GlobalsTableEntry {
8445 guint32 value, index;
8446 struct GlobalsTableEntry *next;
8447 } GlobalsTableEntry;
8450 emit_globals (MonoAotCompile *acfg)
8456 GlobalsTableEntry *entry, *new_entry;
8458 if (!acfg->aot_opts.static_link)
8462 * When static linking, we emit a table containing our globals.
8466 * Construct a chained hash table for mapping global names to their index in
8467 * the globals table.
8469 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8470 table = g_ptr_array_sized_new (table_size);
8471 for (i = 0; i < table_size; ++i)
8472 g_ptr_array_add (table, NULL);
8473 for (i = 0; i < acfg->globals->len; ++i) {
8474 char *name = g_ptr_array_index (acfg->globals, i);
8476 hash = mono_metadata_str_hash (name) % table_size;
8478 /* FIXME: Allocate from the mempool */
8479 new_entry = g_new0 (GlobalsTableEntry, 1);
8480 new_entry->value = i;
8482 entry = g_ptr_array_index (table, hash);
8483 if (entry == NULL) {
8484 new_entry->index = hash;
8485 g_ptr_array_index (table, hash) = new_entry;
8488 entry = entry->next;
8490 entry->next = new_entry;
8491 new_entry->index = table->len;
8492 g_ptr_array_add (table, new_entry);
8496 /* Emit the table */
8497 sprintf (symbol, ".Lglobals_hash");
8498 emit_section_change (acfg, RODATA_SECT, 0);
8499 emit_alignment (acfg, 8);
8500 emit_label (acfg, symbol);
8502 /* FIXME: Optimize memory usage */
8503 g_assert (table_size < 65000);
8504 emit_int16 (acfg, table_size);
8505 for (i = 0; i < table->len; ++i) {
8506 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8508 if (entry == NULL) {
8509 emit_int16 (acfg, 0);
8510 emit_int16 (acfg, 0);
8512 emit_int16 (acfg, entry->value + 1);
8514 emit_int16 (acfg, entry->next->index);
8516 emit_int16 (acfg, 0);
8520 /* Emit the names */
8521 for (i = 0; i < acfg->globals->len; ++i) {
8522 char *name = g_ptr_array_index (acfg->globals, i);
8524 sprintf (symbol, "name_%d", i);
8525 emit_section_change (acfg, RODATA_SECT, 1);
8527 emit_alignment (acfg, 4);
8529 emit_label (acfg, symbol);
8530 emit_string (acfg, name);
8533 /* Emit the globals table */
8534 sprintf (symbol, "globals");
8535 emit_section_change (acfg, ".data", 0);
8536 /* This is not a global, since it is accessed by the init function */
8537 emit_alignment (acfg, 8);
8538 emit_info_symbol (acfg, symbol);
8540 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8541 emit_pointer (acfg, symbol);
8543 for (i = 0; i < acfg->globals->len; ++i) {
8544 char *name = g_ptr_array_index (acfg->globals, i);
8546 sprintf (symbol, "name_%d", i);
8547 emit_pointer (acfg, symbol);
8549 g_assert (strlen (name) < sizeof (symbol));
8550 sprintf (symbol, "%s", name);
8551 emit_pointer (acfg, symbol);
8553 /* Null terminate the table */
8554 emit_int32 (acfg, 0);
8555 emit_int32 (acfg, 0);
8559 emit_autoreg (MonoAotCompile *acfg)
8564 * Emit a function into the .ctor section which will be called by the ELF
8565 * loader to register this module with the runtime.
8567 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8570 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8572 arch_emit_autoreg (acfg, symbol);
8578 emit_mem_end (MonoAotCompile *acfg)
8582 sprintf (symbol, "mem_end");
8583 emit_section_change (acfg, ".text", 1);
8584 emit_alignment_code (acfg, 8);
8585 emit_label (acfg, symbol);
8589 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info, int gc_name_offset)
8593 info->version = MONO_AOT_FILE_VERSION;
8594 info->plt_got_offset_base = acfg->plt_got_offset_base;
8595 info->got_size = acfg->got_offset * sizeof (gpointer);
8596 info->plt_size = acfg->plt_offset;
8597 info->nmethods = acfg->nmethods;
8598 info->flags = acfg->flags;
8599 info->opts = acfg->opts;
8600 info->simd_opts = acfg->simd_opts;
8601 info->gc_name_index = gc_name_offset;
8602 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8603 info->num_trampolines [i] = acfg->num_trampolines [i];
8604 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8605 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
8606 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8607 info->trampoline_size [i] = acfg->trampoline_size [i];
8608 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
8610 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8615 memset (&t, 0, sizeof (MonoType));
8616 t.type = MONO_TYPE_R8;
8617 mono_type_size (&t, &align);
8618 info->double_align = align;
8620 memset (&t, 0, sizeof (MonoType));
8621 t.type = MONO_TYPE_I8;
8622 mono_type_size (&t, &align);
8623 info->long_align = align;
8626 info->double_align = MONO_ABI_ALIGNOF (double);
8627 info->long_align = MONO_ABI_ALIGNOF (gint64);
8629 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
8630 info->tramp_page_size = acfg->tramp_page_size;
8631 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8632 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
8636 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
8640 const char **symbols;
8642 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8644 symbols [sindex ++] = acfg->got_symbol;
8646 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
8647 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
8649 symbols [sindex ++] = NULL;
8650 symbols [sindex ++] = NULL;
8652 symbols [sindex ++] = "jit_code_start";
8653 symbols [sindex ++] = "jit_code_end";
8654 symbols [sindex ++] = "method_addresses";
8655 symbols [sindex ++] = "blob";
8656 symbols [sindex ++] = "class_name_table";
8657 symbols [sindex ++] = "class_info_offsets";
8658 symbols [sindex ++] = "method_info_offsets";
8659 symbols [sindex ++] = "ex_info_offsets";
8660 symbols [sindex ++] = "extra_method_info_offsets";
8661 symbols [sindex ++] = "extra_method_table";
8662 symbols [sindex ++] = "got_info_offsets";
8664 symbols [sindex ++] = "llvm_got_info_offsets";
8666 symbols [sindex ++] = NULL;
8667 symbols [sindex ++] = "mem_end";
8668 symbols [sindex ++] = "image_table";
8669 symbols [sindex ++] = "assembly_guid";
8670 symbols [sindex ++] = "runtime_version";
8671 if (acfg->num_trampoline_got_entries) {
8672 symbols [sindex ++] = "specific_trampolines";
8673 symbols [sindex ++] = "static_rgctx_trampolines";
8674 symbols [sindex ++] = "imt_thunks";
8675 symbols [sindex ++] = "gsharedvt_arg_trampolines";
8677 symbols [sindex ++] = NULL;
8678 symbols [sindex ++] = NULL;
8679 symbols [sindex ++] = NULL;
8680 symbols [sindex ++] = NULL;
8682 if (acfg->aot_opts.static_link) {
8683 symbols [sindex ++] = "globals";
8685 symbols [sindex ++] = NULL;
8687 symbols [sindex ++] = "assembly_name";
8688 symbols [sindex ++] = "plt";
8689 symbols [sindex ++] = "plt_end";
8690 symbols [sindex ++] = "unwind_info";
8691 symbols [sindex ++] = "unbox_trampolines";
8692 symbols [sindex ++] = "unbox_trampolines_end";
8693 symbols [sindex ++] = "unbox_trampoline_addresses";
8694 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
8696 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8697 emit_section_change (acfg, ".data", 0);
8698 emit_alignment (acfg, 8);
8699 emit_label (acfg, symbol);
8700 if (!acfg->aot_opts.static_link)
8701 emit_global (acfg, symbol, FALSE);
8703 /* The data emitted here must match MonoAotFileInfo. */
8705 emit_int32 (acfg, info->version);
8706 emit_int32 (acfg, info->dummy);
8709 * We emit pointers to our data structures instead of emitting global symbols which
8710 * point to them, to reduce the number of globals, and because using globals leads to
8711 * various problems (i.e. arm/thumb).
8713 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
8714 emit_pointer (acfg, symbols [i]);
8716 emit_int32 (acfg, info->plt_got_offset_base);
8717 emit_int32 (acfg, info->got_size);
8718 emit_int32 (acfg, info->plt_size);
8719 emit_int32 (acfg, info->nmethods);
8720 emit_int32 (acfg, info->flags);
8721 emit_int32 (acfg, info->opts);
8722 emit_int32 (acfg, info->simd_opts);
8723 emit_int32 (acfg, info->gc_name_index);
8724 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
8725 emit_int32 (acfg, info->double_align);
8726 emit_int32 (acfg, info->long_align);
8727 emit_int32 (acfg, info->generic_tramp_num);
8728 emit_int32 (acfg, info->tramp_page_size);
8730 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8731 emit_int32 (acfg, info->num_trampolines [i]);
8732 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8733 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
8734 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8735 emit_int32 (acfg, info->trampoline_size [i]);
8736 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8737 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
8739 if (acfg->aot_opts.static_link) {
8743 * Emit a global symbol which can be passed by an embedding app to
8744 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8747 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8749 /* Get rid of characters which cannot occur in symbols */
8751 for (p = symbol; *p; ++p) {
8752 if (!(isalnum (*p) || *p == '_'))
8755 acfg->static_linking_symbol = g_strdup (symbol);
8756 emit_global_inner (acfg, symbol, FALSE);
8757 emit_alignment (acfg, sizeof (gpointer));
8758 emit_label (acfg, symbol);
8759 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8764 * Emit a structure containing all the information not stored elsewhere.
8767 emit_file_info (MonoAotCompile *acfg)
8770 const char *gc_name;
8772 MonoAotFileInfo *info;
8774 if (acfg->aot_opts.bind_to_runtime_version) {
8775 build_info = mono_get_runtime_build_info ();
8776 emit_string_symbol (acfg, "runtime_version", build_info);
8777 g_free (build_info);
8779 emit_string_symbol (acfg, "runtime_version", "");
8782 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8784 /* Emit a string holding the assembly name */
8785 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8788 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8791 gc_name = mono_gc_get_gc_name ();
8792 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8794 info = g_new0 (MonoAotFileInfo, 1);
8795 init_aot_file_info (acfg, info, gc_name_offset);
8798 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
8800 emit_aot_file_info (acfg, info);
8804 emit_blob (MonoAotCompile *acfg)
8809 mono_llvm_emit_aot_data ("blob", (guint8*)acfg->blob.data, acfg->blob.index);
8813 sprintf (symbol, "blob");
8814 emit_section_change (acfg, RODATA_SECT, 1);
8815 emit_alignment (acfg, 8);
8816 emit_label (acfg, symbol);
8818 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8822 emit_objc_selectors (MonoAotCompile *acfg)
8827 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8832 * cat > foo.m << EOF
8835 * return @selector(print:);
8840 mono_img_writer_emit_unset_mode (acfg->w);
8841 g_assert (acfg->fp);
8842 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8843 fprintf (acfg->fp, ".align 3\n");
8844 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8845 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8846 emit_label (acfg, symbol);
8847 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8848 emit_pointer (acfg, symbol);
8851 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8852 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8853 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8854 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8857 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8858 fprintf (acfg->fp, ".align 3\n");
8859 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8860 fprintf (acfg->fp, ".long 0\n");
8861 fprintf (acfg->fp, ".long 16\n");
8865 emit_dwarf_info (MonoAotCompile *acfg)
8867 #ifdef EMIT_DWARF_INFO
8871 /* DIEs for methods */
8872 for (i = 0; i < acfg->nmethods; ++i) {
8873 MonoCompile *cfg = acfg->cfgs [i];
8878 // FIXME: LLVM doesn't define .Lme_...
8879 if (cfg->compile_llvm)
8882 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8884 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 ()));
8890 collect_methods (MonoAotCompile *acfg)
8893 MonoImage *image = acfg->image;
8895 /* Collect methods */
8896 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8899 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8901 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8904 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8905 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8906 mono_error_cleanup (&error);
8910 /* Load all methods eagerly to skip the slower lazy loading code */
8911 mono_class_setup_methods (method->klass);
8913 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8914 /* Compile the wrapper instead */
8915 /* We do this here instead of add_wrappers () because it is easy to do it here */
8916 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
8920 /* FIXME: Some mscorlib methods don't have debug info */
8922 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8923 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8924 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8925 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8926 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8927 if (!mono_debug_lookup_method (method)) {
8928 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8935 if (method->is_generic || method->klass->generic_container)
8936 /* Compile the ref shared version instead */
8937 method = mini_get_shared_method (method);
8939 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8940 add_method_with_index (acfg, method, i, FALSE);
8941 acfg->method_index ++;
8944 /* gsharedvt methods */
8945 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8948 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8950 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8953 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8954 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8956 if (method->is_generic || method->klass->generic_container) {
8957 MonoMethod *gshared;
8959 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8960 add_extra_method (acfg, gshared);
8964 add_generic_instances (acfg);
8966 if (mono_aot_mode_is_full (&acfg->aot_opts))
8967 add_wrappers (acfg);
8972 compile_methods (MonoAotCompile *acfg)
8976 if (acfg->aot_opts.nthreads > 0) {
8981 gpointer *user_data;
8982 MonoMethod **methods;
8984 methods_len = acfg->methods->len;
8986 len = acfg->methods->len / acfg->aot_opts.nthreads;
8989 * Partition the list of methods into fragments, and hand it to threads to
8992 threads = g_ptr_array_new ();
8993 /* Make a copy since acfg->methods is modified by compile_method () */
8994 methods = g_new0 (MonoMethod*, methods_len);
8995 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8996 for (i = 0; i < methods_len; ++i)
8997 methods [i] = g_ptr_array_index (acfg->methods, i);
8999 while (i < methods_len) {
9000 frag = g_ptr_array_new ();
9001 for (j = 0; j < len; ++j) {
9002 if (i < methods_len) {
9003 g_ptr_array_add (frag, methods [i]);
9008 user_data = g_new0 (gpointer, 3);
9009 user_data [0] = mono_domain_get ();
9010 user_data [1] = acfg;
9011 user_data [2] = frag;
9013 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
9014 g_ptr_array_add (threads, handle);
9018 for (i = 0; i < threads->len; ++i) {
9019 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9025 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9026 for (i = methods_len; i < acfg->methods->len; ++i) {
9027 /* This can new methods to acfg->methods */
9028 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
9033 compile_asm (MonoAotCompile *acfg)
9035 char *command, *objfile;
9036 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9037 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9038 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9040 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9041 #define AS_OPTIONS "--64"
9042 #elif defined(TARGET_POWERPC64)
9043 #define AS_OPTIONS "-a64 -mppc64"
9044 #define LD_OPTIONS "-m elf64ppc"
9045 #elif defined(sparc) && SIZEOF_VOID_P == 8
9046 #define AS_OPTIONS "-xarch=v9"
9047 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9048 #define AS_OPTIONS "-arch i386"
9050 #define AS_OPTIONS ""
9053 #ifdef __native_client_codegen__
9054 #if defined(TARGET_AMD64)
9055 #define AS_NAME "nacl64-as"
9057 #define AS_NAME "nacl-as"
9059 #elif defined(TARGET_OSX)
9060 #define AS_NAME "clang"
9062 #define AS_NAME "as"
9066 #define LD_OPTIONS ""
9070 #define LD_NAME "ld -shared -G"
9071 #elif defined(__ppc__) && defined(TARGET_MACH)
9072 #define LD_NAME "gcc -dynamiclib"
9073 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9074 #define LD_NAME "clang --shared"
9075 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9076 #define LD_NAME "gcc -shared --dll"
9077 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9078 #define LD_NAME "clang -m32 -dynamiclib"
9079 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9080 #define LD_NAME "gcc --shared"
9083 if (acfg->aot_opts.asm_only) {
9084 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9085 if (acfg->aot_opts.static_link)
9086 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9088 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9092 if (acfg->aot_opts.static_link) {
9093 if (acfg->aot_opts.outfile)
9094 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9096 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9098 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9102 g_string_append (acfg->as_args, "-c -x assembler");
9105 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);
9106 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9107 if (execute_system (command) != 0) {
9113 if (acfg->llvm && !acfg->llvm_owriter) {
9114 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);
9115 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9116 if (execute_system (command) != 0) {
9125 if (acfg->aot_opts.static_link) {
9126 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9127 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9132 if (acfg->aot_opts.outfile)
9133 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9135 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9137 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9140 llvm_ofile = g_strdup (acfg->llvm_ofile);
9142 llvm_ofile = g_strdup ("");
9145 /* replace the ; flags separators with spaces */
9146 g_strdelimit (ld_flags, ";", ' ');
9149 command = g_strdup_printf ("%s -o \"%s\" \"%s\" \"%s.o\" %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
9151 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
9152 acfg->tmpfname, ld_flags);
9154 aot_printf (acfg, "Executing the native linker: %s\n", command);
9155 if (execute_system (command) != 0) {
9156 g_free (tmp_outfile_name);
9157 g_free (outfile_name);
9166 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9167 printf ("Stripping the binary: %s\n", com);
9168 execute_system (com);
9171 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9173 * gas generates 'mapping symbols' each time code and data is mixed, which
9174 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9176 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9177 aot_printf (acfg, "Stripping the binary: %s\n", command);
9178 if (execute_system (command) != 0) {
9179 g_free (tmp_outfile_name);
9180 g_free (outfile_name);
9187 rename (tmp_outfile_name, outfile_name);
9189 #if defined(TARGET_MACH)
9190 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9191 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9192 if (execute_system (command) != 0) {
9197 if (!acfg->aot_opts.save_temps)
9200 g_free (tmp_outfile_name);
9201 g_free (outfile_name);
9204 if (acfg->aot_opts.save_temps)
9205 aot_printf (acfg, "Retained input file.\n");
9207 unlink (acfg->tmpfname);
9212 static void init_got_info (GotInfo *info)
9216 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9217 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9218 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9219 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9220 info->got_patches = g_ptr_array_new ();
9223 static MonoAotCompile*
9224 acfg_create (MonoAssembly *ass, guint32 opts)
9226 MonoImage *image = ass->image;
9227 MonoAotCompile *acfg;
9229 acfg = g_new0 (MonoAotCompile, 1);
9230 acfg->methods = g_ptr_array_new ();
9231 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9232 acfg->method_depth = g_hash_table_new (NULL, NULL);
9233 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9234 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9235 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9236 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9237 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9238 acfg->image_hash = g_hash_table_new (NULL, NULL);
9239 acfg->image_table = g_ptr_array_new ();
9240 acfg->globals = g_ptr_array_new ();
9241 acfg->image = image;
9243 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9244 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9245 acfg->mempool = mono_mempool_new ();
9246 acfg->extra_methods = g_ptr_array_new ();
9247 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9248 acfg->unwind_ops = g_ptr_array_new ();
9249 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9250 acfg->method_order = g_ptr_array_new ();
9251 acfg->export_names = g_hash_table_new (NULL, NULL);
9252 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9253 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9254 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9255 mono_mutex_init_recursive (&acfg->mutex);
9257 init_got_info (&acfg->got_info);
9258 init_got_info (&acfg->llvm_got_info);
9264 got_info_free (GotInfo *info)
9268 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9269 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9270 g_free (info->patch_to_got_offset_by_type);
9271 g_hash_table_destroy (info->patch_to_got_offset);
9272 g_ptr_array_free (info->got_patches, TRUE);
9276 acfg_free (MonoAotCompile *acfg)
9280 mono_img_writer_destroy (acfg->w);
9281 for (i = 0; i < acfg->nmethods; ++i)
9283 g_free (acfg->cfgs [i]);
9284 g_free (acfg->cfgs);
9285 g_free (acfg->static_linking_symbol);
9286 g_free (acfg->got_symbol);
9287 g_free (acfg->plt_symbol);
9288 g_ptr_array_free (acfg->methods, TRUE);
9289 g_ptr_array_free (acfg->image_table, TRUE);
9290 g_ptr_array_free (acfg->globals, TRUE);
9291 g_ptr_array_free (acfg->unwind_ops, TRUE);
9292 g_hash_table_destroy (acfg->method_indexes);
9293 g_hash_table_destroy (acfg->method_depth);
9294 g_hash_table_destroy (acfg->plt_offset_to_entry);
9295 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9296 if (acfg->patch_to_plt_entry [i])
9297 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9299 g_free (acfg->patch_to_plt_entry);
9300 g_hash_table_destroy (acfg->method_to_cfg);
9301 g_hash_table_destroy (acfg->token_info_hash);
9302 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9303 g_hash_table_destroy (acfg->image_hash);
9304 g_hash_table_destroy (acfg->unwind_info_offsets);
9305 g_hash_table_destroy (acfg->method_label_hash);
9306 g_hash_table_destroy (acfg->export_names);
9307 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9308 g_hash_table_destroy (acfg->klass_blob_hash);
9309 g_hash_table_destroy (acfg->method_blob_hash);
9310 got_info_free (&acfg->got_info);
9311 got_info_free (&acfg->llvm_got_info);
9312 mono_mempool_destroy (acfg->mempool);
9316 #define WRAPPER(e,n) n,
9317 static const char* const
9318 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9319 #include "mono/metadata/wrapper-types.h"
9323 static G_GNUC_UNUSED const char*
9324 get_wrapper_type_name (int type)
9326 return wrapper_type_names [type];
9332 static void aot_dump (MonoAotCompile *acfg)
9338 mono_json_writer_init (&writer);
9340 mono_json_writer_object_begin(&writer);
9343 mono_json_writer_indent (&writer);
9344 mono_json_writer_object_key(&writer, "methods");
9345 mono_json_writer_array_begin (&writer);
9348 for (i = 0; i < acfg->nmethods; ++i) {
9353 cfg = acfg->cfgs [i];
9357 method = cfg->orig_method;
9359 mono_json_writer_indent (&writer);
9360 mono_json_writer_object_begin(&writer);
9362 mono_json_writer_indent (&writer);
9363 mono_json_writer_object_key(&writer, "name");
9364 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9366 mono_json_writer_indent (&writer);
9367 mono_json_writer_object_key(&writer, "signature");
9368 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9369 /*signature=*/TRUE));
9371 mono_json_writer_indent (&writer);
9372 mono_json_writer_object_key(&writer, "code_size");
9373 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9375 klass = method->klass;
9377 mono_json_writer_indent (&writer);
9378 mono_json_writer_object_key(&writer, "class");
9379 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9381 mono_json_writer_indent (&writer);
9382 mono_json_writer_object_key(&writer, "namespace");
9383 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9385 mono_json_writer_indent (&writer);
9386 mono_json_writer_object_key(&writer, "wrapper_type");
9387 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9389 mono_json_writer_indent_pop (&writer);
9390 mono_json_writer_indent (&writer);
9391 mono_json_writer_object_end (&writer);
9392 mono_json_writer_printf (&writer, ",\n");
9395 mono_json_writer_indent_pop (&writer);
9396 mono_json_writer_indent (&writer);
9397 mono_json_writer_array_end (&writer);
9398 mono_json_writer_printf (&writer, ",\n");
9402 mono_json_writer_indent_push (&writer);
9403 mono_json_writer_indent (&writer);
9404 mono_json_writer_object_key(&writer, "plt");
9405 mono_json_writer_array_begin (&writer);
9407 for (i = 0; i < acfg->plt_offset; ++i) {
9408 MonoPltEntry *plt_entry = NULL;
9413 * The first plt entry is unused.
9417 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9420 mono_json_writer_indent (&writer);
9421 mono_json_writer_printf (&writer, "{ ");
9422 mono_json_writer_object_key(&writer, "symbol");
9423 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9426 mono_json_writer_indent_pop (&writer);
9427 mono_json_writer_indent (&writer);
9428 mono_json_writer_array_end (&writer);
9429 mono_json_writer_printf (&writer, ",\n");
9434 mono_json_writer_indent_push (&writer);
9435 mono_json_writer_indent (&writer);
9436 mono_json_writer_object_key(&writer, "got");
9437 mono_json_writer_array_begin (&writer);
9439 mono_json_writer_indent_push (&writer);
9440 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9441 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9443 mono_json_writer_indent (&writer);
9444 mono_json_writer_printf (&writer, "{ ");
9445 mono_json_writer_object_key(&writer, "patch_name");
9446 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9449 mono_json_writer_indent_pop (&writer);
9450 mono_json_writer_indent (&writer);
9451 mono_json_writer_array_end (&writer);
9452 mono_json_writer_printf (&writer, ",\n");
9455 mono_json_writer_indent_pop (&writer);
9456 mono_json_writer_indent (&writer);
9457 mono_json_writer_object_end (&writer);
9459 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9460 dumpfile = fopen (dumpname, "w+");
9463 fprintf (dumpfile, "%s", writer.text->str);
9466 mono_json_writer_destroy (&writer);
9470 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9472 MonoImage *image = ass->image;
9475 MonoAotCompile *acfg;
9476 char *outfile_name, *tmp_outfile_name, *p;
9477 char llvm_stats_msg [256];
9481 acfg = acfg_create (ass, opts);
9483 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9484 acfg->aot_opts.write_symbols = TRUE;
9485 acfg->aot_opts.ntrampolines = 1024;
9486 acfg->aot_opts.nrgctx_trampolines = 1024;
9487 acfg->aot_opts.nimt_trampolines = 128;
9488 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9489 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9490 acfg->aot_opts.llvm_path = g_strdup ("");
9491 acfg->aot_opts.temp_path = g_strdup ("");
9493 acfg->aot_opts.use_trampolines_page = TRUE;
9496 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9498 if (acfg->aot_opts.logfile) {
9499 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9502 if (acfg->aot_opts.static_link)
9503 acfg->aot_opts.autoreg = TRUE;
9505 //acfg->aot_opts.print_skipped_methods = TRUE;
9507 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9508 if (opts & MONO_OPT_GSHAREDVT) {
9509 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9514 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9516 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9517 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
9518 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9523 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9524 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9528 if (acfg->aot_opts.static_link)
9529 acfg->aot_opts.asm_writer = TRUE;
9531 if (acfg->aot_opts.soft_debug) {
9532 MonoDebugOptions *opt = mini_get_debug_options ();
9534 opt->mdb_optimizations = TRUE;
9535 opt->gen_sdb_seq_points = TRUE;
9537 if (!mono_debug_enabled ()) {
9538 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9541 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9544 if (mono_use_llvm || acfg->aot_opts.llvm) {
9546 acfg->aot_opts.asm_writer = TRUE;
9547 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9549 if (acfg->aot_opts.soft_debug) {
9550 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9556 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9557 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9562 * Emit all LLVM code into a separate assembly/object file and link with it
9565 if (!acfg->aot_opts.asm_only) {
9566 acfg->llvm_owriter = TRUE;
9567 } else if (acfg->aot_opts.llvm_outfile) {
9568 int len = strlen (acfg->aot_opts.llvm_outfile);
9570 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
9571 acfg->llvm_owriter = TRUE;
9575 if (mono_aot_mode_is_full (&acfg->aot_opts))
9576 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9578 if (acfg->aot_opts.instances_logfile_path) {
9579 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9580 if (!acfg->instances_logfile) {
9581 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9586 load_profile_files (acfg);
9588 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
9589 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9590 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
9592 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
9593 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9594 if (acfg->opts & MONO_OPT_GSHAREDVT)
9595 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9598 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
9602 if (acfg->llvm && acfg->thumb_mixed)
9603 acfg->flags |= MONO_AOT_FILE_FLAG_LLVM_THUMB;
9605 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9606 /* Get rid of characters which cannot occur in symbols */
9607 for (p = acfg->assembly_name_sym; *p; ++p) {
9608 if (!(isalnum (*p) || *p == '_'))
9612 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
9613 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
9614 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
9616 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
9617 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
9620 acfg->method_index = 1;
9622 if (mono_aot_mode_is_full (&acfg->aot_opts))
9623 mono_set_partial_sharing_supported (TRUE);
9625 res = collect_methods (acfg);
9629 acfg->cfgs_size = acfg->methods->len + 32;
9630 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9632 /* PLT offset 0 is reserved for the PLT trampoline */
9633 acfg->plt_offset = 1;
9638 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link);
9642 /* GOT offset 0 is reserved for the address of the current assembly */
9646 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9647 ji->type = MONO_PATCH_INFO_IMAGE;
9648 ji->data.image = acfg->image;
9650 get_got_offset (acfg, FALSE, ji);
9651 get_got_offset (acfg, TRUE, ji);
9653 /* Slot 1 is reserved for the mscorlib got addr */
9654 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9655 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9656 get_got_offset (acfg, FALSE, ji);
9657 get_got_offset (acfg, TRUE, ji);
9659 /* This is very common */
9660 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9661 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9662 get_got_offset (acfg, FALSE, ji);
9663 get_got_offset (acfg, TRUE, ji);
9665 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9666 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9667 get_got_offset (acfg, FALSE, ji);
9668 get_got_offset (acfg, TRUE, ji);
9670 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9671 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9672 get_got_offset (acfg, FALSE, ji);
9673 get_got_offset (acfg, TRUE, ji);
9678 compile_methods (acfg);
9682 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9688 if (acfg->aot_opts.asm_only) {
9689 if (acfg->aot_opts.outfile) {
9690 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9691 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9693 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9694 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9696 g_assert (acfg->aot_opts.llvm_outfile);
9697 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9698 if (acfg->llvm_owriter)
9699 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
9701 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9703 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
9704 g_strdup_printf ("%s", "temp") :
9705 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
9707 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9708 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
9709 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
9714 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && mono_bin_writer_supported ()) {
9715 if (acfg->aot_opts.outfile)
9716 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9718 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9721 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9722 * it might be in another file system so the rename () won't work.
9724 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9726 acfg->fp = fopen (tmp_outfile_name, "w");
9728 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9732 acfg->w = mono_img_writer_create (acfg->fp, TRUE);
9733 acfg->use_bin_writer = TRUE;
9735 if (acfg->aot_opts.asm_only) {
9736 if (acfg->aot_opts.outfile)
9737 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9739 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9740 acfg->fp = fopen (acfg->tmpfname, "w+");
9742 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9743 acfg->fp = fdopen (i, "w+");
9745 if (acfg->fp == 0) {
9746 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9749 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
9751 tmp_outfile_name = NULL;
9752 outfile_name = NULL;
9755 /* Compute symbols for methods */
9756 for (i = 0; i < acfg->nmethods; ++i) {
9757 if (acfg->cfgs [i]) {
9758 MonoCompile *cfg = acfg->cfgs [i];
9759 int method_index = get_method_index (acfg, cfg->orig_method);
9761 if (COMPILE_LLVM (cfg))
9762 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9763 else if (acfg->global_symbols || acfg->llvm)
9764 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9766 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9767 cfg->asm_debug_symbol = cfg->asm_symbol;
9771 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9773 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9774 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9777 //acfg->gas_line_numbers = TRUE;
9780 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
9781 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9782 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9785 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9788 mono_img_writer_emit_start (acfg->w);
9791 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9797 emit_extra_methods (acfg);
9799 emit_trampolines (acfg);
9801 emit_class_name_table (acfg);
9803 emit_got_info (acfg, FALSE);
9805 emit_got_info (acfg, TRUE);
9807 emit_exception_info (acfg);
9809 emit_unwind_info (acfg);
9811 emit_class_info (acfg);
9815 emit_image_table (acfg);
9819 emit_file_info (acfg);
9823 emit_objc_selectors (acfg);
9825 emit_globals (acfg);
9827 emit_autoreg (acfg);
9830 emit_dwarf_info (acfg);
9831 mono_dwarf_writer_close (acfg->dwarf);
9834 emit_mem_end (acfg);
9836 if (acfg->need_pt_gnu_stack) {
9837 /* This is required so the .so doesn't have an executable stack */
9838 /* The bin writer already emits this */
9839 if (!acfg->use_bin_writer)
9840 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9847 res = emit_llvm_file (acfg);
9855 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9858 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9860 strcpy (llvm_stats_msg, "");
9862 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;
9864 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",
9865 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9866 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9867 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9868 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9869 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9870 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,
9871 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9872 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9873 (int)(acfg->got_offset * sizeof (gpointer)));
9874 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9875 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9877 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9878 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9879 if (acfg->stats.genericcount)
9880 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9881 if (acfg->stats.abscount)
9882 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9883 if (acfg->stats.lmfcount)
9884 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9885 if (acfg->stats.ocount)
9886 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9889 res = mono_img_writer_emit_writeout (acfg->w);
9894 if (acfg->use_bin_writer) {
9895 int err = rename (tmp_outfile_name, outfile_name);
9898 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9902 res = compile_asm (acfg);
9909 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9911 if (acfg->aot_opts.stats) {
9914 aot_printf (acfg, "GOT slot distribution:\n");
9915 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9916 if (acfg->stats.got_slot_types [i])
9917 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]);
9920 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);
9922 if (acfg->aot_opts.dump_json)
9935 mono_aot_readonly_field_override (MonoClassField *field)
9941 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)