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/reflection-internals.h>
44 #include <mono/metadata/marshal.h>
45 #include <mono/metadata/gc-internals.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-internals.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>
55 #include "aot-compiler.h"
56 #include "seq-points.h"
57 #include "image-writer.h"
58 #include "dwarfwriter.h"
60 #include "mini-llvm.h"
62 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
64 #if defined(__linux__) || defined(__native_client_codegen__)
65 #define RODATA_SECT ".rodata"
66 #elif defined(TARGET_MACH)
67 #define RODATA_SECT ".section __TEXT, __const"
69 #define RODATA_SECT ".text"
72 #define TV_DECLARE(name) gint64 name
73 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
74 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
76 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
77 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
78 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
80 /* predefined values for static readonly fields without needed to run the .cctor */
81 typedef struct _ReadOnlyValue ReadOnlyValue;
82 struct _ReadOnlyValue {
85 int type; /* to be used later for typechecking to prevent user errors */
94 static ReadOnlyValue *readonly_values;
96 typedef struct MonoAotOptions {
101 gboolean write_symbols;
102 gboolean metadata_only;
103 gboolean bind_to_runtime_version;
106 gboolean static_link;
110 gboolean dwarf_debug;
112 gboolean log_generics;
113 gboolean log_instances;
114 gboolean gen_seq_points_file;
115 char *gen_seq_points_file_path;
116 gboolean direct_pinvoke;
117 gboolean direct_icalls;
118 gboolean no_direct_calls;
119 gboolean use_trampolines_page;
120 gboolean no_instances;
126 int nrgctx_trampolines;
127 int nimt_trampolines;
128 int ngsharedvt_arg_trampolines;
129 int nrgctx_fetch_trampolines;
130 gboolean print_skipped_methods;
137 char *instances_logfile_path;
144 METHOD_CAT_GSHAREDVT,
150 typedef struct MonoAotStats {
151 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
152 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
153 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
154 int got_slots, offsets_size;
155 int method_categories [METHOD_CAT_NUM];
156 int got_slot_types [MONO_PATCH_INFO_NUM];
157 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
158 int jit_time, gen_time, link_time;
161 typedef struct GotInfo {
162 GHashTable *patch_to_got_offset;
163 GHashTable **patch_to_got_offset_by_type;
164 GPtrArray *got_patches;
167 typedef struct MonoAotCompile {
170 GHashTable *method_indexes;
171 GHashTable *method_depth;
174 GHashTable **patch_to_plt_entry;
175 GHashTable *plt_offset_to_entry;
176 //GHashTable *patch_to_got_offset;
177 //GHashTable **patch_to_got_offset_by_type;
178 //GPtrArray *got_patches;
179 GotInfo got_info, llvm_got_info;
180 GHashTable *image_hash;
181 GHashTable *method_to_cfg;
182 GHashTable *token_info_hash;
183 GHashTable *method_to_pinvoke_import;
184 GPtrArray *extra_methods;
185 GPtrArray *image_table;
187 GPtrArray *method_order;
188 GHashTable *export_names;
189 /* Maps MonoClass* -> blob offset */
190 GHashTable *klass_blob_hash;
191 /* Maps MonoMethod* -> blob offset */
192 GHashTable *method_blob_hash;
193 GHashTable *gsharedvt_in_signatures;
194 GHashTable *gsharedvt_out_signatures;
195 guint32 *plt_got_info_offsets;
196 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
197 /* Number of GOT entries reserved for trampolines */
198 guint32 num_trampoline_got_entries;
199 guint32 tramp_page_size;
201 guint32 table_offsets [MONO_AOT_TABLE_NUM];
202 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
203 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
204 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
205 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
207 MonoAotOptions aot_opts;
211 MonoMemPool *mempool;
214 char *static_linking_symbol;
216 gboolean gas_line_numbers;
217 /* Whenever to emit an object file directly from llc */
218 gboolean llvm_owriter;
220 MonoDwarfWriter *dwarf;
227 GHashTable *unwind_info_offsets;
228 GPtrArray *unwind_ops;
229 guint32 unwind_info_offset;
232 char *llvm_got_symbol;
234 char *llvm_eh_frame_symbol;
235 GHashTable *method_label_hash;
236 const char *temp_prefix;
237 const char *user_symbol_prefix;
238 const char *llvm_label_prefix;
239 const char *inst_directive;
241 guint32 label_generator;
243 gboolean has_jitted_code;
244 MonoAotFileFlags flags;
245 MonoDynamicStream blob;
246 gboolean blob_closed;
247 MonoClass **typespec_classes;
250 char *assembly_name_sym;
251 GHashTable *plt_entry_debug_sym_cache;
252 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
253 GHashTable *ginst_hash;
254 GHashTable *dwarf_ln_filenames;
255 gboolean global_symbols;
256 int objc_selector_index, objc_selector_index_2;
257 GPtrArray *objc_selectors;
258 GHashTable *objc_selector_to_index;
260 FILE *instances_logfile;
268 char *symbol, *llvm_symbol, *debug_sym;
270 gboolean jit_used, llvm_used;
273 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
274 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
276 /* This points to the current acfg in LLVM mode */
277 static MonoAotCompile *llvm_acfg;
279 #ifdef HAVE_ARRAY_ELEM_INIT
280 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
281 #define MSGSTRFIELD1(line) str##line
282 static const struct msgstr_t {
283 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
284 #include "patch-info.h"
287 #define PATCH_INFO(a,b) b,
288 #include "patch-info.h"
291 static const gint16 opidx [] = {
292 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
293 #include "patch-info.h"
297 static G_GNUC_UNUSED const char*
298 get_patch_name (int info)
300 return (const char*)&opstr + opidx [info];
304 #define PATCH_INFO(a,b) b,
305 static const char* const
306 patch_types [MONO_PATCH_INFO_NUM + 1] = {
307 #include "patch-info.h"
311 static G_GNUC_UNUSED const char*
312 get_patch_name (int info)
314 return patch_types [info];
320 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
323 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
326 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
332 output = acfg->logfile;
336 va_start (args, format);
337 vfprintf (output, format, args);
342 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
348 output = acfg->logfile;
352 va_start (args, format);
353 vfprintf (output, format, args);
358 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
363 if (mono_error_ok (error))
367 output = acfg->logfile;
371 va_start (args, format);
372 vfprintf (output, format, args);
374 mono_error_cleanup (error);
376 g_error ("FullAOT cannot continue if there are loader errors");
379 /* Wrappers around the image writer functions */
382 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
384 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
388 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
390 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
394 emit_label (MonoAotCompile *acfg, const char *name)
396 mono_img_writer_emit_label (acfg->w, name);
400 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
402 mono_img_writer_emit_bytes (acfg->w, buf, size);
406 emit_string (MonoAotCompile *acfg, const char *value)
408 mono_img_writer_emit_string (acfg->w, value);
412 emit_line (MonoAotCompile *acfg)
414 mono_img_writer_emit_line (acfg->w);
418 emit_alignment (MonoAotCompile *acfg, int size)
420 mono_img_writer_emit_alignment (acfg->w, size);
424 emit_alignment_code (MonoAotCompile *acfg, int size)
426 if (acfg->align_pad_value)
427 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
429 mono_img_writer_emit_alignment (acfg->w, size);
433 emit_padding (MonoAotCompile *acfg, int size)
438 if (acfg->align_pad_value) {
439 for (i = 0; i < 16; ++i)
440 buf [i] = acfg->align_pad_value;
442 memset (buf, 0, sizeof (buf));
445 for (i = 0; i < size; i += 16) {
447 emit_bytes (acfg, buf, size - i);
449 emit_bytes (acfg, buf, 16);
454 emit_pointer (MonoAotCompile *acfg, const char *target)
456 mono_img_writer_emit_pointer (acfg->w, target);
460 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
462 if (prefix [0] != '\0') {
463 char *s = g_strdup_printf ("%s%s", prefix, target);
464 mono_img_writer_emit_pointer (acfg->w, s);
467 mono_img_writer_emit_pointer (acfg->w, target);
472 emit_int16 (MonoAotCompile *acfg, int value)
474 mono_img_writer_emit_int16 (acfg->w, value);
478 emit_int32 (MonoAotCompile *acfg, int value)
480 mono_img_writer_emit_int32 (acfg->w, value);
484 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
486 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
490 emit_zero_bytes (MonoAotCompile *acfg, int num)
492 mono_img_writer_emit_zero_bytes (acfg->w, num);
496 emit_byte (MonoAotCompile *acfg, guint8 val)
498 mono_img_writer_emit_byte (acfg->w, val);
501 #ifdef __native_client_codegen__
503 emit_nacl_call_alignment (MonoAotCompile *acfg)
505 mono_img_writer_emit_nacl_call_alignment (acfg->w);
509 static G_GNUC_UNUSED void
510 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
512 mono_img_writer_emit_global (acfg->w, name, func);
516 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
518 if (acfg->aot_opts.no_dlsym) {
519 g_ptr_array_add (acfg->globals, g_strdup (name));
520 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
522 mono_img_writer_emit_global (acfg->w, name, func);
527 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
529 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
532 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
534 emit_info_symbol (MonoAotCompile *acfg, const char *name)
539 emit_label (acfg, name);
540 /* LLVM generated code references this */
541 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
542 emit_label (acfg, symbol);
543 emit_global_inner (acfg, symbol, FALSE);
545 emit_label (acfg, name);
550 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
553 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
557 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
559 /* On apple, all symbols need to be aligned to avoid warnings from ld */
560 emit_alignment (acfg, 4);
562 mono_img_writer_emit_label (acfg->w, name);
563 mono_img_writer_emit_string (acfg->w, value);
566 static G_GNUC_UNUSED void
567 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
570 guint8 b = value & 0x7f;
572 if (value != 0) /* more bytes to come */
578 static G_GNUC_UNUSED void
579 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
582 gboolean negative = (value < 0);
589 /* the following is unnecessary if the
590 * implementation of >>= uses an arithmetic rather
591 * than logical shift for a signed left operand
595 value |= - ((gint64)1 <<(size - 7));
596 /* sign bit of byte is second high order bit (0x40) */
597 if ((value == 0 && !(byte & 0x40)) ||
598 (value == -1 && (byte & 0x40)))
602 emit_byte (acfg, byte);
606 static G_GNUC_UNUSED void
607 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
612 guint8 b = value & 0x7f;
614 if (value != 0) /* more bytes to come */
622 static G_GNUC_UNUSED void
623 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
626 gboolean negative = (value < 0);
634 /* the following is unnecessary if the
635 * implementation of >>= uses an arithmetic rather
636 * than logical shift for a signed left operand
640 value |= - (1 <<(size - 7));
641 /* sign bit of byte is second high order bit (0x40) */
642 if ((value == 0 && !(byte & 0x40)) ||
643 (value == -1 && (byte & 0x40)))
654 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
657 buf [0] = (val >> 0) & 0xff;
658 buf [1] = (val >> 8) & 0xff;
659 buf [2] = (val >> 16) & 0xff;
660 buf [3] = (val >> 24) & 0xff;
666 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
668 buf [0] = (val >> 0) & 0xff;
669 buf [1] = (val >> 8) & 0xff;
675 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
677 int len = strlen (s);
679 memcpy (buf, s, len + 1);
680 *endbuf = buf + len + 1;
684 emit_unset_mode (MonoAotCompile *acfg)
686 mono_img_writer_emit_unset_mode (acfg->w);
689 static G_GNUC_UNUSED void
690 emit_set_thumb_mode (MonoAotCompile *acfg)
692 emit_unset_mode (acfg);
693 fprintf (acfg->fp, ".code 16\n");
696 static G_GNUC_UNUSED void
697 emit_set_arm_mode (MonoAotCompile *acfg)
699 emit_unset_mode (acfg);
700 fprintf (acfg->fp, ".code 32\n");
704 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
709 g_assert (size % 4 == 0);
710 emit_unset_mode (acfg);
711 for (i = 0; i < size; i += 4)
712 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
714 emit_bytes (acfg, buf, size);
718 /* ARCHITECTURE SPECIFIC CODE */
720 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
721 #define EMIT_DWARF_INFO 1
724 #if defined(TARGET_ARM)
725 #define AOT_FUNC_ALIGNMENT 4
727 #define AOT_FUNC_ALIGNMENT 16
729 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
730 #undef AOT_FUNC_ALIGNMENT
731 #define AOT_FUNC_ALIGNMENT 32
734 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
735 #define PPC_LD_OP "ld"
736 #define PPC_LDX_OP "ldx"
738 #define PPC_LD_OP "lwz"
739 #define PPC_LDX_OP "lwzx"
743 #define AOT_TARGET_STR "AMD64"
748 #define AOT_TARGET_STR "ARM (MACH)"
750 #define AOT_TARGET_STR "ARM (!MACH)"
756 #define AOT_TARGET_STR "ARM64 (MACH)"
758 #define AOT_TARGET_STR "ARM64 (!MACH)"
762 #ifdef TARGET_POWERPC64
763 #ifdef __mono_ilp32__
764 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
766 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
769 #ifdef TARGET_POWERPC
770 #ifdef __mono_ilp32__
771 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
773 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
780 #define AOT_TARGET_STR "X86 (WIN32)"
781 #elif defined(__native_client_codegen__)
782 #define AOT_TARGET_STR "X86 (native client codegen)"
784 #define AOT_TARGET_STR "X86 (!native client codegen)"
788 #ifndef AOT_TARGET_STR
789 #define AOT_TARGET_STR ""
793 arch_init (MonoAotCompile *acfg)
795 acfg->llc_args = g_string_new ("");
796 acfg->as_args = g_string_new ("");
799 * The prefix LLVM likes to put in front of symbol names on darwin.
800 * The mach-os specs require this for globals, but LLVM puts them in front of all
801 * symbols. We need to handle this, since we need to refer to LLVM generated
804 acfg->llvm_label_prefix = "";
805 acfg->user_symbol_prefix = "";
807 #if defined(TARGET_X86)
808 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
811 #if defined(TARGET_AMD64)
812 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
814 acfg->align_pad_value = 0x90;
818 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
819 g_string_append (acfg->llc_args, "-mattr=+v6");
822 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
823 g_string_append (acfg->as_args, " -mfpu=vfp3");
825 g_string_append (acfg->llc_args, " -soft-float");
828 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
829 acfg->thumb_mixed = TRUE;
831 if (acfg->aot_opts.mtriple)
832 mono_arch_set_target (acfg->aot_opts.mtriple);
836 acfg->inst_directive = ".inst";
837 if (acfg->aot_opts.mtriple)
838 mono_arch_set_target (acfg->aot_opts.mtriple);
842 acfg->user_symbol_prefix = "_";
843 acfg->llvm_label_prefix = "_";
844 acfg->inst_directive = ".word";
845 acfg->need_no_dead_strip = TRUE;
846 acfg->aot_opts.gnu_asm = TRUE;
849 #if defined(__linux__) && !defined(TARGET_ARM)
850 acfg->need_pt_gnu_stack = TRUE;
854 acfg->global_symbols = TRUE;
860 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
864 #ifdef MONO_ARCH_AOT_SUPPORTED
866 * arch_emit_direct_call:
868 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
872 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
874 #if defined(TARGET_X86) || defined(TARGET_AMD64)
875 /* Need to make sure this is exactly 5 bytes long */
876 emit_unset_mode (acfg);
877 fprintf (acfg->fp, "call %s\n", target);
879 #elif defined(TARGET_ARM)
880 emit_unset_mode (acfg);
882 fprintf (acfg->fp, "blx %s\n", target);
884 fprintf (acfg->fp, "bl %s\n", target);
886 #elif defined(TARGET_ARM64)
887 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
888 #elif defined(TARGET_POWERPC)
889 emit_unset_mode (acfg);
890 fprintf (acfg->fp, "bl %s\n", target);
893 g_assert_not_reached ();
900 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
902 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
903 * in in the 2. slot of every GOT, and require every method to place the GOT
904 * address in r30, even when it doesn't access the GOT otherwise. This way,
905 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
910 * PPC64 uses function descriptors which greatly complicate all code, since
911 * these are used very inconsistently in the runtime. Some functions like
912 * mono_compile_method () return ftn descriptors, while others like the
913 * trampoline creation functions do not.
914 * We assume that all GOT slots contain function descriptors, and create
915 * descriptors in aot-runtime.c when needed.
916 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
917 * from function descriptors, we could do the same, but it would require
918 * rewriting all the ppc/aot code to handle function descriptors properly.
919 * So instead, we use the same approach as on PPC32.
920 * This is a horrible mess, but fixing it would probably lead to an even bigger
926 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
929 #ifdef MONO_ARCH_AOT_SUPPORTED
931 * arch_emit_got_offset:
933 * The memory pointed to by CODE should hold native code for computing the GOT
934 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
935 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
938 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
940 #if defined(TARGET_POWERPC64)
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 emit_unset_mode (acfg);
956 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
957 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
958 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
959 acfg->label_generator ++;
962 guint32 offset = mono_arch_get_patch_offset (code);
963 emit_bytes (acfg, code, offset);
964 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
966 *code_size = offset + 4;
971 * arch_emit_got_access:
973 * The memory pointed to by CODE should hold native code for loading a GOT
974 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
975 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
978 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
981 /* mov reg, got+offset(%rip) */
983 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
987 /* Decode reg, see amd64_mov_reg_membase () */
988 rex_r = code [0] & AMD64_REX_R;
989 g_assert (code [0] == 0x49 + rex_r);
990 g_assert (code [1] == 0x8b);
991 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
993 emit_unset_mode (acfg);
994 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
997 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
998 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
999 *code_size = mono_arch_get_patch_offset (code) + 4;
1001 #elif defined(TARGET_X86)
1002 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1003 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1004 *code_size = mono_arch_get_patch_offset (code) + 4;
1005 #elif defined(TARGET_ARM)
1006 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1007 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1008 *code_size = mono_arch_get_patch_offset (code) + 4;
1009 #elif defined(TARGET_ARM64)
1010 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1011 arm64_emit_got_access (acfg, code, got_slot, code_size);
1012 #elif defined(TARGET_POWERPC)
1017 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1019 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1020 g_assert (code - buf == 8);
1021 emit_bytes (acfg, buf, code - buf);
1022 *code_size = code - buf;
1025 g_assert_not_reached ();
1031 #ifdef MONO_ARCH_AOT_SUPPORTED
1033 * arch_emit_objc_selector_ref:
1035 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1038 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1040 #if defined(TARGET_ARM)
1043 int lindex = acfg->objc_selector_index_2 ++;
1045 /* Emit ldr.imm/b */
1046 emit_bytes (acfg, code, 8);
1048 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1049 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1051 emit_label (acfg, symbol1);
1052 mono_img_writer_emit_unset_mode (acfg->w);
1053 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1056 #elif defined(TARGET_ARM64)
1057 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1059 g_assert_not_reached ();
1065 * arch_emit_plt_entry:
1067 * Emit code for the PLT entry.
1068 * The plt entry should look like this:
1069 * <indirect jump to GOT_SYMBOL + OFFSET>
1070 * <INFO_OFFSET embedded into the instruction stream>
1073 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1075 #if defined(TARGET_X86)
1076 #if defined(__default_codegen__)
1077 /* jmp *<offset>(%ebx) */
1078 emit_byte (acfg, 0xff);
1079 emit_byte (acfg, 0xa3);
1080 emit_int32 (acfg, offset);
1081 /* Used by mono_aot_get_plt_info_offset */
1082 emit_int32 (acfg, info_offset);
1083 #elif defined(__native_client_codegen__)
1084 const guint8 kSizeOfNaClJmp = 11;
1085 guint8 bytes[kSizeOfNaClJmp];
1086 guint8 *pbytes = &bytes[0];
1088 x86_jump_membase32 (pbytes, X86_EBX, offset);
1089 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1090 /* four bytes of data, used by mono_arch_patch_plt_entry */
1091 /* For Native Client, make this work with data embedded in push. */
1092 emit_byte (acfg, 0x68); /* hide data in a push */
1093 emit_int32 (acfg, info_offset);
1094 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1095 #endif /*__native_client_codegen__*/
1096 #elif defined(TARGET_AMD64)
1097 #if defined(__default_codegen__)
1098 emit_unset_mode (acfg);
1099 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1100 /* Used by mono_aot_get_plt_info_offset */
1101 emit_int32 (acfg, info_offset);
1102 acfg->stats.plt_size += 10;
1103 #elif defined(__native_client_codegen__)
1105 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1106 guint8 *code = buf_aligned;
1108 /* mov <OFFSET>(%rip), %r11d */
1109 emit_byte (acfg, '\x45');
1110 emit_byte (acfg, '\x8b');
1111 emit_byte (acfg, '\x1d');
1112 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1114 amd64_jump_reg (code, AMD64_R11);
1115 /* This should be constant for the plt patch */
1116 g_assert ((size_t)(code-buf_aligned) == 10);
1117 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1119 /* Hide data in a push imm32 so it passes validation */
1120 emit_byte (acfg, 0x68); /* push */
1121 emit_int32 (acfg, info_offset);
1122 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1123 #endif /*__native_client_codegen__*/
1124 #elif defined(TARGET_ARM)
1129 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1130 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1131 emit_bytes (acfg, buf, code - buf);
1132 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1133 /* Used by mono_aot_get_plt_info_offset */
1134 emit_int32 (acfg, info_offset);
1135 #elif defined(TARGET_ARM64)
1136 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1137 #elif defined(TARGET_POWERPC)
1138 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1139 emit_unset_mode (acfg);
1140 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1141 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1142 fprintf (acfg->fp, "add 11, 11, 30\n");
1143 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1144 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1145 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1146 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1148 fprintf (acfg->fp, "mtctr 11\n");
1149 fprintf (acfg->fp, "bctr\n");
1150 emit_int32 (acfg, info_offset);
1152 g_assert_not_reached ();
1157 * arch_emit_llvm_plt_entry:
1159 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1160 * This is only needed on arm to handle thumb interop.
1163 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1165 #if defined(TARGET_ARM)
1166 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1167 /* The caller already transitioned to thumb */
1168 /* The code below should be 12 bytes long */
1169 /* clang has trouble encoding these instructions, so emit the binary */
1171 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1172 /* thumb can't encode ld pc, [pc, ip] */
1173 fprintf (acfg->fp, "add ip, pc, ip\n");
1174 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1175 fprintf (acfg->fp, "bx ip\n");
1177 emit_set_thumb_mode (acfg);
1178 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1179 fprintf (acfg->fp, ".2byte 0x44fc\n");
1180 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1181 fprintf (acfg->fp, ".2byte 0x4760\n");
1182 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1183 emit_int32 (acfg, info_offset);
1184 emit_unset_mode (acfg);
1185 emit_set_arm_mode (acfg);
1187 g_assert_not_reached ();
1191 /* Save unwind_info in the module and emit the offset to the information at symbol */
1192 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1194 guint32 uw_offset, encoded_len;
1197 emit_section_change (acfg, RODATA_SECT, 0);
1198 emit_global (acfg, symbol, FALSE);
1199 emit_label (acfg, symbol);
1201 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1202 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1204 emit_int32 (acfg, uw_offset);
1208 * arch_emit_specific_trampoline_pages:
1210 * Emits a page full of trampolines: each trampoline uses its own address to
1211 * lookup both the generic trampoline code and the data argument.
1212 * This page can be remapped in process multiple times so we can get an
1213 * unlimited number of trampolines.
1214 * Specifically this implementation uses the following trick: two memory pages
1215 * are allocated, with the first containing the data and the second containing the trampolines.
1216 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1217 * implementation does all the lifting.
1218 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1219 * on the arm 32 bit system.
1222 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1224 #if defined(TARGET_ARM)
1227 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1229 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1230 GSList *unwind_ops = NULL;
1231 #define COMMON_TRAMP_SIZE 16
1232 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1233 int imm8, rot_amount;
1236 if (!acfg->aot_opts.use_trampolines_page)
1239 acfg->tramp_page_size = pagesize;
1241 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1242 emit_alignment (acfg, pagesize);
1243 emit_global (acfg, symbol, TRUE);
1244 emit_label (acfg, symbol);
1246 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1248 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1249 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1250 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1251 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1253 g_assert (code - buf == COMMON_TRAMP_SIZE);
1256 emit_bytes (acfg, buf, code - buf);
1258 for (i = 0; i < count; ++i) {
1260 ARM_PUSH (code, 0x5fff);
1262 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1263 g_assert (code - buf == 8);
1264 emit_bytes (acfg, buf, code - buf);
1267 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1268 * the instruction pointer address, so the generic trampoline at the start of the page
1269 * subtracts 4096 to get to the data page and loads the values
1270 * We again fit the generic trampiline in 16 bytes.
1272 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1273 emit_global (acfg, symbol, TRUE);
1274 emit_label (acfg, symbol);
1276 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1277 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1278 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1279 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1281 g_assert (code - buf == COMMON_TRAMP_SIZE);
1284 emit_bytes (acfg, buf, code - buf);
1286 for (i = 0; i < count; ++i) {
1288 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1290 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1291 g_assert (code - buf == 8);
1292 emit_bytes (acfg, buf, code - buf);
1296 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1298 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1299 emit_global (acfg, symbol, TRUE);
1300 emit_label (acfg, symbol);
1302 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1303 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1304 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1305 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1306 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1307 g_assert (code - buf == COMMON_TRAMP_SIZE);
1309 emit_bytes (acfg, buf, code - buf);
1311 for (i = 0; i < count; ++i) {
1313 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1315 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1316 g_assert (code - buf == 8);
1317 emit_bytes (acfg, buf, code - buf);
1320 /* now the imt trampolines: each specific trampolines puts in the ip register
1321 * the instruction pointer address, so the generic trampoline at the start of the page
1322 * subtracts 4096 to get to the data page and loads the values
1324 #define IMT_TRAMP_SIZE 72
1325 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1326 emit_global (acfg, symbol, TRUE);
1327 emit_label (acfg, symbol);
1329 /* Need at least two free registers, plus a slot for storing the pc */
1330 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1332 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1333 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1334 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1336 /* The IMT method is in v5, r0 has the imt array address */
1339 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1340 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1341 imt_found_check = code;
1342 ARM_B_COND (code, ARMCOND_EQ, 0);
1344 /* End-of-loop check */
1345 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1346 loop_end_check = code;
1347 ARM_B_COND (code, ARMCOND_EQ, 0);
1350 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1351 loop_branch_back = code;
1353 arm_patch (loop_branch_back, loop_start);
1356 arm_patch (imt_found_check, code);
1357 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1358 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1359 /* Save it to the third stack slot */
1360 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1361 /* Restore the registers and branch */
1362 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1365 arm_patch (loop_end_check, code);
1366 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1367 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1368 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1372 g_assert (code - buf == IMT_TRAMP_SIZE);
1373 emit_bytes (acfg, buf, code - buf);
1375 for (i = 0; i < count; ++i) {
1377 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1379 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1380 g_assert (code - buf == 8);
1381 emit_bytes (acfg, buf, code - buf);
1384 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1385 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1386 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1387 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1389 /* Unwind info for specifc trampolines */
1390 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1391 /* We unwind to the original caller, from the stack, since lr is clobbered */
1392 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1393 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1394 save_unwind_info (acfg, symbol, unwind_ops);
1395 mono_free_unwind_info (unwind_ops);
1397 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1398 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1399 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1400 save_unwind_info (acfg, symbol, unwind_ops);
1401 mono_free_unwind_info (unwind_ops);
1403 /* Unwind info for rgctx trampolines */
1404 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1405 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1406 save_unwind_info (acfg, symbol, unwind_ops);
1408 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1409 save_unwind_info (acfg, symbol, unwind_ops);
1410 mono_free_unwind_info (unwind_ops);
1412 /* Unwind info for gsharedvt trampolines */
1413 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1414 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1415 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1416 save_unwind_info (acfg, symbol, unwind_ops);
1417 mono_free_unwind_info (unwind_ops);
1419 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1420 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1421 save_unwind_info (acfg, symbol, unwind_ops);
1422 mono_free_unwind_info (unwind_ops);
1424 /* Unwind info for imt trampolines */
1425 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1426 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1427 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1428 save_unwind_info (acfg, symbol, unwind_ops);
1429 mono_free_unwind_info (unwind_ops);
1431 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1432 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1433 save_unwind_info (acfg, symbol, unwind_ops);
1434 mono_free_unwind_info (unwind_ops);
1435 #elif defined(TARGET_ARM64)
1436 arm64_emit_specific_trampoline_pages (acfg);
1441 * arch_emit_specific_trampoline:
1443 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1444 * two GOT slots which contain the generic trampoline address and the trampoline
1445 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1448 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1451 * The trampolines created here are variations of the specific
1452 * trampolines created in mono_arch_create_specific_trampoline (). The
1454 * - the generic trampoline address is taken from a got slot.
1455 * - the offset of the got slot where the trampoline argument is stored
1456 * is embedded in the instruction stream, and the generic trampoline
1457 * can load the argument by loading the offset, adding it to the
1458 * address of the trampoline to get the address of the got slot, and
1459 * loading the argument from there.
1460 * - all the trampolines should be of the same length.
1462 #if defined(TARGET_AMD64)
1463 #if defined(__default_codegen__)
1464 /* This should be exactly 8 bytes long */
1466 /* call *<offset>(%rip) */
1468 emit_unset_mode (acfg);
1469 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1470 emit_zero_bytes (acfg, 2);
1472 emit_byte (acfg, '\x41');
1473 emit_byte (acfg, '\xff');
1474 emit_byte (acfg, '\x15');
1475 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1476 emit_zero_bytes (acfg, 1);
1478 #elif defined(__native_client_codegen__)
1480 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1481 guint8 *code = buf_aligned;
1486 /* Emit this call in 'code' so we can find out how long it is. */
1487 amd64_call_reg (code, AMD64_R11);
1488 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1489 call_len = code - call_start;
1491 /* The tramp_size is twice the NaCl alignment because it starts with */
1492 /* a call which needs to be aligned to the end of the boundary. */
1493 *tramp_size = kNaClAlignment*2;
1495 /* Emit nops to align call site below which is 7 bytes plus */
1496 /* the length of the call sequence emitted above. */
1497 /* Note: this requires the specific trampoline starts on a */
1498 /* kNaclAlignedment aligned address, which it does because */
1499 /* it's its own function that is aligned. */
1500 guint8 nop_buf[256];
1501 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1502 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1503 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1505 /* The trampoline is stored at the offset'th pointer, the -4 is */
1506 /* present because RIP relative addressing starts at the end of */
1507 /* the current instruction, while the label "." is relative to */
1508 /* the beginning of the current asm location, which in this case */
1509 /* is not the mov instruction, but the offset itself, due to the */
1510 /* way the bytes and ints are emitted here. */
1511 got_offset = (offset * sizeof(gpointer)) - 4;
1513 /* mov <OFFSET>(%rip), %r11d */
1514 emit_byte (acfg, '\x45');
1515 emit_byte (acfg, '\x8b');
1516 emit_byte (acfg, '\x1d');
1517 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1520 emit_bytes (acfg, call_start, call_len);
1522 /* The arg is stored at the offset+1 pointer, relative to beginning */
1523 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1524 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1526 /* We can't emit this data directly, hide in a "push imm32" */
1527 emit_byte (acfg, '\x68'); /* push */
1528 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1529 emit_alignment (acfg, kNaClAlignment);
1530 #endif /*__native_client_codegen__*/
1531 #elif defined(TARGET_ARM)
1535 /* This should be exactly 20 bytes long */
1538 ARM_PUSH (code, 0x5fff);
1539 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1540 /* Load the value from the GOT */
1541 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1543 ARM_BLX_REG (code, ARMREG_R1);
1545 g_assert (code - buf == 16);
1548 emit_bytes (acfg, buf, code - buf);
1550 * Only one offset is needed, since the second one would be equal to the
1553 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1554 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1555 #elif defined(TARGET_ARM64)
1556 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1557 #elif defined(TARGET_POWERPC)
1565 * PPC has no ip relative addressing, so we need to compute the address
1566 * of the mscorlib got. That is slow and complex, so instead, we store it
1567 * in the second got slot of every aot image. The caller already computed
1568 * the address of its got and placed it into r30.
1570 emit_unset_mode (acfg);
1571 /* Load mscorlib got address */
1572 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1573 /* Load generic trampoline address */
1574 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1575 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1576 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1577 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1578 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1580 fprintf (acfg->fp, "mtctr 11\n");
1581 /* Load trampoline argument */
1582 /* On ppc, we pass it normally to the generic trampoline */
1583 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1584 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1585 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1586 /* Branch to generic trampoline */
1587 fprintf (acfg->fp, "bctr\n");
1589 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1590 *tramp_size = 10 * 4;
1592 *tramp_size = 9 * 4;
1594 #elif defined(TARGET_X86)
1598 /* Similar to the PPC code above */
1600 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1603 /* Load mscorlib got address */
1604 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1605 /* Push trampoline argument */
1606 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1607 /* Load generic trampoline address */
1608 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1609 /* Branch to generic trampoline */
1610 x86_jump_reg (code, X86_ECX);
1612 #ifdef __native_client_codegen__
1614 /* emit nops to next 32 byte alignment */
1615 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1616 while (code < (buf + a)) x86_nop(code);
1619 emit_bytes (acfg, buf, code - buf);
1621 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1622 g_assert (code - buf == *tramp_size);
1624 g_assert_not_reached ();
1629 * arch_emit_unbox_trampoline:
1631 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1632 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1635 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1637 #if defined(TARGET_AMD64)
1642 this_reg = mono_arch_get_this_arg_reg (NULL);
1644 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1646 emit_bytes (acfg, buf, code - buf);
1649 emit_unset_mode (acfg);
1650 fprintf (acfg->fp, "jmp %s\n", call_target);
1652 emit_byte (acfg, '\xe9');
1653 emit_symbol_diff (acfg, call_target, ".", -4);
1655 #elif defined(TARGET_X86)
1662 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1664 emit_bytes (acfg, buf, code - buf);
1667 emit_byte (acfg, '\xe9');
1668 emit_symbol_diff (acfg, call_target, ".", -4);
1669 #elif defined(TARGET_ARM)
1673 if (acfg->thumb_mixed && cfg->compile_llvm) {
1674 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1675 fprintf (acfg->fp, "b %s\n", call_target);
1676 fprintf (acfg->fp, ".arm\n");
1677 fprintf (acfg->fp, ".align 2\n");
1683 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1685 emit_bytes (acfg, buf, code - buf);
1686 /* jump to method */
1687 if (acfg->thumb_mixed && cfg->compile_llvm)
1688 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1690 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1691 #elif defined(TARGET_ARM64)
1692 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1693 #elif defined(TARGET_POWERPC)
1696 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1697 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1699 g_assert_not_reached ();
1704 * arch_emit_static_rgctx_trampoline:
1706 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1707 * two GOT slots which contain the rgctx argument, and the method to jump to.
1708 * TRAMP_SIZE is set to the size of the emitted trampoline.
1709 * These kinds of trampolines cannot be enumerated statically, since there could
1710 * be one trampoline per method instantiation, so we emit the same code for all
1711 * trampolines, and parameterize them using two GOT slots.
1714 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1716 #if defined(TARGET_AMD64)
1717 #if defined(__default_codegen__)
1718 /* This should be exactly 13 bytes long */
1722 emit_unset_mode (acfg);
1723 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1724 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1726 /* mov <OFFSET>(%rip), %r10 */
1727 emit_byte (acfg, '\x4d');
1728 emit_byte (acfg, '\x8b');
1729 emit_byte (acfg, '\x15');
1730 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1732 /* jmp *<offset>(%rip) */
1733 emit_byte (acfg, '\xff');
1734 emit_byte (acfg, '\x25');
1735 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1737 #elif defined(__native_client_codegen__)
1739 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1740 guint8 *code = buf_aligned;
1742 /* mov <OFFSET>(%rip), %r10d */
1743 emit_byte (acfg, '\x45');
1744 emit_byte (acfg, '\x8b');
1745 emit_byte (acfg, '\x15');
1746 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1748 /* mov <OFFSET>(%rip), %r11d */
1749 emit_byte (acfg, '\x45');
1750 emit_byte (acfg, '\x8b');
1751 emit_byte (acfg, '\x1d');
1752 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1755 amd64_jump_reg (code, AMD64_R11);
1756 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1758 emit_alignment (acfg, kNaClAlignment);
1759 *tramp_size = kNaClAlignment;
1760 #endif /*__native_client_codegen__*/
1762 #elif defined(TARGET_ARM)
1766 /* This should be exactly 24 bytes long */
1769 /* Load rgctx value */
1770 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1771 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1772 /* Load branch addr + branch */
1773 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1774 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1776 g_assert (code - buf == 16);
1779 emit_bytes (acfg, buf, code - buf);
1780 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1781 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1782 #elif defined(TARGET_ARM64)
1783 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1784 #elif defined(TARGET_POWERPC)
1792 * PPC has no ip relative addressing, so we need to compute the address
1793 * of the mscorlib got. That is slow and complex, so instead, we store it
1794 * in the second got slot of every aot image. The caller already computed
1795 * the address of its got and placed it into r30.
1797 emit_unset_mode (acfg);
1798 /* Load mscorlib got address */
1799 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1801 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1802 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1803 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1804 /* Load target address */
1805 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1806 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1807 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1808 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1809 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1810 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1812 fprintf (acfg->fp, "mtctr 11\n");
1813 /* Branch to the target address */
1814 fprintf (acfg->fp, "bctr\n");
1816 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1817 *tramp_size = 11 * 4;
1819 *tramp_size = 9 * 4;
1822 #elif defined(TARGET_X86)
1826 /* Similar to the PPC code above */
1828 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1831 /* Load mscorlib got address */
1832 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1834 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1835 /* Branch to the target address */
1836 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1838 #ifdef __native_client_codegen__
1840 /* emit nops to next 32 byte alignment */
1841 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1842 while (code < (buf + a)) x86_nop(code);
1846 emit_bytes (acfg, buf, code - buf);
1848 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1849 g_assert (code - buf == *tramp_size);
1851 g_assert_not_reached ();
1856 * arch_emit_imt_thunk:
1858 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1859 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1860 * key is the IMT key, and ptr holds the address of a memory location holding
1861 * the address to branch to if the IMT arg matches the key. The array is
1862 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1864 * TRAMP_SIZE is set to the size of the emitted trampoline.
1867 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1869 #if defined(TARGET_AMD64)
1871 #if defined(__native_client_codegen__)
1874 guint8 *labels [16];
1876 guint8 *mov_buf_ptr = mov_buf;
1878 const int kSizeOfMove = 7;
1879 #if defined(__default_codegen__)
1880 code = buf = (guint8 *)g_malloc (256);
1881 #elif defined(__native_client_codegen__)
1882 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1883 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1884 /* The RIP relative move below is emitted first */
1889 /* FIXME: Optimize this, i.e. use binary search etc. */
1890 /* Maybe move the body into a separate function (slower, but much smaller) */
1892 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1895 emit_unset_mode (acfg);
1896 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1900 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1902 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1905 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1907 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1910 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1911 amd64_jump_code (code, labels [0]);
1914 mono_amd64_patch (labels [2], code);
1915 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1916 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1919 mono_amd64_patch (labels [1], code);
1920 /* Load fail tramp */
1921 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1922 /* Check if there is a fail tramp */
1923 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1925 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1926 /* Jump to fail tramp */
1927 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1930 mono_amd64_patch (labels [3], code);
1931 x86_breakpoint (code);
1934 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1935 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1936 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1937 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1938 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1939 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1941 emit_bytes (acfg, buf, code - buf);
1943 *tramp_size = code - buf + kSizeOfMove;
1944 #if defined(__native_client_codegen__)
1945 /* The tramp will be padded to the next kNaClAlignment bundle. */
1946 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1949 #if defined(__default_codegen__)
1951 #elif defined(__native_client_codegen__)
1955 #elif defined(TARGET_X86)
1957 #ifdef __native_client_codegen__
1960 guint8 *labels [16];
1962 #if defined(__default_codegen__)
1963 code = buf = g_malloc (256);
1964 #elif defined(__native_client_codegen__)
1965 buf_alloc = g_malloc (256 + kNaClAlignment);
1966 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1969 /* Allocate a temporary stack slot */
1970 x86_push_reg (code, X86_EAX);
1972 x86_push_reg (code, X86_EAX);
1974 /* Load mscorlib got address */
1975 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1977 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1980 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1982 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1985 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1987 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1990 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1991 x86_jump_code (code, labels [0]);
1994 mono_x86_patch (labels [2], code);
1995 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1996 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1997 /* Save the target address to the temporary stack location */
1998 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2000 x86_pop_reg (code, X86_EAX);
2001 /* Jump to the target address */
2005 mono_x86_patch (labels [1], code);
2006 /* Load fail tramp */
2007 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2008 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2010 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2011 /* Jump to fail tramp */
2012 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2013 x86_pop_reg (code, X86_EAX);
2017 mono_x86_patch (labels [3], code);
2018 x86_breakpoint (code);
2020 #ifdef __native_client_codegen__
2022 /* emit nops to next 32 byte alignment */
2023 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2024 while (code < (buf + a)) x86_nop(code);
2027 emit_bytes (acfg, buf, code - buf);
2029 *tramp_size = code - buf;
2031 #if defined(__default_codegen__)
2033 #elif defined(__native_client_codegen__)
2037 #elif defined(TARGET_ARM)
2039 guint8 *code, *code2, *labels [16];
2043 /* The IMT method is in v5 */
2045 /* Need at least two free registers, plus a slot for storing the pc */
2046 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2048 /* Load the parameter from the GOT */
2049 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2050 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2053 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2054 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2056 ARM_B_COND (code, ARMCOND_EQ, 0);
2058 /* End-of-loop check */
2059 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2061 ARM_B_COND (code, ARMCOND_EQ, 0);
2064 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2067 arm_patch (labels [4], labels [1]);
2070 arm_patch (labels [2], code);
2071 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2072 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2073 /* Save it to the third stack slot */
2074 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2075 /* Restore the registers and branch */
2076 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2079 arm_patch (labels [3], code);
2080 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2081 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2082 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2086 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2088 emit_bytes (acfg, buf, code - buf);
2089 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2091 *tramp_size = code - buf + 4;
2092 #elif defined(TARGET_ARM64)
2093 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2094 #elif defined(TARGET_POWERPC)
2096 guint8 *code, *labels [16];
2100 /* Load the mscorlib got address */
2101 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2102 /* Load the parameter from the GOT */
2103 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2104 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2106 /* Load and check key */
2108 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2109 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2111 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2113 /* End-of-loop check */
2114 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2116 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2119 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2122 mono_ppc_patch (labels [4], labels [1]);
2125 mono_ppc_patch (labels [2], code);
2126 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2127 /* r12 now contains the value of the vtable slot */
2128 /* this is not a function descriptor on ppc64 */
2129 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2130 ppc_mtctr (code, ppc_r12);
2131 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2134 mono_ppc_patch (labels [3], code);
2138 *tramp_size = code - buf;
2140 emit_bytes (acfg, buf, code - buf);
2142 g_assert_not_reached ();
2147 #if defined (TARGET_AMD64)
2150 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2153 g_assert (acfg->fp);
2154 emit_unset_mode (acfg);
2156 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2163 * arch_emit_gsharedvt_arg_trampoline:
2165 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2166 * two GOT slots which contain the argument, and the code to jump to.
2167 * TRAMP_SIZE is set to the size of the emitted trampoline.
2168 * These kinds of trampolines cannot be enumerated statically, since there could
2169 * be one trampoline per method instantiation, so we emit the same code for all
2170 * trampolines, and parameterize them using two GOT slots.
2173 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2175 #if defined(TARGET_X86)
2179 /* Similar to the PPC code above */
2181 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2184 /* Load mscorlib got address */
2185 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2187 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2188 /* Branch to the target address */
2189 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2191 #ifdef __native_client_codegen__
2193 /* emit nops to next 32 byte alignment */
2194 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2195 while (code < (buf + a)) x86_nop(code);
2199 emit_bytes (acfg, buf, code - buf);
2201 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2202 g_assert (code - buf == *tramp_size);
2203 #elif defined(TARGET_ARM)
2207 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2208 /* Similar to arch_emit_specific_trampoline () */
2211 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2212 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2213 /* Load the arg value from the GOT */
2214 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2215 /* Load the addr from the GOT */
2216 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2218 ARM_BX (code, ARMREG_R1);
2220 g_assert (code - buf == 20);
2223 emit_bytes (acfg, buf, code - buf);
2224 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2225 #elif defined(TARGET_ARM64)
2226 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2227 #elif defined (TARGET_AMD64)
2229 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2230 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2231 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2232 fprintf (acfg->fp, "jmp *%%r11\n");
2236 g_assert_not_reached ();
2240 /* END OF ARCH SPECIFIC CODE */
2243 mono_get_field_token (MonoClassField *field)
2245 MonoClass *klass = field->parent;
2248 for (i = 0; i < klass->field.count; ++i) {
2249 if (field == &klass->fields [i])
2250 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2253 g_assert_not_reached ();
2258 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2262 //printf ("ENCODE: %d 0x%x.\n", value, value);
2265 * Same encoding as the one used in the metadata, extended to handle values
2266 * greater than 0x1fffffff.
2268 if ((value >= 0) && (value <= 127))
2270 else if ((value >= 0) && (value <= 16383)) {
2271 p [0] = 0x80 | (value >> 8);
2272 p [1] = value & 0xff;
2274 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2275 p [0] = (value >> 24) | 0xc0;
2276 p [1] = (value >> 16) & 0xff;
2277 p [2] = (value >> 8) & 0xff;
2278 p [3] = value & 0xff;
2283 p [1] = (value >> 24) & 0xff;
2284 p [2] = (value >> 16) & 0xff;
2285 p [3] = (value >> 8) & 0xff;
2286 p [4] = value & 0xff;
2294 stream_init (MonoDynamicStream *sh)
2297 sh->alloc_size = 4096;
2298 sh->data = (char *)g_malloc (4096);
2300 /* So offsets are > 0 */
2306 make_room_in_stream (MonoDynamicStream *stream, int size)
2308 if (size <= stream->alloc_size)
2311 while (stream->alloc_size <= size) {
2312 if (stream->alloc_size < 4096)
2313 stream->alloc_size = 4096;
2315 stream->alloc_size *= 2;
2318 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2322 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2326 make_room_in_stream (stream, stream->index + len);
2327 memcpy (stream->data + stream->index, data, len);
2328 idx = stream->index;
2329 stream->index += len;
2336 * Add data to the binary blob inside the aot image. Returns the offset inside the
2337 * blob where the data was stored.
2340 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2342 g_assert (!acfg->blob_closed);
2344 if (acfg->blob.alloc_size == 0)
2345 stream_init (&acfg->blob);
2347 return add_stream_data (&acfg->blob, (char*)data, data_len);
2351 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2356 if (acfg->blob.alloc_size == 0)
2357 stream_init (&acfg->blob);
2359 count = acfg->blob.index % align;
2361 /* we assume the stream data will be aligned */
2363 add_stream_data (&acfg->blob, buf, 4 - count);
2365 return add_stream_data (&acfg->blob, (char*)data, data_len);
2368 /* Emit a table of data into the aot image */
2370 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2372 if (acfg->data_outfile) {
2373 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2374 fwrite (data,1, size, acfg->data_outfile);
2375 acfg->datafile_offset += size;
2376 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2377 int align = 8 - size % 8;
2378 acfg->datafile_offset += align;
2379 guint8 align_buf [16];
2380 memset (&align_buf, 0, sizeof (align_buf));
2381 fwrite (align_buf, align, 1, acfg->data_outfile);
2382 } else if (acfg->llvm) {
2383 mono_llvm_emit_aot_data (symbol, data, size);
2385 emit_section_change (acfg, RODATA_SECT, 0);
2386 emit_alignment (acfg, 8);
2387 emit_label (acfg, symbol);
2388 emit_bytes (acfg, data, size);
2393 * emit_offset_table:
2395 * Emit a table of increasing offsets in a compact form using differential encoding.
2396 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2397 * group size, the more compact the table becomes, but the slower it becomes to compute
2398 * a given entry. Returns the size of the table.
2401 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2403 gint32 current_offset;
2404 int i, buf_size, ngroups, index_entry_size;
2406 guint8 *data_p, *data_buf;
2407 guint32 *index_offsets;
2409 ngroups = (noffsets + (group_size - 1)) / group_size;
2411 index_offsets = g_new0 (guint32, ngroups);
2413 buf_size = noffsets * 4;
2414 p = buf = (guint8 *)g_malloc0 (buf_size);
2417 for (i = 0; i < noffsets; ++i) {
2418 //printf ("D: %d -> %d\n", i, offsets [i]);
2419 if ((i % group_size) == 0) {
2420 index_offsets [i / group_size] = p - buf;
2421 /* Emit the full value for these entries */
2422 encode_value (offsets [i], p, &p);
2424 /* The offsets are allowed to be non-increasing */
2425 //g_assert (offsets [i] >= current_offset);
2426 encode_value (offsets [i] - current_offset, p, &p);
2428 current_offset = offsets [i];
2433 if (ngroups && index_offsets [ngroups - 1] < 65000)
2434 index_entry_size = 2;
2436 index_entry_size = 4;
2438 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2439 p = buf = (guint8 *)g_malloc0 (buf_size);
2441 /* Emit the header */
2442 encode_int (noffsets, p, &p);
2443 encode_int (group_size, p, &p);
2444 encode_int (ngroups, p, &p);
2445 encode_int (index_entry_size, p, &p);
2447 /* Emit the index */
2448 for (i = 0; i < ngroups; ++i) {
2449 if (index_entry_size == 2)
2450 encode_int16 (index_offsets [i], p, &p);
2452 encode_int (index_offsets [i], p, &p);
2455 memcpy (p, data_buf, data_p - data_buf);
2456 p += data_p - data_buf;
2458 g_assert (p - buf <= buf_size);
2460 emit_aot_data (acfg, table, symbol, buf, p - buf);
2465 return (int)(p - buf);
2469 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2473 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2477 index = g_hash_table_size (cfg->image_hash);
2478 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2479 g_ptr_array_add (cfg->image_table, image);
2485 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2488 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2490 /* FIXME: Search referenced images as well */
2491 if (!acfg->typespec_classes) {
2492 acfg->typespec_classes = (MonoClass **)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2493 for (i = 0; i < len; ++i) {
2495 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2496 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2499 for (i = 0; i < len; ++i) {
2500 if (acfg->typespec_classes [i] == klass)
2505 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2511 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2514 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2517 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2520 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2523 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2528 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2532 if (klass->generic_class) {
2534 g_assert (klass->type_token);
2536 /* Find a typespec for a class if possible */
2537 token = find_typespec_for_class (acfg, klass);
2539 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2540 encode_value (token, p, &p);
2542 MonoClass *gclass = klass->generic_class->container_class;
2543 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2544 static int count = 0;
2547 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2548 encode_klass_ref (acfg, gclass, p, &p);
2549 encode_ginst (acfg, inst, p, &p);
2553 } else if (klass->type_token) {
2554 int iindex = get_image_index (acfg, klass->image);
2556 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2558 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2559 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2561 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2562 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2563 encode_value (get_image_index (acfg, klass->image), p, &p);
2565 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2566 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2567 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2569 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2571 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2572 if (par->gshared_constraint) {
2573 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2574 encode_type (acfg, par->gshared_constraint, p, &p);
2575 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2577 encode_value (klass->byval_arg.type, p, &p);
2578 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2580 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2582 if (!container->is_anonymous) {
2583 encode_value (container->is_method, p, &p);
2584 if (container->is_method)
2585 encode_method_ref (acfg, container->owner.method, p, &p);
2587 encode_klass_ref (acfg, container->owner.klass, p, &p);
2590 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2591 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2592 encode_type (acfg, &klass->byval_arg, p, &p);
2595 g_assert (klass->rank > 0);
2596 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2597 encode_value (klass->rank, p, &p);
2598 encode_klass_ref (acfg, klass->element_class, p, &p);
2606 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2607 * standard metadata encoding.
2610 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2612 gboolean shared = FALSE;
2615 * The encoding of generic instances is large so emit them only once.
2617 if (klass->generic_class) {
2619 g_assert (klass->type_token);
2621 /* Find a typespec for a class if possible */
2622 token = find_typespec_for_class (acfg, klass);
2625 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2630 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2634 buf2 = (guint8 *)g_malloc (1024);
2637 encode_klass_ref_inner (acfg, klass, p, &p);
2638 g_assert (p - buf2 < 1024);
2640 offset = add_to_blob (acfg, buf2, p - buf2);
2643 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2649 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2650 encode_value (offset, p, &p);
2655 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2659 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2661 guint32 token = mono_get_field_token (field);
2664 encode_klass_ref (cfg, field->parent, p, &p);
2665 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2666 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2671 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2676 encode_value (inst->type_argc, p, &p);
2677 for (i = 0; i < inst->type_argc; ++i)
2678 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2683 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2686 MonoGenericInst *inst;
2688 inst = context->class_inst;
2690 g_assert (inst->type_argc);
2691 encode_ginst (acfg, inst, p, &p);
2693 encode_value (0, p, &p);
2695 inst = context->method_inst;
2697 g_assert (inst->type_argc);
2698 encode_ginst (acfg, inst, p, &p);
2700 encode_value (0, p, &p);
2706 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2710 g_assert (t->num_mods == 0);
2711 /* t->attrs can be ignored */
2712 //g_assert (t->attrs == 0);
2715 *p = MONO_TYPE_PINNED;
2719 *p = MONO_TYPE_BYREF;
2727 case MONO_TYPE_VOID:
2728 case MONO_TYPE_BOOLEAN:
2729 case MONO_TYPE_CHAR:
2742 case MONO_TYPE_STRING:
2743 case MONO_TYPE_OBJECT:
2744 case MONO_TYPE_TYPEDBYREF:
2746 case MONO_TYPE_VALUETYPE:
2747 case MONO_TYPE_CLASS:
2748 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2750 case MONO_TYPE_SZARRAY:
2751 encode_klass_ref (acfg, t->data.klass, p, &p);
2754 encode_type (acfg, t->data.type, p, &p);
2756 case MONO_TYPE_GENERICINST: {
2757 MonoClass *gclass = t->data.generic_class->container_class;
2758 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2760 encode_klass_ref (acfg, gclass, p, &p);
2761 encode_ginst (acfg, inst, p, &p);
2764 case MONO_TYPE_ARRAY: {
2765 MonoArrayType *array = t->data.array;
2768 encode_klass_ref (acfg, array->eklass, p, &p);
2769 encode_value (array->rank, p, &p);
2770 encode_value (array->numsizes, p, &p);
2771 for (i = 0; i < array->numsizes; ++i)
2772 encode_value (array->sizes [i], p, &p);
2773 encode_value (array->numlobounds, p, &p);
2774 for (i = 0; i < array->numlobounds; ++i)
2775 encode_value (array->lobounds [i], p, &p);
2779 case MONO_TYPE_MVAR:
2780 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2783 g_assert_not_reached ();
2790 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2796 /* Similar to the metadata encoding */
2797 if (sig->generic_param_count)
2801 if (sig->explicit_this)
2803 flags |= (sig->call_convention & 0x0F);
2807 if (sig->generic_param_count)
2808 encode_value (sig->generic_param_count, p, &p);
2809 encode_value (sig->param_count, p, &p);
2811 encode_type (acfg, sig->ret, p, &p);
2812 for (i = 0; i < sig->param_count; ++i) {
2813 if (sig->sentinelpos == i) {
2814 *p = MONO_TYPE_SENTINEL;
2817 encode_type (acfg, sig->params [i], p, &p);
2823 #define MAX_IMAGE_INDEX 250
2826 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2828 guint32 image_index = get_image_index (acfg, method->klass->image);
2829 guint32 token = method->token;
2830 MonoJumpInfoToken *ji;
2834 * The encoding for most methods is as follows:
2835 * - image index encoded as a leb128
2836 * - token index encoded as a leb128
2837 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2838 * types of method encodings.
2841 /* Mark methods which can't use aot trampolines because they need the further
2842 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2844 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2845 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2846 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2848 if (method->wrapper_type) {
2849 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2851 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2853 encode_value (method->wrapper_type, p, &p);
2855 switch (method->wrapper_type) {
2856 case MONO_WRAPPER_REMOTING_INVOKE:
2857 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2858 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2861 m = mono_marshal_method_from_wrapper (method);
2863 encode_method_ref (acfg, m, p, &p);
2866 case MONO_WRAPPER_PROXY_ISINST:
2867 case MONO_WRAPPER_LDFLD:
2868 case MONO_WRAPPER_LDFLDA:
2869 case MONO_WRAPPER_STFLD:
2870 case MONO_WRAPPER_ISINST: {
2872 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2875 case MONO_WRAPPER_LDFLD_REMOTE:
2876 case MONO_WRAPPER_STFLD_REMOTE:
2878 case MONO_WRAPPER_ALLOC: {
2879 /* The GC name is saved once in MonoAotFileInfo */
2880 g_assert (info->d.alloc.alloc_type != -1);
2881 encode_value (info->d.alloc.alloc_type, p, &p);
2884 case MONO_WRAPPER_WRITE_BARRIER: {
2888 case MONO_WRAPPER_STELEMREF: {
2890 encode_value (info->subtype, p, &p);
2891 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2892 encode_value (info->d.virtual_stelemref.kind, p, &p);
2895 case MONO_WRAPPER_UNKNOWN: {
2897 encode_value (info->subtype, p, &p);
2898 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2899 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2900 encode_klass_ref (acfg, method->klass, p, &p);
2901 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2902 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2903 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2904 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2905 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
2906 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2907 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
2908 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2911 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2913 encode_value (info->subtype, p, &p);
2914 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2915 strcpy ((char*)p, method->name);
2916 p += strlen (method->name) + 1;
2917 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2918 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2920 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2921 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2925 case MONO_WRAPPER_SYNCHRONIZED: {
2928 m = mono_marshal_method_from_wrapper (method);
2930 g_assert (m != method);
2931 encode_method_ref (acfg, m, p, &p);
2934 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2936 encode_value (info->subtype, p, &p);
2938 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2939 encode_value (info->d.element_addr.rank, p, &p);
2940 encode_value (info->d.element_addr.elem_size, p, &p);
2941 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2942 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2944 g_assert_not_reached ();
2948 case MONO_WRAPPER_CASTCLASS: {
2950 encode_value (info->subtype, p, &p);
2953 case MONO_WRAPPER_RUNTIME_INVOKE: {
2955 encode_value (info->subtype, p, &p);
2956 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2957 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2958 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2959 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2962 case MONO_WRAPPER_DELEGATE_INVOKE:
2963 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2964 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2965 if (method->is_inflated) {
2966 /* These wrappers are identified by their class */
2967 encode_value (1, p, &p);
2968 encode_klass_ref (acfg, method->klass, p, &p);
2970 MonoMethodSignature *sig = mono_method_signature (method);
2971 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2973 encode_value (0, p, &p);
2974 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2975 encode_value (info ? info->subtype : 0, p, &p);
2976 encode_signature (acfg, sig, p, &p);
2980 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2982 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2983 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2987 g_assert_not_reached ();
2989 } else if (mono_method_signature (method)->is_inflated) {
2991 * This is a generic method, find the original token which referenced it and
2993 * Obtain the token from information recorded by the JIT.
2995 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
2997 image_index = get_image_index (acfg, ji->image);
2998 g_assert (image_index < MAX_IMAGE_INDEX);
3001 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3002 encode_value (image_index, p, &p);
3003 encode_value (token, p, &p);
3005 MonoMethod *declaring;
3006 MonoGenericContext *context = mono_method_get_context (method);
3008 g_assert (method->is_inflated);
3009 declaring = ((MonoMethodInflated*)method)->declaring;
3012 * This might be a non-generic method of a generic instance, which
3013 * doesn't have a token since the reference is generated by the JIT
3014 * like Nullable:Box/Unbox, or by generic sharing.
3016 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3017 /* Encode the klass */
3018 encode_klass_ref (acfg, method->klass, p, &p);
3019 /* Encode the method */
3020 image_index = get_image_index (acfg, method->klass->image);
3021 g_assert (image_index < MAX_IMAGE_INDEX);
3022 g_assert (declaring->token);
3023 token = declaring->token;
3024 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3025 encode_value (image_index, p, &p);
3026 encode_value (token, p, &p);
3027 encode_generic_context (acfg, context, p, &p);
3029 } else if (token == 0) {
3030 /* This might be a method of a constructed type like int[,].Set */
3031 /* Obtain the token from information recorded by the JIT */
3032 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3034 image_index = get_image_index (acfg, ji->image);
3035 g_assert (image_index < MAX_IMAGE_INDEX);
3038 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3039 encode_value (image_index, p, &p);
3040 encode_value (token, p, &p);
3043 g_assert (method->klass->rank);
3045 /* Encode directly */
3046 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3047 encode_klass_ref (acfg, method->klass, p, &p);
3048 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3049 encode_value (0, p, &p);
3050 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3051 encode_value (1, p, &p);
3052 else if (!strcmp (method->name, "Get"))
3053 encode_value (2, p, &p);
3054 else if (!strcmp (method->name, "Address"))
3055 encode_value (3, p, &p);
3056 else if (!strcmp (method->name, "Set"))
3057 encode_value (4, p, &p);
3059 g_assert_not_reached ();
3062 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3064 if (image_index >= MONO_AOT_METHODREF_MIN) {
3065 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3066 encode_value (image_index, p, &p);
3067 encode_value (mono_metadata_token_index (token), p, &p);
3069 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3076 compare_patches (gconstpointer a, gconstpointer b)
3080 i = (*(MonoJumpInfo**)a)->ip.i;
3081 j = (*(MonoJumpInfo**)b)->ip.i;
3092 static G_GNUC_UNUSED char*
3093 patch_to_string (MonoJumpInfo *patch_info)
3097 str = g_string_new ("");
3099 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3101 switch (patch_info->type) {
3102 case MONO_PATCH_INFO_VTABLE:
3103 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3108 g_string_append_printf (str, ")");
3109 return g_string_free (str, FALSE);
3115 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3118 static inline gboolean
3119 is_plt_patch (MonoJumpInfo *patch_info)
3121 switch (patch_info->type) {
3122 case MONO_PATCH_INFO_METHOD:
3123 case MONO_PATCH_INFO_INTERNAL_METHOD:
3124 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3125 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3126 case MONO_PATCH_INFO_RGCTX_FETCH:
3136 * Return the symbol identifying the plt entry PLT_OFFSET.
3139 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3143 * The Apple linker reorganizes object files, so it doesn't like branches to local
3144 * labels, since those have no relocations.
3146 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3148 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3155 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3157 static MonoPltEntry*
3158 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3161 gboolean synchronized = FALSE;
3162 static int synchronized_symbol_idx;
3164 if (!is_plt_patch (patch_info))
3167 if (!acfg->patch_to_plt_entry [patch_info->type])
3168 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3169 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3171 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3173 * Allocate a separate PLT slot for each such patch, since some plt
3174 * entries will refer to the method itself, and some will refer to the
3178 synchronized = TRUE;
3182 MonoJumpInfo *new_ji;
3184 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3186 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3187 res->plt_offset = acfg->plt_offset;
3189 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3190 if (acfg->aot_opts.write_symbols)
3191 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3193 /* Avoid duplicate symbols because we don't cache */
3194 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3196 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3197 synchronized_symbol_idx ++;
3200 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3202 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3204 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3206 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3208 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3209 //mono_print_ji (patch_info); printf ("\n");
3210 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3212 acfg->plt_offset ++;
3221 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3222 * JI could be found if it exists, otherwise allocates a new one.
3225 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3228 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3230 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3232 return got_offset - 1;
3235 got_offset = acfg->llvm_got_offset;
3236 acfg->llvm_got_offset ++;
3238 got_offset = acfg->got_offset;
3239 acfg->got_offset ++;
3242 acfg->stats.got_slots ++;
3243 acfg->stats.got_slot_types [ji->type] ++;
3245 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3246 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3247 g_ptr_array_add (info->got_patches, ji);
3252 /* Add a method to the list of methods which need to be emitted */
3254 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3257 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3258 g_ptr_array_add (acfg->methods, method);
3259 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3260 acfg->nmethods = acfg->methods->len + 1;
3263 if (method->wrapper_type || extra)
3264 g_ptr_array_add (acfg->extra_methods, method);
3268 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3270 /* One instantiation with valuetypes is generated for each async method */
3271 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3278 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3280 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3288 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3292 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3296 index = acfg->method_index;
3297 add_method_with_index (acfg, method, index, extra);
3299 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3301 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3303 acfg->method_index ++;
3309 add_method (MonoAotCompile *acfg, MonoMethod *method)
3311 return add_method_full (acfg, method, FALSE, 0);
3315 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3317 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3318 method = mini_get_shared_method (method);
3319 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3320 /* Use the gsharedvt version */
3321 method = mini_get_shared_method_full (method, TRUE, TRUE);
3323 if (acfg->aot_opts.log_generics)
3324 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3326 add_method_full (acfg, method, TRUE, depth);
3330 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3332 add_extra_method_with_depth (acfg, method, 0);
3336 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3338 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3339 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3340 MonoMethod *wrapper;
3346 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3347 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3350 add_method (acfg, wrapper);
3354 get_runtime_invoke_sig (MonoMethodSignature *sig)
3356 MonoMethodBuilder *mb;
3359 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3360 m = mono_mb_create_method (mb, sig, 16);
3361 return mono_marshal_get_runtime_invoke (m, FALSE);
3365 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3367 return mono_marshal_get_runtime_invoke (method, virtual_);
3371 can_marshal_struct (MonoClass *klass)
3373 MonoClassField *field;
3374 gboolean can_marshal = TRUE;
3375 gpointer iter = NULL;
3376 MonoMarshalType *info;
3379 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3382 info = mono_marshal_load_type_info (klass);
3384 /* Only allow a few field types to avoid asserts in the marshalling code */
3385 while ((field = mono_class_get_fields (klass, &iter))) {
3386 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3389 switch (field->type->type) {
3394 case MONO_TYPE_BOOLEAN:
3397 case MONO_TYPE_CHAR:
3405 case MONO_TYPE_STRING:
3407 case MONO_TYPE_VALUETYPE:
3408 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3409 can_marshal = FALSE;
3411 case MONO_TYPE_SZARRAY: {
3412 gboolean has_mspec = FALSE;
3415 for (i = 0; i < info->num_fields; ++i) {
3416 if (info->fields [i].field == field && info->fields [i].mspec)
3421 can_marshal = FALSE;
3425 can_marshal = FALSE;
3431 /* Its hard to compute whenever these can be marshalled or not */
3432 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3439 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3441 /* Create a vtype instantiation */
3442 MonoGenericContext shared_context;
3444 MonoGenericInst *inst;
3445 MonoGenericContainer *container;
3446 MonoClass **constraints;
3449 memset (ctx, 0, sizeof (MonoGenericContext));
3451 if (method->klass->generic_container) {
3452 shared_context = method->klass->generic_container->context;
3453 inst = shared_context.class_inst;
3455 args = g_new0 (MonoType*, inst->type_argc);
3456 for (i = 0; i < inst->type_argc; ++i) {
3457 args [i] = &mono_defaults.int_class->byval_arg;
3459 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3461 if (method->is_generic) {
3462 container = mono_method_get_generic_container (method);
3463 shared_context = container->context;
3464 inst = shared_context.method_inst;
3466 args = g_new0 (MonoType*, inst->type_argc);
3467 for (i = 0; i < container->type_argc; ++i) {
3468 MonoGenericParamInfo *info = &container->type_params [i].info;
3469 gboolean ref_only = FALSE;
3471 if (info && info->constraints) {
3472 constraints = info->constraints;
3474 while (*constraints) {
3475 MonoClass *cklass = *constraints;
3476 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3477 /* Inflaring the method with our vtype would not be valid */
3484 args [i] = &mono_defaults.object_class->byval_arg;
3486 args [i] = &mono_defaults.int_class->byval_arg;
3488 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3493 add_wrappers (MonoAotCompile *acfg)
3495 MonoMethod *method, *m;
3497 MonoMethodSignature *sig, *csig;
3501 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3502 * so there is only one wrapper of a given type, or inlining their contents into their
3505 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3508 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3509 gboolean skip = FALSE;
3511 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3512 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3514 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3515 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3516 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3519 /* Skip methods which can not be handled by get_runtime_invoke () */
3520 sig = mono_method_signature (method);
3523 if ((sig->ret->type == MONO_TYPE_PTR) ||
3524 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3526 if (mono_class_is_open_constructed_type (sig->ret))
3529 for (j = 0; j < sig->param_count; j++) {
3530 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3532 if (mono_class_is_open_constructed_type (sig->params [j]))
3536 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3537 if (!mono_class_is_contextbound (method->klass)) {
3538 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3539 gboolean has_nullable = FALSE;
3541 for (j = 0; j < sig->param_count; j++) {
3542 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3543 has_nullable = TRUE;
3546 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3547 /* Supported by the dynamic runtime-invoke wrapper */
3551 mono_arch_dyn_call_free (info);
3555 if (acfg->aot_opts.llvm_only)
3556 /* Supported by the gsharedvt based runtime-invoke wrapper */
3560 //printf ("%s\n", mono_method_full_name (method, TRUE));
3561 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3565 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3568 /* Runtime invoke wrappers */
3570 /* void runtime-invoke () [.cctor] */
3571 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3572 csig->ret = &mono_defaults.void_class->byval_arg;
3573 add_method (acfg, get_runtime_invoke_sig (csig));
3575 /* void runtime-invoke () [Finalize] */
3576 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3578 csig->ret = &mono_defaults.void_class->byval_arg;
3579 add_method (acfg, get_runtime_invoke_sig (csig));
3581 /* void runtime-invoke (string) [exception ctor] */
3582 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3584 csig->ret = &mono_defaults.void_class->byval_arg;
3585 csig->params [0] = &mono_defaults.string_class->byval_arg;
3586 add_method (acfg, get_runtime_invoke_sig (csig));
3588 /* void runtime-invoke (string, string) [exception ctor] */
3589 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3591 csig->ret = &mono_defaults.void_class->byval_arg;
3592 csig->params [0] = &mono_defaults.string_class->byval_arg;
3593 csig->params [1] = &mono_defaults.string_class->byval_arg;
3594 add_method (acfg, get_runtime_invoke_sig (csig));
3596 /* string runtime-invoke () [Exception.ToString ()] */
3597 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3599 csig->ret = &mono_defaults.string_class->byval_arg;
3600 add_method (acfg, get_runtime_invoke_sig (csig));
3602 /* void runtime-invoke (string, Exception) [exception ctor] */
3603 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3605 csig->ret = &mono_defaults.void_class->byval_arg;
3606 csig->params [0] = &mono_defaults.string_class->byval_arg;
3607 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3608 add_method (acfg, get_runtime_invoke_sig (csig));
3610 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3611 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3613 csig->ret = &(mono_class_load_from_name (
3614 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3615 csig->params [0] = &mono_defaults.string_class->byval_arg;
3616 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3617 add_method (acfg, get_runtime_invoke_sig (csig));
3619 /* runtime-invoke used by finalizers */
3620 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3622 /* This is used by mono_runtime_capture_context () */
3623 method = mono_get_context_capture_method ();
3625 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3627 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3628 if (!acfg->aot_opts.llvm_only)
3629 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3632 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3633 if (acfg->aot_opts.llvm_only) {
3636 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3637 for (variants = 0; variants < 4; ++variants) {
3638 for (i = 0; i < 16; ++i) {
3639 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3640 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3648 add_method (acfg, mono_marshal_get_stelemref ());
3650 if (MONO_ARCH_HAVE_TLS_GET) {
3651 /* Managed Allocators */
3652 nallocators = mono_gc_get_managed_allocator_types ();
3653 for (i = 0; i < nallocators; ++i) {
3654 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3656 add_method (acfg, m);
3658 for (i = 0; i < nallocators; ++i) {
3659 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3661 add_method (acfg, m);
3665 /* write barriers */
3666 if (mono_gc_is_moving ()) {
3667 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3668 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3671 /* Stelemref wrappers */
3673 MonoMethod **wrappers;
3676 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3677 for (i = 0; i < nwrappers; ++i)
3678 add_method (acfg, wrappers [i]);
3682 /* castclass_with_check wrapper */
3683 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3684 /* isinst_with_check wrapper */
3685 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3687 /* JIT icall wrappers */
3688 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3689 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3693 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3694 * we use the original method instead at runtime.
3695 * Since full-aot doesn't support remoting, this is not a problem.
3698 /* remoting-invoke wrappers */
3699 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3701 MonoMethodSignature *sig;
3703 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3704 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3705 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3707 sig = mono_method_signature (method);
3709 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3710 m = mono_marshal_get_remoting_invoke_with_check (method);
3712 add_method (acfg, m);
3717 /* delegate-invoke wrappers */
3718 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3721 MonoCustomAttrInfo *cattr;
3723 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3724 klass = mono_class_get_checked (acfg->image, token, &error);
3727 mono_error_cleanup (&error);
3731 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3734 if (!klass->generic_container) {
3735 method = mono_get_delegate_invoke (klass);
3737 m = mono_marshal_get_delegate_invoke (method, NULL);
3739 add_method (acfg, m);
3741 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3743 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3745 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3747 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3749 cattr = mono_custom_attrs_from_class_checked (klass, &error);
3750 if (!is_ok (&error)) {
3751 mono_error_cleanup (&error);
3758 for (j = 0; j < cattr->num_attrs; ++j)
3759 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3761 if (j < cattr->num_attrs) {
3763 MonoMethod *wrapper;
3764 MonoMethod *del_invoke;
3766 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3767 invoke = mono_get_delegate_invoke (klass);
3768 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3769 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3770 add_method (acfg, wrapper);
3771 add_method (acfg, del_invoke);
3774 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3776 MonoGenericContext ctx;
3777 MonoMethod *inst, *gshared;
3780 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3783 method = mono_get_delegate_invoke (klass);
3784 create_gsharedvt_inst (acfg, method, &ctx);
3786 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3787 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3789 m = mono_marshal_get_delegate_invoke (inst, NULL);
3790 g_assert (m->is_inflated);
3792 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3793 add_extra_method (acfg, gshared);
3796 method = mono_get_delegate_begin_invoke (klass);
3797 create_gsharedvt_inst (acfg, method, &ctx);
3799 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3800 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3802 m = mono_marshal_get_delegate_begin_invoke (inst);
3803 g_assert (m->is_inflated);
3805 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3806 add_extra_method (acfg, gshared);
3809 method = mono_get_delegate_end_invoke (klass);
3810 create_gsharedvt_inst (acfg, method, &ctx);
3812 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3813 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3815 m = mono_marshal_get_delegate_end_invoke (inst);
3816 g_assert (m->is_inflated);
3818 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3819 add_extra_method (acfg, gshared);
3824 /* array access wrappers */
3825 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3829 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3830 klass = mono_class_get_checked (acfg->image, token, &error);
3833 mono_error_cleanup (&error);
3837 if (!acfg->aot_opts.llvm_only && klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3838 MonoMethod *m, *wrapper;
3840 /* Add runtime-invoke wrappers too */
3842 m = mono_class_get_method_from_name (klass, "Get", -1);
3844 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3845 add_extra_method (acfg, wrapper);
3846 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3848 m = mono_class_get_method_from_name (klass, "Set", -1);
3850 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3851 add_extra_method (acfg, wrapper);
3852 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3856 /* Synchronized wrappers */
3857 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3859 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3860 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3861 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3863 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3864 if (method->is_generic) {
3866 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3868 MonoGenericContext ctx;
3869 MonoMethod *inst, *gshared, *m;
3872 * Create a generic wrapper for a generic instance, and AOT that.
3874 create_gsharedvt_inst (acfg, method, &ctx);
3875 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3876 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3877 m = mono_marshal_get_synchronized_wrapper (inst);
3878 g_assert (m->is_inflated);
3879 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3880 add_method (acfg, gshared);
3882 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3887 /* pinvoke wrappers */
3888 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3891 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3893 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3894 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3896 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3897 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3898 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3902 /* native-to-managed wrappers */
3903 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3906 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3907 MonoCustomAttrInfo *cattr;
3910 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3911 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3914 * Only generate native-to-managed wrappers for methods which have an
3915 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3916 * name to avoid defining a new assembly to contain it.
3918 cattr = mono_custom_attrs_from_method_checked (method, &error);
3919 if (!is_ok (&error)) {
3920 char *name = mono_method_get_full_name (method);
3921 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
3926 for (j = 0; j < cattr->num_attrs; ++j)
3927 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3929 if (j < cattr->num_attrs) {
3930 MonoCustomAttrEntry *e = &cattr->attrs [j];
3931 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3932 const char *p = (const char*)e->data;
3934 int slen, num_named, named_type;
3938 char *export_name = NULL;
3939 MonoMethod *wrapper;
3941 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3942 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3943 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3944 mono_method_full_name (method, TRUE));
3948 g_assert (sig->param_count == 1);
3949 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3952 * Decode the cattr manually since we can't create objects
3953 * during aot compilation.
3959 /* From load_cattr_value () in reflection.c */
3960 slen = mono_metadata_decode_value (p, &p);
3961 n = (char *)g_memdup (p, slen + 1);
3963 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
3965 mono_error_assert_ok (&error);
3968 klass = mono_class_from_mono_type (t);
3969 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3973 num_named = read16 (p);
3976 g_assert (num_named < 2);
3977 if (num_named == 1) {
3981 /* parse ExportSymbol attribute */
3983 named_type = *named;
3985 /* data_type = *named; */
3988 name_len = mono_metadata_decode_blob_size (named, &named);
3989 name = (char *)g_malloc (name_len + 1);
3990 memcpy (name, named, name_len);
3991 name [name_len] = 0;
3994 g_assert (named_type == 0x54);
3995 g_assert (!strcmp (name, "ExportSymbol"));
3997 /* load_cattr_value (), string case */
3998 g_assert (*named != (char)0xff);
3999 slen = mono_metadata_decode_value (named, &named);
4000 export_name = (char *)g_malloc (slen + 1);
4001 memcpy (export_name, named, slen);
4002 export_name [slen] = 0;
4006 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4007 add_method (acfg, wrapper);
4009 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4013 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4014 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4015 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4019 /* StructureToPtr/PtrToStructure wrappers */
4020 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4024 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4025 klass = mono_class_get_checked (acfg->image, token, &error);
4028 mono_error_cleanup (&error);
4032 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4033 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4034 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4035 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4041 has_type_vars (MonoClass *klass)
4043 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4046 return has_type_vars (klass->element_class);
4047 if (klass->generic_class) {
4048 MonoGenericContext *context = &klass->generic_class->context;
4049 if (context->class_inst) {
4052 for (i = 0; i < context->class_inst->type_argc; ++i)
4053 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4057 if (klass->generic_container)
4063 is_vt_inst (MonoGenericInst *inst)
4067 for (i = 0; i < inst->type_argc; ++i) {
4068 MonoType *t = inst->type_argv [i];
4069 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4076 method_has_type_vars (MonoMethod *method)
4078 if (has_type_vars (method->klass))
4081 if (method->is_inflated) {
4082 MonoGenericContext *context = mono_method_get_context (method);
4083 if (context->method_inst) {
4086 for (i = 0; i < context->method_inst->type_argc; ++i)
4087 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4095 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4097 return opts->mode == MONO_AOT_MODE_FULL;
4100 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4103 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4105 /* This might lead to a huge code blowup so only do it if neccesary */
4106 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4109 add_generic_class_with_depth (acfg, klass, 0, ref);
4113 check_type_depth (MonoType *t, int depth)
4121 case MONO_TYPE_GENERICINST: {
4122 MonoGenericClass *gklass = t->data.generic_class;
4123 MonoGenericInst *ginst = gklass->context.class_inst;
4126 for (i = 0; i < ginst->type_argc; ++i) {
4127 if (check_type_depth (ginst->type_argv [i], depth + 1))
4141 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4144 * add_generic_class:
4146 * Add all methods of a generic class.
4149 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4152 MonoClassField *field;
4154 gboolean use_gsharedvt = FALSE;
4156 if (!acfg->ginst_hash)
4157 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4159 mono_class_init (klass);
4161 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4164 if (has_type_vars (klass))
4167 if (!klass->generic_class && !klass->rank)
4170 if (mono_class_has_failure (klass))
4173 if (!acfg->ginst_hash)
4174 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4176 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4179 if (check_type_depth (&klass->byval_arg, 0))
4182 if (acfg->aot_opts.log_generics)
4183 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4185 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4188 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4189 * Enable this only for some classes since gsharedvt might not support all methods.
4191 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) &&
4192 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4193 use_gsharedvt = TRUE;
4196 while ((method = mono_class_get_methods (klass, &iter))) {
4197 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4199 * This is partial sharing, and we can't handle it yet
4204 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4206 add_types_from_method_header (acfg, method);
4210 if (method->is_generic)
4215 * FIXME: Instances which are referenced by these methods are not added,
4216 * for example Array.Resize<int> for List<int>.Add ().
4218 add_extra_method_with_depth (acfg, method, depth + 1);
4222 while ((field = mono_class_get_fields (klass, &iter))) {
4223 if (field->type->type == MONO_TYPE_GENERICINST)
4224 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4227 if (klass->delegate) {
4228 method = mono_get_delegate_invoke (klass);
4230 method = mono_marshal_get_delegate_invoke (method, NULL);
4232 if (acfg->aot_opts.log_generics)
4233 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4235 add_method (acfg, method);
4238 /* Add superclasses */
4240 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4243 * For ICollection<T>, add instances of the helper methods
4244 * in Array, since a T[] could be cast to ICollection<T>.
4246 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4247 (!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"))) {
4248 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4249 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4253 if (!strcmp (klass->name, "IEnumerator`1"))
4254 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4256 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4258 /* Add the T[]/InternalEnumerator class */
4259 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4264 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4265 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4269 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (klass->generic_class), &error);
4270 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4271 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4275 while ((method = mono_class_get_methods (array_class, &iter))) {
4276 if (strstr (method->name, name_prefix)) {
4277 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4279 add_extra_method_with_depth (acfg, m, depth);
4283 g_free (name_prefix);
4286 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4287 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4289 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4290 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4291 MonoGenericContext ctx;
4292 MonoType *args [16];
4294 memset (&ctx, 0, sizeof (ctx));
4296 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4298 args [0] = &tclass->byval_arg;
4299 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4301 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4302 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4304 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4305 MonoClass *gcomparer_inst;
4306 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4307 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4308 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4310 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4314 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4315 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4317 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4318 MonoClass *iface, *gcomparer, *iface_inst;
4319 MonoGenericContext ctx;
4320 MonoType *args [16];
4322 memset (&ctx, 0, sizeof (ctx));
4324 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4326 args [0] = &tclass->byval_arg;
4327 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4329 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4330 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4332 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4333 MonoClass *gcomparer_inst;
4336 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4337 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4338 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4339 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4343 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4344 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4345 MonoClass *enum_comparer;
4346 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4347 MonoGenericContext ctx;
4348 MonoType *args [16];
4350 if (mono_class_is_enum (tclass)) {
4351 MonoClass *enum_comparer_inst;
4354 memset (&ctx, 0, sizeof (ctx));
4355 args [0] = &tclass->byval_arg;
4356 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4358 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4359 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4360 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4361 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4365 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4366 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4367 MonoClass *comparer;
4368 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4369 MonoGenericContext ctx;
4370 MonoType *args [16];
4372 if (mono_class_is_enum (tclass)) {
4373 MonoClass *comparer_inst;
4376 memset (&ctx, 0, sizeof (ctx));
4377 args [0] = &tclass->byval_arg;
4378 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4380 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4381 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4382 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4383 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4389 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4392 MonoGenericContext ctx;
4393 MonoType *args [16];
4395 if (acfg->aot_opts.no_instances)
4398 memset (&ctx, 0, sizeof (ctx));
4400 for (i = 0; i < ninsts; ++i) {
4402 MonoClass *generic_inst;
4403 args [0] = insts [i];
4404 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4405 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4406 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4407 add_generic_class (acfg, generic_inst, force, "");
4412 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4415 MonoMethodHeader *header;
4416 MonoMethodSignature *sig;
4419 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4421 sig = mono_method_signature (method);
4424 for (j = 0; j < sig->param_count; ++j)
4425 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4426 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4429 header = mono_method_get_header_checked (method, &error);
4432 for (j = 0; j < header->num_locals; ++j)
4433 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4434 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4436 mono_error_cleanup (&error); /* FIXME report the error */
4441 * add_generic_instances:
4443 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4446 add_generic_instances (MonoAotCompile *acfg)
4451 MonoGenericContext *context;
4453 if (acfg->aot_opts.no_instances)
4456 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4458 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4459 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4462 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4463 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4464 mono_error_cleanup (&error);
4468 if (method->klass->image != acfg->image)
4471 context = mono_method_get_context (method);
4473 if (context && ((context->class_inst && context->class_inst->is_open)))
4477 * For open methods, create an instantiation which can be passed to the JIT.
4478 * FIXME: Handle class_inst as well.
4480 if (context && context->method_inst && context->method_inst->is_open) {
4482 MonoGenericContext shared_context;
4483 MonoGenericInst *inst;
4484 MonoType **type_argv;
4486 MonoMethod *declaring_method;
4487 gboolean supported = TRUE;
4489 /* Check that the context doesn't contain open constructed types */
4490 if (context->class_inst) {
4491 inst = context->class_inst;
4492 for (i = 0; i < inst->type_argc; ++i) {
4493 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)
4495 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4499 if (context->method_inst) {
4500 inst = context->method_inst;
4501 for (i = 0; i < inst->type_argc; ++i) {
4502 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)
4504 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4512 memset (&shared_context, 0, sizeof (MonoGenericContext));
4514 inst = context->class_inst;
4516 type_argv = g_new0 (MonoType*, inst->type_argc);
4517 for (i = 0; i < inst->type_argc; ++i) {
4518 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)
4519 type_argv [i] = &mono_defaults.object_class->byval_arg;
4521 type_argv [i] = inst->type_argv [i];
4524 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4528 inst = context->method_inst;
4530 type_argv = g_new0 (MonoType*, inst->type_argc);
4531 for (i = 0; i < inst->type_argc; ++i) {
4532 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)
4533 type_argv [i] = &mono_defaults.object_class->byval_arg;
4535 type_argv [i] = inst->type_argv [i];
4538 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4542 if (method->is_generic || method->klass->generic_container)
4543 declaring_method = method;
4545 declaring_method = mono_method_get_declaring_generic_method (method);
4547 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4548 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4552 * If the method is fully sharable, it was already added in place of its
4553 * generic definition.
4555 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4559 * FIXME: Partially shared methods are not shared here, so we end up with
4560 * many identical methods.
4562 add_extra_method (acfg, method);
4565 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4569 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4571 klass = mono_class_get_checked (acfg->image, token, &error);
4572 if (!klass || klass->rank) {
4573 mono_error_cleanup (&error);
4577 add_generic_class (acfg, klass, FALSE, "typespec");
4580 /* Add types of args/locals */
4581 for (i = 0; i < acfg->methods->len; ++i) {
4582 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4583 add_types_from_method_header (acfg, method);
4586 if (acfg->image == mono_defaults.corlib) {
4588 MonoType *insts [256];
4591 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4592 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4593 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4594 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4595 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4596 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4597 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4598 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4599 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4600 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4601 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4602 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4604 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4605 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4607 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4608 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4610 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4612 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4614 MonoClass *enum_comparer;
4615 MonoType *insts [16];
4619 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4620 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4621 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4622 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4623 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4624 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4627 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4628 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4629 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4632 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4633 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4634 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4636 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4638 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4639 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4640 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4643 /* Add instances of the array generic interfaces for primitive types */
4644 /* This will add instances of the InternalArray_ helper methods in Array too */
4645 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4647 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4649 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4651 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4653 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4655 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4658 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4659 * used for all instances of GetGenericValueImpl by the AOT runtime.
4662 MonoGenericContext ctx;
4663 MonoType *args [16];
4664 MonoMethod *get_method;
4665 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4667 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4671 memset (&ctx, 0, sizeof (ctx));
4672 args [0] = &mono_defaults.object_class->byval_arg;
4673 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4674 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4675 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4679 /* Same for CompareExchange<T>/Exchange<T> */
4681 MonoGenericContext ctx;
4682 MonoType *args [16];
4684 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4685 gpointer iter = NULL;
4687 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4688 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4690 memset (&ctx, 0, sizeof (ctx));
4691 args [0] = &mono_defaults.object_class->byval_arg;
4692 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4693 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4694 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4699 /* Same for Volatile.Read/Write<T> */
4701 MonoGenericContext ctx;
4702 MonoType *args [16];
4704 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4705 gpointer iter = NULL;
4707 if (volatile_klass) {
4708 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4709 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4711 memset (&ctx, 0, sizeof (ctx));
4712 args [0] = &mono_defaults.object_class->byval_arg;
4713 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4714 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4715 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4721 /* object[] accessor wrappers. */
4723 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
4726 m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
4729 m = mono_marshal_get_array_accessor_wrapper (m);
4730 add_extra_method (acfg, m);
4732 m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
4735 m = mono_marshal_get_array_accessor_wrapper (m);
4736 add_extra_method (acfg, m);
4738 m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
4741 m = mono_marshal_get_array_accessor_wrapper (m);
4742 add_extra_method (acfg, m);
4748 * is_direct_callable:
4750 * Return whenever the method identified by JI is directly callable without
4751 * going through the PLT.
4754 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4756 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4757 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4759 gboolean direct_callable = TRUE;
4761 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4762 direct_callable = FALSE;
4763 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4764 // FIXME: Maybe call the wrapper directly ?
4765 direct_callable = FALSE;
4767 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4768 /* Disable this so all calls go through load_method (), see the
4769 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4770 * mono_debugger_agent_init ().
4772 direct_callable = FALSE;
4775 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4776 /* sgen does some initialization when the allocator method is created */
4777 direct_callable = FALSE;
4778 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4779 /* we don't know at compile time whether sgen is concurrent or not */
4780 direct_callable = FALSE;
4782 if (direct_callable)
4785 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4786 if (acfg->aot_opts.direct_pinvoke)
4788 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
4789 if (acfg->aot_opts.direct_icalls)
4797 #ifdef MONO_ARCH_AOT_SUPPORTED
4799 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4801 MonoImage *image = method->klass->image;
4802 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4803 MonoTableInfo *tables = image->tables;
4804 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4805 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4806 guint32 im_cols [MONO_IMPLMAP_SIZE];
4809 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4813 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4816 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4818 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4821 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4823 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4829 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4836 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4838 if (a->native_offset == b->native_offset)
4839 return a->il_offset - b->il_offset;
4841 return a->native_offset - b->native_offset;
4845 * compute_line_numbers:
4847 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4850 static MonoDebugSourceLocation**
4851 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4853 MonoDebugMethodInfo *minfo;
4854 MonoDebugLineNumberEntry *ln_array;
4855 MonoDebugSourceLocation *loc;
4856 int i, prev_line, prev_il_offset;
4857 int *native_to_il_offset = NULL;
4858 MonoDebugSourceLocation **res;
4861 minfo = mono_debug_lookup_method (method);
4864 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4865 if (debug_info->code_size != code_size)
4868 g_assert (code_size);
4870 /* Compute the native->IL offset mapping */
4872 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4873 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4875 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
4877 native_to_il_offset = g_new0 (int, code_size + 1);
4879 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4881 MonoDebugLineNumberEntry *lne = &ln_array [i];
4884 for (j = 0; j < lne->native_offset; ++j)
4885 native_to_il_offset [j] = -1;
4888 if (i < debug_info->num_line_numbers - 1) {
4889 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4891 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4892 native_to_il_offset [j] = lne->il_offset;
4894 for (j = lne->native_offset; j < code_size; ++j)
4895 native_to_il_offset [j] = lne->il_offset;
4900 /* Compute the native->line number mapping */
4901 res = g_new0 (MonoDebugSourceLocation*, code_size);
4902 prev_il_offset = -1;
4905 for (i = 0; i < code_size; ++i) {
4906 int il_offset = native_to_il_offset [i];
4908 if (il_offset == -1 || il_offset == prev_il_offset)
4910 prev_il_offset = il_offset;
4911 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4912 if (!(loc && loc->source_file))
4914 if (loc->row == prev_line) {
4915 mono_debug_symfile_free_location (loc);
4918 prev_line = loc->row;
4919 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4921 /* This will cover the prolog too */
4931 get_file_index (MonoAotCompile *acfg, const char *source_file)
4935 // FIXME: Free these
4936 if (!acfg->dwarf_ln_filenames)
4937 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4938 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4940 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4941 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4942 emit_unset_mode (acfg);
4943 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4955 * emit_and_reloc_code:
4957 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4958 * is true, calls are made through the GOT too. This is used for emitting trampolines
4959 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4960 * since trampolines are needed to make PTL work.
4963 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4965 int i, pindex, start_index;
4967 MonoJumpInfo *patch_info;
4968 MonoDebugSourceLocation **locs = NULL;
4970 #ifdef MONO_ARCH_AOT_SUPPORTED
4971 gboolean direct_call, external_call;
4973 const char *direct_call_target = 0;
4974 const char *direct_pinvoke;
4977 if (acfg->gas_line_numbers && method && debug_info) {
4978 locs = compute_line_numbers (method, code_len, debug_info);
4980 int findex = get_file_index (acfg, "<unknown>");
4981 emit_unset_mode (acfg);
4982 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4986 /* Collect and sort relocations */
4987 patches = g_ptr_array_new ();
4988 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4989 g_ptr_array_add (patches, patch_info);
4990 g_ptr_array_sort (patches, compare_patches);
4993 for (i = 0; i < code_len; i += INST_LEN) {
4995 for (pindex = start_index; pindex < patches->len; ++pindex) {
4996 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
4997 if (patch_info->ip.i >= i)
5001 if (locs && locs [i]) {
5002 MonoDebugSourceLocation *loc = locs [i];
5005 findex = get_file_index (acfg, loc->source_file);
5006 emit_unset_mode (acfg);
5007 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
5008 mono_debug_symfile_free_location (loc);
5012 #ifdef MONO_ARCH_AOT_SUPPORTED
5013 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5014 start_index = pindex;
5016 switch (patch_info->type) {
5017 case MONO_PATCH_INFO_NONE:
5019 case MONO_PATCH_INFO_GOT_OFFSET: {
5022 arch_emit_got_offset (acfg, code + i, &code_size);
5023 i += code_size - INST_LEN;
5025 patch_info->type = MONO_PATCH_INFO_NONE;
5028 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5029 int code_size, index;
5030 char *selector = (char *)patch_info->data.target;
5032 if (!acfg->objc_selector_to_index)
5033 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5034 if (!acfg->objc_selectors)
5035 acfg->objc_selectors = g_ptr_array_new ();
5036 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5040 index = acfg->objc_selector_index;
5041 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5042 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5043 acfg->objc_selector_index ++;
5046 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5047 i += code_size - INST_LEN;
5049 patch_info->type = MONO_PATCH_INFO_NONE;
5054 * If this patch is a call, try emitting a direct call instead of
5055 * through a PLT entry. This is possible if the called method is in
5056 * the same assembly and requires no initialization.
5058 direct_call = FALSE;
5059 external_call = FALSE;
5060 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5061 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5062 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5063 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5065 direct_call_target = callee_cfg->asm_symbol;
5066 patch_info->type = MONO_PATCH_INFO_NONE;
5067 acfg->stats.direct_calls ++;
5070 acfg->stats.all_calls ++;
5071 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5072 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5073 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5074 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5076 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5077 if (direct_pinvoke) {
5079 g_assert (strlen (direct_pinvoke) < 1000);
5080 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5083 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5084 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5085 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5086 /* Call to a C function implementing a jit icall */
5088 external_call = TRUE;
5089 g_assert (strlen (sym) < 1000);
5090 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5092 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5093 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5094 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5095 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5096 /* Call to a jit icall without a wrapper */
5098 external_call = TRUE;
5099 g_assert (strlen (sym) < 1000);
5100 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5105 patch_info->type = MONO_PATCH_INFO_NONE;
5106 acfg->stats.direct_calls ++;
5109 if (!got_only && !direct_call) {
5110 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5112 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5114 direct_call_target = plt_entry->symbol;
5116 /* Nullify the patch */
5117 patch_info->type = MONO_PATCH_INFO_NONE;
5118 plt_entry->jit_used = TRUE;
5125 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5126 i += call_size - INST_LEN;
5130 got_slot = get_got_offset (acfg, FALSE, patch_info);
5132 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5133 i += code_size - INST_LEN;
5139 #endif /* MONO_ARCH_AOT_SUPPORTED */
5142 /* Find next patch */
5144 for (pindex = start_index; pindex < patches->len; ++pindex) {
5145 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5146 if (patch_info->ip.i >= i)
5150 /* Try to emit multiple bytes at once */
5151 if (pindex < patches->len && patch_info->ip.i > i) {
5154 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5155 if (locs && locs [limit])
5159 emit_code_bytes (acfg, code + i, limit - i);
5160 i = limit - INST_LEN;
5162 emit_code_bytes (acfg, code + i, INST_LEN);
5173 * Return a modified version of S which only includes characters permissible in symbols.
5176 sanitize_symbol (MonoAotCompile *acfg, char *s)
5178 gboolean process = FALSE;
5187 for (i = 0; i < len; ++i)
5188 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5193 gs = g_string_sized_new (len);
5194 for (i = 0; i < len; ++i) {
5196 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5197 g_string_append_c (gs, c);
5198 } else if (c > 0x7f) {
5199 /* multi-byte utf8 */
5200 g_string_append_printf (gs, "_0x%x", c);
5203 while (c >> 6 == 0x2) {
5204 g_string_append_printf (gs, "%x", c);
5208 g_string_append_printf (gs, "_");
5211 g_string_append_c (gs, '_');
5215 res = mono_mempool_strdup (acfg->mempool, gs->str);
5216 g_string_free (gs, TRUE);
5221 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5223 char *name1, *name2, *cached;
5224 int i, j, len, count;
5225 MonoMethod *cached_method;
5227 name1 = mono_method_full_name (method, TRUE);
5230 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5231 if ((!prefix || !*prefix) && name1 [0] == 'L')
5235 len = strlen (name1);
5236 name2 = (char *)malloc (strlen (prefix) + len + 16);
5237 memcpy (name2, prefix, strlen (prefix));
5238 j = strlen (prefix);
5239 for (i = 0; i < len; ++i) {
5240 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5242 } else if (isalnum (name1 [i])) {
5243 name2 [j ++] = name1 [i];
5244 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5246 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5249 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5259 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5260 if (!(cached_method && cached_method != method))
5262 sprintf (name2 + j, "_%d", count);
5266 cached = g_strdup (name2);
5267 g_hash_table_insert (cache, cached, method);
5273 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5278 char *debug_sym = NULL;
5279 char *symbol = NULL;
5280 int func_alignment = AOT_FUNC_ALIGNMENT;
5283 method = cfg->orig_method;
5284 code = cfg->native_code;
5286 method_index = get_method_index (acfg, method);
5287 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5289 /* Make the labels local */
5290 emit_section_change (acfg, ".text", 0);
5291 emit_alignment_code (acfg, func_alignment);
5293 if (acfg->global_symbols && acfg->need_no_dead_strip)
5294 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5296 emit_label (acfg, cfg->asm_symbol);
5298 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5300 * Write a C style symbol for every method, this has two uses:
5301 * - it works on platforms where the dwarf debugging info is not
5303 * - it allows the setting of breakpoints of aot-ed methods.
5305 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5306 cfg->asm_debug_symbol = g_strdup (debug_sym);
5308 if (acfg->need_no_dead_strip)
5309 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5310 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5311 emit_label (acfg, debug_sym);
5314 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5316 /* Emit a global symbol for the method */
5317 emit_global_inner (acfg, export_name, TRUE);
5318 emit_label (acfg, export_name);
5321 if (cfg->verbose_level > 0)
5322 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5324 acfg->stats.code_size += cfg->code_len;
5326 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5328 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 ()));
5332 if (acfg->aot_opts.write_symbols) {
5334 emit_symbol_size (acfg, debug_sym, ".");
5336 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5340 emit_label (acfg, symbol);
5347 * Encode PATCH_INFO into its disk representation.
5350 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5354 switch (patch_info->type) {
5355 case MONO_PATCH_INFO_NONE:
5357 case MONO_PATCH_INFO_IMAGE:
5358 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5360 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5361 case MONO_PATCH_INFO_JIT_TLS_ID:
5362 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5363 case MONO_PATCH_INFO_GC_NURSERY_START:
5364 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5366 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5367 encode_value (patch_info->data.index, p, &p);
5369 case MONO_PATCH_INFO_METHOD_REL:
5370 encode_value ((gint)patch_info->data.offset, p, &p);
5372 case MONO_PATCH_INFO_SWITCH: {
5373 gpointer *table = (gpointer *)patch_info->data.table->table;
5376 encode_value (patch_info->data.table->table_size, p, &p);
5377 for (k = 0; k < patch_info->data.table->table_size; k++)
5378 encode_value ((int)(gssize)table [k], p, &p);
5381 case MONO_PATCH_INFO_METHODCONST:
5382 case MONO_PATCH_INFO_METHOD:
5383 case MONO_PATCH_INFO_METHOD_JUMP:
5384 case MONO_PATCH_INFO_ICALL_ADDR:
5385 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5386 case MONO_PATCH_INFO_METHOD_RGCTX:
5387 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5388 encode_method_ref (acfg, patch_info->data.method, p, &p);
5390 case MONO_PATCH_INFO_AOT_JIT_INFO:
5391 encode_value (patch_info->data.index, p, &p);
5393 case MONO_PATCH_INFO_INTERNAL_METHOD:
5394 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5395 guint32 len = strlen (patch_info->data.name);
5397 encode_value (len, p, &p);
5399 memcpy (p, patch_info->data.name, len);
5404 case MONO_PATCH_INFO_LDSTR: {
5405 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5406 guint32 token = patch_info->data.token->token;
5407 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5408 encode_value (image_index, p, &p);
5409 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5412 case MONO_PATCH_INFO_RVA:
5413 case MONO_PATCH_INFO_DECLSEC:
5414 case MONO_PATCH_INFO_LDTOKEN:
5415 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5416 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5417 encode_value (patch_info->data.token->token, p, &p);
5418 encode_value (patch_info->data.token->has_context, p, &p);
5419 if (patch_info->data.token->has_context)
5420 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5422 case MONO_PATCH_INFO_EXC_NAME: {
5423 MonoClass *ex_class;
5426 mono_class_load_from_name (mono_defaults.exception_class->image,
5427 "System", (const char *)patch_info->data.target);
5428 encode_klass_ref (acfg, ex_class, p, &p);
5431 case MONO_PATCH_INFO_R4:
5432 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5434 case MONO_PATCH_INFO_R8:
5435 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5436 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5438 case MONO_PATCH_INFO_VTABLE:
5439 case MONO_PATCH_INFO_CLASS:
5440 case MONO_PATCH_INFO_IID:
5441 case MONO_PATCH_INFO_ADJUSTED_IID:
5442 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5444 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5445 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5446 if (patch_info->data.del_tramp->method) {
5447 encode_value (1, p, &p);
5448 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5450 encode_value (0, p, &p);
5452 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5454 case MONO_PATCH_INFO_FIELD:
5455 case MONO_PATCH_INFO_SFLDA:
5456 encode_field_info (acfg, patch_info->data.field, p, &p);
5458 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5460 case MONO_PATCH_INFO_RGCTX_FETCH:
5461 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5462 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5467 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5468 * reference the same method, so encode the method only once.
5470 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5472 buf2 = (guint8 *)g_malloc (1024);
5475 encode_method_ref (acfg, entry->method, p2, &p2);
5476 g_assert (p2 - buf2 < 1024);
5478 offset = add_to_blob (acfg, buf2, p2 - buf2);
5481 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5486 encode_value (offset, p, &p);
5487 g_assert ((int)entry->info_type < 256);
5488 g_assert (entry->data->type < 256);
5489 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5490 encode_patch (acfg, entry->data, p, &p);
5493 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5494 case MONO_PATCH_INFO_AOT_MODULE:
5496 case MONO_PATCH_INFO_SIGNATURE:
5497 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5498 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5500 case MONO_PATCH_INFO_TLS_OFFSET:
5501 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5503 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5504 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5505 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5507 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5508 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5511 encode_method_ref (acfg, info->method, p, &p);
5512 encode_value (info->num_entries, p, &p);
5513 for (i = 0; i < info->num_entries; ++i) {
5514 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5516 encode_value (template_->info_type, p, &p);
5517 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5518 case MONO_PATCH_INFO_CLASS:
5519 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5521 case MONO_PATCH_INFO_FIELD:
5522 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5525 g_assert_not_reached ();
5531 case MONO_PATCH_INFO_LDSTR_LIT: {
5532 const char *s = (const char *)patch_info->data.target;
5533 int len = strlen (s);
5535 encode_value (len, p, &p);
5536 memcpy (p, s, len + 1);
5540 case MONO_PATCH_INFO_VIRT_METHOD:
5541 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5542 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5544 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5547 g_warning ("unable to handle jump info %d", patch_info->type);
5548 g_assert_not_reached ();
5555 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5558 guint32 pindex, offset;
5559 MonoJumpInfo *patch_info;
5561 encode_value (n_patches, p, &p);
5563 for (pindex = 0; pindex < patches->len; ++pindex) {
5564 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5566 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5570 offset = get_got_offset (acfg, llvm, patch_info);
5571 encode_value (offset, p, &p);
5578 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5581 int pindex, buf_size, n_patches;
5583 MonoJumpInfo *patch_info;
5584 guint32 method_index;
5586 guint32 first_got_offset;
5588 method = cfg->orig_method;
5590 method_index = get_method_index (acfg, method);
5592 /* Sort relocations */
5593 patches = g_ptr_array_new ();
5594 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5595 g_ptr_array_add (patches, patch_info);
5596 g_ptr_array_sort (patches, compare_patches);
5598 first_got_offset = acfg->cfgs [method_index]->got_offset;
5600 /**********************/
5601 /* Encode method info */
5602 /**********************/
5604 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5605 p = buf = (guint8 *)g_malloc (buf_size);
5607 if (mono_class_get_cctor (method->klass)) {
5608 encode_value (1, p, &p);
5609 encode_klass_ref (acfg, method->klass, p, &p);
5611 /* Not needed when loading the method */
5612 encode_value (0, p, &p);
5615 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5618 for (pindex = 0; pindex < patches->len; ++pindex) {
5619 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5621 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5622 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5623 patch_info->type = MONO_PATCH_INFO_NONE;
5628 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5629 /* Stored in a GOT slot initialized at module load time */
5630 patch_info->type = MONO_PATCH_INFO_NONE;
5634 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5635 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5636 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5637 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5638 /* Stored in a GOT slot initialized at module load time */
5639 patch_info->type = MONO_PATCH_INFO_NONE;
5643 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5644 /* Calls are made through the PLT */
5645 patch_info->type = MONO_PATCH_INFO_NONE;
5653 g_assert (cfg->has_got_slots);
5655 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5657 acfg->stats.info_size += p - buf;
5659 g_assert (p - buf < buf_size);
5661 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5666 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5668 guint32 cache_index;
5671 /* Reuse the unwind module to canonize and store unwind info entries */
5672 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5674 /* Use +/- 1 to distinguish 0s from missing entries */
5675 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5683 * It would be easier to use assembler symbols, but the caller needs an
5686 offset = acfg->unwind_info_offset;
5687 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5688 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5691 encode_value (encoded_len, p, &p);
5693 acfg->unwind_info_offset += encoded_len + (p - buf);
5699 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5702 guint32 debug_info_size, seq_points_size;
5704 MonoMethodHeader *header;
5705 guint8 *p, *buf, *debug_info;
5706 MonoJitInfo *jinfo = cfg->jit_info;
5708 gboolean use_unwind_ops = FALSE;
5709 MonoSeqPointInfo *seq_points;
5711 code = cfg->native_code;
5712 header = cfg->header;
5714 if (!acfg->aot_opts.nodebug) {
5715 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5718 debug_info_size = 0;
5721 seq_points = cfg->seq_point_info;
5722 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5724 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5726 p = buf = (guint8 *)g_malloc (buf_size);
5728 use_unwind_ops = cfg->unwind_ops != NULL;
5730 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);
5732 encode_value (flags, p, &p);
5734 if (use_unwind_ops) {
5735 guint32 encoded_len;
5737 guint32 unwind_desc;
5739 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5741 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5742 encode_value (unwind_desc, p, &p);
5744 encode_value (jinfo->unwind_info, p, &p);
5747 /*Encode the number of holes before the number of clauses to make decoding easier*/
5748 if (jinfo->has_try_block_holes) {
5749 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5750 encode_value (table->num_holes, p, &p);
5753 if (jinfo->has_arch_eh_info) {
5755 * In AOT mode, the code length is calculated from the address of the previous method,
5756 * which could include alignment padding, so calculating the start of the epilog as
5757 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5759 encode_value (jinfo->code_size, p, &p);
5762 /* Exception table */
5763 if (cfg->compile_llvm) {
5765 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5766 * since the information is only available to llc. Instead, we let llc save the data
5767 * into the LSDA, and read it from there at runtime.
5769 /* The assembly might be CIL stripped so emit the data ourselves */
5770 if (header->num_clauses)
5771 encode_value (header->num_clauses, p, &p);
5773 for (k = 0; k < header->num_clauses; ++k) {
5774 MonoExceptionClause *clause;
5776 clause = &header->clauses [k];
5778 encode_value (clause->flags, p, &p);
5779 if (clause->data.catch_class) {
5780 encode_value (1, p, &p);
5781 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5783 encode_value (0, p, &p);
5786 /* Emit the IL ranges too, since they might not be available at runtime */
5787 encode_value (clause->try_offset, p, &p);
5788 encode_value (clause->try_len, p, &p);
5789 encode_value (clause->handler_offset, p, &p);
5790 encode_value (clause->handler_len, p, &p);
5792 /* Emit a list of nesting clauses */
5793 for (i = 0; i < header->num_clauses; ++i) {
5795 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5797 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5799 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5800 encode_value (i, p, &p);
5802 encode_value (-1, p, &p);
5805 if (jinfo->num_clauses)
5806 encode_value (jinfo->num_clauses, p, &p);
5808 for (k = 0; k < jinfo->num_clauses; ++k) {
5809 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5811 encode_value (ei->flags, p, &p);
5812 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5813 /* Not used for catch clauses */
5814 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5815 encode_value (ei->exvar_offset, p, &p);
5817 encode_value (ei->exvar_offset, p, &p);
5820 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5821 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5823 if (ei->data.catch_class) {
5827 buf2 = (guint8 *)g_malloc (4096);
5829 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5831 g_assert (len < 4096);
5832 encode_value (len, p, &p);
5833 memcpy (p, buf2, len);
5837 encode_value (0, p, &p);
5841 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5842 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5843 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5847 if (jinfo->has_try_block_holes) {
5848 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5849 for (i = 0; i < table->num_holes; ++i) {
5850 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5851 encode_value (hole->clause, p, &p);
5852 encode_value (hole->length, p, &p);
5853 encode_value (hole->offset, p, &p);
5857 if (jinfo->has_arch_eh_info) {
5858 MonoArchEHJitInfo *eh_info;
5860 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5861 encode_value (eh_info->stack_size, p, &p);
5862 encode_value (eh_info->epilog_size, p, &p);
5865 if (jinfo->has_generic_jit_info) {
5866 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5867 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5871 encode_value (gi->nlocs, p, &p);
5873 for (i = 0; i < gi->nlocs; ++i) {
5874 MonoDwarfLocListEntry *entry = &gi->locations [i];
5876 encode_value (entry->is_reg ? 1 : 0, p, &p);
5877 encode_value (entry->reg, p, &p);
5879 encode_value (entry->offset, p, &p);
5881 g_assert (entry->from == 0);
5883 encode_value (entry->from, p, &p);
5884 encode_value (entry->to, p, &p);
5887 if (!cfg->compile_llvm) {
5888 encode_value (gi->has_this ? 1 : 0, p, &p);
5889 encode_value (gi->this_reg, p, &p);
5890 encode_value (gi->this_offset, p, &p);
5895 * Need to encode jinfo->method too, since it is not equal to 'method'
5896 * when using generic sharing.
5898 buf2 = (guint8 *)g_malloc (4096);
5900 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5902 g_assert (len < 4096);
5903 encode_value (len, p, &p);
5904 memcpy (p, buf2, len);
5908 if (gsctx && gsctx->is_gsharedvt) {
5909 encode_value (1, p, &p);
5911 encode_value (0, p, &p);
5915 if (seq_points_size)
5916 p += mono_seq_point_info_write (seq_points, p);
5918 g_assert (debug_info_size < buf_size);
5920 encode_value (debug_info_size, p, &p);
5921 if (debug_info_size) {
5922 memcpy (p, debug_info, debug_info_size);
5923 p += debug_info_size;
5924 g_free (debug_info);
5929 encode_value (cfg->gc_map_size, p, &p);
5930 /* The GC map requires 4 bytes of alignment */
5931 while ((gsize)p % 4)
5933 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5934 p += cfg->gc_map_size;
5937 acfg->stats.ex_info_size += p - buf;
5939 g_assert (p - buf < buf_size);
5942 /* The GC Map requires 4 byte alignment */
5943 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5948 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5951 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5953 int i, buf_size, res;
5954 gboolean no_special_static, cant_encode;
5955 gpointer iter = NULL;
5958 mono_error_cleanup (&error);
5962 p = buf = (guint8 *)g_malloc (buf_size);
5964 /* Mark as unusable */
5965 encode_value (-1, p, &p);
5967 res = add_to_blob (acfg, buf, p - buf);
5973 buf_size = 10240 + (klass->vtable_size * 16);
5974 p = buf = (guint8 *)g_malloc (buf_size);
5978 mono_class_init (klass);
5980 mono_class_get_nested_types (klass, &iter);
5981 g_assert (klass->nested_classes_inited);
5983 mono_class_setup_vtable (klass);
5986 * Emit all the information which is required for creating vtables so
5987 * the runtime does not need to create the MonoMethod structures which
5988 * take up a lot of space.
5991 no_special_static = !mono_class_has_special_static_fields (klass);
5993 /* Check whenever we have enough info to encode the vtable */
5994 cant_encode = FALSE;
5995 for (i = 0; i < klass->vtable_size; ++i) {
5996 MonoMethod *cm = klass->vtable [i];
5998 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6002 mono_class_has_finalizer (klass);
6004 if (klass->generic_container || cant_encode) {
6005 encode_value (-1, p, &p);
6007 encode_value (klass->vtable_size, p, &p);
6008 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);
6009 if (klass->has_cctor)
6010 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6011 if (klass->has_finalize)
6012 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6014 encode_value (klass->instance_size, p, &p);
6015 encode_value (mono_class_data_size (klass), p, &p);
6016 encode_value (klass->packing_size, p, &p);
6017 encode_value (klass->min_align, p, &p);
6019 for (i = 0; i < klass->vtable_size; ++i) {
6020 MonoMethod *cm = klass->vtable [i];
6023 encode_method_ref (acfg, cm, p, &p);
6025 encode_value (0, p, &p);
6029 acfg->stats.class_info_size += p - buf;
6031 g_assert (p - buf < buf_size);
6032 res = add_to_blob (acfg, buf, p - buf);
6039 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6041 char *debug_sym = NULL;
6044 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6045 /* Need to add a prefix to create unique symbols */
6046 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6048 prefix = g_strdup ("plt_");
6052 case MONO_PATCH_INFO_METHOD:
6053 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6055 case MONO_PATCH_INFO_INTERNAL_METHOD:
6056 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6058 case MONO_PATCH_INFO_RGCTX_FETCH:
6059 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6061 case MONO_PATCH_INFO_ICALL_ADDR:
6062 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6063 char *s = get_debug_sym (ji->data.method, "", cache);
6065 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6069 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6070 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6078 return sanitize_symbol (acfg, debug_sym);
6082 * Calls made from AOTed code are routed through a table of jumps similar to the
6083 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6084 * control to the AOT runtime through a trampoline.
6087 emit_plt (MonoAotCompile *acfg)
6091 if (acfg->aot_opts.llvm_only) {
6092 g_assert (acfg->plt_offset == 1);
6098 emit_section_change (acfg, ".text", 0);
6099 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
6100 emit_info_symbol (acfg, "plt");
6101 emit_label (acfg, acfg->plt_symbol);
6103 for (i = 0; i < acfg->plt_offset; ++i) {
6104 char *debug_sym = NULL;
6105 MonoPltEntry *plt_entry = NULL;
6109 * The first plt entry is unused.
6113 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6115 debug_sym = plt_entry->debug_sym;
6117 if (acfg->thumb_mixed && !plt_entry->jit_used)
6118 /* Emit only a thumb version */
6121 /* Skip plt entries not actually called */
6122 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6125 if (acfg->llvm && !acfg->thumb_mixed) {
6126 emit_label (acfg, plt_entry->llvm_symbol);
6128 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6129 #if defined(TARGET_MACH)
6130 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6136 if (acfg->need_no_dead_strip) {
6137 emit_unset_mode (acfg);
6138 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6140 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6141 emit_label (acfg, debug_sym);
6144 emit_label (acfg, plt_entry->symbol);
6146 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6149 emit_symbol_size (acfg, debug_sym, ".");
6152 if (acfg->thumb_mixed) {
6153 /* Make sure the ARM symbols don't alias the thumb ones */
6154 emit_zero_bytes (acfg, 16);
6157 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6160 for (i = 0; i < acfg->plt_offset; ++i) {
6161 char *debug_sym = NULL;
6162 MonoPltEntry *plt_entry = NULL;
6167 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6169 /* Skip plt entries not actually called by LLVM code */
6170 if (!plt_entry->llvm_used)
6173 if (acfg->aot_opts.write_symbols) {
6174 if (plt_entry->debug_sym)
6175 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6179 #if defined(TARGET_MACH)
6180 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6181 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6183 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6184 emit_label (acfg, debug_sym);
6186 fprintf (acfg->fp, "\n.thumb_func\n");
6188 emit_label (acfg, plt_entry->llvm_symbol);
6191 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6193 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6196 emit_symbol_size (acfg, debug_sym, ".");
6202 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6204 emit_info_symbol (acfg, "plt_end");
6208 * emit_trampoline_full:
6210 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6211 * create_jit_info_for_trampoline ().
6213 static G_GNUC_UNUSED void
6214 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6216 char start_symbol [256];
6217 char end_symbol [256];
6219 guint32 buf_size, info_offset;
6220 MonoJumpInfo *patch_info;
6233 code_size = info->code_size;
6235 unwind_ops = info->unwind_ops;
6237 #ifdef __native_client_codegen__
6238 mono_nacl_fix_patches (code, ji);
6243 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6245 emit_section_change (acfg, ".text", 0);
6246 emit_global (acfg, start_symbol, TRUE);
6247 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6248 emit_label (acfg, start_symbol);
6250 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6251 emit_label (acfg, symbol);
6254 * The code should access everything through the GOT, so we pass
6257 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6259 emit_symbol_size (acfg, start_symbol, ".");
6262 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6263 emit_label (acfg, end_symbol);
6268 /* Sort relocations */
6269 patches = g_ptr_array_new ();
6270 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6271 if (patch_info->type != MONO_PATCH_INFO_NONE)
6272 g_ptr_array_add (patches, patch_info);
6273 g_ptr_array_sort (patches, compare_patches);
6275 buf_size = patches->len * 128 + 128;
6276 buf = (guint8 *)g_malloc (buf_size);
6279 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6280 g_assert (p - buf < buf_size);
6282 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6284 info_offset = add_to_blob (acfg, buf, p - buf);
6286 emit_section_change (acfg, RODATA_SECT, 0);
6287 emit_global (acfg, symbol, FALSE);
6288 emit_label (acfg, symbol);
6290 emit_int32 (acfg, info_offset);
6294 guint32 encoded_len;
6298 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6300 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6301 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6304 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6305 emit_int32 (acfg, uw_offset);
6308 /* Emit debug info */
6312 sprintf (symbol, "%s", name);
6313 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6316 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6320 static G_GNUC_UNUSED void
6321 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6323 emit_trampoline_full (acfg, got_offset, info, TRUE);
6327 emit_trampolines (MonoAotCompile *acfg)
6330 char end_symbol [256];
6331 int i, tramp_got_offset;
6333 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6337 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6340 g_assert (acfg->image->assembly);
6342 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6343 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6344 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6345 MonoTrampInfo *info;
6348 * Emit the generic trampolines.
6350 * We could save some code by treating the generic trampolines as a wrapper
6351 * method, but that approach has its own complexities, so we choose the simpler
6354 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6355 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6356 #ifdef DISABLE_REMOTING
6357 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6360 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6361 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6364 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6365 emit_trampoline (acfg, acfg->got_offset, info);
6368 /* Emit the exception related code pieces */
6369 mono_arch_get_restore_context (&info, TRUE);
6370 emit_trampoline (acfg, acfg->got_offset, info);
6371 mono_arch_get_call_filter (&info, TRUE);
6372 emit_trampoline (acfg, acfg->got_offset, info);
6373 mono_arch_get_throw_exception (&info, TRUE);
6374 emit_trampoline (acfg, acfg->got_offset, info);
6375 mono_arch_get_rethrow_exception (&info, TRUE);
6376 emit_trampoline (acfg, acfg->got_offset, info);
6377 mono_arch_get_throw_corlib_exception (&info, TRUE);
6378 emit_trampoline (acfg, acfg->got_offset, info);
6380 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6381 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6382 emit_trampoline (acfg, acfg->got_offset, info);
6383 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6384 emit_trampoline (acfg, acfg->got_offset, info);
6387 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6388 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6390 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6392 /* Create a separate out trampoline for more information in stack traces */
6393 info->name = g_strdup ("gsharedvt_out_trampoline");
6394 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6398 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6400 GSList *l = mono_arch_get_trampolines (TRUE);
6403 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6405 emit_trampoline (acfg, acfg->got_offset, info);
6411 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6414 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6415 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6416 emit_trampoline (acfg, acfg->got_offset, info);
6418 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6419 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6420 emit_trampoline (acfg, acfg->got_offset, info);
6423 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6424 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6425 emit_trampoline (acfg, acfg->got_offset, info);
6431 /* delegate_invoke_impl trampolines */
6432 l = mono_arch_get_delegate_invoke_impls ();
6434 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6436 emit_trampoline (acfg, acfg->got_offset, info);
6441 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6443 /* Emit trampolines which are numerous */
6446 * These include the following:
6447 * - specific trampolines
6448 * - static rgctx invoke trampolines
6450 * These trampolines have the same code, they are parameterized by GOT
6452 * They are defined in this file, in the arch_... routines instead of
6453 * in tramp-<ARCH>.c, since it is easier to do it this way.
6457 * When running in aot-only mode, we can't create specific trampolines at
6458 * runtime, so we create a few, and save them in the AOT file.
6459 * Normal trampolines embed their argument as a literal inside the
6460 * trampoline code, we can't do that here, so instead we embed an offset
6461 * which needs to be added to the trampoline address to get the address of
6462 * the GOT slot which contains the argument value.
6463 * The generated trampolines jump to the generic trampolines using another
6464 * GOT slot, which will be setup by the AOT loader to point to the
6465 * generic trampoline code of the given type.
6469 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6473 emit_section_change (acfg, ".text", 0);
6475 tramp_got_offset = acfg->got_offset;
6477 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6479 case MONO_AOT_TRAMP_SPECIFIC:
6480 sprintf (symbol, "specific_trampolines");
6482 case MONO_AOT_TRAMP_STATIC_RGCTX:
6483 sprintf (symbol, "static_rgctx_trampolines");
6485 case MONO_AOT_TRAMP_IMT_THUNK:
6486 sprintf (symbol, "imt_thunks");
6488 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6489 sprintf (symbol, "gsharedvt_arg_trampolines");
6492 g_assert_not_reached ();
6495 sprintf (end_symbol, "%s_e", symbol);
6497 if (acfg->aot_opts.write_symbols)
6498 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6500 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6501 emit_info_symbol (acfg, symbol);
6503 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6505 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6509 case MONO_AOT_TRAMP_SPECIFIC:
6510 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6511 tramp_got_offset += 2;
6513 case MONO_AOT_TRAMP_STATIC_RGCTX:
6514 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6515 tramp_got_offset += 2;
6517 case MONO_AOT_TRAMP_IMT_THUNK:
6518 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6519 tramp_got_offset += 1;
6521 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6522 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6523 tramp_got_offset += 2;
6526 g_assert_not_reached ();
6528 #ifdef __native_client_codegen__
6529 /* align to avoid 32-byte boundary crossings */
6530 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6533 if (!acfg->trampoline_size [ntype]) {
6534 g_assert (tramp_size);
6535 acfg->trampoline_size [ntype] = tramp_size;
6539 emit_label (acfg, end_symbol);
6540 emit_int32 (acfg, 0);
6543 arch_emit_specific_trampoline_pages (acfg);
6545 /* Reserve some entries at the end of the GOT for our use */
6546 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6549 acfg->got_offset += acfg->num_trampoline_got_entries;
6553 str_begins_with (const char *str1, const char *str2)
6555 int len = strlen (str2);
6556 return strncmp (str1, str2, len) == 0;
6560 mono_aot_readonly_field_override (MonoClassField *field)
6563 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6564 char *p = rdv->name;
6566 len = strlen (field->parent->name_space);
6567 if (strncmp (p, field->parent->name_space, len))
6572 len = strlen (field->parent->name);
6573 if (strncmp (p, field->parent->name, len))
6578 if (strcmp (p, field->name))
6580 switch (rdv->type) {
6582 return &rdv->value.i1;
6584 return &rdv->value.i2;
6586 return &rdv->value.i4;
6595 add_readonly_value (MonoAotOptions *opts, const char *val)
6600 /* the format of val is:
6601 * namespace.typename.fieldname=type/value
6602 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6604 fval = strrchr (val, '/');
6606 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6609 tval = strrchr (val, '=');
6611 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6614 rdv = g_new0 (ReadOnlyValue, 1);
6615 rdv->name = (char *)g_malloc0 (tval - val + 1);
6616 memcpy (rdv->name, val, tval - val);
6619 if (strncmp (tval, "i1", 2) == 0) {
6620 rdv->value.i1 = atoi (fval);
6621 rdv->type = MONO_TYPE_I1;
6622 } else if (strncmp (tval, "i2", 2) == 0) {
6623 rdv->value.i2 = atoi (fval);
6624 rdv->type = MONO_TYPE_I2;
6625 } else if (strncmp (tval, "i4", 2) == 0) {
6626 rdv->value.i4 = atoi (fval);
6627 rdv->type = MONO_TYPE_I4;
6629 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6632 rdv->next = readonly_values;
6633 readonly_values = rdv;
6637 clean_path (gchar * path)
6642 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6645 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6652 wrap_path (gchar * path)
6658 // If the string contains no spaces, just return the original string.
6659 if (strstr (path, " ") == NULL)
6662 // If the string is already wrapped in quotes, return it.
6663 len = strlen (path);
6664 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6667 // If the string contains spaces, then wrap it in quotes.
6668 gchar *clean = g_strdup_printf ("\"%s\"", path);
6673 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
6675 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
6677 ptrdiff_t len = end-start;
6679 g_ptr_array_add (args, g_strndup (start, len));
6683 mono_aot_split_options (const char *aot_options)
6685 enum MonoAotOptionState {
6686 MONO_AOT_OPTION_STATE_DEFAULT,
6687 MONO_AOT_OPTION_STATE_STRING,
6688 MONO_AOT_OPTION_STATE_ESCAPE,
6691 GPtrArray *args = g_ptr_array_new ();
6692 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6693 gchar const *opt_start = aot_options;
6694 gboolean end_of_string = FALSE;
6697 g_return_val_if_fail (aot_options != NULL, NULL);
6699 while ((cur = *aot_options) != '\0') {
6700 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6705 // If we find a quote, then if we're in the default case then
6706 // it means we've found the start of a string, if not then it
6707 // means we've found the end of the string and should switch
6708 // back to the default case.
6710 case MONO_AOT_OPTION_STATE_DEFAULT:
6711 state = MONO_AOT_OPTION_STATE_STRING;
6713 case MONO_AOT_OPTION_STATE_STRING:
6714 state = MONO_AOT_OPTION_STATE_DEFAULT;
6716 case MONO_AOT_OPTION_STATE_ESCAPE:
6717 g_assert_not_reached ();
6722 // If we've found an escaping operator, then this means we
6723 // should not process the next character if inside a string.
6724 if (state == MONO_AOT_OPTION_STATE_STRING)
6725 state = MONO_AOT_OPTION_STATE_ESCAPE;
6728 // If we're in the default state then this means we've found
6729 // an option, store it for later processing.
6730 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6738 // If the next character is end of string, then process the last option.
6739 if (*(aot_options) == '\0') {
6740 end_of_string = TRUE;
6746 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
6747 opt_start = ++aot_options;
6750 goto restart; // Check for null and continue loop
6757 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6761 args = mono_aot_split_options (aot_options ? aot_options : "");
6762 for (int i = 0; i < args->len; ++i) {
6763 const char *arg = (const char *)g_ptr_array_index (args, i);
6765 if (str_begins_with (arg, "outfile=")) {
6766 opts->outfile = g_strdup (arg + strlen ("outfile="));
6767 } else if (str_begins_with (arg, "llvm-outfile=")) {
6768 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6769 } else if (str_begins_with (arg, "temp-path=")) {
6770 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6771 } else if (str_begins_with (arg, "save-temps")) {
6772 opts->save_temps = TRUE;
6773 } else if (str_begins_with (arg, "keep-temps")) {
6774 opts->save_temps = TRUE;
6775 } else if (str_begins_with (arg, "write-symbols")) {
6776 opts->write_symbols = TRUE;
6777 } else if (str_begins_with (arg, "no-write-symbols")) {
6778 opts->write_symbols = FALSE;
6779 } else if (str_begins_with (arg, "metadata-only")) {
6780 opts->metadata_only = TRUE;
6781 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6782 opts->bind_to_runtime_version = TRUE;
6783 } else if (str_begins_with (arg, "full")) {
6784 opts->mode = MONO_AOT_MODE_FULL;
6785 } else if (str_begins_with (arg, "hybrid")) {
6786 opts->mode = MONO_AOT_MODE_HYBRID;
6787 } else if (str_begins_with (arg, "threads=")) {
6788 opts->nthreads = atoi (arg + strlen ("threads="));
6789 } else if (str_begins_with (arg, "static")) {
6790 opts->static_link = TRUE;
6791 opts->no_dlsym = TRUE;
6792 } else if (str_begins_with (arg, "asmonly")) {
6793 opts->asm_only = TRUE;
6794 } else if (str_begins_with (arg, "asmwriter")) {
6795 opts->asm_writer = TRUE;
6796 } else if (str_begins_with (arg, "nodebug")) {
6797 opts->nodebug = TRUE;
6798 } else if (str_begins_with (arg, "dwarfdebug")) {
6799 opts->dwarf_debug = TRUE;
6800 } else if (str_begins_with (arg, "nopagetrampolines")) {
6801 opts->use_trampolines_page = FALSE;
6802 } else if (str_begins_with (arg, "ntrampolines=")) {
6803 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6804 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6805 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6806 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6807 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6808 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6809 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6810 } else if (str_begins_with (arg, "tool-prefix=")) {
6811 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6812 } else if (str_begins_with (arg, "ld-flags=")) {
6813 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6814 } else if (str_begins_with (arg, "soft-debug")) {
6815 opts->soft_debug = TRUE;
6816 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
6817 debug_options.gen_seq_points_compact_data = TRUE;
6818 opts->gen_seq_points_file = TRUE;
6819 opts->gen_seq_points_file_path = g_strdup (arg + strlen ("gen-seq-points-file="));;
6820 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6821 debug_options.gen_seq_points_compact_data = TRUE;
6822 opts->gen_seq_points_file = TRUE;
6823 } else if (str_begins_with (arg, "direct-pinvoke")) {
6824 opts->direct_pinvoke = TRUE;
6825 } else if (str_begins_with (arg, "direct-icalls")) {
6826 opts->direct_icalls = TRUE;
6827 } else if (str_begins_with (arg, "no-direct-calls")) {
6828 opts->no_direct_calls = TRUE;
6829 } else if (str_begins_with (arg, "print-skipped")) {
6830 opts->print_skipped_methods = TRUE;
6831 } else if (str_begins_with (arg, "stats")) {
6833 } else if (str_begins_with (arg, "no-instances")) {
6834 opts->no_instances = TRUE;
6835 } else if (str_begins_with (arg, "log-generics")) {
6836 opts->log_generics = TRUE;
6837 } else if (str_begins_with (arg, "log-instances=")) {
6838 opts->log_instances = TRUE;
6839 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6840 } else if (str_begins_with (arg, "log-instances")) {
6841 opts->log_instances = TRUE;
6842 } else if (str_begins_with (arg, "internal-logfile=")) {
6843 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6844 } else if (str_begins_with (arg, "mtriple=")) {
6845 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6846 } else if (str_begins_with (arg, "llvm-path=")) {
6847 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6848 } else if (!strcmp (arg, "llvm")) {
6850 } else if (str_begins_with (arg, "readonly-value=")) {
6851 add_readonly_value (opts, arg + strlen ("readonly-value="));
6852 } else if (str_begins_with (arg, "info")) {
6853 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6855 } else if (str_begins_with (arg, "gc-maps")) {
6856 mini_gc_enable_gc_maps_for_aot ();
6857 } else if (str_begins_with (arg, "dump")) {
6858 opts->dump_json = TRUE;
6859 } else if (str_begins_with (arg, "llvmonly")) {
6860 opts->mode = MONO_AOT_MODE_FULL;
6862 opts->llvm_only = TRUE;
6863 } else if (str_begins_with (arg, "data-outfile=")) {
6864 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
6865 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6866 printf ("Supported options for --aot:\n");
6867 printf (" outfile=\n");
6868 printf (" llvm-outfile=\n");
6869 printf (" llvm-path=\n");
6870 printf (" temp-path=\n");
6871 printf (" save-temps\n");
6872 printf (" keep-temps\n");
6873 printf (" write-symbols\n");
6874 printf (" metadata-only\n");
6875 printf (" bind-to-runtime-version\n");
6877 printf (" threads=\n");
6878 printf (" static\n");
6879 printf (" asmonly\n");
6880 printf (" asmwriter\n");
6881 printf (" nodebug\n");
6882 printf (" dwarfdebug\n");
6883 printf (" ntrampolines=\n");
6884 printf (" nrgctx-trampolines=\n");
6885 printf (" nimt-trampolines=\n");
6886 printf (" ngsharedvt-trampolines=\n");
6887 printf (" tool-prefix=\n");
6888 printf (" readonly-value=\n");
6889 printf (" soft-debug\n");
6890 printf (" gen-seq-points-file\n");
6891 printf (" gc-maps\n");
6892 printf (" print-skipped\n");
6893 printf (" no-instances\n");
6894 printf (" stats\n");
6897 printf (" help/?\n");
6900 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6904 g_free ((gpointer) arg);
6907 if (opts->use_trampolines_page) {
6908 opts->ntrampolines = 0;
6909 opts->nrgctx_trampolines = 0;
6910 opts->nimt_trampolines = 0;
6911 opts->ngsharedvt_arg_trampolines = 0;
6914 g_ptr_array_free (args, /*free_seg=*/TRUE);
6918 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6920 MonoMethod *method = (MonoMethod*)key;
6921 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6922 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
6923 MonoJumpInfoToken *new_ji;
6925 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6926 new_ji->image = ji->image;
6927 new_ji->token = ji->token;
6928 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6932 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6934 if (klass->type_token)
6936 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6939 return can_encode_class (acfg, klass->element_class);
6944 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6946 if (method->wrapper_type) {
6947 switch (method->wrapper_type) {
6948 case MONO_WRAPPER_NONE:
6949 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6950 case MONO_WRAPPER_XDOMAIN_INVOKE:
6951 case MONO_WRAPPER_STFLD:
6952 case MONO_WRAPPER_LDFLD:
6953 case MONO_WRAPPER_LDFLDA:
6954 case MONO_WRAPPER_LDFLD_REMOTE:
6955 case MONO_WRAPPER_STFLD_REMOTE:
6956 case MONO_WRAPPER_STELEMREF:
6957 case MONO_WRAPPER_ISINST:
6958 case MONO_WRAPPER_PROXY_ISINST:
6959 case MONO_WRAPPER_ALLOC:
6960 case MONO_WRAPPER_REMOTING_INVOKE:
6961 case MONO_WRAPPER_UNKNOWN:
6962 case MONO_WRAPPER_WRITE_BARRIER:
6963 case MONO_WRAPPER_DELEGATE_INVOKE:
6964 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6965 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6966 case MONO_WRAPPER_SYNCHRONIZED:
6968 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6969 case MONO_WRAPPER_CASTCLASS: {
6970 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6979 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6983 if (!method->token) {
6984 /* The method is part of a constructed type like Int[,].Set (). */
6985 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6986 if (method->klass->rank)
6996 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6998 switch (patch_info->type) {
6999 case MONO_PATCH_INFO_METHOD:
7000 case MONO_PATCH_INFO_METHODCONST:
7001 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7002 MonoMethod *method = patch_info->data.method;
7004 return can_encode_method (acfg, method);
7006 case MONO_PATCH_INFO_VTABLE:
7007 case MONO_PATCH_INFO_CLASS:
7008 case MONO_PATCH_INFO_IID:
7009 case MONO_PATCH_INFO_ADJUSTED_IID:
7010 if (!can_encode_class (acfg, patch_info->data.klass)) {
7011 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7015 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7016 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7017 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7022 case MONO_PATCH_INFO_RGCTX_FETCH:
7023 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7024 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7026 if (!can_encode_method (acfg, entry->method))
7028 if (!can_encode_patch (acfg, entry->data))
7040 is_concrete_type (MonoType *t)
7045 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7047 if (t->type == MONO_TYPE_GENERICINST) {
7048 MonoGenericContext *orig_ctx;
7049 MonoGenericInst *inst;
7052 if (!MONO_TYPE_ISSTRUCT (t))
7054 klass = mono_class_from_mono_type (t);
7055 orig_ctx = &klass->generic_class->context;
7057 inst = orig_ctx->class_inst;
7059 for (i = 0; i < inst->type_argc; ++i) {
7060 arg = mini_get_underlying_type (inst->type_argv [i]);
7061 if (!is_concrete_type (arg))
7065 inst = orig_ctx->method_inst;
7067 for (i = 0; i < inst->type_argc; ++i) {
7068 arg = mini_get_underlying_type (inst->type_argv [i]);
7069 if (!is_concrete_type (arg))
7077 /* LOCKING: Assumes the loader lock is held */
7079 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7081 MonoMethod *wrapper;
7082 gboolean concrete = TRUE;
7083 gboolean add_in = gsharedvt_in;
7084 gboolean add_out = gsharedvt_out;
7086 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7088 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7091 if (!add_in && !add_out)
7094 if (mini_is_gsharedvt_variable_signature (sig))
7098 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7100 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7102 if (!sig->has_type_parameters) {
7103 //printf ("%s\n", mono_signature_full_name (sig));
7106 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7107 add_extra_method (acfg, wrapper);
7109 if (gsharedvt_out) {
7110 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7111 add_extra_method (acfg, wrapper);
7114 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7115 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7118 //printf ("%s\n", mono_signature_full_name (sig));
7120 copy->ret = mini_get_underlying_type (sig->ret);
7121 if (!is_concrete_type (copy->ret))
7123 for (i = 0; i < sig->param_count; ++i) {
7124 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7125 if (!is_concrete_type (copy->params [i]))
7129 copy->has_type_parameters = 0;
7132 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7133 add_extra_method (acfg, wrapper);
7136 if (gsharedvt_out) {
7137 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7138 add_extra_method (acfg, wrapper);
7141 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7149 * AOT compile a given method.
7150 * This function might be called by multiple threads, so it must be thread-safe.
7153 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7156 MonoJumpInfo *patch_info;
7159 MonoMethod *wrapped;
7163 if (acfg->aot_opts.metadata_only)
7166 mono_acfg_lock (acfg);
7167 index = get_method_index (acfg, method);
7168 mono_acfg_unlock (acfg);
7170 /* fixme: maybe we can also precompile wrapper methods */
7171 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7172 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7173 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7174 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7178 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7181 wrapped = mono_marshal_method_from_wrapper (method);
7182 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7183 // FIXME: The wrapper should be generic too, but it is not
7186 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7189 InterlockedIncrement (&acfg->stats.mcount);
7192 if (method->is_generic || method->klass->generic_container) {
7193 InterlockedIncrement (&acfg->stats.genericcount);
7198 //acfg->aot_opts.print_skipped_methods = TRUE;
7201 * Since these methods are the only ones which are compiled with
7202 * AOT support, and they are not used by runtime startup/shutdown code,
7203 * the runtime will not see AOT methods during AOT compilation,so it
7204 * does not need to support them by creating a fake GOT etc.
7206 flags = JIT_FLAG_AOT;
7207 if (mono_aot_mode_is_full (&acfg->aot_opts))
7208 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7210 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7211 if (acfg->aot_opts.llvm_only)
7212 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7213 if (acfg->aot_opts.no_direct_calls)
7214 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7216 jit_timer = mono_time_track_start ();
7217 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7218 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7220 mono_loader_clear_error ();
7222 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7223 if (acfg->aot_opts.print_skipped_methods)
7224 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7225 InterlockedIncrement (&acfg->stats.genericcount);
7228 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7229 if (acfg->aot_opts.print_skipped_methods)
7230 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7231 /* Let the exception happen at runtime */
7235 if (cfg->disable_aot) {
7236 if (acfg->aot_opts.print_skipped_methods)
7237 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7238 InterlockedIncrement (&acfg->stats.ocount);
7239 mono_destroy_compile (cfg);
7242 cfg->method_index = index;
7244 /* Nullify patches which need no aot processing */
7245 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7246 switch (patch_info->type) {
7247 case MONO_PATCH_INFO_LABEL:
7248 case MONO_PATCH_INFO_BB:
7249 patch_info->type = MONO_PATCH_INFO_NONE;
7256 /* Collect method->token associations from the cfg */
7257 mono_acfg_lock (acfg);
7258 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7259 mono_acfg_unlock (acfg);
7260 g_hash_table_destroy (cfg->token_info_hash);
7261 cfg->token_info_hash = NULL;
7264 * Check for absolute addresses.
7267 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7268 switch (patch_info->type) {
7269 case MONO_PATCH_INFO_ABS:
7270 /* unable to handle this */
7279 if (acfg->aot_opts.print_skipped_methods)
7280 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7281 InterlockedIncrement (&acfg->stats.abscount);
7282 mono_destroy_compile (cfg);
7286 /* Lock for the rest of the code */
7287 mono_acfg_lock (acfg);
7290 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7291 else if (cfg->gshared)
7292 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7293 else if (cfg->method->wrapper_type)
7294 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7296 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7299 * Check for methods/klasses we can't encode.
7302 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7303 if (!can_encode_patch (acfg, patch_info))
7308 if (acfg->aot_opts.print_skipped_methods)
7309 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7310 acfg->stats.ocount++;
7311 mono_destroy_compile (cfg);
7312 mono_acfg_unlock (acfg);
7316 if (!cfg->compile_llvm)
7317 acfg->has_jitted_code = TRUE;
7319 if (method->is_inflated && acfg->aot_opts.log_instances) {
7320 if (acfg->instances_logfile)
7321 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7323 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7326 /* Adds generic instances referenced by this method */
7328 * The depth is used to avoid infinite loops when generic virtual recursion is
7331 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7332 if (!acfg->aot_opts.no_instances && depth < 32) {
7333 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7334 switch (patch_info->type) {
7335 case MONO_PATCH_INFO_RGCTX_FETCH:
7336 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7337 case MONO_PATCH_INFO_METHOD: {
7338 MonoMethod *m = NULL;
7340 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7341 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7343 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7344 m = e->data->data.method;
7346 m = patch_info->data.method;
7351 if (m->is_inflated) {
7352 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7353 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7354 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7355 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7356 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7357 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7359 add_extra_method_with_depth (acfg, m, depth + 1);
7360 add_types_from_method_header (acfg, m);
7363 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7365 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7366 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7368 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7369 add_extra_method_with_depth (acfg, m, depth + 1);
7373 case MONO_PATCH_INFO_VTABLE: {
7374 MonoClass *klass = patch_info->data.klass;
7376 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7377 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7380 case MONO_PATCH_INFO_SFLDA: {
7381 MonoClass *klass = patch_info->data.field->parent;
7383 /* The .cctor needs to run at runtime. */
7384 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7385 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7394 /* Determine whenever the method has GOT slots */
7395 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7396 switch (patch_info->type) {
7397 case MONO_PATCH_INFO_GOT_OFFSET:
7398 case MONO_PATCH_INFO_NONE:
7399 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7400 case MONO_PATCH_INFO_GC_NURSERY_START:
7401 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7403 case MONO_PATCH_INFO_IMAGE:
7404 /* The assembly is stored in GOT slot 0 */
7405 if (patch_info->data.image != acfg->image)
7406 cfg->has_got_slots = TRUE;
7409 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7410 cfg->has_got_slots = TRUE;
7415 if (!cfg->has_got_slots)
7416 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7418 /* Add gsharedvt wrappers for signatures used by the method */
7419 if (acfg->aot_opts.llvm_only) {
7422 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7423 /* These only need out wrappers */
7424 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7426 for (l = cfg->signatures; l; l = l->next) {
7427 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7429 /* These only need in wrappers */
7430 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7435 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7437 /* Make a copy of the patch info which is in the mempool */
7439 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7441 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7442 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7445 patches = new_patch_info;
7447 patches_end->next = new_patch_info;
7448 patches_end = new_patch_info;
7450 cfg->patch_info = patches;
7452 /* Make a copy of the unwind info */
7454 GSList *l, *unwind_ops;
7458 for (l = cfg->unwind_ops; l; l = l->next) {
7459 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7460 memcpy (op, l->data, sizeof (MonoUnwindOp));
7461 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7463 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7465 /* Make a copy of the argument/local info */
7468 MonoInst **args, **locals;
7469 MonoMethodSignature *sig;
7470 MonoMethodHeader *header;
7473 sig = mono_method_signature (method);
7474 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7475 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7476 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7477 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7481 header = mono_method_get_header_checked (method, &error);
7482 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7483 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7484 for (i = 0; i < header->num_locals; ++i) {
7485 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7486 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7488 cfg->locals = locals;
7491 /* Free some fields used by cfg to conserve memory */
7492 mono_mempool_destroy (cfg->mempool);
7493 cfg->mempool = NULL;
7494 g_free (cfg->varinfo);
7495 cfg->varinfo = NULL;
7499 mono_regstate_free (cfg->rs);
7503 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7505 while (index >= acfg->cfgs_size) {
7506 MonoCompile **new_cfgs;
7509 new_size = acfg->cfgs_size * 2;
7510 new_cfgs = g_new0 (MonoCompile*, new_size);
7511 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7512 g_free (acfg->cfgs);
7513 acfg->cfgs = new_cfgs;
7514 acfg->cfgs_size = new_size;
7516 acfg->cfgs [index] = cfg;
7518 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7520 mono_update_jit_stats (cfg);
7523 if (cfg->orig_method->wrapper_type)
7524 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7527 mono_acfg_unlock (acfg);
7529 InterlockedIncrement (&acfg->stats.ccount);
7533 compile_thread_main (gpointer *user_data)
7535 MonoDomain *domain = (MonoDomain *)user_data [0];
7536 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7537 GPtrArray *methods = (GPtrArray *)user_data [2];
7540 mono_thread_attach (domain);
7542 for (i = 0; i < methods->len; ++i)
7543 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7547 load_profile_files (MonoAotCompile *acfg)
7551 int file_index, res, method_index, i;
7554 GList *unordered, *l;
7559 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7561 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7566 infile = fopen (tmp, "r");
7569 printf ("Using profile data file '%s'\n", tmp);
7574 res = fscanf (infile, "%32s\n", ver);
7575 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7576 printf ("Profile file has wrong version or invalid.\n");
7583 MonoMethodDesc *desc;
7586 if (fgets (name, 1023, infile) == NULL)
7589 /* Kill the newline */
7590 if (strlen (name) > 0)
7591 name [strlen (name) - 1] = '\0';
7593 desc = mono_method_desc_new (name, TRUE);
7595 method = mono_method_desc_search_in_image (desc, acfg->image);
7597 if (method && mono_method_get_token (method)) {
7598 token = mono_method_get_token (method);
7599 method_index = mono_metadata_token_index (token) - 1;
7602 for (i = 0; i < acfg->method_order->len; ++i) {
7603 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7609 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7611 //printf ("No method found matching '%s'.\n", name);
7617 /* Add missing methods */
7619 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7621 for (i = 0; i < acfg->method_order->len; ++i) {
7622 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7628 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7630 unordered = g_list_reverse (unordered);
7631 for (l = unordered; l; l = l->next)
7632 g_ptr_array_add (acfg->method_order, l->data);
7635 /* Used by the LLVM backend */
7637 mono_aot_get_got_offset (MonoJumpInfo *ji)
7639 return get_got_offset (llvm_acfg, TRUE, ji);
7643 * mono_aot_is_shared_got_offset:
7645 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7646 * when the AOT image is loaded.
7649 mono_aot_is_shared_got_offset (int offset)
7651 return offset < llvm_acfg->nshared_got_entries;
7655 mono_aot_get_method_name (MonoCompile *cfg)
7657 if (llvm_acfg->aot_opts.static_link)
7658 /* Include the assembly name too to avoid duplicate symbol errors */
7659 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7661 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7665 * mono_aot_is_linkonce_method:
7667 * Return whenever METHOD should be emitted with linkonce linkage,
7668 * eliminating duplicate copies when compiling in static mode.
7671 mono_aot_is_linkonce_method (MonoMethod *method)
7675 // FIXME: Add more cases
7676 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7678 info = mono_marshal_get_wrapper_info (method);
7679 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7685 append_mangled_type (GString *s, MonoType *t)
7688 g_string_append_printf (s, "b");
7690 case MONO_TYPE_VOID:
7691 g_string_append_printf (s, "void_");
7694 g_string_append_printf (s, "i1");
7697 g_string_append_printf (s, "u1");
7700 g_string_append_printf (s, "i2");
7703 g_string_append_printf (s, "u2");
7706 g_string_append_printf (s, "i4");
7709 g_string_append_printf (s, "u4");
7712 g_string_append_printf (s, "i8");
7715 g_string_append_printf (s, "u8");
7718 g_string_append_printf (s, "ii");
7721 g_string_append_printf (s, "ui");
7724 g_string_append_printf (s, "fl");
7727 g_string_append_printf (s, "do");
7730 char *fullname = mono_type_full_name (t);
7736 * Have to create a mangled name which is:
7740 temp = g_string_new ("");
7741 len = strlen (fullname);
7742 for (i = 0; i < len; ++i) {
7743 char c = fullname [i];
7745 g_string_append_c (temp, c);
7746 } else if (c == '_') {
7747 g_string_append_c (temp, '_');
7748 g_string_append_c (temp, '_');
7750 g_string_append_c (temp, '_');
7751 g_string_append_printf (temp, "%x", (int)c);
7754 temps = g_string_free (temp, FALSE);
7755 /* Include the length to avoid different length type names aliasing each other */
7756 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
7765 append_mangled_signature (GString *s, MonoMethodSignature *sig)
7770 supported = append_mangled_type (s, sig->ret);
7774 g_string_append_printf (s, "this_");
7775 for (i = 0; i < sig->param_count; ++i) {
7776 supported = append_mangled_type (s, sig->params [i]);
7785 * mono_aot_get_mangled_method_name:
7787 * Return a unique mangled name for METHOD, or NULL.
7790 mono_aot_get_mangled_method_name (MonoMethod *method)
7796 // FIXME: Add more cases
7797 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7799 info = mono_marshal_get_wrapper_info (method);
7800 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7803 s = g_string_new ("");
7805 g_string_append_printf (s, "aot_method_w_");
7807 switch (info->subtype) {
7808 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
7809 g_string_append_printf (s, "gsharedvt_in_");
7811 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
7812 g_string_append_printf (s, "gsharedvt_out_");
7815 g_assert_not_reached ();
7819 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
7821 g_string_free (s, TRUE);
7825 return g_string_free (s, FALSE);
7829 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7831 return is_direct_callable (llvm_acfg, NULL, patch_info);
7835 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7837 MonoPltEntry *plt_entry;
7839 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7840 plt_entry->llvm_used = FALSE;
7844 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
7846 const char *sym = NULL;
7848 if (llvm_acfg->aot_opts.direct_icalls) {
7849 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7850 /* Call to a C function implementing a jit icall */
7851 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7852 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
7853 MonoMethod *method = (MonoMethod *)data;
7854 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7855 sym = mono_lookup_icall_symbol (method);
7856 else if (llvm_acfg->aot_opts.direct_pinvoke)
7857 sym = get_pinvoke_import (llvm_acfg, method);
7860 return g_strdup (sym);
7866 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7868 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7869 MonoPltEntry *plt_entry;
7870 const char *sym = NULL;
7873 ji->data.target = data;
7875 if (!can_encode_patch (llvm_acfg, ji))
7878 if (llvm_acfg->aot_opts.direct_icalls) {
7879 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7880 /* Call to a C function implementing a jit icall */
7881 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7882 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
7883 MonoMethod *method = (MonoMethod *)data;
7884 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7885 sym = mono_lookup_icall_symbol (method);
7888 return g_strdup (sym);
7891 plt_entry = get_plt_entry (llvm_acfg, ji);
7892 plt_entry->llvm_used = TRUE;
7894 #if defined(TARGET_MACH)
7895 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7897 return g_strdup_printf (plt_entry->llvm_symbol);
7902 mono_aot_get_method_index (MonoMethod *method)
7904 g_assert (llvm_acfg);
7905 return get_method_index (llvm_acfg, method);
7909 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7913 mono_acfg_lock (llvm_acfg);
7914 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7915 mono_acfg_unlock (llvm_acfg);
7921 execute_system (const char * command)
7926 // We need an extra set of quotes around the whole command to properly handle commands
7927 // with spaces since internally the command is called through "cmd /c.
7928 command = g_strdup_printf ("\"%s\"", command);
7930 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7931 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7932 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7933 status = _wsystem (wstr);
7937 #elif defined (HAVE_SYSTEM)
7938 status = system (command);
7940 g_assert_not_reached ();
7951 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7955 emit_llvm_file (MonoAotCompile *acfg)
7957 char *command, *opts, *tempbc, *optbc, *output_fname;
7959 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
7960 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7961 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
7963 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7964 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
7967 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7970 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7971 * a lot of time, and doesn't seem to save much space.
7972 * The following optimizations cannot be enabled:
7974 * - 'jump-threading' changes our blockaddress references to int constants.
7975 * - 'basiccg' fails because it contains:
7976 * if (CS && !isa<IntrinsicInst>(II)) {
7977 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7978 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7979 * The opt list below was produced by taking the output of:
7980 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7981 * then removing tailcallelim + the global opts.
7982 * strip-dead-prototypes deletes unused intrinsics definitions.
7984 /* The dse pass is disabled because of #13734 and #17616 */
7986 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7987 * // If we have no DataLayout information around, then the size of the store
7988 * // is inferrable from the pointee type. If they are the same type, then
7989 * // we know that the store is safe.
7990 * if (AA.getDataLayout() == 0 &&
7991 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7992 * return OverwriteComplete;
7993 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7995 if (acfg->aot_opts.llvm_only)
7996 // FIXME: This doesn't work yet
7997 opts = g_strdup ("");
7999 #if LLVM_API_VERSION > 100
8000 opts = g_strdup ("-O2");
8002 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");
8004 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8005 aot_printf (acfg, "Executing opt: %s\n", command);
8006 if (execute_system (command) != 0)
8010 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8011 /* Nothing else to do */
8014 if (acfg->aot_opts.llvm_only) {
8015 /* Use the stock clang from xcode */
8017 command = g_strdup_printf ("clang -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
8019 aot_printf (acfg, "Executing clang: %s\n", command);
8020 if (execute_system (command) != 0)
8025 if (!acfg->llc_args)
8026 acfg->llc_args = g_string_new ("");
8028 /* Verbose asm slows down llc greatly */
8029 g_string_append (acfg->llc_args, " -asm-verbose=false");
8031 if (acfg->aot_opts.mtriple)
8032 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8034 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8036 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8038 #if LLVM_API_VERSION > 100
8039 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8042 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8043 /* ios requires PIC code now */
8044 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8046 if (llvm_acfg->aot_opts.static_link)
8047 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8049 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8052 if (acfg->llvm_owriter) {
8053 /* Emit an object file directly */
8054 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8055 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8057 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8059 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8060 g_free (output_fname);
8062 aot_printf (acfg, "Executing llc: %s\n", command);
8064 if (execute_system (command) != 0)
8071 emit_code (MonoAotCompile *acfg)
8073 int oindex, i, prev_index;
8074 gboolean saved_unbox_info = FALSE;
8077 if (acfg->aot_opts.llvm_only)
8080 #if defined(TARGET_POWERPC64)
8081 sprintf (symbol, ".Lgot_addr");
8082 emit_section_change (acfg, ".text", 0);
8083 emit_alignment (acfg, 8);
8084 emit_label (acfg, symbol);
8085 emit_pointer (acfg, acfg->got_symbol);
8089 * This global symbol is used to compute the address of each method using the
8090 * code_offsets array. It is also used to compute the memory ranges occupied by
8091 * AOT code, so it must be equal to the address of the first emitted method.
8093 emit_section_change (acfg, ".text", 0);
8094 emit_alignment_code (acfg, 8);
8095 emit_info_symbol (acfg, "jit_code_start");
8098 * Emit some padding so the local symbol for the first method doesn't have the
8099 * same address as 'methods'.
8101 #if defined(__default_codegen__)
8102 emit_padding (acfg, 16);
8103 #elif defined(__native_client_codegen__)
8105 const int kPaddingSize = 16;
8106 guint8 pad_buffer[kPaddingSize];
8107 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
8108 emit_bytes (acfg, pad_buffer, kPaddingSize);
8112 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8116 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8118 cfg = acfg->cfgs [i];
8123 method = cfg->orig_method;
8125 /* Emit unbox trampoline */
8126 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8127 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8129 emit_section_change (acfg, ".text", 0);
8130 #ifdef __native_client_codegen__
8131 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
8134 if (acfg->thumb_mixed && cfg->compile_llvm) {
8135 emit_set_thumb_mode (acfg);
8136 fprintf (acfg->fp, "\n.thumb_func\n");
8139 emit_label (acfg, symbol);
8141 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8143 if (acfg->thumb_mixed && cfg->compile_llvm)
8144 emit_set_arm_mode (acfg);
8146 if (!saved_unbox_info) {
8147 char user_symbol [128];
8149 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8151 emit_label (acfg, "ut_end");
8153 unwind_ops = mono_unwind_get_cie_program ();
8154 save_unwind_info (acfg, user_symbol, unwind_ops);
8155 mono_free_unwind_info (unwind_ops);
8157 /* Save the unbox trampoline size */
8158 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8160 saved_unbox_info = TRUE;
8164 if (cfg->compile_llvm)
8165 acfg->stats.llvm_count ++;
8167 emit_method_code (acfg, cfg);
8170 emit_section_change (acfg, ".text", 0);
8171 emit_alignment_code (acfg, 8);
8172 emit_info_symbol (acfg, "jit_code_end");
8174 /* To distinguish it from the next symbol */
8175 emit_padding (acfg, 4);
8178 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8179 * from optimizing them away, since it doesn't see that code_offsets references them.
8180 * JITted methods don't need this since they are referenced using assembler local
8182 * FIXME: This is why write-symbols doesn't work on OSX ?
8184 if (acfg->llvm && acfg->need_no_dead_strip) {
8185 fprintf (acfg->fp, "\n");
8186 for (i = 0; i < acfg->nmethods; ++i) {
8187 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8188 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8193 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8194 * This is PIE code, and the linker can update it if needed.
8196 sprintf (symbol, "method_addresses");
8197 emit_section_change (acfg, ".text", 1);
8198 emit_alignment_code (acfg, 8);
8199 emit_info_symbol (acfg, symbol);
8200 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8201 emit_unset_mode (acfg);
8202 if (acfg->need_no_dead_strip)
8203 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8205 for (i = 0; i < acfg->nmethods; ++i) {
8206 #ifdef MONO_ARCH_AOT_SUPPORTED
8209 if (acfg->cfgs [i]) {
8210 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
8211 /* Obtained by calling a generated function in the LLVM image */
8212 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8214 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8216 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8221 sprintf (symbol, "method_addresses_end");
8222 emit_label (acfg, symbol);
8225 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8226 sprintf (symbol, "unbox_trampolines");
8227 emit_section_change (acfg, RODATA_SECT, 0);
8228 emit_alignment (acfg, 8);
8229 emit_info_symbol (acfg, symbol);
8232 for (i = 0; i < acfg->nmethods; ++i) {
8237 cfg = acfg->cfgs [i];
8241 method = cfg->orig_method;
8243 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8244 index = get_method_index (acfg, method);
8246 emit_int32 (acfg, index);
8247 /* Make sure the table is sorted by index */
8248 g_assert (index > prev_index);
8252 sprintf (symbol, "unbox_trampolines_end");
8253 emit_info_symbol (acfg, symbol);
8254 emit_int32 (acfg, 0);
8256 /* Emit a separate table with the trampoline addresses/offsets */
8257 sprintf (symbol, "unbox_trampoline_addresses");
8258 emit_section_change (acfg, ".text", 0);
8259 emit_alignment_code (acfg, 8);
8260 emit_info_symbol (acfg, symbol);
8262 for (i = 0; i < acfg->nmethods; ++i) {
8267 cfg = acfg->cfgs [i];
8271 method = cfg->orig_method;
8273 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8274 #ifdef MONO_ARCH_AOT_SUPPORTED
8277 index = get_method_index (acfg, method);
8278 sprintf (symbol, "ut_%d", index);
8280 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8284 emit_int32 (acfg, 0);
8288 emit_info (MonoAotCompile *acfg)
8293 offsets = g_new0 (gint32, acfg->nmethods);
8295 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8296 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8298 if (acfg->cfgs [i]) {
8299 emit_method_info (acfg, acfg->cfgs [i]);
8300 offsets [i] = acfg->cfgs [i]->method_info_offset;
8306 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8311 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8313 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8314 #define mix(a,b,c) { \
8315 a -= c; a ^= rot(c, 4); c += b; \
8316 b -= a; b ^= rot(a, 6); a += c; \
8317 c -= b; c ^= rot(b, 8); b += a; \
8318 a -= c; a ^= rot(c,16); c += b; \
8319 b -= a; b ^= rot(a,19); a += c; \
8320 c -= b; c ^= rot(b, 4); b += a; \
8322 #define final(a,b,c) { \
8323 c ^= b; c -= rot(b,14); \
8324 a ^= c; a -= rot(c,11); \
8325 b ^= a; b -= rot(a,25); \
8326 c ^= b; c -= rot(b,16); \
8327 a ^= c; a -= rot(c,4); \
8328 b ^= a; b -= rot(a,14); \
8329 c ^= b; c -= rot(b,24); \
8333 mono_aot_type_hash (MonoType *t1)
8335 guint hash = t1->type;
8337 hash |= t1->byref << 6; /* do not collide with t1->type values */
8339 case MONO_TYPE_VALUETYPE:
8340 case MONO_TYPE_CLASS:
8341 case MONO_TYPE_SZARRAY:
8342 /* check if the distribution is good enough */
8343 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8345 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8346 case MONO_TYPE_ARRAY:
8347 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8348 case MONO_TYPE_GENERICINST:
8349 return ((hash << 5) - hash) ^ 0;
8356 * mono_aot_method_hash:
8358 * Return a hash code for methods which only depends on metadata.
8361 mono_aot_method_hash (MonoMethod *method)
8363 MonoMethodSignature *sig;
8367 guint32 *hashes_start, *hashes;
8369 MonoGenericInst *class_ginst = NULL;
8370 MonoGenericInst *ginst = NULL;
8372 /* Similar to the hash in mono_method_get_imt_slot () */
8374 sig = mono_method_signature (method);
8376 if (method->klass->generic_class)
8377 class_ginst = method->klass->generic_class->context.class_inst;
8378 if (method->is_inflated)
8379 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8381 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8382 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8383 hashes = hashes_start;
8385 /* Some wrappers are assigned to random classes */
8386 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8387 klass = method->klass;
8389 klass = mono_defaults.object_class;
8391 if (!method->wrapper_type) {
8394 if (klass->generic_class)
8395 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8397 full_name = mono_type_full_name (&klass->byval_arg);
8399 hashes [0] = mono_metadata_str_hash (full_name);
8403 hashes [0] = mono_metadata_str_hash (klass->name);
8404 hashes [1] = mono_metadata_str_hash (klass->name_space);
8406 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8407 /* The method name includes a stringified pointer */
8410 hashes [2] = mono_metadata_str_hash (method->name);
8411 hashes [3] = method->wrapper_type;
8412 hashes [4] = mono_aot_type_hash (sig->ret);
8414 for (i = 0; i < sig->param_count; i++) {
8415 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8418 for (i = 0; i < class_ginst->type_argc; ++i)
8419 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8422 for (i = 0; i < ginst->type_argc; ++i)
8423 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8425 g_assert (hindex == hashes_count);
8427 /* Setup internal state */
8428 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8430 /* Handle most of the hashes */
8431 while (hashes_count > 3) {
8440 /* Handle the last 3 hashes (all the case statements fall through) */
8441 switch (hashes_count) {
8442 case 3 : c += hashes [2];
8443 case 2 : b += hashes [1];
8444 case 1 : a += hashes [0];
8446 case 0: /* nothing left to add */
8450 free (hashes_start);
8459 * mono_aot_get_array_helper_from_wrapper;
8461 * Get the helper method in Array called by an array wrapper method.
8464 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8468 MonoGenericContext ctx;
8469 MonoType *args [16];
8470 char *mname, *iname, *s, *s2, *helper_name = NULL;
8472 prefix = "System.Collections.Generic";
8473 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8474 s2 = strstr (s, "`1.");
8480 //printf ("X: %s %s\n", iname, mname);
8482 if (!strcmp (iname, "IList"))
8483 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8485 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8486 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8488 g_free (helper_name);
8491 if (m->is_generic) {
8493 memset (&ctx, 0, sizeof (ctx));
8494 args [0] = &method->klass->element_class->byval_arg;
8495 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8496 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8497 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8503 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8505 typedef struct HashEntry {
8506 guint32 key, value, index;
8507 struct HashEntry *next;
8511 * emit_extra_methods:
8513 * Emit methods which are not in the METHOD table, like wrappers.
8516 emit_extra_methods (MonoAotCompile *acfg)
8518 int i, table_size, buf_size;
8520 guint32 *info_offsets;
8523 HashEntry *entry, *new_entry;
8524 int nmethods, max_chain_length;
8527 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8529 /* Emit method info */
8531 for (i = 0; i < acfg->extra_methods->len; ++i) {
8532 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8533 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8539 p = buf = (guint8 *)g_malloc (buf_size);
8543 method = cfg->method_to_register;
8545 encode_method_ref (acfg, method, p, &p);
8547 g_assert ((p - buf) < buf_size);
8549 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8554 * Construct a chained hash table for mapping indexes in extra_method_info to
8557 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8558 table = g_ptr_array_sized_new (table_size);
8559 for (i = 0; i < table_size; ++i)
8560 g_ptr_array_add (table, NULL);
8561 chain_lengths = g_new0 (int, table_size);
8562 max_chain_length = 0;
8563 for (i = 0; i < acfg->extra_methods->len; ++i) {
8564 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8565 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8571 key = info_offsets [i];
8572 value = get_method_index (acfg, method);
8574 hash = mono_aot_method_hash (method) % table_size;
8575 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8577 chain_lengths [hash] ++;
8578 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8580 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8581 new_entry->key = key;
8582 new_entry->value = value;
8584 entry = (HashEntry *)g_ptr_array_index (table, hash);
8585 if (entry == NULL) {
8586 new_entry->index = hash;
8587 g_ptr_array_index (table, hash) = new_entry;
8590 entry = entry->next;
8592 entry->next = new_entry;
8593 new_entry->index = table->len;
8594 g_ptr_array_add (table, new_entry);
8598 //printf ("MAX: %d\n", max_chain_length);
8600 buf_size = table->len * 12 + 4;
8601 p = buf = (guint8 *)g_malloc (buf_size);
8602 encode_int (table_size, p, &p);
8604 for (i = 0; i < table->len; ++i) {
8605 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8607 if (entry == NULL) {
8608 encode_int (0, p, &p);
8609 encode_int (0, p, &p);
8610 encode_int (0, p, &p);
8612 //g_assert (entry->key > 0);
8613 encode_int (entry->key, p, &p);
8614 encode_int (entry->value, p, &p);
8616 encode_int (entry->next->index, p, &p);
8618 encode_int (0, p, &p);
8621 g_assert (p - buf <= buf_size);
8623 /* Emit the table */
8624 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8627 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8628 * This is used by mono_aot_find_jit_info ().
8630 buf_size = acfg->extra_methods->len * 8 + 4;
8631 p = buf = (guint8 *)g_malloc (buf_size);
8632 encode_int (acfg->extra_methods->len, p, &p);
8633 for (i = 0; i < acfg->extra_methods->len; ++i) {
8634 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8636 encode_int (get_method_index (acfg, method), p, &p);
8637 encode_int (info_offsets [i], p, &p);
8639 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8643 emit_exception_info (MonoAotCompile *acfg)
8647 SeqPointData sp_data;
8648 gboolean seq_points_to_file = FALSE;
8650 offsets = g_new0 (gint32, acfg->nmethods);
8651 for (i = 0; i < acfg->nmethods; ++i) {
8652 if (acfg->cfgs [i]) {
8653 MonoCompile *cfg = acfg->cfgs [i];
8655 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8656 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8657 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8658 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8659 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8661 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8662 offsets [i] = cfg->ex_info_offset;
8664 if (method_seq_points_to_file) {
8665 if (!seq_points_to_file) {
8666 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8667 seq_points_to_file = TRUE;
8669 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8676 if (seq_points_to_file) {
8677 char *seq_points_aot_file = acfg->aot_opts.gen_seq_points_file_path ? acfg->aot_opts.gen_seq_points_file_path
8678 : g_strdup_printf("%s%s", acfg->image->name, SEQ_POINT_AOT_EXT);
8679 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8680 mono_seq_point_data_free (&sp_data);
8681 g_free (seq_points_aot_file);
8684 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8689 emit_unwind_info (MonoAotCompile *acfg)
8694 if (acfg->aot_opts.llvm_only) {
8695 g_assert (acfg->unwind_ops->len == 0);
8700 * The unwind info contains a lot of duplicates so we emit each unique
8701 * entry once, and only store the offset from the start of the table in the
8705 sprintf (symbol, "unwind_info");
8706 emit_section_change (acfg, RODATA_SECT, 1);
8707 emit_alignment (acfg, 8);
8708 emit_info_symbol (acfg, symbol);
8710 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8711 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8712 guint8 *unwind_info;
8713 guint32 unwind_info_len;
8717 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8720 encode_value (unwind_info_len, p, &p);
8721 emit_bytes (acfg, buf, p - buf);
8722 emit_bytes (acfg, unwind_info, unwind_info_len);
8724 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8729 emit_class_info (MonoAotCompile *acfg)
8734 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8735 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8736 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8738 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", MONO_AOT_TABLE_CLASS_INFO_OFFSETS, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8742 typedef struct ClassNameTableEntry {
8743 guint32 token, index;
8744 struct ClassNameTableEntry *next;
8745 } ClassNameTableEntry;
8748 emit_class_name_table (MonoAotCompile *acfg)
8750 int i, table_size, buf_size;
8751 guint32 token, hash;
8756 ClassNameTableEntry *entry, *new_entry;
8759 * Construct a chained hash table for mapping class names to typedef tokens.
8761 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8762 table = g_ptr_array_sized_new (table_size);
8763 for (i = 0; i < table_size; ++i)
8764 g_ptr_array_add (table, NULL);
8765 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8767 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8768 klass = mono_class_get_checked (acfg->image, token, &error);
8770 mono_error_cleanup (&error);
8773 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8774 hash = mono_metadata_str_hash (full_name) % table_size;
8777 /* FIXME: Allocate from the mempool */
8778 new_entry = g_new0 (ClassNameTableEntry, 1);
8779 new_entry->token = token;
8781 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
8782 if (entry == NULL) {
8783 new_entry->index = hash;
8784 g_ptr_array_index (table, hash) = new_entry;
8787 entry = entry->next;
8789 entry->next = new_entry;
8790 new_entry->index = table->len;
8791 g_ptr_array_add (table, new_entry);
8795 /* Emit the table */
8796 buf_size = table->len * 4 + 4;
8797 p = buf = (guint8 *)g_malloc0 (buf_size);
8799 /* FIXME: Optimize memory usage */
8800 g_assert (table_size < 65000);
8801 encode_int16 (table_size, p, &p);
8802 g_assert (table->len < 65000);
8803 for (i = 0; i < table->len; ++i) {
8804 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
8806 if (entry == NULL) {
8807 encode_int16 (0, p, &p);
8808 encode_int16 (0, p, &p);
8810 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8812 encode_int16 (entry->next->index, p, &p);
8814 encode_int16 (0, p, &p);
8817 g_assert (p - buf <= buf_size);
8819 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
8823 emit_image_table (MonoAotCompile *acfg)
8829 * The image table is small but referenced in a lot of places.
8830 * So we emit it at once, and reference its elements by an index.
8832 buf_size = acfg->image_table->len * 28 + 4;
8833 for (i = 0; i < acfg->image_table->len; i++) {
8834 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8835 MonoAssemblyName *aname = &image->assembly->aname;
8837 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8840 buf = p = (guint8 *)g_malloc0 (buf_size);
8841 encode_int (acfg->image_table->len, p, &p);
8842 for (i = 0; i < acfg->image_table->len; i++) {
8843 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8844 MonoAssemblyName *aname = &image->assembly->aname;
8846 /* FIXME: Support multi-module assemblies */
8847 g_assert (image->assembly->image == image);
8849 encode_string (image->assembly_name, p, &p);
8850 encode_string (image->guid, p, &p);
8851 encode_string (aname->culture ? aname->culture : "", p, &p);
8852 encode_string ((const char*)aname->public_key_token, p, &p);
8854 while (GPOINTER_TO_UINT (p) % 8 != 0)
8857 encode_int (aname->flags, p, &p);
8858 encode_int (aname->major, p, &p);
8859 encode_int (aname->minor, p, &p);
8860 encode_int (aname->build, p, &p);
8861 encode_int (aname->revision, p, &p);
8863 g_assert (p - buf <= buf_size);
8865 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
8871 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8873 int i, first_plt_got_patch = 0, buf_size;
8875 guint32 *got_info_offsets;
8876 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8878 /* Add the patches needed by the PLT to the GOT */
8880 acfg->plt_got_offset_base = acfg->got_offset;
8881 first_plt_got_patch = info->got_patches->len;
8882 for (i = 1; i < acfg->plt_offset; ++i) {
8883 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8885 g_ptr_array_add (info->got_patches, plt_entry->ji);
8887 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8890 acfg->got_offset += acfg->plt_offset;
8895 * - optimize offsets table.
8896 * - reduce number of exported symbols.
8897 * - emit info for a klass only once.
8898 * - determine when a method uses a GOT slot which is guaranteed to be already
8900 * - clean up and document the code.
8901 * - use String.Empty in class libs.
8904 /* Encode info required to decode shared GOT entries */
8905 buf_size = info->got_patches->len * 128;
8906 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
8907 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8909 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8911 if (acfg->plt_offset)
8912 acfg->plt_got_info_offsets [0] = 0;
8914 for (i = 0; i < info->got_patches->len; ++i) {
8915 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
8920 encode_value (ji->type, p, &p);
8922 encode_patch (acfg, ji, p, &p);
8923 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8924 g_assert (p - buf <= buf_size);
8925 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8927 if (!llvm && i >= first_plt_got_patch)
8928 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8929 acfg->stats.got_info_size += p - buf;
8932 /* Emit got_info_offsets table */
8934 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8935 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS : MONO_AOT_TABLE_GOT_INFO_OFFSETS, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8939 emit_got (MonoAotCompile *acfg)
8943 if (acfg->aot_opts.llvm_only)
8946 /* Don't make GOT global so accesses to it don't need relocations */
8947 sprintf (symbol, "%s", acfg->got_symbol);
8950 emit_unset_mode (acfg);
8951 fprintf (acfg->fp, ".section __DATA, __bss\n");
8952 emit_alignment (acfg, 8);
8954 emit_info_symbol (acfg, "jit_got");
8955 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8957 emit_section_change (acfg, ".bss", 0);
8958 emit_alignment (acfg, 8);
8959 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8960 emit_label (acfg, symbol);
8962 emit_info_symbol (acfg, "jit_got");
8963 if (acfg->got_offset > 0)
8964 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8967 sprintf (symbol, "got_end");
8968 emit_label (acfg, symbol);
8971 typedef struct GlobalsTableEntry {
8972 guint32 value, index;
8973 struct GlobalsTableEntry *next;
8974 } GlobalsTableEntry;
8977 emit_globals (MonoAotCompile *acfg)
8983 GlobalsTableEntry *entry, *new_entry;
8985 if (!acfg->aot_opts.static_link)
8987 if (acfg->aot_opts.llvm_only) {
8988 g_assert (acfg->globals->len == 0);
8993 * When static linking, we emit a table containing our globals.
8997 * Construct a chained hash table for mapping global names to their index in
8998 * the globals table.
9000 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9001 table = g_ptr_array_sized_new (table_size);
9002 for (i = 0; i < table_size; ++i)
9003 g_ptr_array_add (table, NULL);
9004 for (i = 0; i < acfg->globals->len; ++i) {
9005 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9007 hash = mono_metadata_str_hash (name) % table_size;
9009 /* FIXME: Allocate from the mempool */
9010 new_entry = g_new0 (GlobalsTableEntry, 1);
9011 new_entry->value = i;
9013 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9014 if (entry == NULL) {
9015 new_entry->index = hash;
9016 g_ptr_array_index (table, hash) = new_entry;
9019 entry = entry->next;
9021 entry->next = new_entry;
9022 new_entry->index = table->len;
9023 g_ptr_array_add (table, new_entry);
9027 /* Emit the table */
9028 sprintf (symbol, ".Lglobals_hash");
9029 emit_section_change (acfg, RODATA_SECT, 0);
9030 emit_alignment (acfg, 8);
9031 emit_label (acfg, symbol);
9033 /* FIXME: Optimize memory usage */
9034 g_assert (table_size < 65000);
9035 emit_int16 (acfg, table_size);
9036 for (i = 0; i < table->len; ++i) {
9037 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9039 if (entry == NULL) {
9040 emit_int16 (acfg, 0);
9041 emit_int16 (acfg, 0);
9043 emit_int16 (acfg, entry->value + 1);
9045 emit_int16 (acfg, entry->next->index);
9047 emit_int16 (acfg, 0);
9051 /* Emit the names */
9052 for (i = 0; i < acfg->globals->len; ++i) {
9053 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9055 sprintf (symbol, "name_%d", i);
9056 emit_section_change (acfg, RODATA_SECT, 1);
9058 emit_alignment (acfg, 4);
9060 emit_label (acfg, symbol);
9061 emit_string (acfg, name);
9064 /* Emit the globals table */
9065 sprintf (symbol, "globals");
9066 emit_section_change (acfg, ".data", 0);
9067 /* This is not a global, since it is accessed by the init function */
9068 emit_alignment (acfg, 8);
9069 emit_info_symbol (acfg, symbol);
9071 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9072 emit_pointer (acfg, symbol);
9074 for (i = 0; i < acfg->globals->len; ++i) {
9075 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9077 sprintf (symbol, "name_%d", i);
9078 emit_pointer (acfg, symbol);
9080 g_assert (strlen (name) < sizeof (symbol));
9081 sprintf (symbol, "%s", name);
9082 emit_pointer (acfg, symbol);
9084 /* Null terminate the table */
9085 emit_int32 (acfg, 0);
9086 emit_int32 (acfg, 0);
9090 emit_mem_end (MonoAotCompile *acfg)
9094 if (acfg->aot_opts.llvm_only)
9097 sprintf (symbol, "mem_end");
9098 emit_section_change (acfg, ".text", 1);
9099 emit_alignment_code (acfg, 8);
9100 emit_label (acfg, symbol);
9104 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9108 info->version = MONO_AOT_FILE_VERSION;
9109 info->plt_got_offset_base = acfg->plt_got_offset_base;
9110 info->got_size = acfg->got_offset * sizeof (gpointer);
9111 info->plt_size = acfg->plt_offset;
9112 info->nmethods = acfg->nmethods;
9113 info->flags = acfg->flags;
9114 info->opts = acfg->opts;
9115 info->simd_opts = acfg->simd_opts;
9116 info->gc_name_index = acfg->gc_name_offset;
9117 info->datafile_size = acfg->datafile_offset;
9118 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9119 info->table_offsets [i] = acfg->table_offsets [i];
9120 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9121 info->num_trampolines [i] = acfg->num_trampolines [i];
9122 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9123 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9124 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9125 info->trampoline_size [i] = acfg->trampoline_size [i];
9126 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9128 info->double_align = MONO_ABI_ALIGNOF (double);
9129 info->long_align = MONO_ABI_ALIGNOF (gint64);
9130 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9131 info->tramp_page_size = acfg->tramp_page_size;
9132 info->nshared_got_entries = acfg->nshared_got_entries;
9133 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9134 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9138 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9142 const char **symbols;
9144 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9146 symbols [sindex ++] = acfg->got_symbol;
9148 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9149 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9151 symbols [sindex ++] = NULL;
9152 symbols [sindex ++] = NULL;
9154 /* llvm_get_method */
9155 symbols [sindex ++] = NULL;
9156 /* llvm_get_unbox_tramp */
9157 symbols [sindex ++] = NULL;
9158 if (!acfg->aot_opts.llvm_only) {
9159 symbols [sindex ++] = "jit_code_start";
9160 symbols [sindex ++] = "jit_code_end";
9161 symbols [sindex ++] = "method_addresses";
9163 symbols [sindex ++] = NULL;
9164 symbols [sindex ++] = NULL;
9165 symbols [sindex ++] = NULL;
9167 if (acfg->data_outfile) {
9168 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9169 symbols [sindex ++] = NULL;
9171 symbols [sindex ++] = "blob";
9172 symbols [sindex ++] = "class_name_table";
9173 symbols [sindex ++] = "class_info_offsets";
9174 symbols [sindex ++] = "method_info_offsets";
9175 symbols [sindex ++] = "ex_info_offsets";
9176 symbols [sindex ++] = "extra_method_info_offsets";
9177 symbols [sindex ++] = "extra_method_table";
9178 symbols [sindex ++] = "got_info_offsets";
9180 symbols [sindex ++] = "llvm_got_info_offsets";
9182 symbols [sindex ++] = NULL;
9183 symbols [sindex ++] = "image_table";
9185 symbols [sindex ++] = "mem_end";
9186 symbols [sindex ++] = "assembly_guid";
9187 symbols [sindex ++] = "runtime_version";
9188 if (acfg->num_trampoline_got_entries) {
9189 symbols [sindex ++] = "specific_trampolines";
9190 symbols [sindex ++] = "static_rgctx_trampolines";
9191 symbols [sindex ++] = "imt_thunks";
9192 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9194 symbols [sindex ++] = NULL;
9195 symbols [sindex ++] = NULL;
9196 symbols [sindex ++] = NULL;
9197 symbols [sindex ++] = NULL;
9199 if (acfg->aot_opts.static_link) {
9200 symbols [sindex ++] = "globals";
9202 symbols [sindex ++] = NULL;
9204 symbols [sindex ++] = "assembly_name";
9205 symbols [sindex ++] = "plt";
9206 symbols [sindex ++] = "plt_end";
9207 symbols [sindex ++] = "unwind_info";
9208 if (!acfg->aot_opts.llvm_only) {
9209 symbols [sindex ++] = "unbox_trampolines";
9210 symbols [sindex ++] = "unbox_trampolines_end";
9211 symbols [sindex ++] = "unbox_trampoline_addresses";
9213 symbols [sindex ++] = NULL;
9214 symbols [sindex ++] = NULL;
9215 symbols [sindex ++] = NULL;
9218 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9220 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9221 emit_section_change (acfg, ".data", 0);
9222 emit_alignment (acfg, 8);
9223 emit_label (acfg, symbol);
9224 if (!acfg->aot_opts.static_link)
9225 emit_global (acfg, symbol, FALSE);
9227 /* The data emitted here must match MonoAotFileInfo. */
9229 emit_int32 (acfg, info->version);
9230 emit_int32 (acfg, info->dummy);
9233 * We emit pointers to our data structures instead of emitting global symbols which
9234 * point to them, to reduce the number of globals, and because using globals leads to
9235 * various problems (i.e. arm/thumb).
9237 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9238 emit_pointer (acfg, symbols [i]);
9240 emit_int32 (acfg, info->plt_got_offset_base);
9241 emit_int32 (acfg, info->got_size);
9242 emit_int32 (acfg, info->plt_size);
9243 emit_int32 (acfg, info->nmethods);
9244 emit_int32 (acfg, info->flags);
9245 emit_int32 (acfg, info->opts);
9246 emit_int32 (acfg, info->simd_opts);
9247 emit_int32 (acfg, info->gc_name_index);
9248 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9249 emit_int32 (acfg, info->double_align);
9250 emit_int32 (acfg, info->long_align);
9251 emit_int32 (acfg, info->generic_tramp_num);
9252 emit_int32 (acfg, info->tramp_page_size);
9253 emit_int32 (acfg, info->nshared_got_entries);
9254 emit_int32 (acfg, info->datafile_size);
9256 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9257 emit_int32 (acfg, info->table_offsets [i]);
9258 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9259 emit_int32 (acfg, info->num_trampolines [i]);
9260 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9261 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9262 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9263 emit_int32 (acfg, info->trampoline_size [i]);
9264 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9265 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9267 if (acfg->aot_opts.static_link) {
9268 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9269 emit_alignment (acfg, sizeof (gpointer));
9270 emit_label (acfg, acfg->static_linking_symbol);
9271 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9276 * Emit a structure containing all the information not stored elsewhere.
9279 emit_file_info (MonoAotCompile *acfg)
9282 MonoAotFileInfo *info;
9284 if (acfg->aot_opts.bind_to_runtime_version) {
9285 build_info = mono_get_runtime_build_info ();
9286 emit_string_symbol (acfg, "runtime_version", build_info);
9287 g_free (build_info);
9289 emit_string_symbol (acfg, "runtime_version", "");
9292 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9294 /* Emit a string holding the assembly name */
9295 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9297 info = g_new0 (MonoAotFileInfo, 1);
9298 init_aot_file_info (acfg, info);
9300 if (acfg->aot_opts.static_link) {
9305 * Emit a global symbol which can be passed by an embedding app to
9306 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9309 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9311 /* Get rid of characters which cannot occur in symbols */
9313 for (p = symbol; *p; ++p) {
9314 if (!(isalnum (*p) || *p == '_'))
9317 acfg->static_linking_symbol = g_strdup (symbol);
9321 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9323 emit_aot_file_info (acfg, info);
9327 emit_blob (MonoAotCompile *acfg)
9329 acfg->blob_closed = TRUE;
9331 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9335 emit_objc_selectors (MonoAotCompile *acfg)
9340 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9345 * cat > foo.m << EOF
9348 * return @selector(print:);
9353 mono_img_writer_emit_unset_mode (acfg->w);
9354 g_assert (acfg->fp);
9355 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9356 fprintf (acfg->fp, ".align 3\n");
9357 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9358 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9359 emit_label (acfg, symbol);
9360 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9361 emit_pointer (acfg, symbol);
9364 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9365 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9366 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9367 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9370 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9371 fprintf (acfg->fp, ".align 3\n");
9372 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9373 fprintf (acfg->fp, ".long 0\n");
9374 fprintf (acfg->fp, ".long 16\n");
9378 emit_dwarf_info (MonoAotCompile *acfg)
9380 #ifdef EMIT_DWARF_INFO
9384 /* DIEs for methods */
9385 for (i = 0; i < acfg->nmethods; ++i) {
9386 MonoCompile *cfg = acfg->cfgs [i];
9391 // FIXME: LLVM doesn't define .Lme_...
9392 if (cfg->compile_llvm)
9395 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9397 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, (guint8 *)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 ()));
9403 collect_methods (MonoAotCompile *acfg)
9406 MonoImage *image = acfg->image;
9408 /* Collect methods */
9409 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9412 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9414 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9417 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9418 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9419 mono_error_cleanup (&error);
9423 /* Load all methods eagerly to skip the slower lazy loading code */
9424 mono_class_setup_methods (method->klass);
9426 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9427 /* Compile the wrapper instead */
9428 /* We do this here instead of add_wrappers () because it is easy to do it here */
9429 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9433 /* FIXME: Some mscorlib methods don't have debug info */
9435 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9436 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9437 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9438 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9439 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9440 if (!mono_debug_lookup_method (method)) {
9441 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9448 if (method->is_generic || method->klass->generic_container)
9449 /* Compile the ref shared version instead */
9450 method = mini_get_shared_method (method);
9452 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9453 add_method_with_index (acfg, method, i, FALSE);
9454 acfg->method_index ++;
9457 /* gsharedvt methods */
9458 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9461 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9463 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9466 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9467 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9469 if (method->is_generic || method->klass->generic_container) {
9470 MonoMethod *gshared;
9472 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9473 add_extra_method (acfg, gshared);
9477 add_generic_instances (acfg);
9479 if (mono_aot_mode_is_full (&acfg->aot_opts))
9480 add_wrappers (acfg);
9485 compile_methods (MonoAotCompile *acfg)
9489 if (acfg->aot_opts.nthreads > 0) {
9494 gpointer *user_data;
9495 MonoMethod **methods;
9497 methods_len = acfg->methods->len;
9499 len = acfg->methods->len / acfg->aot_opts.nthreads;
9502 * Partition the list of methods into fragments, and hand it to threads to
9505 threads = g_ptr_array_new ();
9506 /* Make a copy since acfg->methods is modified by compile_method () */
9507 methods = g_new0 (MonoMethod*, methods_len);
9508 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9509 for (i = 0; i < methods_len; ++i)
9510 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9512 while (i < methods_len) {
9513 frag = g_ptr_array_new ();
9514 for (j = 0; j < len; ++j) {
9515 if (i < methods_len) {
9516 g_ptr_array_add (frag, methods [i]);
9521 user_data = g_new0 (gpointer, 3);
9522 user_data [0] = mono_domain_get ();
9523 user_data [1] = acfg;
9524 user_data [2] = frag;
9526 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9527 g_ptr_array_add (threads, handle);
9531 for (i = 0; i < threads->len; ++i) {
9532 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9538 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9539 for (i = methods_len; i < acfg->methods->len; ++i) {
9540 /* This can new methods to acfg->methods */
9541 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9546 compile_asm (MonoAotCompile *acfg)
9548 char *command, *objfile;
9549 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9550 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9551 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9553 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9554 #define AS_OPTIONS "--64"
9555 #elif defined(TARGET_POWERPC64)
9556 #define AS_OPTIONS "-a64 -mppc64"
9557 #elif defined(sparc) && SIZEOF_VOID_P == 8
9558 #define AS_OPTIONS "-xarch=v9"
9559 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9560 #define AS_OPTIONS "-arch i386"
9562 #define AS_OPTIONS ""
9565 #ifdef __native_client_codegen__
9566 #if defined(TARGET_AMD64)
9567 #define AS_NAME "nacl64-as"
9569 #define AS_NAME "nacl-as"
9571 #elif defined(TARGET_OSX)
9572 #define AS_NAME "clang"
9574 #define AS_NAME "as"
9578 #define LD_NAME "ld"
9579 #define LD_OPTIONS "-shared -G"
9580 #elif defined(__ppc__) && defined(TARGET_MACH)
9581 #define LD_NAME "gcc"
9582 #define LD_OPTIONS "-dynamiclib"
9583 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9584 #define LD_NAME "clang"
9585 #define LD_OPTIONS "--shared"
9586 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9587 #define LD_NAME "gcc"
9588 #define LD_OPTIONS "-shared"
9589 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9590 #define LD_NAME "clang"
9591 #define LD_OPTIONS "-m32 -dynamiclib"
9592 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9593 #define LD_NAME "gcc"
9594 #define LD_OPTIONS "--shared"
9595 #elif defined(TARGET_POWERPC64)
9596 #define LD_OPTIONS "-m elf64ppc"
9600 #define LD_OPTIONS ""
9603 if (acfg->aot_opts.asm_only) {
9604 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9605 if (acfg->aot_opts.static_link)
9606 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9608 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9612 if (acfg->aot_opts.static_link) {
9613 if (acfg->aot_opts.outfile)
9614 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9616 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9618 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9622 g_string_append (acfg->as_args, "-c -x assembler");
9625 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9626 acfg->as_args ? acfg->as_args->str : "",
9627 wrap_path (objfile), wrap_path (acfg->tmpfname));
9628 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9629 if (execute_system (command) != 0) {
9635 if (acfg->llvm && !acfg->llvm_owriter) {
9636 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9637 acfg->as_args ? acfg->as_args->str : "",
9638 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9639 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9640 if (execute_system (command) != 0) {
9649 if (acfg->aot_opts.static_link) {
9650 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9651 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9656 if (acfg->aot_opts.outfile)
9657 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9659 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9661 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9664 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9666 llvm_ofile = g_strdup ("");
9669 /* replace the ; flags separators with spaces */
9670 g_strdelimit (ld_flags, ";", ' ');
9672 if (acfg->aot_opts.llvm_only)
9673 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9676 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
9677 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9678 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9681 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9682 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9683 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9685 aot_printf (acfg, "Executing the native linker: %s\n", command);
9686 if (execute_system (command) != 0) {
9687 g_free (tmp_outfile_name);
9688 g_free (outfile_name);
9697 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9698 printf ("Stripping the binary: %s\n", com);
9699 execute_system (com);
9702 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9704 * gas generates 'mapping symbols' each time code and data is mixed, which
9705 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9707 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9708 aot_printf (acfg, "Stripping the binary: %s\n", command);
9709 if (execute_system (command) != 0) {
9710 g_free (tmp_outfile_name);
9711 g_free (outfile_name);
9718 rename (tmp_outfile_name, outfile_name);
9720 #if defined(TARGET_MACH)
9721 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9722 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9723 if (execute_system (command) != 0) {
9728 if (!acfg->aot_opts.save_temps)
9731 g_free (tmp_outfile_name);
9732 g_free (outfile_name);
9735 if (acfg->aot_opts.save_temps)
9736 aot_printf (acfg, "Retained input file.\n");
9738 unlink (acfg->tmpfname);
9743 static void init_got_info (GotInfo *info)
9747 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9748 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9749 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9750 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9751 info->got_patches = g_ptr_array_new ();
9754 static MonoAotCompile*
9755 acfg_create (MonoAssembly *ass, guint32 opts)
9757 MonoImage *image = ass->image;
9758 MonoAotCompile *acfg;
9760 acfg = g_new0 (MonoAotCompile, 1);
9761 acfg->methods = g_ptr_array_new ();
9762 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9763 acfg->method_depth = g_hash_table_new (NULL, NULL);
9764 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9765 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9766 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9767 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9768 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9769 acfg->image_hash = g_hash_table_new (NULL, NULL);
9770 acfg->image_table = g_ptr_array_new ();
9771 acfg->globals = g_ptr_array_new ();
9772 acfg->image = image;
9774 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9775 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9776 acfg->mempool = mono_mempool_new ();
9777 acfg->extra_methods = g_ptr_array_new ();
9778 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9779 acfg->unwind_ops = g_ptr_array_new ();
9780 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9781 acfg->method_order = g_ptr_array_new ();
9782 acfg->export_names = g_hash_table_new (NULL, NULL);
9783 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9784 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9785 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9786 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9787 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9788 mono_os_mutex_init_recursive (&acfg->mutex);
9790 init_got_info (&acfg->got_info);
9791 init_got_info (&acfg->llvm_got_info);
9797 got_info_free (GotInfo *info)
9801 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9802 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9803 g_free (info->patch_to_got_offset_by_type);
9804 g_hash_table_destroy (info->patch_to_got_offset);
9805 g_ptr_array_free (info->got_patches, TRUE);
9809 acfg_free (MonoAotCompile *acfg)
9813 mono_img_writer_destroy (acfg->w);
9814 for (i = 0; i < acfg->nmethods; ++i)
9816 g_free (acfg->cfgs [i]);
9817 g_free (acfg->cfgs);
9818 g_free (acfg->static_linking_symbol);
9819 g_free (acfg->got_symbol);
9820 g_free (acfg->plt_symbol);
9821 g_ptr_array_free (acfg->methods, TRUE);
9822 g_ptr_array_free (acfg->image_table, TRUE);
9823 g_ptr_array_free (acfg->globals, TRUE);
9824 g_ptr_array_free (acfg->unwind_ops, TRUE);
9825 g_hash_table_destroy (acfg->method_indexes);
9826 g_hash_table_destroy (acfg->method_depth);
9827 g_hash_table_destroy (acfg->plt_offset_to_entry);
9828 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9829 if (acfg->patch_to_plt_entry [i])
9830 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9832 g_free (acfg->patch_to_plt_entry);
9833 g_hash_table_destroy (acfg->method_to_cfg);
9834 g_hash_table_destroy (acfg->token_info_hash);
9835 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9836 g_hash_table_destroy (acfg->image_hash);
9837 g_hash_table_destroy (acfg->unwind_info_offsets);
9838 g_hash_table_destroy (acfg->method_label_hash);
9839 g_hash_table_destroy (acfg->export_names);
9840 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9841 g_hash_table_destroy (acfg->klass_blob_hash);
9842 g_hash_table_destroy (acfg->method_blob_hash);
9843 got_info_free (&acfg->got_info);
9844 got_info_free (&acfg->llvm_got_info);
9845 mono_mempool_destroy (acfg->mempool);
9849 #define WRAPPER(e,n) n,
9850 static const char* const
9851 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9852 #include "mono/metadata/wrapper-types.h"
9856 static G_GNUC_UNUSED const char*
9857 get_wrapper_type_name (int type)
9859 return wrapper_type_names [type];
9865 static void aot_dump (MonoAotCompile *acfg)
9871 mono_json_writer_init (&writer);
9873 mono_json_writer_object_begin(&writer);
9876 mono_json_writer_indent (&writer);
9877 mono_json_writer_object_key(&writer, "methods");
9878 mono_json_writer_array_begin (&writer);
9881 for (i = 0; i < acfg->nmethods; ++i) {
9886 cfg = acfg->cfgs [i];
9890 method = cfg->orig_method;
9892 mono_json_writer_indent (&writer);
9893 mono_json_writer_object_begin(&writer);
9895 mono_json_writer_indent (&writer);
9896 mono_json_writer_object_key(&writer, "name");
9897 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9899 mono_json_writer_indent (&writer);
9900 mono_json_writer_object_key(&writer, "signature");
9901 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
9903 mono_json_writer_indent (&writer);
9904 mono_json_writer_object_key(&writer, "code_size");
9905 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9907 klass = method->klass;
9909 mono_json_writer_indent (&writer);
9910 mono_json_writer_object_key(&writer, "class");
9911 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9913 mono_json_writer_indent (&writer);
9914 mono_json_writer_object_key(&writer, "namespace");
9915 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9917 mono_json_writer_indent (&writer);
9918 mono_json_writer_object_key(&writer, "wrapper_type");
9919 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9921 mono_json_writer_indent_pop (&writer);
9922 mono_json_writer_indent (&writer);
9923 mono_json_writer_object_end (&writer);
9924 mono_json_writer_printf (&writer, ",\n");
9927 mono_json_writer_indent_pop (&writer);
9928 mono_json_writer_indent (&writer);
9929 mono_json_writer_array_end (&writer);
9930 mono_json_writer_printf (&writer, ",\n");
9934 mono_json_writer_indent_push (&writer);
9935 mono_json_writer_indent (&writer);
9936 mono_json_writer_object_key(&writer, "plt");
9937 mono_json_writer_array_begin (&writer);
9939 for (i = 0; i < acfg->plt_offset; ++i) {
9940 MonoPltEntry *plt_entry = NULL;
9945 * The first plt entry is unused.
9949 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9952 mono_json_writer_indent (&writer);
9953 mono_json_writer_printf (&writer, "{ ");
9954 mono_json_writer_object_key(&writer, "symbol");
9955 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9958 mono_json_writer_indent_pop (&writer);
9959 mono_json_writer_indent (&writer);
9960 mono_json_writer_array_end (&writer);
9961 mono_json_writer_printf (&writer, ",\n");
9966 mono_json_writer_indent_push (&writer);
9967 mono_json_writer_indent (&writer);
9968 mono_json_writer_object_key(&writer, "got");
9969 mono_json_writer_array_begin (&writer);
9971 mono_json_writer_indent_push (&writer);
9972 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9973 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9975 mono_json_writer_indent (&writer);
9976 mono_json_writer_printf (&writer, "{ ");
9977 mono_json_writer_object_key(&writer, "patch_name");
9978 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9981 mono_json_writer_indent_pop (&writer);
9982 mono_json_writer_indent (&writer);
9983 mono_json_writer_array_end (&writer);
9984 mono_json_writer_printf (&writer, ",\n");
9987 mono_json_writer_indent_pop (&writer);
9988 mono_json_writer_indent (&writer);
9989 mono_json_writer_object_end (&writer);
9991 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9992 dumpfile = fopen (dumpname, "w+");
9995 fprintf (dumpfile, "%s", writer.text->str);
9998 mono_json_writer_destroy (&writer);
10001 static const char *preinited_jit_icalls[] = {
10002 "mono_aot_init_llvm_method",
10003 "mono_aot_init_gshared_method_this",
10004 "mono_aot_init_gshared_method_mrgctx",
10005 "mono_aot_init_gshared_method_vtable",
10006 "mono_llvm_throw_corlib_exception",
10007 "mono_init_vtable_slot",
10008 "mono_helper_ldstr_mscorlib"
10012 add_preinit_got_slots (MonoAotCompile *acfg)
10018 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10019 * during method initialization etc.
10022 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10023 ji->type = MONO_PATCH_INFO_IMAGE;
10024 ji->data.image = acfg->image;
10025 get_got_offset (acfg, FALSE, ji);
10026 get_got_offset (acfg, TRUE, ji);
10028 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10029 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10030 get_got_offset (acfg, FALSE, ji);
10031 get_got_offset (acfg, TRUE, ji);
10033 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10034 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10035 get_got_offset (acfg, FALSE, ji);
10036 get_got_offset (acfg, TRUE, ji);
10038 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10039 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10040 get_got_offset (acfg, FALSE, ji);
10041 get_got_offset (acfg, TRUE, ji);
10043 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10044 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
10045 get_got_offset (acfg, FALSE, ji);
10046 get_got_offset (acfg, TRUE, ji);
10048 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10049 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10050 get_got_offset (acfg, FALSE, ji);
10051 get_got_offset (acfg, TRUE, ji);
10053 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10054 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10055 get_got_offset (acfg, FALSE, ji);
10056 get_got_offset (acfg, TRUE, ji);
10058 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10059 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10060 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10061 ji->data.name = preinited_jit_icalls [i];
10062 get_got_offset (acfg, FALSE, ji);
10063 get_got_offset (acfg, TRUE, ji);
10066 acfg->nshared_got_entries = acfg->got_offset;
10070 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10072 MonoImage *image = ass->image;
10075 MonoAotCompile *acfg;
10076 char *outfile_name, *tmp_outfile_name, *p;
10077 char llvm_stats_msg [256];
10081 acfg = acfg_create (ass, opts);
10083 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10084 acfg->aot_opts.write_symbols = TRUE;
10085 acfg->aot_opts.ntrampolines = 4096;
10086 acfg->aot_opts.nrgctx_trampolines = 4096;
10087 acfg->aot_opts.nimt_trampolines = 512;
10088 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10089 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10090 acfg->aot_opts.llvm_path = g_strdup ("");
10091 acfg->aot_opts.temp_path = g_strdup ("");
10093 acfg->aot_opts.use_trampolines_page = TRUE;
10096 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10098 if (acfg->aot_opts.logfile) {
10099 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10102 if (acfg->aot_opts.data_outfile) {
10103 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10104 if (!acfg->data_outfile) {
10105 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10108 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10111 //acfg->aot_opts.print_skipped_methods = TRUE;
10113 #if !defined(ENABLE_GSHAREDVT)
10114 if (opts & MONO_OPT_GSHAREDVT) {
10115 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10120 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10121 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10122 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10127 if (acfg->aot_opts.llvm_only) {
10128 #ifndef ENABLE_GSHAREDVT
10129 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with --enable-gsharedvt.\n");
10134 #if defined(ENABLE_GSHAREDVT) && defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10135 acfg->opts |= MONO_OPT_GSHAREDVT;
10136 opts |= MONO_OPT_GSHAREDVT;
10139 if (opts & MONO_OPT_GSHAREDVT)
10140 mono_set_generic_sharing_vt_supported (TRUE);
10142 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10144 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10145 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10146 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10151 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10152 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10156 if (acfg->aot_opts.static_link)
10157 acfg->aot_opts.asm_writer = TRUE;
10159 if (acfg->aot_opts.soft_debug) {
10160 MonoDebugOptions *opt = mini_get_debug_options ();
10162 opt->mdb_optimizations = TRUE;
10163 opt->gen_sdb_seq_points = TRUE;
10165 if (!mono_debug_enabled ()) {
10166 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10169 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10172 if (mono_use_llvm || acfg->aot_opts.llvm) {
10174 acfg->aot_opts.asm_writer = TRUE;
10175 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10177 if (acfg->aot_opts.soft_debug) {
10178 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10184 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10185 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10190 * Emit all LLVM code into a separate assembly/object file and link with it
10193 if (!acfg->aot_opts.asm_only) {
10194 acfg->llvm_owriter = TRUE;
10195 } else if (acfg->aot_opts.llvm_outfile) {
10196 int len = strlen (acfg->aot_opts.llvm_outfile);
10198 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10199 acfg->llvm_owriter = TRUE;
10203 if (mono_aot_mode_is_full (&acfg->aot_opts))
10204 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10206 if (mono_threads_is_coop_enabled ())
10207 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10209 if (acfg->aot_opts.instances_logfile_path) {
10210 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10211 if (!acfg->instances_logfile) {
10212 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10217 load_profile_files (acfg);
10219 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10220 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10221 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10223 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10224 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10225 if (acfg->opts & MONO_OPT_GSHAREDVT)
10226 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10229 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10233 if (acfg->llvm && acfg->thumb_mixed)
10234 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10235 if (acfg->aot_opts.llvm_only)
10236 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10238 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10239 /* Get rid of characters which cannot occur in symbols */
10240 for (p = acfg->assembly_name_sym; *p; ++p) {
10241 if (!(isalnum (*p) || *p == '_'))
10245 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10246 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10247 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10249 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10250 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10253 acfg->method_index = 1;
10255 if (mono_aot_mode_is_full (&acfg->aot_opts))
10256 mono_set_partial_sharing_supported (TRUE);
10258 res = collect_methods (acfg);
10262 acfg->cfgs_size = acfg->methods->len + 32;
10263 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10265 /* PLT offset 0 is reserved for the PLT trampoline */
10266 acfg->plt_offset = 1;
10267 add_preinit_got_slots (acfg);
10272 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10278 compile_methods (acfg);
10282 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10288 if (acfg->aot_opts.asm_only) {
10289 if (acfg->aot_opts.outfile) {
10290 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10291 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10293 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10294 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10296 g_assert (acfg->aot_opts.llvm_outfile);
10297 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10298 if (acfg->llvm_owriter)
10299 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10301 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10303 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10304 g_strdup_printf ("%s", "temp") :
10305 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10307 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10308 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10309 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10314 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10315 if (acfg->aot_opts.outfile)
10316 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10318 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10319 acfg->fp = fopen (acfg->tmpfname, "w+");
10321 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10322 acfg->fp = fdopen (i, "w+");
10324 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10325 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10329 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10331 tmp_outfile_name = NULL;
10332 outfile_name = NULL;
10334 /* Compute symbols for methods */
10335 for (i = 0; i < acfg->nmethods; ++i) {
10336 if (acfg->cfgs [i]) {
10337 MonoCompile *cfg = acfg->cfgs [i];
10338 int method_index = get_method_index (acfg, cfg->orig_method);
10340 if (COMPILE_LLVM (cfg))
10341 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10342 else if (acfg->global_symbols || acfg->llvm)
10343 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10345 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10346 cfg->asm_debug_symbol = cfg->asm_symbol;
10350 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
10352 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10353 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
10354 * .byte directives.
10356 //acfg->gas_line_numbers = TRUE;
10359 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10360 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10361 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10364 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
10368 mono_img_writer_emit_start (acfg->w);
10371 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10377 emit_extra_methods (acfg);
10379 emit_trampolines (acfg);
10381 emit_class_name_table (acfg);
10383 emit_got_info (acfg, FALSE);
10385 emit_got_info (acfg, TRUE);
10387 emit_exception_info (acfg);
10389 emit_unwind_info (acfg);
10391 emit_class_info (acfg);
10395 emit_image_table (acfg);
10401 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10404 const char *gc_name = mono_gc_get_gc_name ();
10405 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10410 emit_objc_selectors (acfg);
10412 emit_globals (acfg);
10414 emit_file_info (acfg);
10417 emit_dwarf_info (acfg);
10418 mono_dwarf_writer_close (acfg->dwarf);
10421 emit_mem_end (acfg);
10423 if (acfg->need_pt_gnu_stack) {
10424 /* This is required so the .so doesn't have an executable stack */
10425 /* The bin writer already emits this */
10426 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10429 if (acfg->aot_opts.data_outfile)
10430 fclose (acfg->data_outfile);
10436 res = emit_llvm_file (acfg);
10444 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10447 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10449 strcpy (llvm_stats_msg, "");
10451 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;
10453 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",
10454 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10455 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10456 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10457 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10458 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10459 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,
10460 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10461 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10462 (int)(acfg->got_offset * sizeof (gpointer)));
10463 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10464 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10466 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10467 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10468 if (acfg->stats.genericcount)
10469 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10470 if (acfg->stats.abscount)
10471 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10472 if (acfg->stats.lmfcount)
10473 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10474 if (acfg->stats.ocount)
10475 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10479 res = mono_img_writer_emit_writeout (acfg->w);
10484 res = compile_asm (acfg);
10491 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10493 if (acfg->aot_opts.stats) {
10496 aot_printf (acfg, "GOT slot distribution:\n");
10497 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10498 if (acfg->stats.got_slot_types [i])
10499 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]);
10500 aot_printf (acfg, "\nMethod stats:\n");
10501 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10502 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10503 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10504 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10507 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);
10509 if (acfg->aot_opts.dump_json)
10522 mono_aot_readonly_field_override (MonoClassField *field)
10528 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10534 mono_aot_is_shared_got_offset (int offset)