2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
14 #include <sys/types.h>
34 #include <mono/metadata/abi-details.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/tokentype.h>
39 #include <mono/metadata/appdomain.h>
40 #include <mono/metadata/debug-helpers.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/metadata-internals.h>
43 #include <mono/metadata/marshal.h>
44 #include <mono/metadata/gc-internals.h>
45 #include <mono/metadata/mempool-internals.h>
46 #include <mono/metadata/mono-endian.h>
47 #include <mono/metadata/threads-types.h>
48 #include <mono/utils/mono-logger-internals.h>
49 #include <mono/utils/mono-compiler.h>
50 #include <mono/utils/mono-time.h>
51 #include <mono/utils/mono-mmap.h>
52 #include <mono/utils/json.h>
54 #include "aot-compiler.h"
55 #include "seq-points.h"
56 #include "image-writer.h"
57 #include "dwarfwriter.h"
59 #include "mini-llvm.h"
61 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
63 #if defined(__linux__) || defined(__native_client_codegen__)
64 #define RODATA_SECT ".rodata"
65 #elif defined(TARGET_MACH)
66 #define RODATA_SECT ".section __TEXT, __const"
68 #define RODATA_SECT ".text"
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
75 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
76 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
77 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
79 /* predefined values for static readonly fields without needed to run the .cctor */
80 typedef struct _ReadOnlyValue ReadOnlyValue;
81 struct _ReadOnlyValue {
84 int type; /* to be used later for typechecking to prevent user errors */
93 static ReadOnlyValue *readonly_values;
95 typedef struct MonoAotOptions {
100 gboolean write_symbols;
101 gboolean metadata_only;
102 gboolean bind_to_runtime_version;
105 gboolean static_link;
109 gboolean dwarf_debug;
111 gboolean log_generics;
112 gboolean log_instances;
113 gboolean gen_seq_points_file;
114 gboolean direct_pinvoke;
115 gboolean direct_icalls;
116 gboolean no_direct_calls;
117 gboolean use_trampolines_page;
118 gboolean no_instances;
124 int nrgctx_trampolines;
125 int nimt_trampolines;
126 int ngsharedvt_arg_trampolines;
127 int nrgctx_fetch_trampolines;
128 gboolean print_skipped_methods;
135 char *instances_logfile_path;
142 METHOD_CAT_GSHAREDVT,
148 typedef struct MonoAotStats {
149 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
150 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
151 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
152 int got_slots, offsets_size;
153 int method_categories [METHOD_CAT_NUM];
154 int got_slot_types [MONO_PATCH_INFO_NONE];
155 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
156 int jit_time, gen_time, link_time;
159 typedef struct GotInfo {
160 GHashTable *patch_to_got_offset;
161 GHashTable **patch_to_got_offset_by_type;
162 GPtrArray *got_patches;
165 typedef struct MonoAotCompile {
168 GHashTable *method_indexes;
169 GHashTable *method_depth;
172 GHashTable **patch_to_plt_entry;
173 GHashTable *plt_offset_to_entry;
174 //GHashTable *patch_to_got_offset;
175 //GHashTable **patch_to_got_offset_by_type;
176 //GPtrArray *got_patches;
177 GotInfo got_info, llvm_got_info;
178 GHashTable *image_hash;
179 GHashTable *method_to_cfg;
180 GHashTable *token_info_hash;
181 GHashTable *method_to_pinvoke_import;
182 GPtrArray *extra_methods;
183 GPtrArray *image_table;
185 GPtrArray *method_order;
186 GHashTable *export_names;
187 /* Maps MonoClass* -> blob offset */
188 GHashTable *klass_blob_hash;
189 /* Maps MonoMethod* -> blob offset */
190 GHashTable *method_blob_hash;
191 GHashTable *gsharedvt_in_signatures;
192 GHashTable *gsharedvt_out_signatures;
193 guint32 *plt_got_info_offsets;
194 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
195 /* Number of GOT entries reserved for trampolines */
196 guint32 num_trampoline_got_entries;
197 guint32 tramp_page_size;
199 guint32 table_offsets [MONO_AOT_TABLE_NUM];
200 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
201 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
202 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
203 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
205 MonoAotOptions aot_opts;
209 MonoMemPool *mempool;
212 char *static_linking_symbol;
214 gboolean gas_line_numbers;
215 /* Whenever to emit an object file directly from llc */
216 gboolean llvm_owriter;
218 MonoDwarfWriter *dwarf;
225 GHashTable *unwind_info_offsets;
226 GPtrArray *unwind_ops;
227 guint32 unwind_info_offset;
230 char *llvm_got_symbol;
232 char *llvm_eh_frame_symbol;
233 GHashTable *method_label_hash;
234 const char *temp_prefix;
235 const char *user_symbol_prefix;
236 const char *llvm_label_prefix;
237 const char *inst_directive;
239 guint32 label_generator;
241 gboolean has_jitted_code;
242 MonoAotFileFlags flags;
243 MonoDynamicStream blob;
244 gboolean blob_closed;
245 MonoClass **typespec_classes;
248 char *assembly_name_sym;
249 GHashTable *plt_entry_debug_sym_cache;
250 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
251 GHashTable *ginst_hash;
252 GHashTable *dwarf_ln_filenames;
253 gboolean global_symbols;
254 int objc_selector_index, objc_selector_index_2;
255 GPtrArray *objc_selectors;
256 GHashTable *objc_selector_to_index;
258 FILE *instances_logfile;
266 char *symbol, *llvm_symbol, *debug_sym;
268 gboolean jit_used, llvm_used;
271 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
272 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
274 /* This points to the current acfg in LLVM mode */
275 static MonoAotCompile *llvm_acfg;
277 #ifdef HAVE_ARRAY_ELEM_INIT
278 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
279 #define MSGSTRFIELD1(line) str##line
280 static const struct msgstr_t {
281 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
282 #include "patch-info.h"
285 #define PATCH_INFO(a,b) b,
286 #include "patch-info.h"
289 static const gint16 opidx [] = {
290 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
291 #include "patch-info.h"
295 static G_GNUC_UNUSED const char*
296 get_patch_name (int info)
298 return (const char*)&opstr + opidx [info];
302 #define PATCH_INFO(a,b) b,
303 static const char* const
304 patch_types [MONO_PATCH_INFO_NUM + 1] = {
305 #include "patch-info.h"
309 static G_GNUC_UNUSED const char*
310 get_patch_name (int info)
312 return patch_types [info];
318 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
321 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
324 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
330 output = acfg->logfile;
334 va_start (args, format);
335 vfprintf (output, format, args);
340 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
346 output = acfg->logfile;
350 va_start (args, format);
351 vfprintf (output, format, args);
356 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
361 if (mono_error_ok (error))
365 output = acfg->logfile;
369 va_start (args, format);
370 vfprintf (output, format, args);
372 mono_error_cleanup (error);
374 g_error ("FullAOT cannot continue if there are loader errors");
377 /* Wrappers around the image writer functions */
380 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
382 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
386 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
388 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
392 emit_label (MonoAotCompile *acfg, const char *name)
394 mono_img_writer_emit_label (acfg->w, name);
398 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
400 mono_img_writer_emit_bytes (acfg->w, buf, size);
404 emit_string (MonoAotCompile *acfg, const char *value)
406 mono_img_writer_emit_string (acfg->w, value);
410 emit_line (MonoAotCompile *acfg)
412 mono_img_writer_emit_line (acfg->w);
416 emit_alignment (MonoAotCompile *acfg, int size)
418 mono_img_writer_emit_alignment (acfg->w, size);
422 emit_alignment_code (MonoAotCompile *acfg, int size)
424 if (acfg->align_pad_value)
425 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
427 mono_img_writer_emit_alignment (acfg->w, size);
431 emit_padding (MonoAotCompile *acfg, int size)
436 if (acfg->align_pad_value) {
437 for (i = 0; i < 16; ++i)
438 buf [i] = acfg->align_pad_value;
440 memset (buf, 0, sizeof (buf));
443 for (i = 0; i < size; i += 16) {
445 emit_bytes (acfg, buf, size - i);
447 emit_bytes (acfg, buf, 16);
452 emit_pointer (MonoAotCompile *acfg, const char *target)
454 mono_img_writer_emit_pointer (acfg->w, target);
458 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
460 if (prefix [0] != '\0') {
461 char *s = g_strdup_printf ("%s%s", prefix, target);
462 mono_img_writer_emit_pointer (acfg->w, s);
465 mono_img_writer_emit_pointer (acfg->w, target);
470 emit_int16 (MonoAotCompile *acfg, int value)
472 mono_img_writer_emit_int16 (acfg->w, value);
476 emit_int32 (MonoAotCompile *acfg, int value)
478 mono_img_writer_emit_int32 (acfg->w, value);
482 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
484 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
488 emit_zero_bytes (MonoAotCompile *acfg, int num)
490 mono_img_writer_emit_zero_bytes (acfg->w, num);
494 emit_byte (MonoAotCompile *acfg, guint8 val)
496 mono_img_writer_emit_byte (acfg->w, val);
499 #ifdef __native_client_codegen__
501 emit_nacl_call_alignment (MonoAotCompile *acfg)
503 mono_img_writer_emit_nacl_call_alignment (acfg->w);
507 static G_GNUC_UNUSED void
508 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
510 mono_img_writer_emit_global (acfg->w, name, func);
514 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
516 if (acfg->aot_opts.no_dlsym) {
517 g_ptr_array_add (acfg->globals, g_strdup (name));
518 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
520 mono_img_writer_emit_global (acfg->w, name, func);
525 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
527 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
530 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
532 emit_info_symbol (MonoAotCompile *acfg, const char *name)
537 emit_label (acfg, name);
538 /* LLVM generated code references this */
539 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
540 emit_label (acfg, symbol);
541 emit_global_inner (acfg, symbol, FALSE);
543 emit_label (acfg, name);
548 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
551 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
555 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
557 /* On apple, all symbols need to be aligned to avoid warnings from ld */
558 emit_alignment (acfg, 4);
560 mono_img_writer_emit_label (acfg->w, name);
561 mono_img_writer_emit_string (acfg->w, value);
564 static G_GNUC_UNUSED void
565 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
568 guint8 b = value & 0x7f;
570 if (value != 0) /* more bytes to come */
576 static G_GNUC_UNUSED void
577 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
580 gboolean negative = (value < 0);
587 /* the following is unnecessary if the
588 * implementation of >>= uses an arithmetic rather
589 * than logical shift for a signed left operand
593 value |= - ((gint64)1 <<(size - 7));
594 /* sign bit of byte is second high order bit (0x40) */
595 if ((value == 0 && !(byte & 0x40)) ||
596 (value == -1 && (byte & 0x40)))
600 emit_byte (acfg, byte);
604 static G_GNUC_UNUSED void
605 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
610 guint8 b = value & 0x7f;
612 if (value != 0) /* more bytes to come */
620 static G_GNUC_UNUSED void
621 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
624 gboolean negative = (value < 0);
632 /* the following is unnecessary if the
633 * implementation of >>= uses an arithmetic rather
634 * than logical shift for a signed left operand
638 value |= - (1 <<(size - 7));
639 /* sign bit of byte is second high order bit (0x40) */
640 if ((value == 0 && !(byte & 0x40)) ||
641 (value == -1 && (byte & 0x40)))
652 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
655 buf [0] = (val >> 0) & 0xff;
656 buf [1] = (val >> 8) & 0xff;
657 buf [2] = (val >> 16) & 0xff;
658 buf [3] = (val >> 24) & 0xff;
664 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
666 buf [0] = (val >> 0) & 0xff;
667 buf [1] = (val >> 8) & 0xff;
673 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
675 int len = strlen (s);
677 memcpy (buf, s, len + 1);
678 *endbuf = buf + len + 1;
682 emit_unset_mode (MonoAotCompile *acfg)
684 mono_img_writer_emit_unset_mode (acfg->w);
687 static G_GNUC_UNUSED void
688 emit_set_thumb_mode (MonoAotCompile *acfg)
690 emit_unset_mode (acfg);
691 fprintf (acfg->fp, ".code 16\n");
694 static G_GNUC_UNUSED void
695 emit_set_arm_mode (MonoAotCompile *acfg)
697 emit_unset_mode (acfg);
698 fprintf (acfg->fp, ".code 32\n");
702 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
707 g_assert (size % 4 == 0);
708 emit_unset_mode (acfg);
709 for (i = 0; i < size; i += 4)
710 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
712 emit_bytes (acfg, buf, size);
716 /* ARCHITECTURE SPECIFIC CODE */
718 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
719 #define EMIT_DWARF_INFO 1
722 #if defined(TARGET_ARM)
723 #define AOT_FUNC_ALIGNMENT 4
725 #define AOT_FUNC_ALIGNMENT 16
727 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
728 #undef AOT_FUNC_ALIGNMENT
729 #define AOT_FUNC_ALIGNMENT 32
732 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
733 #define PPC_LD_OP "ld"
734 #define PPC_LDX_OP "ldx"
736 #define PPC_LD_OP "lwz"
737 #define PPC_LDX_OP "lwzx"
741 #define AOT_TARGET_STR "AMD64"
746 #define AOT_TARGET_STR "ARM (MACH)"
748 #define AOT_TARGET_STR "ARM (!MACH)"
754 #define AOT_TARGET_STR "ARM64 (MACH)"
756 #define AOT_TARGET_STR "ARM64 (!MACH)"
760 #ifdef TARGET_POWERPC64
761 #ifdef __mono_ilp32__
762 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
764 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
767 #ifdef TARGET_POWERPC
768 #ifdef __mono_ilp32__
769 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
771 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
778 #define AOT_TARGET_STR "X86 (WIN32)"
779 #elif defined(__native_client_codegen__)
780 #define AOT_TARGET_STR "X86 (native client codegen)"
782 #define AOT_TARGET_STR "X86 (!native client codegen)"
786 #ifndef AOT_TARGET_STR
787 #define AOT_TARGET_STR ""
791 arch_init (MonoAotCompile *acfg)
793 acfg->llc_args = g_string_new ("");
794 acfg->as_args = g_string_new ("");
797 * The prefix LLVM likes to put in front of symbol names on darwin.
798 * The mach-os specs require this for globals, but LLVM puts them in front of all
799 * symbols. We need to handle this, since we need to refer to LLVM generated
802 acfg->llvm_label_prefix = "";
803 acfg->user_symbol_prefix = "";
805 #if defined(TARGET_X86)
806 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
809 #if defined(TARGET_AMD64)
810 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
812 acfg->align_pad_value = 0x90;
816 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
817 g_string_append (acfg->llc_args, "-mattr=+v6");
820 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
821 g_string_append (acfg->as_args, " -mfpu=vfp3");
823 g_string_append (acfg->llc_args, " -soft-float");
826 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
827 acfg->thumb_mixed = TRUE;
829 if (acfg->aot_opts.mtriple)
830 mono_arch_set_target (acfg->aot_opts.mtriple);
834 acfg->inst_directive = ".inst";
835 if (acfg->aot_opts.mtriple)
836 mono_arch_set_target (acfg->aot_opts.mtriple);
840 acfg->user_symbol_prefix = "_";
841 acfg->llvm_label_prefix = "_";
842 acfg->inst_directive = ".word";
843 acfg->need_no_dead_strip = TRUE;
844 acfg->aot_opts.gnu_asm = TRUE;
847 #if defined(__linux__) && !defined(TARGET_ARM)
848 acfg->need_pt_gnu_stack = TRUE;
852 acfg->global_symbols = TRUE;
858 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
862 #ifdef MONO_ARCH_AOT_SUPPORTED
864 * arch_emit_direct_call:
866 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
870 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
872 #if defined(TARGET_X86) || defined(TARGET_AMD64)
873 /* Need to make sure this is exactly 5 bytes long */
874 emit_unset_mode (acfg);
875 fprintf (acfg->fp, "call %s\n", target);
877 #elif defined(TARGET_ARM)
878 emit_unset_mode (acfg);
880 fprintf (acfg->fp, "blx %s\n", target);
882 fprintf (acfg->fp, "bl %s\n", target);
884 #elif defined(TARGET_ARM64)
885 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
886 #elif defined(TARGET_POWERPC)
887 emit_unset_mode (acfg);
888 fprintf (acfg->fp, "bl %s\n", target);
891 g_assert_not_reached ();
898 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
900 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
901 * in in the 2. slot of every GOT, and require every method to place the GOT
902 * address in r30, even when it doesn't access the GOT otherwise. This way,
903 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
908 * PPC64 uses function descriptors which greatly complicate all code, since
909 * these are used very inconsistently in the runtime. Some functions like
910 * mono_compile_method () return ftn descriptors, while others like the
911 * trampoline creation functions do not.
912 * We assume that all GOT slots contain function descriptors, and create
913 * descriptors in aot-runtime.c when needed.
914 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
915 * from function descriptors, we could do the same, but it would require
916 * rewriting all the ppc/aot code to handle function descriptors properly.
917 * So instead, we use the same approach as on PPC32.
918 * This is a horrible mess, but fixing it would probably lead to an even bigger
924 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
927 #ifdef MONO_ARCH_AOT_SUPPORTED
929 * arch_emit_got_offset:
931 * The memory pointed to by CODE should hold native code for computing the GOT
932 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
933 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
936 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
938 #if defined(TARGET_POWERPC64)
939 emit_unset_mode (acfg);
941 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
942 * unsupported relocations. So we store the got address into the .Lgot_addr
943 * symbol which is in the text segment, compute its address, and load it.
945 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
946 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
947 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
948 fprintf (acfg->fp, "add 30, 30, 0\n");
949 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
950 acfg->label_generator ++;
952 #elif defined(TARGET_POWERPC)
953 emit_unset_mode (acfg);
954 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
955 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
956 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
957 acfg->label_generator ++;
960 guint32 offset = mono_arch_get_patch_offset (code);
961 emit_bytes (acfg, code, offset);
962 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
964 *code_size = offset + 4;
969 * arch_emit_got_access:
971 * The memory pointed to by CODE should hold native code for loading a GOT
972 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
973 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
976 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
979 /* mov reg, got+offset(%rip) */
981 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
985 /* Decode reg, see amd64_mov_reg_membase () */
986 rex_r = code [0] & AMD64_REX_R;
987 g_assert (code [0] == 0x49 + rex_r);
988 g_assert (code [1] == 0x8b);
989 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
991 emit_unset_mode (acfg);
992 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
995 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
996 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
997 *code_size = mono_arch_get_patch_offset (code) + 4;
999 #elif defined(TARGET_X86)
1000 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1001 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1002 *code_size = mono_arch_get_patch_offset (code) + 4;
1003 #elif defined(TARGET_ARM)
1004 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1005 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1006 *code_size = mono_arch_get_patch_offset (code) + 4;
1007 #elif defined(TARGET_ARM64)
1008 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1009 arm64_emit_got_access (acfg, code, got_slot, code_size);
1010 #elif defined(TARGET_POWERPC)
1015 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1017 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1018 g_assert (code - buf == 8);
1019 emit_bytes (acfg, buf, code - buf);
1020 *code_size = code - buf;
1023 g_assert_not_reached ();
1029 #ifdef MONO_ARCH_AOT_SUPPORTED
1031 * arch_emit_objc_selector_ref:
1033 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1036 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1038 #if defined(TARGET_ARM)
1041 int lindex = acfg->objc_selector_index_2 ++;
1043 /* Emit ldr.imm/b */
1044 emit_bytes (acfg, code, 8);
1046 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1047 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1049 emit_label (acfg, symbol1);
1050 mono_img_writer_emit_unset_mode (acfg->w);
1051 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1054 #elif defined(TARGET_ARM64)
1055 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1057 g_assert_not_reached ();
1063 * arch_emit_plt_entry:
1065 * Emit code for the PLT entry.
1066 * The plt entry should look like this:
1067 * <indirect jump to GOT_SYMBOL + OFFSET>
1068 * <INFO_OFFSET embedded into the instruction stream>
1071 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1073 #if defined(TARGET_X86)
1074 #if defined(__default_codegen__)
1075 /* jmp *<offset>(%ebx) */
1076 emit_byte (acfg, 0xff);
1077 emit_byte (acfg, 0xa3);
1078 emit_int32 (acfg, offset);
1079 /* Used by mono_aot_get_plt_info_offset */
1080 emit_int32 (acfg, info_offset);
1081 #elif defined(__native_client_codegen__)
1082 const guint8 kSizeOfNaClJmp = 11;
1083 guint8 bytes[kSizeOfNaClJmp];
1084 guint8 *pbytes = &bytes[0];
1086 x86_jump_membase32 (pbytes, X86_EBX, offset);
1087 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1088 /* four bytes of data, used by mono_arch_patch_plt_entry */
1089 /* For Native Client, make this work with data embedded in push. */
1090 emit_byte (acfg, 0x68); /* hide data in a push */
1091 emit_int32 (acfg, info_offset);
1092 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1093 #endif /*__native_client_codegen__*/
1094 #elif defined(TARGET_AMD64)
1095 #if defined(__default_codegen__)
1096 emit_unset_mode (acfg);
1097 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1098 /* Used by mono_aot_get_plt_info_offset */
1099 emit_int32 (acfg, info_offset);
1100 acfg->stats.plt_size += 10;
1101 #elif defined(__native_client_codegen__)
1103 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1104 guint8 *code = buf_aligned;
1106 /* mov <OFFSET>(%rip), %r11d */
1107 emit_byte (acfg, '\x45');
1108 emit_byte (acfg, '\x8b');
1109 emit_byte (acfg, '\x1d');
1110 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1112 amd64_jump_reg (code, AMD64_R11);
1113 /* This should be constant for the plt patch */
1114 g_assert ((size_t)(code-buf_aligned) == 10);
1115 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1117 /* Hide data in a push imm32 so it passes validation */
1118 emit_byte (acfg, 0x68); /* push */
1119 emit_int32 (acfg, info_offset);
1120 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1121 #endif /*__native_client_codegen__*/
1122 #elif defined(TARGET_ARM)
1127 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1128 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1129 emit_bytes (acfg, buf, code - buf);
1130 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1131 /* Used by mono_aot_get_plt_info_offset */
1132 emit_int32 (acfg, info_offset);
1133 #elif defined(TARGET_ARM64)
1134 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1135 #elif defined(TARGET_POWERPC)
1136 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1137 emit_unset_mode (acfg);
1138 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1139 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1140 fprintf (acfg->fp, "add 11, 11, 30\n");
1141 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1142 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1143 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1144 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1146 fprintf (acfg->fp, "mtctr 11\n");
1147 fprintf (acfg->fp, "bctr\n");
1148 emit_int32 (acfg, info_offset);
1150 g_assert_not_reached ();
1155 * arch_emit_llvm_plt_entry:
1157 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1158 * This is only needed on arm to handle thumb interop.
1161 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1163 #if defined(TARGET_ARM)
1164 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1165 /* The caller already transitioned to thumb */
1166 /* The code below should be 12 bytes long */
1167 /* clang has trouble encoding these instructions, so emit the binary */
1169 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1170 /* thumb can't encode ld pc, [pc, ip] */
1171 fprintf (acfg->fp, "add ip, pc, ip\n");
1172 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1173 fprintf (acfg->fp, "bx ip\n");
1175 emit_set_thumb_mode (acfg);
1176 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1177 fprintf (acfg->fp, ".2byte 0x44fc\n");
1178 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1179 fprintf (acfg->fp, ".2byte 0x4760\n");
1180 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1181 emit_int32 (acfg, info_offset);
1182 emit_unset_mode (acfg);
1183 emit_set_arm_mode (acfg);
1185 g_assert_not_reached ();
1189 /* Save unwind_info in the module and emit the offset to the information at symbol */
1190 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1192 guint32 uw_offset, encoded_len;
1195 emit_section_change (acfg, RODATA_SECT, 0);
1196 emit_global (acfg, symbol, FALSE);
1197 emit_label (acfg, symbol);
1199 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1200 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1202 emit_int32 (acfg, uw_offset);
1206 * arch_emit_specific_trampoline_pages:
1208 * Emits a page full of trampolines: each trampoline uses its own address to
1209 * lookup both the generic trampoline code and the data argument.
1210 * This page can be remapped in process multiple times so we can get an
1211 * unlimited number of trampolines.
1212 * Specifically this implementation uses the following trick: two memory pages
1213 * are allocated, with the first containing the data and the second containing the trampolines.
1214 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1215 * implementation does all the lifting.
1216 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1217 * on the arm 32 bit system.
1220 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1222 #if defined(TARGET_ARM)
1225 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1227 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1228 GSList *unwind_ops = NULL;
1229 #define COMMON_TRAMP_SIZE 16
1230 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1231 int imm8, rot_amount;
1234 if (!acfg->aot_opts.use_trampolines_page)
1237 acfg->tramp_page_size = pagesize;
1239 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1240 emit_alignment (acfg, pagesize);
1241 emit_global (acfg, symbol, TRUE);
1242 emit_label (acfg, symbol);
1244 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1246 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1247 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1248 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1249 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1251 g_assert (code - buf == COMMON_TRAMP_SIZE);
1254 emit_bytes (acfg, buf, code - buf);
1256 for (i = 0; i < count; ++i) {
1258 ARM_PUSH (code, 0x5fff);
1260 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1261 g_assert (code - buf == 8);
1262 emit_bytes (acfg, buf, code - buf);
1265 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1266 * the instruction pointer address, so the generic trampoline at the start of the page
1267 * subtracts 4096 to get to the data page and loads the values
1268 * We again fit the generic trampiline in 16 bytes.
1270 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1271 emit_global (acfg, symbol, TRUE);
1272 emit_label (acfg, symbol);
1274 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1275 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1276 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1277 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1279 g_assert (code - buf == COMMON_TRAMP_SIZE);
1282 emit_bytes (acfg, buf, code - buf);
1284 for (i = 0; i < count; ++i) {
1286 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1288 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1289 g_assert (code - buf == 8);
1290 emit_bytes (acfg, buf, code - buf);
1294 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1296 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1297 emit_global (acfg, symbol, TRUE);
1298 emit_label (acfg, symbol);
1300 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1301 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1302 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1303 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1304 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1305 g_assert (code - buf == COMMON_TRAMP_SIZE);
1307 emit_bytes (acfg, buf, code - buf);
1309 for (i = 0; i < count; ++i) {
1311 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1313 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1314 g_assert (code - buf == 8);
1315 emit_bytes (acfg, buf, code - buf);
1318 /* now the imt trampolines: each specific trampolines puts in the ip register
1319 * the instruction pointer address, so the generic trampoline at the start of the page
1320 * subtracts 4096 to get to the data page and loads the values
1322 #define IMT_TRAMP_SIZE 72
1323 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1324 emit_global (acfg, symbol, TRUE);
1325 emit_label (acfg, symbol);
1327 /* Need at least two free registers, plus a slot for storing the pc */
1328 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1330 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1331 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1332 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1334 /* The IMT method is in v5, r0 has the imt array address */
1337 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1338 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1339 imt_found_check = code;
1340 ARM_B_COND (code, ARMCOND_EQ, 0);
1342 /* End-of-loop check */
1343 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1344 loop_end_check = code;
1345 ARM_B_COND (code, ARMCOND_EQ, 0);
1348 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1349 loop_branch_back = code;
1351 arm_patch (loop_branch_back, loop_start);
1354 arm_patch (imt_found_check, code);
1355 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1356 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1357 /* Save it to the third stack slot */
1358 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1359 /* Restore the registers and branch */
1360 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1363 arm_patch (loop_end_check, code);
1364 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1365 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1366 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1370 g_assert (code - buf == IMT_TRAMP_SIZE);
1371 emit_bytes (acfg, buf, code - buf);
1373 for (i = 0; i < count; ++i) {
1375 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1377 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1378 g_assert (code - buf == 8);
1379 emit_bytes (acfg, buf, code - buf);
1382 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1383 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1384 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1385 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1387 /* Unwind info for specifc trampolines */
1388 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1389 /* We unwind to the original caller, from the stack, since lr is clobbered */
1390 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1391 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1392 save_unwind_info (acfg, symbol, unwind_ops);
1393 mono_free_unwind_info (unwind_ops);
1395 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1396 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1397 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1398 save_unwind_info (acfg, symbol, unwind_ops);
1399 mono_free_unwind_info (unwind_ops);
1401 /* Unwind info for rgctx trampolines */
1402 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1403 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1404 save_unwind_info (acfg, symbol, unwind_ops);
1406 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1407 save_unwind_info (acfg, symbol, unwind_ops);
1408 mono_free_unwind_info (unwind_ops);
1410 /* Unwind info for gsharedvt trampolines */
1411 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1412 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1413 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1414 save_unwind_info (acfg, symbol, unwind_ops);
1415 mono_free_unwind_info (unwind_ops);
1417 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1418 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1419 save_unwind_info (acfg, symbol, unwind_ops);
1420 mono_free_unwind_info (unwind_ops);
1422 /* Unwind info for imt trampolines */
1423 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1424 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1425 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1426 save_unwind_info (acfg, symbol, unwind_ops);
1427 mono_free_unwind_info (unwind_ops);
1429 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1430 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1431 save_unwind_info (acfg, symbol, unwind_ops);
1432 mono_free_unwind_info (unwind_ops);
1433 #elif defined(TARGET_ARM64)
1434 arm64_emit_specific_trampoline_pages (acfg);
1439 * arch_emit_specific_trampoline:
1441 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1442 * two GOT slots which contain the generic trampoline address and the trampoline
1443 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1446 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1449 * The trampolines created here are variations of the specific
1450 * trampolines created in mono_arch_create_specific_trampoline (). The
1452 * - the generic trampoline address is taken from a got slot.
1453 * - the offset of the got slot where the trampoline argument is stored
1454 * is embedded in the instruction stream, and the generic trampoline
1455 * can load the argument by loading the offset, adding it to the
1456 * address of the trampoline to get the address of the got slot, and
1457 * loading the argument from there.
1458 * - all the trampolines should be of the same length.
1460 #if defined(TARGET_AMD64)
1461 #if defined(__default_codegen__)
1462 /* This should be exactly 8 bytes long */
1464 /* call *<offset>(%rip) */
1466 emit_unset_mode (acfg);
1467 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1468 emit_zero_bytes (acfg, 2);
1470 emit_byte (acfg, '\x41');
1471 emit_byte (acfg, '\xff');
1472 emit_byte (acfg, '\x15');
1473 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1474 emit_zero_bytes (acfg, 1);
1476 #elif defined(__native_client_codegen__)
1478 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1479 guint8 *code = buf_aligned;
1484 /* Emit this call in 'code' so we can find out how long it is. */
1485 amd64_call_reg (code, AMD64_R11);
1486 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1487 call_len = code - call_start;
1489 /* The tramp_size is twice the NaCl alignment because it starts with */
1490 /* a call which needs to be aligned to the end of the boundary. */
1491 *tramp_size = kNaClAlignment*2;
1493 /* Emit nops to align call site below which is 7 bytes plus */
1494 /* the length of the call sequence emitted above. */
1495 /* Note: this requires the specific trampoline starts on a */
1496 /* kNaclAlignedment aligned address, which it does because */
1497 /* it's its own function that is aligned. */
1498 guint8 nop_buf[256];
1499 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1500 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1501 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1503 /* The trampoline is stored at the offset'th pointer, the -4 is */
1504 /* present because RIP relative addressing starts at the end of */
1505 /* the current instruction, while the label "." is relative to */
1506 /* the beginning of the current asm location, which in this case */
1507 /* is not the mov instruction, but the offset itself, due to the */
1508 /* way the bytes and ints are emitted here. */
1509 got_offset = (offset * sizeof(gpointer)) - 4;
1511 /* mov <OFFSET>(%rip), %r11d */
1512 emit_byte (acfg, '\x45');
1513 emit_byte (acfg, '\x8b');
1514 emit_byte (acfg, '\x1d');
1515 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1518 emit_bytes (acfg, call_start, call_len);
1520 /* The arg is stored at the offset+1 pointer, relative to beginning */
1521 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1522 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1524 /* We can't emit this data directly, hide in a "push imm32" */
1525 emit_byte (acfg, '\x68'); /* push */
1526 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1527 emit_alignment (acfg, kNaClAlignment);
1528 #endif /*__native_client_codegen__*/
1529 #elif defined(TARGET_ARM)
1533 /* This should be exactly 20 bytes long */
1536 ARM_PUSH (code, 0x5fff);
1537 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1538 /* Load the value from the GOT */
1539 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1541 ARM_BLX_REG (code, ARMREG_R1);
1543 g_assert (code - buf == 16);
1546 emit_bytes (acfg, buf, code - buf);
1548 * Only one offset is needed, since the second one would be equal to the
1551 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1552 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1553 #elif defined(TARGET_ARM64)
1554 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1555 #elif defined(TARGET_POWERPC)
1563 * PPC has no ip relative addressing, so we need to compute the address
1564 * of the mscorlib got. That is slow and complex, so instead, we store it
1565 * in the second got slot of every aot image. The caller already computed
1566 * the address of its got and placed it into r30.
1568 emit_unset_mode (acfg);
1569 /* Load mscorlib got address */
1570 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1571 /* Load generic trampoline address */
1572 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1573 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1574 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1575 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1576 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1578 fprintf (acfg->fp, "mtctr 11\n");
1579 /* Load trampoline argument */
1580 /* On ppc, we pass it normally to the generic trampoline */
1581 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1582 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1583 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1584 /* Branch to generic trampoline */
1585 fprintf (acfg->fp, "bctr\n");
1587 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1588 *tramp_size = 10 * 4;
1590 *tramp_size = 9 * 4;
1592 #elif defined(TARGET_X86)
1596 /* Similar to the PPC code above */
1598 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1601 /* Load mscorlib got address */
1602 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1603 /* Push trampoline argument */
1604 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1605 /* Load generic trampoline address */
1606 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1607 /* Branch to generic trampoline */
1608 x86_jump_reg (code, X86_ECX);
1610 #ifdef __native_client_codegen__
1612 /* emit nops to next 32 byte alignment */
1613 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1614 while (code < (buf + a)) x86_nop(code);
1617 emit_bytes (acfg, buf, code - buf);
1619 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1620 g_assert (code - buf == *tramp_size);
1622 g_assert_not_reached ();
1627 * arch_emit_unbox_trampoline:
1629 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1630 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1633 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1635 #if defined(TARGET_AMD64)
1640 this_reg = mono_arch_get_this_arg_reg (NULL);
1642 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1644 emit_bytes (acfg, buf, code - buf);
1647 emit_unset_mode (acfg);
1648 fprintf (acfg->fp, "jmp %s\n", call_target);
1650 emit_byte (acfg, '\xe9');
1651 emit_symbol_diff (acfg, call_target, ".", -4);
1653 #elif defined(TARGET_X86)
1660 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1662 emit_bytes (acfg, buf, code - buf);
1665 emit_byte (acfg, '\xe9');
1666 emit_symbol_diff (acfg, call_target, ".", -4);
1667 #elif defined(TARGET_ARM)
1671 if (acfg->thumb_mixed && cfg->compile_llvm) {
1672 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1673 fprintf (acfg->fp, "b %s\n", call_target);
1674 fprintf (acfg->fp, ".arm\n");
1675 fprintf (acfg->fp, ".align 2\n");
1681 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1683 emit_bytes (acfg, buf, code - buf);
1684 /* jump to method */
1685 if (acfg->thumb_mixed && cfg->compile_llvm)
1686 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1688 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1689 #elif defined(TARGET_ARM64)
1690 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1691 #elif defined(TARGET_POWERPC)
1694 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1695 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1697 g_assert_not_reached ();
1702 * arch_emit_static_rgctx_trampoline:
1704 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1705 * two GOT slots which contain the rgctx argument, and the method to jump to.
1706 * TRAMP_SIZE is set to the size of the emitted trampoline.
1707 * These kinds of trampolines cannot be enumerated statically, since there could
1708 * be one trampoline per method instantiation, so we emit the same code for all
1709 * trampolines, and parameterize them using two GOT slots.
1712 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1714 #if defined(TARGET_AMD64)
1715 #if defined(__default_codegen__)
1716 /* This should be exactly 13 bytes long */
1720 emit_unset_mode (acfg);
1721 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1722 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1724 /* mov <OFFSET>(%rip), %r10 */
1725 emit_byte (acfg, '\x4d');
1726 emit_byte (acfg, '\x8b');
1727 emit_byte (acfg, '\x15');
1728 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1730 /* jmp *<offset>(%rip) */
1731 emit_byte (acfg, '\xff');
1732 emit_byte (acfg, '\x25');
1733 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1735 #elif defined(__native_client_codegen__)
1737 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1738 guint8 *code = buf_aligned;
1740 /* mov <OFFSET>(%rip), %r10d */
1741 emit_byte (acfg, '\x45');
1742 emit_byte (acfg, '\x8b');
1743 emit_byte (acfg, '\x15');
1744 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1746 /* mov <OFFSET>(%rip), %r11d */
1747 emit_byte (acfg, '\x45');
1748 emit_byte (acfg, '\x8b');
1749 emit_byte (acfg, '\x1d');
1750 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1753 amd64_jump_reg (code, AMD64_R11);
1754 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1756 emit_alignment (acfg, kNaClAlignment);
1757 *tramp_size = kNaClAlignment;
1758 #endif /*__native_client_codegen__*/
1760 #elif defined(TARGET_ARM)
1764 /* This should be exactly 24 bytes long */
1767 /* Load rgctx value */
1768 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1769 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1770 /* Load branch addr + branch */
1771 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1772 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1774 g_assert (code - buf == 16);
1777 emit_bytes (acfg, buf, code - buf);
1778 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1779 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1780 #elif defined(TARGET_ARM64)
1781 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1782 #elif defined(TARGET_POWERPC)
1790 * PPC has no ip relative addressing, so we need to compute the address
1791 * of the mscorlib got. That is slow and complex, so instead, we store it
1792 * in the second got slot of every aot image. The caller already computed
1793 * the address of its got and placed it into r30.
1795 emit_unset_mode (acfg);
1796 /* Load mscorlib got address */
1797 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1799 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1800 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1801 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1802 /* Load target address */
1803 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1804 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1805 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1806 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1807 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1808 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1810 fprintf (acfg->fp, "mtctr 11\n");
1811 /* Branch to the target address */
1812 fprintf (acfg->fp, "bctr\n");
1814 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1815 *tramp_size = 11 * 4;
1817 *tramp_size = 9 * 4;
1820 #elif defined(TARGET_X86)
1824 /* Similar to the PPC code above */
1826 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1829 /* Load mscorlib got address */
1830 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1832 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1833 /* Branch to the target address */
1834 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1836 #ifdef __native_client_codegen__
1838 /* emit nops to next 32 byte alignment */
1839 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1840 while (code < (buf + a)) x86_nop(code);
1844 emit_bytes (acfg, buf, code - buf);
1846 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1847 g_assert (code - buf == *tramp_size);
1849 g_assert_not_reached ();
1854 * arch_emit_imt_thunk:
1856 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1857 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1858 * key is the IMT key, and ptr holds the address of a memory location holding
1859 * the address to branch to if the IMT arg matches the key. The array is
1860 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1862 * TRAMP_SIZE is set to the size of the emitted trampoline.
1865 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1867 #if defined(TARGET_AMD64)
1869 #if defined(__native_client_codegen__)
1872 guint8 *labels [16];
1874 guint8 *mov_buf_ptr = mov_buf;
1876 const int kSizeOfMove = 7;
1877 #if defined(__default_codegen__)
1878 code = buf = (guint8 *)g_malloc (256);
1879 #elif defined(__native_client_codegen__)
1880 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1881 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1882 /* The RIP relative move below is emitted first */
1887 /* FIXME: Optimize this, i.e. use binary search etc. */
1888 /* Maybe move the body into a separate function (slower, but much smaller) */
1890 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1893 emit_unset_mode (acfg);
1894 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1898 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1900 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1903 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1905 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1908 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1909 amd64_jump_code (code, labels [0]);
1912 mono_amd64_patch (labels [2], code);
1913 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1914 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1917 mono_amd64_patch (labels [1], code);
1918 /* Load fail tramp */
1919 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1920 /* Check if there is a fail tramp */
1921 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1923 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1924 /* Jump to fail tramp */
1925 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1928 mono_amd64_patch (labels [3], code);
1929 x86_breakpoint (code);
1932 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1933 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1934 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1935 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1936 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1937 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1939 emit_bytes (acfg, buf, code - buf);
1941 *tramp_size = code - buf + kSizeOfMove;
1942 #if defined(__native_client_codegen__)
1943 /* The tramp will be padded to the next kNaClAlignment bundle. */
1944 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1947 #if defined(__default_codegen__)
1949 #elif defined(__native_client_codegen__)
1953 #elif defined(TARGET_X86)
1955 #ifdef __native_client_codegen__
1958 guint8 *labels [16];
1960 #if defined(__default_codegen__)
1961 code = buf = g_malloc (256);
1962 #elif defined(__native_client_codegen__)
1963 buf_alloc = g_malloc (256 + kNaClAlignment);
1964 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1967 /* Allocate a temporary stack slot */
1968 x86_push_reg (code, X86_EAX);
1970 x86_push_reg (code, X86_EAX);
1972 /* Load mscorlib got address */
1973 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1975 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1978 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1980 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1983 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1985 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1988 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1989 x86_jump_code (code, labels [0]);
1992 mono_x86_patch (labels [2], code);
1993 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1994 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1995 /* Save the target address to the temporary stack location */
1996 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1998 x86_pop_reg (code, X86_EAX);
1999 /* Jump to the target address */
2003 mono_x86_patch (labels [1], code);
2004 /* Load fail tramp */
2005 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2006 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2008 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2009 /* Jump to fail tramp */
2010 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2011 x86_pop_reg (code, X86_EAX);
2015 mono_x86_patch (labels [3], code);
2016 x86_breakpoint (code);
2018 #ifdef __native_client_codegen__
2020 /* emit nops to next 32 byte alignment */
2021 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2022 while (code < (buf + a)) x86_nop(code);
2025 emit_bytes (acfg, buf, code - buf);
2027 *tramp_size = code - buf;
2029 #if defined(__default_codegen__)
2031 #elif defined(__native_client_codegen__)
2035 #elif defined(TARGET_ARM)
2037 guint8 *code, *code2, *labels [16];
2041 /* The IMT method is in v5 */
2043 /* Need at least two free registers, plus a slot for storing the pc */
2044 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2046 /* Load the parameter from the GOT */
2047 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2048 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2051 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2052 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2054 ARM_B_COND (code, ARMCOND_EQ, 0);
2056 /* End-of-loop check */
2057 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2059 ARM_B_COND (code, ARMCOND_EQ, 0);
2062 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2065 arm_patch (labels [4], labels [1]);
2068 arm_patch (labels [2], code);
2069 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2070 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2071 /* Save it to the third stack slot */
2072 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2073 /* Restore the registers and branch */
2074 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2077 arm_patch (labels [3], code);
2078 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2079 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2080 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2084 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2086 emit_bytes (acfg, buf, code - buf);
2087 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2089 *tramp_size = code - buf + 4;
2090 #elif defined(TARGET_ARM64)
2091 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2092 #elif defined(TARGET_POWERPC)
2094 guint8 *code, *labels [16];
2098 /* Load the mscorlib got address */
2099 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2100 /* Load the parameter from the GOT */
2101 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2102 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2104 /* Load and check key */
2106 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2107 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2109 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2111 /* End-of-loop check */
2112 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2114 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2117 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2120 mono_ppc_patch (labels [4], labels [1]);
2123 mono_ppc_patch (labels [2], code);
2124 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2125 /* r12 now contains the value of the vtable slot */
2126 /* this is not a function descriptor on ppc64 */
2127 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2128 ppc_mtctr (code, ppc_r12);
2129 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2132 mono_ppc_patch (labels [3], code);
2136 *tramp_size = code - buf;
2138 emit_bytes (acfg, buf, code - buf);
2140 g_assert_not_reached ();
2145 #if defined (TARGET_AMD64)
2148 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2151 g_assert (acfg->fp);
2152 emit_unset_mode (acfg);
2154 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2161 * arch_emit_gsharedvt_arg_trampoline:
2163 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2164 * two GOT slots which contain the argument, and the code to jump to.
2165 * TRAMP_SIZE is set to the size of the emitted trampoline.
2166 * These kinds of trampolines cannot be enumerated statically, since there could
2167 * be one trampoline per method instantiation, so we emit the same code for all
2168 * trampolines, and parameterize them using two GOT slots.
2171 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2173 #if defined(TARGET_X86)
2177 /* Similar to the PPC code above */
2179 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2182 /* Load mscorlib got address */
2183 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2185 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2186 /* Branch to the target address */
2187 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2189 #ifdef __native_client_codegen__
2191 /* emit nops to next 32 byte alignment */
2192 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2193 while (code < (buf + a)) x86_nop(code);
2197 emit_bytes (acfg, buf, code - buf);
2199 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2200 g_assert (code - buf == *tramp_size);
2201 #elif defined(TARGET_ARM)
2205 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2206 /* Similar to arch_emit_specific_trampoline () */
2209 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2210 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2211 /* Load the arg value from the GOT */
2212 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2213 /* Load the addr from the GOT */
2214 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2216 ARM_BX (code, ARMREG_R1);
2218 g_assert (code - buf == 20);
2221 emit_bytes (acfg, buf, code - buf);
2222 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2223 #elif defined(TARGET_ARM64)
2224 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2225 #elif defined (TARGET_AMD64)
2227 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2228 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2229 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2230 fprintf (acfg->fp, "jmp *%%r11\n");
2234 g_assert_not_reached ();
2238 /* END OF ARCH SPECIFIC CODE */
2241 mono_get_field_token (MonoClassField *field)
2243 MonoClass *klass = field->parent;
2246 for (i = 0; i < klass->field.count; ++i) {
2247 if (field == &klass->fields [i])
2248 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2251 g_assert_not_reached ();
2256 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2260 //printf ("ENCODE: %d 0x%x.\n", value, value);
2263 * Same encoding as the one used in the metadata, extended to handle values
2264 * greater than 0x1fffffff.
2266 if ((value >= 0) && (value <= 127))
2268 else if ((value >= 0) && (value <= 16383)) {
2269 p [0] = 0x80 | (value >> 8);
2270 p [1] = value & 0xff;
2272 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2273 p [0] = (value >> 24) | 0xc0;
2274 p [1] = (value >> 16) & 0xff;
2275 p [2] = (value >> 8) & 0xff;
2276 p [3] = value & 0xff;
2281 p [1] = (value >> 24) & 0xff;
2282 p [2] = (value >> 16) & 0xff;
2283 p [3] = (value >> 8) & 0xff;
2284 p [4] = value & 0xff;
2292 stream_init (MonoDynamicStream *sh)
2295 sh->alloc_size = 4096;
2296 sh->data = (char *)g_malloc (4096);
2298 /* So offsets are > 0 */
2304 make_room_in_stream (MonoDynamicStream *stream, int size)
2306 if (size <= stream->alloc_size)
2309 while (stream->alloc_size <= size) {
2310 if (stream->alloc_size < 4096)
2311 stream->alloc_size = 4096;
2313 stream->alloc_size *= 2;
2316 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2320 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2324 make_room_in_stream (stream, stream->index + len);
2325 memcpy (stream->data + stream->index, data, len);
2326 idx = stream->index;
2327 stream->index += len;
2334 * Add data to the binary blob inside the aot image. Returns the offset inside the
2335 * blob where the data was stored.
2338 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2340 g_assert (!acfg->blob_closed);
2342 if (acfg->blob.alloc_size == 0)
2343 stream_init (&acfg->blob);
2345 return add_stream_data (&acfg->blob, (char*)data, data_len);
2349 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2354 if (acfg->blob.alloc_size == 0)
2355 stream_init (&acfg->blob);
2357 count = acfg->blob.index % align;
2359 /* we assume the stream data will be aligned */
2361 add_stream_data (&acfg->blob, buf, 4 - count);
2363 return add_stream_data (&acfg->blob, (char*)data, data_len);
2366 /* Emit a table of data into the aot image */
2368 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2370 if (acfg->data_outfile) {
2371 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2372 fwrite (data,1, size, acfg->data_outfile);
2373 acfg->datafile_offset += size;
2374 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2375 int align = 8 - size % 8;
2376 acfg->datafile_offset += align;
2377 guint8 align_buf [16];
2378 memset (&align_buf, 0, sizeof (align_buf));
2379 fwrite (align_buf, align, 1, acfg->data_outfile);
2380 } else if (acfg->llvm) {
2381 mono_llvm_emit_aot_data (symbol, data, size);
2383 emit_section_change (acfg, RODATA_SECT, 0);
2384 emit_alignment (acfg, 8);
2385 emit_label (acfg, symbol);
2386 emit_bytes (acfg, data, size);
2391 * emit_offset_table:
2393 * Emit a table of increasing offsets in a compact form using differential encoding.
2394 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2395 * group size, the more compact the table becomes, but the slower it becomes to compute
2396 * a given entry. Returns the size of the table.
2399 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2401 gint32 current_offset;
2402 int i, buf_size, ngroups, index_entry_size;
2404 guint8 *data_p, *data_buf;
2405 guint32 *index_offsets;
2407 ngroups = (noffsets + (group_size - 1)) / group_size;
2409 index_offsets = g_new0 (guint32, ngroups);
2411 buf_size = noffsets * 4;
2412 p = buf = (guint8 *)g_malloc0 (buf_size);
2415 for (i = 0; i < noffsets; ++i) {
2416 //printf ("D: %d -> %d\n", i, offsets [i]);
2417 if ((i % group_size) == 0) {
2418 index_offsets [i / group_size] = p - buf;
2419 /* Emit the full value for these entries */
2420 encode_value (offsets [i], p, &p);
2422 /* The offsets are allowed to be non-increasing */
2423 //g_assert (offsets [i] >= current_offset);
2424 encode_value (offsets [i] - current_offset, p, &p);
2426 current_offset = offsets [i];
2431 if (ngroups && index_offsets [ngroups - 1] < 65000)
2432 index_entry_size = 2;
2434 index_entry_size = 4;
2436 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2437 p = buf = (guint8 *)g_malloc0 (buf_size);
2439 /* Emit the header */
2440 encode_int (noffsets, p, &p);
2441 encode_int (group_size, p, &p);
2442 encode_int (ngroups, p, &p);
2443 encode_int (index_entry_size, p, &p);
2445 /* Emit the index */
2446 for (i = 0; i < ngroups; ++i) {
2447 if (index_entry_size == 2)
2448 encode_int16 (index_offsets [i], p, &p);
2450 encode_int (index_offsets [i], p, &p);
2453 memcpy (p, data_buf, data_p - data_buf);
2454 p += data_p - data_buf;
2456 g_assert (p - buf <= buf_size);
2458 emit_aot_data (acfg, table, symbol, buf, p - buf);
2463 return (int)(p - buf);
2467 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2471 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2475 index = g_hash_table_size (cfg->image_hash);
2476 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2477 g_ptr_array_add (cfg->image_table, image);
2483 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2486 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2488 /* FIXME: Search referenced images as well */
2489 if (!acfg->typespec_classes) {
2490 acfg->typespec_classes = (MonoClass **)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2491 for (i = 0; i < len; ++i) {
2493 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2494 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2497 for (i = 0; i < len; ++i) {
2498 if (acfg->typespec_classes [i] == klass)
2503 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2509 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2512 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2515 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2518 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2521 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2526 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2530 if (klass->generic_class) {
2532 g_assert (klass->type_token);
2534 /* Find a typespec for a class if possible */
2535 token = find_typespec_for_class (acfg, klass);
2537 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2538 encode_value (token, p, &p);
2540 MonoClass *gclass = klass->generic_class->container_class;
2541 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2542 static int count = 0;
2545 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2546 encode_klass_ref (acfg, gclass, p, &p);
2547 encode_ginst (acfg, inst, p, &p);
2551 } else if (klass->type_token) {
2552 int iindex = get_image_index (acfg, klass->image);
2554 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2556 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2557 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2559 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2560 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2561 encode_value (get_image_index (acfg, klass->image), p, &p);
2563 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2564 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2565 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2567 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2569 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2570 if (par->gshared_constraint) {
2571 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2572 encode_type (acfg, par->gshared_constraint, p, &p);
2573 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2575 encode_value (klass->byval_arg.type, p, &p);
2576 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2578 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2580 if (!container->is_anonymous) {
2581 encode_value (container->is_method, p, &p);
2582 if (container->is_method)
2583 encode_method_ref (acfg, container->owner.method, p, &p);
2585 encode_klass_ref (acfg, container->owner.klass, p, &p);
2588 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2589 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2590 encode_type (acfg, &klass->byval_arg, p, &p);
2593 g_assert (klass->rank > 0);
2594 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2595 encode_value (klass->rank, p, &p);
2596 encode_klass_ref (acfg, klass->element_class, p, &p);
2604 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2605 * standard metadata encoding.
2608 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2610 gboolean shared = FALSE;
2613 * The encoding of generic instances is large so emit them only once.
2615 if (klass->generic_class) {
2617 g_assert (klass->type_token);
2619 /* Find a typespec for a class if possible */
2620 token = find_typespec_for_class (acfg, klass);
2623 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2628 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2632 buf2 = (guint8 *)g_malloc (1024);
2635 encode_klass_ref_inner (acfg, klass, p, &p);
2636 g_assert (p - buf2 < 1024);
2638 offset = add_to_blob (acfg, buf2, p - buf2);
2641 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2647 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2648 encode_value (offset, p, &p);
2653 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2657 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2659 guint32 token = mono_get_field_token (field);
2662 encode_klass_ref (cfg, field->parent, p, &p);
2663 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2664 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2669 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2674 encode_value (inst->type_argc, p, &p);
2675 for (i = 0; i < inst->type_argc; ++i)
2676 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2681 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2684 MonoGenericInst *inst;
2686 inst = context->class_inst;
2688 g_assert (inst->type_argc);
2689 encode_ginst (acfg, inst, p, &p);
2691 encode_value (0, p, &p);
2693 inst = context->method_inst;
2695 g_assert (inst->type_argc);
2696 encode_ginst (acfg, inst, p, &p);
2698 encode_value (0, p, &p);
2704 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2708 g_assert (t->num_mods == 0);
2709 /* t->attrs can be ignored */
2710 //g_assert (t->attrs == 0);
2713 *p = MONO_TYPE_PINNED;
2717 *p = MONO_TYPE_BYREF;
2725 case MONO_TYPE_VOID:
2726 case MONO_TYPE_BOOLEAN:
2727 case MONO_TYPE_CHAR:
2740 case MONO_TYPE_STRING:
2741 case MONO_TYPE_OBJECT:
2742 case MONO_TYPE_TYPEDBYREF:
2744 case MONO_TYPE_VALUETYPE:
2745 case MONO_TYPE_CLASS:
2746 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2748 case MONO_TYPE_SZARRAY:
2749 encode_klass_ref (acfg, t->data.klass, p, &p);
2752 encode_type (acfg, t->data.type, p, &p);
2754 case MONO_TYPE_GENERICINST: {
2755 MonoClass *gclass = t->data.generic_class->container_class;
2756 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2758 encode_klass_ref (acfg, gclass, p, &p);
2759 encode_ginst (acfg, inst, p, &p);
2762 case MONO_TYPE_ARRAY: {
2763 MonoArrayType *array = t->data.array;
2766 encode_klass_ref (acfg, array->eklass, p, &p);
2767 encode_value (array->rank, p, &p);
2768 encode_value (array->numsizes, p, &p);
2769 for (i = 0; i < array->numsizes; ++i)
2770 encode_value (array->sizes [i], p, &p);
2771 encode_value (array->numlobounds, p, &p);
2772 for (i = 0; i < array->numlobounds; ++i)
2773 encode_value (array->lobounds [i], p, &p);
2777 case MONO_TYPE_MVAR:
2778 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2781 g_assert_not_reached ();
2788 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2794 /* Similar to the metadata encoding */
2795 if (sig->generic_param_count)
2799 if (sig->explicit_this)
2801 flags |= (sig->call_convention & 0x0F);
2805 if (sig->generic_param_count)
2806 encode_value (sig->generic_param_count, p, &p);
2807 encode_value (sig->param_count, p, &p);
2809 encode_type (acfg, sig->ret, p, &p);
2810 for (i = 0; i < sig->param_count; ++i) {
2811 if (sig->sentinelpos == i) {
2812 *p = MONO_TYPE_SENTINEL;
2815 encode_type (acfg, sig->params [i], p, &p);
2821 #define MAX_IMAGE_INDEX 250
2824 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2826 guint32 image_index = get_image_index (acfg, method->klass->image);
2827 guint32 token = method->token;
2828 MonoJumpInfoToken *ji;
2832 * The encoding for most methods is as follows:
2833 * - image index encoded as a leb128
2834 * - token index encoded as a leb128
2835 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2836 * types of method encodings.
2839 /* Mark methods which can't use aot trampolines because they need the further
2840 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2842 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2843 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2844 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2846 if (method->wrapper_type) {
2847 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2849 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2851 encode_value (method->wrapper_type, p, &p);
2853 switch (method->wrapper_type) {
2854 case MONO_WRAPPER_REMOTING_INVOKE:
2855 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2856 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2859 m = mono_marshal_method_from_wrapper (method);
2861 encode_method_ref (acfg, m, p, &p);
2864 case MONO_WRAPPER_PROXY_ISINST:
2865 case MONO_WRAPPER_LDFLD:
2866 case MONO_WRAPPER_LDFLDA:
2867 case MONO_WRAPPER_STFLD:
2868 case MONO_WRAPPER_ISINST: {
2870 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2873 case MONO_WRAPPER_LDFLD_REMOTE:
2874 case MONO_WRAPPER_STFLD_REMOTE:
2876 case MONO_WRAPPER_ALLOC: {
2877 /* The GC name is saved once in MonoAotFileInfo */
2878 g_assert (info->d.alloc.alloc_type != -1);
2879 encode_value (info->d.alloc.alloc_type, p, &p);
2882 case MONO_WRAPPER_WRITE_BARRIER: {
2886 case MONO_WRAPPER_STELEMREF: {
2888 encode_value (info->subtype, p, &p);
2889 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2890 encode_value (info->d.virtual_stelemref.kind, p, &p);
2893 case MONO_WRAPPER_UNKNOWN: {
2895 encode_value (info->subtype, p, &p);
2896 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2897 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2898 encode_klass_ref (acfg, method->klass, p, &p);
2899 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2900 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2901 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2902 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2903 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
2904 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2905 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
2906 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
2909 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2911 encode_value (info->subtype, p, &p);
2912 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2913 strcpy ((char*)p, method->name);
2914 p += strlen (method->name) + 1;
2915 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2916 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2918 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2919 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2923 case MONO_WRAPPER_SYNCHRONIZED: {
2926 m = mono_marshal_method_from_wrapper (method);
2928 g_assert (m != method);
2929 encode_method_ref (acfg, m, p, &p);
2932 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2934 encode_value (info->subtype, p, &p);
2936 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2937 encode_value (info->d.element_addr.rank, p, &p);
2938 encode_value (info->d.element_addr.elem_size, p, &p);
2939 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2940 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2942 g_assert_not_reached ();
2946 case MONO_WRAPPER_CASTCLASS: {
2948 encode_value (info->subtype, p, &p);
2951 case MONO_WRAPPER_RUNTIME_INVOKE: {
2953 encode_value (info->subtype, p, &p);
2954 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2955 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2956 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2957 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2960 case MONO_WRAPPER_DELEGATE_INVOKE:
2961 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2962 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2963 if (method->is_inflated) {
2964 /* These wrappers are identified by their class */
2965 encode_value (1, p, &p);
2966 encode_klass_ref (acfg, method->klass, p, &p);
2968 MonoMethodSignature *sig = mono_method_signature (method);
2969 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2971 encode_value (0, p, &p);
2972 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2973 encode_value (info ? info->subtype : 0, p, &p);
2974 encode_signature (acfg, sig, p, &p);
2978 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2980 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2981 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2985 g_assert_not_reached ();
2987 } else if (mono_method_signature (method)->is_inflated) {
2989 * This is a generic method, find the original token which referenced it and
2991 * Obtain the token from information recorded by the JIT.
2993 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
2995 image_index = get_image_index (acfg, ji->image);
2996 g_assert (image_index < MAX_IMAGE_INDEX);
2999 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3000 encode_value (image_index, p, &p);
3001 encode_value (token, p, &p);
3003 MonoMethod *declaring;
3004 MonoGenericContext *context = mono_method_get_context (method);
3006 g_assert (method->is_inflated);
3007 declaring = ((MonoMethodInflated*)method)->declaring;
3010 * This might be a non-generic method of a generic instance, which
3011 * doesn't have a token since the reference is generated by the JIT
3012 * like Nullable:Box/Unbox, or by generic sharing.
3014 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3015 /* Encode the klass */
3016 encode_klass_ref (acfg, method->klass, p, &p);
3017 /* Encode the method */
3018 image_index = get_image_index (acfg, method->klass->image);
3019 g_assert (image_index < MAX_IMAGE_INDEX);
3020 g_assert (declaring->token);
3021 token = declaring->token;
3022 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3023 encode_value (image_index, p, &p);
3024 encode_value (token, p, &p);
3025 encode_generic_context (acfg, context, p, &p);
3027 } else if (token == 0) {
3028 /* This might be a method of a constructed type like int[,].Set */
3029 /* Obtain the token from information recorded by the JIT */
3030 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3032 image_index = get_image_index (acfg, ji->image);
3033 g_assert (image_index < MAX_IMAGE_INDEX);
3036 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3037 encode_value (image_index, p, &p);
3038 encode_value (token, p, &p);
3041 g_assert (method->klass->rank);
3043 /* Encode directly */
3044 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3045 encode_klass_ref (acfg, method->klass, p, &p);
3046 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3047 encode_value (0, p, &p);
3048 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3049 encode_value (1, p, &p);
3050 else if (!strcmp (method->name, "Get"))
3051 encode_value (2, p, &p);
3052 else if (!strcmp (method->name, "Address"))
3053 encode_value (3, p, &p);
3054 else if (!strcmp (method->name, "Set"))
3055 encode_value (4, p, &p);
3057 g_assert_not_reached ();
3060 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3062 if (image_index >= MONO_AOT_METHODREF_MIN) {
3063 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3064 encode_value (image_index, p, &p);
3065 encode_value (mono_metadata_token_index (token), p, &p);
3067 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3074 compare_patches (gconstpointer a, gconstpointer b)
3078 i = (*(MonoJumpInfo**)a)->ip.i;
3079 j = (*(MonoJumpInfo**)b)->ip.i;
3090 static G_GNUC_UNUSED char*
3091 patch_to_string (MonoJumpInfo *patch_info)
3095 str = g_string_new ("");
3097 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3099 switch (patch_info->type) {
3100 case MONO_PATCH_INFO_VTABLE:
3101 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3106 g_string_append_printf (str, ")");
3107 return g_string_free (str, FALSE);
3113 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3116 static inline gboolean
3117 is_plt_patch (MonoJumpInfo *patch_info)
3119 switch (patch_info->type) {
3120 case MONO_PATCH_INFO_METHOD:
3121 case MONO_PATCH_INFO_INTERNAL_METHOD:
3122 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3123 case MONO_PATCH_INFO_ICALL_ADDR:
3124 case MONO_PATCH_INFO_RGCTX_FETCH:
3134 * Return the symbol identifying the plt entry PLT_OFFSET.
3137 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3141 * The Apple linker reorganizes object files, so it doesn't like branches to local
3142 * labels, since those have no relocations.
3144 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3146 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3153 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3155 static MonoPltEntry*
3156 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3159 gboolean synchronized = FALSE;
3160 static int synchronized_symbol_idx;
3162 if (!is_plt_patch (patch_info))
3165 if (!acfg->patch_to_plt_entry [patch_info->type])
3166 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3167 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3169 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3171 * Allocate a separate PLT slot for each such patch, since some plt
3172 * entries will refer to the method itself, and some will refer to the
3176 synchronized = TRUE;
3180 MonoJumpInfo *new_ji;
3182 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3184 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3185 res->plt_offset = acfg->plt_offset;
3187 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3188 if (acfg->aot_opts.write_symbols)
3189 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3191 /* Avoid duplicate symbols because we don't cache */
3192 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3194 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3195 synchronized_symbol_idx ++;
3198 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3200 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3202 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3204 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3206 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3207 //mono_print_ji (patch_info); printf ("\n");
3208 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3210 acfg->plt_offset ++;
3219 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3220 * JI could be found if it exists, otherwise allocates a new one.
3223 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3226 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3228 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3230 return got_offset - 1;
3233 got_offset = acfg->llvm_got_offset;
3234 acfg->llvm_got_offset ++;
3236 got_offset = acfg->got_offset;
3237 acfg->got_offset ++;
3240 acfg->stats.got_slots ++;
3241 acfg->stats.got_slot_types [ji->type] ++;
3243 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3244 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3245 g_ptr_array_add (info->got_patches, ji);
3250 /* Add a method to the list of methods which need to be emitted */
3252 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3255 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3256 g_ptr_array_add (acfg->methods, method);
3257 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3258 acfg->nmethods = acfg->methods->len + 1;
3261 if (method->wrapper_type || extra)
3262 g_ptr_array_add (acfg->extra_methods, method);
3266 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3268 /* One instantiation with valuetypes is generated for each async method */
3269 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3276 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3278 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3286 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3290 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3294 index = acfg->method_index;
3295 add_method_with_index (acfg, method, index, extra);
3297 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3299 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3301 acfg->method_index ++;
3307 add_method (MonoAotCompile *acfg, MonoMethod *method)
3309 return add_method_full (acfg, method, FALSE, 0);
3313 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3315 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3316 method = mini_get_shared_method (method);
3317 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3318 /* Use the gsharedvt version */
3319 method = mini_get_shared_method_full (method, TRUE, TRUE);
3321 if (acfg->aot_opts.log_generics)
3322 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3324 add_method_full (acfg, method, TRUE, depth);
3328 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3330 add_extra_method_with_depth (acfg, method, 0);
3334 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3336 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3337 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3338 MonoMethod *wrapper;
3344 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3345 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3348 add_method (acfg, wrapper);
3352 get_runtime_invoke_sig (MonoMethodSignature *sig)
3354 MonoMethodBuilder *mb;
3357 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3358 m = mono_mb_create_method (mb, sig, 16);
3359 return mono_marshal_get_runtime_invoke (m, FALSE);
3363 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3365 return mono_marshal_get_runtime_invoke (method, virtual_);
3369 can_marshal_struct (MonoClass *klass)
3371 MonoClassField *field;
3372 gboolean can_marshal = TRUE;
3373 gpointer iter = NULL;
3374 MonoMarshalType *info;
3377 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3380 info = mono_marshal_load_type_info (klass);
3382 /* Only allow a few field types to avoid asserts in the marshalling code */
3383 while ((field = mono_class_get_fields (klass, &iter))) {
3384 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3387 switch (field->type->type) {
3392 case MONO_TYPE_BOOLEAN:
3395 case MONO_TYPE_CHAR:
3403 case MONO_TYPE_STRING:
3405 case MONO_TYPE_VALUETYPE:
3406 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3407 can_marshal = FALSE;
3409 case MONO_TYPE_SZARRAY: {
3410 gboolean has_mspec = FALSE;
3413 for (i = 0; i < info->num_fields; ++i) {
3414 if (info->fields [i].field == field && info->fields [i].mspec)
3419 can_marshal = FALSE;
3423 can_marshal = FALSE;
3429 /* Its hard to compute whenever these can be marshalled or not */
3430 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3437 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3439 /* Create a vtype instantiation */
3440 MonoGenericContext shared_context;
3442 MonoGenericInst *inst;
3443 MonoGenericContainer *container;
3444 MonoClass **constraints;
3447 memset (ctx, 0, sizeof (MonoGenericContext));
3449 if (method->klass->generic_container) {
3450 shared_context = method->klass->generic_container->context;
3451 inst = shared_context.class_inst;
3453 args = g_new0 (MonoType*, inst->type_argc);
3454 for (i = 0; i < inst->type_argc; ++i) {
3455 args [i] = &mono_defaults.int_class->byval_arg;
3457 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3459 if (method->is_generic) {
3460 container = mono_method_get_generic_container (method);
3461 shared_context = container->context;
3462 inst = shared_context.method_inst;
3464 args = g_new0 (MonoType*, inst->type_argc);
3465 for (i = 0; i < container->type_argc; ++i) {
3466 MonoGenericParamInfo *info = &container->type_params [i].info;
3467 gboolean ref_only = FALSE;
3469 if (info && info->constraints) {
3470 constraints = info->constraints;
3472 while (*constraints) {
3473 MonoClass *cklass = *constraints;
3474 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3475 /* Inflaring the method with our vtype would not be valid */
3482 args [i] = &mono_defaults.object_class->byval_arg;
3484 args [i] = &mono_defaults.int_class->byval_arg;
3486 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3491 add_wrappers (MonoAotCompile *acfg)
3493 MonoMethod *method, *m;
3495 MonoMethodSignature *sig, *csig;
3499 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3500 * so there is only one wrapper of a given type, or inlining their contents into their
3503 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3506 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3507 gboolean skip = FALSE;
3509 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3510 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3512 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3513 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3514 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3517 /* Skip methods which can not be handled by get_runtime_invoke () */
3518 sig = mono_method_signature (method);
3521 if ((sig->ret->type == MONO_TYPE_PTR) ||
3522 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3524 if (mono_class_is_open_constructed_type (sig->ret))
3527 for (j = 0; j < sig->param_count; j++) {
3528 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3530 if (mono_class_is_open_constructed_type (sig->params [j]))
3534 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3535 if (!mono_class_is_contextbound (method->klass)) {
3536 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3537 gboolean has_nullable = FALSE;
3539 for (j = 0; j < sig->param_count; j++) {
3540 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3541 has_nullable = TRUE;
3544 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3545 /* Supported by the dynamic runtime-invoke wrapper */
3549 mono_arch_dyn_call_free (info);
3553 if (acfg->aot_opts.llvm_only)
3554 /* Supported by the gsharedvt based runtime-invoke wrapper */
3558 //printf ("%s\n", mono_method_full_name (method, TRUE));
3559 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3563 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3566 /* Runtime invoke wrappers */
3568 /* void runtime-invoke () [.cctor] */
3569 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3570 csig->ret = &mono_defaults.void_class->byval_arg;
3571 add_method (acfg, get_runtime_invoke_sig (csig));
3573 /* void runtime-invoke () [Finalize] */
3574 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3576 csig->ret = &mono_defaults.void_class->byval_arg;
3577 add_method (acfg, get_runtime_invoke_sig (csig));
3579 /* void runtime-invoke (string) [exception ctor] */
3580 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3582 csig->ret = &mono_defaults.void_class->byval_arg;
3583 csig->params [0] = &mono_defaults.string_class->byval_arg;
3584 add_method (acfg, get_runtime_invoke_sig (csig));
3586 /* void runtime-invoke (string, string) [exception ctor] */
3587 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3589 csig->ret = &mono_defaults.void_class->byval_arg;
3590 csig->params [0] = &mono_defaults.string_class->byval_arg;
3591 csig->params [1] = &mono_defaults.string_class->byval_arg;
3592 add_method (acfg, get_runtime_invoke_sig (csig));
3594 /* string runtime-invoke () [Exception.ToString ()] */
3595 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3597 csig->ret = &mono_defaults.string_class->byval_arg;
3598 add_method (acfg, get_runtime_invoke_sig (csig));
3600 /* void runtime-invoke (string, Exception) [exception ctor] */
3601 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3603 csig->ret = &mono_defaults.void_class->byval_arg;
3604 csig->params [0] = &mono_defaults.string_class->byval_arg;
3605 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3606 add_method (acfg, get_runtime_invoke_sig (csig));
3608 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3609 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3611 csig->ret = &(mono_class_from_name (
3612 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3613 csig->params [0] = &mono_defaults.string_class->byval_arg;
3614 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3615 add_method (acfg, get_runtime_invoke_sig (csig));
3617 /* runtime-invoke used by finalizers */
3618 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3620 /* This is used by mono_runtime_capture_context () */
3621 method = mono_get_context_capture_method ();
3623 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3625 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3626 if (!acfg->aot_opts.llvm_only)
3627 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3630 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3631 if (acfg->aot_opts.llvm_only) {
3634 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3635 for (variants = 0; variants < 4; ++variants) {
3636 for (i = 0; i < 16; ++i) {
3637 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3638 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3646 add_method (acfg, mono_marshal_get_stelemref ());
3648 if (MONO_ARCH_HAVE_TLS_GET) {
3649 /* Managed Allocators */
3650 nallocators = mono_gc_get_managed_allocator_types ();
3651 for (i = 0; i < nallocators; ++i) {
3652 m = mono_gc_get_managed_allocator_by_type (i, TRUE);
3654 add_method (acfg, m);
3656 for (i = 0; i < nallocators; ++i) {
3657 m = mono_gc_get_managed_allocator_by_type (i, FALSE);
3659 add_method (acfg, m);
3663 /* write barriers */
3664 if (mono_gc_is_moving ()) {
3665 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3666 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3669 /* Stelemref wrappers */
3671 MonoMethod **wrappers;
3674 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3675 for (i = 0; i < nwrappers; ++i)
3676 add_method (acfg, wrappers [i]);
3680 /* castclass_with_check wrapper */
3681 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3682 /* isinst_with_check wrapper */
3683 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3685 /* JIT icall wrappers */
3686 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3687 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3691 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3692 * we use the original method instead at runtime.
3693 * Since full-aot doesn't support remoting, this is not a problem.
3696 /* remoting-invoke wrappers */
3697 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3699 MonoMethodSignature *sig;
3701 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3702 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3703 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3705 sig = mono_method_signature (method);
3707 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3708 m = mono_marshal_get_remoting_invoke_with_check (method);
3710 add_method (acfg, m);
3715 /* delegate-invoke wrappers */
3716 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3719 MonoCustomAttrInfo *cattr;
3721 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3722 klass = mono_class_get_checked (acfg->image, token, &error);
3725 mono_error_cleanup (&error);
3729 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3732 if (!klass->generic_container) {
3733 method = mono_get_delegate_invoke (klass);
3735 m = mono_marshal_get_delegate_invoke (method, NULL);
3737 add_method (acfg, m);
3739 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3741 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3743 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3745 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3747 cattr = mono_custom_attrs_from_class (klass);
3752 for (j = 0; j < cattr->num_attrs; ++j)
3753 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3755 if (j < cattr->num_attrs) {
3757 MonoMethod *wrapper;
3758 MonoMethod *del_invoke;
3760 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3761 invoke = mono_get_delegate_invoke (klass);
3762 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3763 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3764 add_method (acfg, wrapper);
3765 add_method (acfg, del_invoke);
3768 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3770 MonoGenericContext ctx;
3771 MonoMethod *inst, *gshared;
3774 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3777 method = mono_get_delegate_invoke (klass);
3778 create_gsharedvt_inst (acfg, method, &ctx);
3780 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3781 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3783 m = mono_marshal_get_delegate_invoke (inst, NULL);
3784 g_assert (m->is_inflated);
3786 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3787 add_extra_method (acfg, gshared);
3790 method = mono_get_delegate_begin_invoke (klass);
3791 create_gsharedvt_inst (acfg, method, &ctx);
3793 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3794 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3796 m = mono_marshal_get_delegate_begin_invoke (inst);
3797 g_assert (m->is_inflated);
3799 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3800 add_extra_method (acfg, gshared);
3803 method = mono_get_delegate_end_invoke (klass);
3804 create_gsharedvt_inst (acfg, method, &ctx);
3806 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3807 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3809 m = mono_marshal_get_delegate_end_invoke (inst);
3810 g_assert (m->is_inflated);
3812 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3813 add_extra_method (acfg, gshared);
3818 /* array access wrappers */
3819 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3823 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3824 klass = mono_class_get_checked (acfg->image, token, &error);
3827 mono_error_cleanup (&error);
3831 if (!acfg->aot_opts.llvm_only && klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3832 MonoMethod *m, *wrapper;
3834 /* Add runtime-invoke wrappers too */
3836 m = mono_class_get_method_from_name (klass, "Get", -1);
3838 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3839 add_extra_method (acfg, wrapper);
3840 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
3842 m = mono_class_get_method_from_name (klass, "Set", -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));
3850 /* Synchronized wrappers */
3851 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3853 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3854 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3855 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3857 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3858 if (method->is_generic) {
3860 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3862 MonoGenericContext ctx;
3863 MonoMethod *inst, *gshared, *m;
3866 * Create a generic wrapper for a generic instance, and AOT that.
3868 create_gsharedvt_inst (acfg, method, &ctx);
3869 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3870 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3871 m = mono_marshal_get_synchronized_wrapper (inst);
3872 g_assert (m->is_inflated);
3873 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3874 add_method (acfg, gshared);
3876 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3881 /* pinvoke wrappers */
3882 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3885 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3887 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3888 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3890 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3891 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3892 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3896 /* native-to-managed wrappers */
3897 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3900 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3901 MonoCustomAttrInfo *cattr;
3904 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3905 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3908 * Only generate native-to-managed wrappers for methods which have an
3909 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3910 * name to avoid defining a new assembly to contain it.
3912 cattr = mono_custom_attrs_from_method (method);
3915 for (j = 0; j < cattr->num_attrs; ++j)
3916 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3918 if (j < cattr->num_attrs) {
3919 MonoCustomAttrEntry *e = &cattr->attrs [j];
3920 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3921 const char *p = (const char*)e->data;
3923 int slen, num_named, named_type;
3927 char *export_name = NULL;
3928 MonoMethod *wrapper;
3930 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3931 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3932 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3933 mono_method_full_name (method, TRUE));
3937 g_assert (sig->param_count == 1);
3938 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3941 * Decode the cattr manually since we can't create objects
3942 * during aot compilation.
3948 /* From load_cattr_value () in reflection.c */
3949 slen = mono_metadata_decode_value (p, &p);
3950 n = (char *)g_memdup (p, slen + 1);
3952 t = mono_reflection_type_from_name (n, acfg->image);
3956 klass = mono_class_from_mono_type (t);
3957 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3961 num_named = read16 (p);
3964 g_assert (num_named < 2);
3965 if (num_named == 1) {
3969 /* parse ExportSymbol attribute */
3971 named_type = *named;
3973 /* data_type = *named; */
3976 name_len = mono_metadata_decode_blob_size (named, &named);
3977 name = (char *)g_malloc (name_len + 1);
3978 memcpy (name, named, name_len);
3979 name [name_len] = 0;
3982 g_assert (named_type == 0x54);
3983 g_assert (!strcmp (name, "ExportSymbol"));
3985 /* load_cattr_value (), string case */
3986 g_assert (*named != (char)0xff);
3987 slen = mono_metadata_decode_value (named, &named);
3988 export_name = (char *)g_malloc (slen + 1);
3989 memcpy (export_name, named, slen);
3990 export_name [slen] = 0;
3994 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3995 add_method (acfg, wrapper);
3997 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4001 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4002 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4003 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4007 /* StructureToPtr/PtrToStructure wrappers */
4008 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4012 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4013 klass = mono_class_get_checked (acfg->image, token, &error);
4016 mono_error_cleanup (&error);
4020 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4021 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4022 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4023 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4029 has_type_vars (MonoClass *klass)
4031 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4034 return has_type_vars (klass->element_class);
4035 if (klass->generic_class) {
4036 MonoGenericContext *context = &klass->generic_class->context;
4037 if (context->class_inst) {
4040 for (i = 0; i < context->class_inst->type_argc; ++i)
4041 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4045 if (klass->generic_container)
4051 is_vt_inst (MonoGenericInst *inst)
4055 for (i = 0; i < inst->type_argc; ++i) {
4056 MonoType *t = inst->type_argv [i];
4057 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4064 method_has_type_vars (MonoMethod *method)
4066 if (has_type_vars (method->klass))
4069 if (method->is_inflated) {
4070 MonoGenericContext *context = mono_method_get_context (method);
4071 if (context->method_inst) {
4074 for (i = 0; i < context->method_inst->type_argc; ++i)
4075 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4083 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4085 return opts->mode == MONO_AOT_MODE_FULL;
4088 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4091 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4093 /* This might lead to a huge code blowup so only do it if neccesary */
4094 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4097 add_generic_class_with_depth (acfg, klass, 0, ref);
4101 check_type_depth (MonoType *t, int depth)
4109 case MONO_TYPE_GENERICINST: {
4110 MonoGenericClass *gklass = t->data.generic_class;
4111 MonoGenericInst *ginst = gklass->context.class_inst;
4114 for (i = 0; i < ginst->type_argc; ++i) {
4115 if (check_type_depth (ginst->type_argv [i], depth + 1))
4129 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4132 * add_generic_class:
4134 * Add all methods of a generic class.
4137 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4140 MonoClassField *field;
4142 gboolean use_gsharedvt = FALSE;
4144 if (!acfg->ginst_hash)
4145 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4147 mono_class_init (klass);
4149 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4152 if (has_type_vars (klass))
4155 if (!klass->generic_class && !klass->rank)
4158 if (klass->exception_type)
4161 if (!acfg->ginst_hash)
4162 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4164 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4167 if (check_type_depth (&klass->byval_arg, 0))
4170 if (acfg->aot_opts.log_generics)
4171 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4173 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4176 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4177 * Enable this only for some classes since gsharedvt might not support all methods.
4179 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) &&
4180 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4181 use_gsharedvt = TRUE;
4184 while ((method = mono_class_get_methods (klass, &iter))) {
4185 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4187 * This is partial sharing, and we can't handle it yet
4192 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4194 add_types_from_method_header (acfg, method);
4198 if (method->is_generic)
4203 * FIXME: Instances which are referenced by these methods are not added,
4204 * for example Array.Resize<int> for List<int>.Add ().
4206 add_extra_method_with_depth (acfg, method, depth + 1);
4210 while ((field = mono_class_get_fields (klass, &iter))) {
4211 if (field->type->type == MONO_TYPE_GENERICINST)
4212 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4215 if (klass->delegate) {
4216 method = mono_get_delegate_invoke (klass);
4218 method = mono_marshal_get_delegate_invoke (method, NULL);
4220 if (acfg->aot_opts.log_generics)
4221 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4223 add_method (acfg, method);
4226 /* Add superclasses */
4228 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4231 * For ICollection<T>, add instances of the helper methods
4232 * in Array, since a T[] could be cast to ICollection<T>.
4234 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4235 (!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"))) {
4236 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4237 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4241 if (!strcmp (klass->name, "IEnumerator`1"))
4242 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4244 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4246 /* Add the T[]/InternalEnumerator class */
4247 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4251 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4252 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4256 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4257 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4261 while ((method = mono_class_get_methods (array_class, &iter))) {
4262 if (strstr (method->name, name_prefix)) {
4263 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4265 add_extra_method_with_depth (acfg, m, depth);
4269 g_free (name_prefix);
4272 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4273 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4274 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4275 MonoClass *icomparable, *gcomparer;
4276 MonoGenericContext ctx;
4277 MonoType *args [16];
4279 memset (&ctx, 0, sizeof (ctx));
4281 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4282 g_assert (icomparable);
4283 args [0] = &tclass->byval_arg;
4284 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4286 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4287 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4288 g_assert (gcomparer);
4289 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4293 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4294 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4295 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4296 MonoClass *iface, *gcomparer;
4297 MonoGenericContext ctx;
4298 MonoType *args [16];
4300 memset (&ctx, 0, sizeof (ctx));
4302 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4304 args [0] = &tclass->byval_arg;
4305 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4307 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4308 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4309 g_assert (gcomparer);
4310 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4314 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4315 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4316 MonoClass *enum_comparer;
4317 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4318 MonoGenericContext ctx;
4319 MonoType *args [16];
4321 if (mono_class_is_enum (tclass)) {
4322 memset (&ctx, 0, sizeof (ctx));
4323 args [0] = &tclass->byval_arg;
4324 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4326 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4327 g_assert (enum_comparer);
4328 add_generic_class (acfg, mono_class_inflate_generic_class (enum_comparer, &ctx), FALSE, "EqualityComparer<T>");
4332 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4333 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4334 MonoClass *comparer;
4335 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4336 MonoGenericContext ctx;
4337 MonoType *args [16];
4339 if (mono_class_is_enum (tclass)) {
4340 memset (&ctx, 0, sizeof (ctx));
4341 args [0] = &tclass->byval_arg;
4342 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4344 comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4345 g_assert (comparer);
4346 add_generic_class (acfg, mono_class_inflate_generic_class (comparer, &ctx), FALSE, "Comparer<T>");
4352 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4355 MonoGenericContext ctx;
4356 MonoType *args [16];
4358 if (acfg->aot_opts.no_instances)
4361 memset (&ctx, 0, sizeof (ctx));
4363 for (i = 0; i < ninsts; ++i) {
4364 args [0] = insts [i];
4365 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4366 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4371 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4373 MonoMethodHeader *header;
4374 MonoMethodSignature *sig;
4377 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4379 sig = mono_method_signature (method);
4382 for (j = 0; j < sig->param_count; ++j)
4383 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4384 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4387 header = mono_method_get_header (method);
4390 for (j = 0; j < header->num_locals; ++j)
4391 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4392 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4394 mono_loader_clear_error ();
4399 * add_generic_instances:
4401 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4404 add_generic_instances (MonoAotCompile *acfg)
4409 MonoGenericContext *context;
4411 if (acfg->aot_opts.no_instances)
4414 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4416 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4417 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4420 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4421 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4422 mono_error_cleanup (&error);
4426 if (method->klass->image != acfg->image)
4429 context = mono_method_get_context (method);
4431 if (context && ((context->class_inst && context->class_inst->is_open)))
4435 * For open methods, create an instantiation which can be passed to the JIT.
4436 * FIXME: Handle class_inst as well.
4438 if (context && context->method_inst && context->method_inst->is_open) {
4440 MonoGenericContext shared_context;
4441 MonoGenericInst *inst;
4442 MonoType **type_argv;
4444 MonoMethod *declaring_method;
4445 gboolean supported = TRUE;
4447 /* Check that the context doesn't contain open constructed types */
4448 if (context->class_inst) {
4449 inst = context->class_inst;
4450 for (i = 0; i < inst->type_argc; ++i) {
4451 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)
4453 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4457 if (context->method_inst) {
4458 inst = context->method_inst;
4459 for (i = 0; i < inst->type_argc; ++i) {
4460 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)
4462 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4470 memset (&shared_context, 0, sizeof (MonoGenericContext));
4472 inst = context->class_inst;
4474 type_argv = g_new0 (MonoType*, inst->type_argc);
4475 for (i = 0; i < inst->type_argc; ++i) {
4476 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)
4477 type_argv [i] = &mono_defaults.object_class->byval_arg;
4479 type_argv [i] = inst->type_argv [i];
4482 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4486 inst = context->method_inst;
4488 type_argv = g_new0 (MonoType*, inst->type_argc);
4489 for (i = 0; i < inst->type_argc; ++i) {
4490 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)
4491 type_argv [i] = &mono_defaults.object_class->byval_arg;
4493 type_argv [i] = inst->type_argv [i];
4496 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4500 if (method->is_generic || method->klass->generic_container)
4501 declaring_method = method;
4503 declaring_method = mono_method_get_declaring_generic_method (method);
4505 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4506 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4510 * If the method is fully sharable, it was already added in place of its
4511 * generic definition.
4513 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4517 * FIXME: Partially shared methods are not shared here, so we end up with
4518 * many identical methods.
4520 add_extra_method (acfg, method);
4523 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4527 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4529 klass = mono_class_get_checked (acfg->image, token, &error);
4530 if (!klass || klass->rank) {
4531 mono_error_cleanup (&error);
4535 add_generic_class (acfg, klass, FALSE, "typespec");
4538 /* Add types of args/locals */
4539 for (i = 0; i < acfg->methods->len; ++i) {
4540 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4541 add_types_from_method_header (acfg, method);
4544 if (acfg->image == mono_defaults.corlib) {
4546 MonoType *insts [256];
4549 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4550 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4551 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4552 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4553 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4554 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4555 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4556 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4557 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4558 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4559 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4560 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4562 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4563 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4565 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4566 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4568 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4570 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4572 MonoClass *enum_comparer;
4573 MonoType *insts [16];
4577 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4578 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4579 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4580 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4581 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4582 g_assert (enum_comparer);
4583 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4586 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4587 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4588 g_assert (enum_comparer);
4589 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4592 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4593 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4594 g_assert (enum_comparer);
4595 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4597 enum_comparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4598 g_assert (enum_comparer);
4600 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4601 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4602 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4605 /* Add instances of the array generic interfaces for primitive types */
4606 /* This will add instances of the InternalArray_ helper methods in Array too */
4607 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4609 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4610 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4612 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4613 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4615 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4618 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4619 * used for all instances of GetGenericValueImpl by the AOT runtime.
4622 MonoGenericContext ctx;
4623 MonoType *args [16];
4624 MonoMethod *get_method;
4625 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4627 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4631 memset (&ctx, 0, sizeof (ctx));
4632 args [0] = &mono_defaults.object_class->byval_arg;
4633 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4634 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4635 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4639 /* Same for CompareExchange<T>/Exchange<T> */
4641 MonoGenericContext ctx;
4642 MonoType *args [16];
4644 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4645 gpointer iter = NULL;
4647 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4648 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4650 memset (&ctx, 0, sizeof (ctx));
4651 args [0] = &mono_defaults.object_class->byval_arg;
4652 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4653 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4654 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4659 /* Same for Volatile.Read/Write<T> */
4661 MonoGenericContext ctx;
4662 MonoType *args [16];
4664 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4665 gpointer iter = NULL;
4667 if (volatile_klass) {
4668 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4669 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
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 (m, &ctx, &error), TRUE, TRUE));
4675 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4681 /* object[] accessor wrappers. */
4683 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, 1);
4686 m = mono_class_get_method_from_name (obj_array_class, "Get", 1);
4689 m = mono_marshal_get_array_accessor_wrapper (m);
4690 add_extra_method (acfg, m);
4692 m = mono_class_get_method_from_name (obj_array_class, "Address", 1);
4695 m = mono_marshal_get_array_accessor_wrapper (m);
4696 add_extra_method (acfg, m);
4698 m = mono_class_get_method_from_name (obj_array_class, "Set", 2);
4701 m = mono_marshal_get_array_accessor_wrapper (m);
4702 add_extra_method (acfg, m);
4708 * is_direct_callable:
4710 * Return whenever the method identified by JI is directly callable without
4711 * going through the PLT.
4714 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4716 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4717 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4719 gboolean direct_callable = TRUE;
4721 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4722 direct_callable = FALSE;
4723 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4724 // FIXME: Maybe call the wrapper directly ?
4725 direct_callable = FALSE;
4727 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4728 /* Disable this so all calls go through load_method (), see the
4729 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4730 * mono_debugger_agent_init ().
4732 direct_callable = FALSE;
4735 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4736 /* sgen does some initialization when the allocator method is created */
4737 direct_callable = FALSE;
4738 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4739 /* we don't know at compile time whether sgen is concurrent or not */
4740 direct_callable = FALSE;
4742 if (direct_callable)
4745 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4746 if (acfg->aot_opts.direct_pinvoke)
4748 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4749 if (acfg->aot_opts.direct_icalls)
4757 #ifdef MONO_ARCH_AOT_SUPPORTED
4759 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4761 MonoImage *image = method->klass->image;
4762 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4763 MonoTableInfo *tables = image->tables;
4764 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4765 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4766 guint32 im_cols [MONO_IMPLMAP_SIZE];
4769 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4773 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4776 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4778 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4781 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4783 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4790 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4792 if (a->native_offset == b->native_offset)
4793 return a->il_offset - b->il_offset;
4795 return a->native_offset - b->native_offset;
4799 * compute_line_numbers:
4801 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4804 static MonoDebugSourceLocation**
4805 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4807 MonoDebugMethodInfo *minfo;
4808 MonoDebugLineNumberEntry *ln_array;
4809 MonoDebugSourceLocation *loc;
4810 int i, prev_line, prev_il_offset;
4811 int *native_to_il_offset = NULL;
4812 MonoDebugSourceLocation **res;
4815 minfo = mono_debug_lookup_method (method);
4818 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4819 if (debug_info->code_size != code_size)
4822 g_assert (code_size);
4824 /* Compute the native->IL offset mapping */
4826 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4827 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4829 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
4831 native_to_il_offset = g_new0 (int, code_size + 1);
4833 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4835 MonoDebugLineNumberEntry *lne = &ln_array [i];
4838 for (j = 0; j < lne->native_offset; ++j)
4839 native_to_il_offset [j] = -1;
4842 if (i < debug_info->num_line_numbers - 1) {
4843 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4845 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4846 native_to_il_offset [j] = lne->il_offset;
4848 for (j = lne->native_offset; j < code_size; ++j)
4849 native_to_il_offset [j] = lne->il_offset;
4854 /* Compute the native->line number mapping */
4855 res = g_new0 (MonoDebugSourceLocation*, code_size);
4856 prev_il_offset = -1;
4859 for (i = 0; i < code_size; ++i) {
4860 int il_offset = native_to_il_offset [i];
4862 if (il_offset == -1 || il_offset == prev_il_offset)
4864 prev_il_offset = il_offset;
4865 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4866 if (!(loc && loc->source_file))
4868 if (loc->row == prev_line) {
4869 mono_debug_symfile_free_location (loc);
4872 prev_line = loc->row;
4873 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4875 /* This will cover the prolog too */
4885 get_file_index (MonoAotCompile *acfg, const char *source_file)
4889 // FIXME: Free these
4890 if (!acfg->dwarf_ln_filenames)
4891 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4892 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4894 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4895 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4896 emit_unset_mode (acfg);
4897 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4909 * emit_and_reloc_code:
4911 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4912 * is true, calls are made through the GOT too. This is used for emitting trampolines
4913 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4914 * since trampolines are needed to make PTL work.
4917 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4919 int i, pindex, start_index;
4921 MonoJumpInfo *patch_info;
4922 MonoDebugSourceLocation **locs = NULL;
4924 #ifdef MONO_ARCH_AOT_SUPPORTED
4925 gboolean direct_call, external_call;
4927 const char *direct_call_target = 0;
4928 const char *direct_pinvoke;
4931 if (acfg->gas_line_numbers && method && debug_info) {
4932 locs = compute_line_numbers (method, code_len, debug_info);
4934 int findex = get_file_index (acfg, "<unknown>");
4935 emit_unset_mode (acfg);
4936 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4940 /* Collect and sort relocations */
4941 patches = g_ptr_array_new ();
4942 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4943 g_ptr_array_add (patches, patch_info);
4944 g_ptr_array_sort (patches, compare_patches);
4947 for (i = 0; i < code_len; i += INST_LEN) {
4949 for (pindex = start_index; pindex < patches->len; ++pindex) {
4950 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
4951 if (patch_info->ip.i >= i)
4955 if (locs && locs [i]) {
4956 MonoDebugSourceLocation *loc = locs [i];
4959 findex = get_file_index (acfg, loc->source_file);
4960 emit_unset_mode (acfg);
4961 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4962 mono_debug_symfile_free_location (loc);
4966 #ifdef MONO_ARCH_AOT_SUPPORTED
4967 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4968 start_index = pindex;
4970 switch (patch_info->type) {
4971 case MONO_PATCH_INFO_NONE:
4973 case MONO_PATCH_INFO_GOT_OFFSET: {
4976 arch_emit_got_offset (acfg, code + i, &code_size);
4977 i += code_size - INST_LEN;
4979 patch_info->type = MONO_PATCH_INFO_NONE;
4982 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4983 int code_size, index;
4984 char *selector = (char *)patch_info->data.target;
4986 if (!acfg->objc_selector_to_index)
4987 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4988 if (!acfg->objc_selectors)
4989 acfg->objc_selectors = g_ptr_array_new ();
4990 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4994 index = acfg->objc_selector_index;
4995 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4996 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4997 acfg->objc_selector_index ++;
5000 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5001 i += code_size - INST_LEN;
5003 patch_info->type = MONO_PATCH_INFO_NONE;
5008 * If this patch is a call, try emitting a direct call instead of
5009 * through a PLT entry. This is possible if the called method is in
5010 * the same assembly and requires no initialization.
5012 direct_call = FALSE;
5013 external_call = FALSE;
5014 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5015 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5016 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5017 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5019 direct_call_target = callee_cfg->asm_symbol;
5020 patch_info->type = MONO_PATCH_INFO_NONE;
5021 acfg->stats.direct_calls ++;
5024 acfg->stats.all_calls ++;
5025 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
5026 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5027 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5028 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5030 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5031 if (direct_pinvoke) {
5033 g_assert (strlen (direct_pinvoke) < 1000);
5034 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5037 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5038 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5039 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5040 /* Call to a C function implementing a jit icall */
5042 external_call = TRUE;
5043 g_assert (strlen (sym) < 1000);
5044 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5046 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5047 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5048 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5049 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5050 /* Call to a jit icall without a wrapper */
5052 external_call = TRUE;
5053 g_assert (strlen (sym) < 1000);
5054 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5059 patch_info->type = MONO_PATCH_INFO_NONE;
5060 acfg->stats.direct_calls ++;
5063 if (!got_only && !direct_call) {
5064 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5066 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5068 direct_call_target = plt_entry->symbol;
5070 /* Nullify the patch */
5071 patch_info->type = MONO_PATCH_INFO_NONE;
5072 plt_entry->jit_used = TRUE;
5079 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5080 i += call_size - INST_LEN;
5084 got_slot = get_got_offset (acfg, FALSE, patch_info);
5086 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5087 i += code_size - INST_LEN;
5093 #endif /* MONO_ARCH_AOT_SUPPORTED */
5096 /* Find next patch */
5098 for (pindex = start_index; pindex < patches->len; ++pindex) {
5099 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5100 if (patch_info->ip.i >= i)
5104 /* Try to emit multiple bytes at once */
5105 if (pindex < patches->len && patch_info->ip.i > i) {
5108 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5109 if (locs && locs [limit])
5113 emit_code_bytes (acfg, code + i, limit - i);
5114 i = limit - INST_LEN;
5116 emit_code_bytes (acfg, code + i, INST_LEN);
5127 * Return a modified version of S which only includes characters permissible in symbols.
5130 sanitize_symbol (MonoAotCompile *acfg, char *s)
5132 gboolean process = FALSE;
5141 for (i = 0; i < len; ++i)
5142 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5147 gs = g_string_sized_new (len);
5148 for (i = 0; i < len; ++i) {
5150 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5151 g_string_append_c (gs, c);
5152 } else if (c > 0x7f) {
5153 /* multi-byte utf8 */
5154 g_string_append_printf (gs, "_0x%x", c);
5157 while (c >> 6 == 0x2) {
5158 g_string_append_printf (gs, "%x", c);
5162 g_string_append_printf (gs, "_");
5165 g_string_append_c (gs, '_');
5169 res = mono_mempool_strdup (acfg->mempool, gs->str);
5170 g_string_free (gs, TRUE);
5175 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5177 char *name1, *name2, *cached;
5178 int i, j, len, count;
5179 MonoMethod *cached_method;
5181 name1 = mono_method_full_name (method, TRUE);
5184 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5185 if ((!prefix || !*prefix) && name1 [0] == 'L')
5189 len = strlen (name1);
5190 name2 = (char *)malloc (strlen (prefix) + len + 16);
5191 memcpy (name2, prefix, strlen (prefix));
5192 j = strlen (prefix);
5193 for (i = 0; i < len; ++i) {
5194 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5196 } else if (isalnum (name1 [i])) {
5197 name2 [j ++] = name1 [i];
5198 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5200 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5203 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5213 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5214 if (!(cached_method && cached_method != method))
5216 sprintf (name2 + j, "_%d", count);
5220 cached = g_strdup (name2);
5221 g_hash_table_insert (cache, cached, method);
5227 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5232 char *debug_sym = NULL;
5233 char *symbol = NULL;
5234 int func_alignment = AOT_FUNC_ALIGNMENT;
5237 method = cfg->orig_method;
5238 code = cfg->native_code;
5240 method_index = get_method_index (acfg, method);
5241 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5243 /* Make the labels local */
5244 emit_section_change (acfg, ".text", 0);
5245 emit_alignment_code (acfg, func_alignment);
5247 if (acfg->global_symbols && acfg->need_no_dead_strip)
5248 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5250 emit_label (acfg, cfg->asm_symbol);
5252 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5254 * Write a C style symbol for every method, this has two uses:
5255 * - it works on platforms where the dwarf debugging info is not
5257 * - it allows the setting of breakpoints of aot-ed methods.
5259 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5260 cfg->asm_debug_symbol = g_strdup (debug_sym);
5262 if (acfg->need_no_dead_strip)
5263 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5264 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5265 emit_label (acfg, debug_sym);
5268 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5270 /* Emit a global symbol for the method */
5271 emit_global_inner (acfg, export_name, TRUE);
5272 emit_label (acfg, export_name);
5275 if (cfg->verbose_level > 0)
5276 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5278 acfg->stats.code_size += cfg->code_len;
5280 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5282 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 ()));
5286 if (acfg->aot_opts.write_symbols) {
5288 emit_symbol_size (acfg, debug_sym, ".");
5290 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5294 emit_label (acfg, symbol);
5301 * Encode PATCH_INFO into its disk representation.
5304 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5308 switch (patch_info->type) {
5309 case MONO_PATCH_INFO_NONE:
5311 case MONO_PATCH_INFO_IMAGE:
5312 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5314 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5315 case MONO_PATCH_INFO_JIT_TLS_ID:
5316 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5317 case MONO_PATCH_INFO_GC_NURSERY_START:
5318 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5320 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5321 encode_value (patch_info->data.index, p, &p);
5323 case MONO_PATCH_INFO_METHOD_REL:
5324 encode_value ((gint)patch_info->data.offset, p, &p);
5326 case MONO_PATCH_INFO_SWITCH: {
5327 gpointer *table = (gpointer *)patch_info->data.table->table;
5330 encode_value (patch_info->data.table->table_size, p, &p);
5331 for (k = 0; k < patch_info->data.table->table_size; k++)
5332 encode_value ((int)(gssize)table [k], p, &p);
5335 case MONO_PATCH_INFO_METHODCONST:
5336 case MONO_PATCH_INFO_METHOD:
5337 case MONO_PATCH_INFO_METHOD_JUMP:
5338 case MONO_PATCH_INFO_ICALL_ADDR:
5339 case MONO_PATCH_INFO_METHOD_RGCTX:
5340 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5341 encode_method_ref (acfg, patch_info->data.method, p, &p);
5343 case MONO_PATCH_INFO_AOT_JIT_INFO:
5344 encode_value (patch_info->data.index, p, &p);
5346 case MONO_PATCH_INFO_INTERNAL_METHOD:
5347 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5348 guint32 len = strlen (patch_info->data.name);
5350 encode_value (len, p, &p);
5352 memcpy (p, patch_info->data.name, len);
5357 case MONO_PATCH_INFO_LDSTR: {
5358 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5359 guint32 token = patch_info->data.token->token;
5360 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5361 encode_value (image_index, p, &p);
5362 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5365 case MONO_PATCH_INFO_RVA:
5366 case MONO_PATCH_INFO_DECLSEC:
5367 case MONO_PATCH_INFO_LDTOKEN:
5368 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5369 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5370 encode_value (patch_info->data.token->token, p, &p);
5371 encode_value (patch_info->data.token->has_context, p, &p);
5372 if (patch_info->data.token->has_context)
5373 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5375 case MONO_PATCH_INFO_EXC_NAME: {
5376 MonoClass *ex_class;
5379 mono_class_from_name (mono_defaults.exception_class->image,
5380 "System", (const char *)patch_info->data.target);
5381 g_assert (ex_class);
5382 encode_klass_ref (acfg, ex_class, p, &p);
5385 case MONO_PATCH_INFO_R4:
5386 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5388 case MONO_PATCH_INFO_R8:
5389 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5390 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5392 case MONO_PATCH_INFO_VTABLE:
5393 case MONO_PATCH_INFO_CLASS:
5394 case MONO_PATCH_INFO_IID:
5395 case MONO_PATCH_INFO_ADJUSTED_IID:
5396 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5398 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5399 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5400 if (patch_info->data.del_tramp->method) {
5401 encode_value (1, p, &p);
5402 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5404 encode_value (0, p, &p);
5406 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5408 case MONO_PATCH_INFO_FIELD:
5409 case MONO_PATCH_INFO_SFLDA:
5410 encode_field_info (acfg, patch_info->data.field, p, &p);
5412 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5414 case MONO_PATCH_INFO_RGCTX_FETCH:
5415 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5416 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5421 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5422 * reference the same method, so encode the method only once.
5424 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5426 buf2 = (guint8 *)g_malloc (1024);
5429 encode_method_ref (acfg, entry->method, p2, &p2);
5430 g_assert (p2 - buf2 < 1024);
5432 offset = add_to_blob (acfg, buf2, p2 - buf2);
5435 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5440 encode_value (offset, p, &p);
5441 g_assert ((int)entry->info_type < 256);
5442 g_assert (entry->data->type < 256);
5443 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5444 encode_patch (acfg, entry->data, p, &p);
5447 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5448 case MONO_PATCH_INFO_AOT_MODULE:
5450 case MONO_PATCH_INFO_SIGNATURE:
5451 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5452 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5454 case MONO_PATCH_INFO_TLS_OFFSET:
5455 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5457 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5458 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5459 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5461 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5462 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5465 encode_method_ref (acfg, info->method, p, &p);
5466 encode_value (info->num_entries, p, &p);
5467 for (i = 0; i < info->num_entries; ++i) {
5468 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5470 encode_value (template_->info_type, p, &p);
5471 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5472 case MONO_PATCH_INFO_CLASS:
5473 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5475 case MONO_PATCH_INFO_FIELD:
5476 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5479 g_assert_not_reached ();
5485 case MONO_PATCH_INFO_LDSTR_LIT: {
5486 const char *s = (const char *)patch_info->data.target;
5487 int len = strlen (s);
5489 encode_value (len, p, &p);
5490 memcpy (p, s, len + 1);
5494 case MONO_PATCH_INFO_VIRT_METHOD:
5495 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5496 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5498 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5501 g_warning ("unable to handle jump info %d", patch_info->type);
5502 g_assert_not_reached ();
5509 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5512 guint32 pindex, offset;
5513 MonoJumpInfo *patch_info;
5515 encode_value (n_patches, p, &p);
5517 for (pindex = 0; pindex < patches->len; ++pindex) {
5518 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5520 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5524 offset = get_got_offset (acfg, llvm, patch_info);
5525 encode_value (offset, p, &p);
5532 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5535 int pindex, buf_size, n_patches;
5537 MonoJumpInfo *patch_info;
5538 guint32 method_index;
5540 guint32 first_got_offset;
5542 method = cfg->orig_method;
5544 method_index = get_method_index (acfg, method);
5546 /* Sort relocations */
5547 patches = g_ptr_array_new ();
5548 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5549 g_ptr_array_add (patches, patch_info);
5550 g_ptr_array_sort (patches, compare_patches);
5552 first_got_offset = acfg->cfgs [method_index]->got_offset;
5554 /**********************/
5555 /* Encode method info */
5556 /**********************/
5558 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5559 p = buf = (guint8 *)g_malloc (buf_size);
5561 if (mono_class_get_cctor (method->klass))
5562 encode_klass_ref (acfg, method->klass, p, &p);
5564 /* Not needed when loading the method */
5565 encode_value (0, p, &p);
5567 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5570 for (pindex = 0; pindex < patches->len; ++pindex) {
5571 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5573 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5574 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5575 patch_info->type = MONO_PATCH_INFO_NONE;
5580 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5581 /* Stored in a GOT slot initialized at module load time */
5582 patch_info->type = MONO_PATCH_INFO_NONE;
5586 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5587 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5588 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5589 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5590 /* Stored in a GOT slot initialized at module load time */
5591 patch_info->type = MONO_PATCH_INFO_NONE;
5595 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5596 /* Calls are made through the PLT */
5597 patch_info->type = MONO_PATCH_INFO_NONE;
5605 g_assert (cfg->has_got_slots);
5607 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5609 acfg->stats.info_size += p - buf;
5611 g_assert (p - buf < buf_size);
5613 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5618 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5620 guint32 cache_index;
5623 /* Reuse the unwind module to canonize and store unwind info entries */
5624 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5626 /* Use +/- 1 to distinguish 0s from missing entries */
5627 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5635 * It would be easier to use assembler symbols, but the caller needs an
5638 offset = acfg->unwind_info_offset;
5639 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5640 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5643 encode_value (encoded_len, p, &p);
5645 acfg->unwind_info_offset += encoded_len + (p - buf);
5651 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5654 guint32 debug_info_size, seq_points_size;
5656 MonoMethodHeader *header;
5657 guint8 *p, *buf, *debug_info;
5658 MonoJitInfo *jinfo = cfg->jit_info;
5660 gboolean use_unwind_ops = FALSE;
5661 MonoSeqPointInfo *seq_points;
5663 code = cfg->native_code;
5664 header = cfg->header;
5666 if (!acfg->aot_opts.nodebug) {
5667 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5670 debug_info_size = 0;
5673 seq_points = cfg->seq_point_info;
5674 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5676 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5678 p = buf = (guint8 *)g_malloc (buf_size);
5680 use_unwind_ops = cfg->unwind_ops != NULL;
5682 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);
5684 encode_value (flags, p, &p);
5686 if (use_unwind_ops) {
5687 guint32 encoded_len;
5689 guint32 unwind_desc;
5691 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5693 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5694 encode_value (unwind_desc, p, &p);
5696 encode_value (jinfo->unwind_info, p, &p);
5699 /*Encode the number of holes before the number of clauses to make decoding easier*/
5700 if (jinfo->has_try_block_holes) {
5701 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5702 encode_value (table->num_holes, p, &p);
5705 if (jinfo->has_arch_eh_info) {
5707 * In AOT mode, the code length is calculated from the address of the previous method,
5708 * which could include alignment padding, so calculating the start of the epilog as
5709 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5711 encode_value (jinfo->code_size, p, &p);
5714 /* Exception table */
5715 if (cfg->compile_llvm) {
5717 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5718 * since the information is only available to llc. Instead, we let llc save the data
5719 * into the LSDA, and read it from there at runtime.
5721 /* The assembly might be CIL stripped so emit the data ourselves */
5722 if (header->num_clauses)
5723 encode_value (header->num_clauses, p, &p);
5725 for (k = 0; k < header->num_clauses; ++k) {
5726 MonoExceptionClause *clause;
5728 clause = &header->clauses [k];
5730 encode_value (clause->flags, p, &p);
5731 if (clause->data.catch_class) {
5732 encode_value (1, p, &p);
5733 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5735 encode_value (0, p, &p);
5738 /* Emit the IL ranges too, since they might not be available at runtime */
5739 encode_value (clause->try_offset, p, &p);
5740 encode_value (clause->try_len, p, &p);
5741 encode_value (clause->handler_offset, p, &p);
5742 encode_value (clause->handler_len, p, &p);
5744 /* Emit a list of nesting clauses */
5745 for (i = 0; i < header->num_clauses; ++i) {
5747 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5749 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5751 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5752 encode_value (i, p, &p);
5754 encode_value (-1, p, &p);
5757 if (jinfo->num_clauses)
5758 encode_value (jinfo->num_clauses, p, &p);
5760 for (k = 0; k < jinfo->num_clauses; ++k) {
5761 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5763 encode_value (ei->flags, p, &p);
5764 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5765 /* Not used for catch clauses */
5766 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5767 encode_value (ei->exvar_offset, p, &p);
5769 encode_value (ei->exvar_offset, p, &p);
5772 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5773 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5775 if (ei->data.catch_class) {
5779 buf2 = (guint8 *)g_malloc (4096);
5781 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5783 g_assert (len < 4096);
5784 encode_value (len, p, &p);
5785 memcpy (p, buf2, len);
5789 encode_value (0, p, &p);
5793 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5794 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5795 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5799 if (jinfo->has_try_block_holes) {
5800 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5801 for (i = 0; i < table->num_holes; ++i) {
5802 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5803 encode_value (hole->clause, p, &p);
5804 encode_value (hole->length, p, &p);
5805 encode_value (hole->offset, p, &p);
5809 if (jinfo->has_arch_eh_info) {
5810 MonoArchEHJitInfo *eh_info;
5812 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5813 encode_value (eh_info->stack_size, p, &p);
5814 encode_value (eh_info->epilog_size, p, &p);
5817 if (jinfo->has_generic_jit_info) {
5818 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5819 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5823 encode_value (gi->nlocs, p, &p);
5825 for (i = 0; i < gi->nlocs; ++i) {
5826 MonoDwarfLocListEntry *entry = &gi->locations [i];
5828 encode_value (entry->is_reg ? 1 : 0, p, &p);
5829 encode_value (entry->reg, p, &p);
5831 encode_value (entry->offset, p, &p);
5833 g_assert (entry->from == 0);
5835 encode_value (entry->from, p, &p);
5836 encode_value (entry->to, p, &p);
5839 if (!cfg->compile_llvm) {
5840 encode_value (gi->has_this ? 1 : 0, p, &p);
5841 encode_value (gi->this_reg, p, &p);
5842 encode_value (gi->this_offset, p, &p);
5847 * Need to encode jinfo->method too, since it is not equal to 'method'
5848 * when using generic sharing.
5850 buf2 = (guint8 *)g_malloc (4096);
5852 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5854 g_assert (len < 4096);
5855 encode_value (len, p, &p);
5856 memcpy (p, buf2, len);
5860 if (gsctx && gsctx->is_gsharedvt) {
5861 encode_value (1, p, &p);
5863 encode_value (0, p, &p);
5867 if (seq_points_size)
5868 p += mono_seq_point_info_write (seq_points, p);
5870 g_assert (debug_info_size < buf_size);
5872 encode_value (debug_info_size, p, &p);
5873 if (debug_info_size) {
5874 memcpy (p, debug_info, debug_info_size);
5875 p += debug_info_size;
5876 g_free (debug_info);
5881 encode_value (cfg->gc_map_size, p, &p);
5882 /* The GC map requires 4 bytes of alignment */
5883 while ((gsize)p % 4)
5885 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5886 p += cfg->gc_map_size;
5889 acfg->stats.ex_info_size += p - buf;
5891 g_assert (p - buf < buf_size);
5894 /* The GC Map requires 4 byte alignment */
5895 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5900 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5903 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5905 int i, buf_size, res;
5906 gboolean no_special_static, cant_encode;
5907 gpointer iter = NULL;
5910 mono_error_cleanup (&error);
5914 p = buf = (guint8 *)g_malloc (buf_size);
5916 /* Mark as unusable */
5917 encode_value (-1, p, &p);
5919 res = add_to_blob (acfg, buf, p - buf);
5925 buf_size = 10240 + (klass->vtable_size * 16);
5926 p = buf = (guint8 *)g_malloc (buf_size);
5930 mono_class_init (klass);
5932 mono_class_get_nested_types (klass, &iter);
5933 g_assert (klass->nested_classes_inited);
5935 mono_class_setup_vtable (klass);
5938 * Emit all the information which is required for creating vtables so
5939 * the runtime does not need to create the MonoMethod structures which
5940 * take up a lot of space.
5943 no_special_static = !mono_class_has_special_static_fields (klass);
5945 /* Check whenever we have enough info to encode the vtable */
5946 cant_encode = FALSE;
5947 for (i = 0; i < klass->vtable_size; ++i) {
5948 MonoMethod *cm = klass->vtable [i];
5950 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5954 mono_class_has_finalizer (klass);
5956 if (klass->generic_container || cant_encode) {
5957 encode_value (-1, p, &p);
5959 encode_value (klass->vtable_size, p, &p);
5960 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);
5961 if (klass->has_cctor)
5962 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5963 if (klass->has_finalize)
5964 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5966 encode_value (klass->instance_size, p, &p);
5967 encode_value (mono_class_data_size (klass), p, &p);
5968 encode_value (klass->packing_size, p, &p);
5969 encode_value (klass->min_align, p, &p);
5971 for (i = 0; i < klass->vtable_size; ++i) {
5972 MonoMethod *cm = klass->vtable [i];
5975 encode_method_ref (acfg, cm, p, &p);
5977 encode_value (0, p, &p);
5981 acfg->stats.class_info_size += p - buf;
5983 g_assert (p - buf < buf_size);
5984 res = add_to_blob (acfg, buf, p - buf);
5991 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5993 char *debug_sym = NULL;
5996 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5997 /* Need to add a prefix to create unique symbols */
5998 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6000 prefix = g_strdup ("plt_");
6004 case MONO_PATCH_INFO_METHOD:
6005 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6007 case MONO_PATCH_INFO_INTERNAL_METHOD:
6008 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6010 case MONO_PATCH_INFO_RGCTX_FETCH:
6011 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6013 case MONO_PATCH_INFO_ICALL_ADDR: {
6014 char *s = get_debug_sym (ji->data.method, "", cache);
6016 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6020 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6021 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6029 return sanitize_symbol (acfg, debug_sym);
6033 * Calls made from AOTed code are routed through a table of jumps similar to the
6034 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6035 * control to the AOT runtime through a trampoline.
6038 emit_plt (MonoAotCompile *acfg)
6042 if (acfg->aot_opts.llvm_only) {
6043 g_assert (acfg->plt_offset == 1);
6049 emit_section_change (acfg, ".text", 0);
6050 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
6051 emit_info_symbol (acfg, "plt");
6052 emit_label (acfg, acfg->plt_symbol);
6054 for (i = 0; i < acfg->plt_offset; ++i) {
6055 char *debug_sym = NULL;
6056 MonoPltEntry *plt_entry = NULL;
6060 * The first plt entry is unused.
6064 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6066 debug_sym = plt_entry->debug_sym;
6068 if (acfg->thumb_mixed && !plt_entry->jit_used)
6069 /* Emit only a thumb version */
6072 /* Skip plt entries not actually called */
6073 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6076 if (acfg->llvm && !acfg->thumb_mixed) {
6077 emit_label (acfg, plt_entry->llvm_symbol);
6079 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6080 #if defined(TARGET_MACH)
6081 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6087 if (acfg->need_no_dead_strip) {
6088 emit_unset_mode (acfg);
6089 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6091 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6092 emit_label (acfg, debug_sym);
6095 emit_label (acfg, plt_entry->symbol);
6097 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6100 emit_symbol_size (acfg, debug_sym, ".");
6103 if (acfg->thumb_mixed) {
6104 /* Make sure the ARM symbols don't alias the thumb ones */
6105 emit_zero_bytes (acfg, 16);
6108 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6111 for (i = 0; i < acfg->plt_offset; ++i) {
6112 char *debug_sym = NULL;
6113 MonoPltEntry *plt_entry = NULL;
6118 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6120 /* Skip plt entries not actually called by LLVM code */
6121 if (!plt_entry->llvm_used)
6124 if (acfg->aot_opts.write_symbols) {
6125 if (plt_entry->debug_sym)
6126 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6130 #if defined(TARGET_MACH)
6131 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6132 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6134 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6135 emit_label (acfg, debug_sym);
6137 fprintf (acfg->fp, "\n.thumb_func\n");
6139 emit_label (acfg, plt_entry->llvm_symbol);
6142 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6144 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6147 emit_symbol_size (acfg, debug_sym, ".");
6153 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6155 emit_info_symbol (acfg, "plt_end");
6159 * emit_trampoline_full:
6161 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6162 * create_jit_info_for_trampoline ().
6164 static G_GNUC_UNUSED void
6165 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6167 char start_symbol [256];
6168 char end_symbol [256];
6170 guint32 buf_size, info_offset;
6171 MonoJumpInfo *patch_info;
6184 code_size = info->code_size;
6186 unwind_ops = info->unwind_ops;
6188 #ifdef __native_client_codegen__
6189 mono_nacl_fix_patches (code, ji);
6194 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6196 emit_section_change (acfg, ".text", 0);
6197 emit_global (acfg, start_symbol, TRUE);
6198 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6199 emit_label (acfg, start_symbol);
6201 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6202 emit_label (acfg, symbol);
6205 * The code should access everything through the GOT, so we pass
6208 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6210 emit_symbol_size (acfg, start_symbol, ".");
6213 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6214 emit_label (acfg, end_symbol);
6219 /* Sort relocations */
6220 patches = g_ptr_array_new ();
6221 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6222 if (patch_info->type != MONO_PATCH_INFO_NONE)
6223 g_ptr_array_add (patches, patch_info);
6224 g_ptr_array_sort (patches, compare_patches);
6226 buf_size = patches->len * 128 + 128;
6227 buf = (guint8 *)g_malloc (buf_size);
6230 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6231 g_assert (p - buf < buf_size);
6233 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6235 info_offset = add_to_blob (acfg, buf, p - buf);
6237 emit_section_change (acfg, RODATA_SECT, 0);
6238 emit_global (acfg, symbol, FALSE);
6239 emit_label (acfg, symbol);
6241 emit_int32 (acfg, info_offset);
6245 guint32 encoded_len;
6249 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6251 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6252 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6255 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6256 emit_int32 (acfg, uw_offset);
6259 /* Emit debug info */
6263 sprintf (symbol, "%s", name);
6264 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6267 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6271 static G_GNUC_UNUSED void
6272 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6274 emit_trampoline_full (acfg, got_offset, info, TRUE);
6278 emit_trampolines (MonoAotCompile *acfg)
6281 char end_symbol [256];
6282 int i, tramp_got_offset;
6284 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6288 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6291 g_assert (acfg->image->assembly);
6293 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6294 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6295 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6296 MonoTrampInfo *info;
6299 * Emit the generic trampolines.
6301 * We could save some code by treating the generic trampolines as a wrapper
6302 * method, but that approach has its own complexities, so we choose the simpler
6305 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6306 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6307 #ifdef DISABLE_REMOTING
6308 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6311 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6312 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6315 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6316 emit_trampoline (acfg, acfg->got_offset, info);
6319 /* Emit the exception related code pieces */
6320 mono_arch_get_restore_context (&info, TRUE);
6321 emit_trampoline (acfg, acfg->got_offset, info);
6322 mono_arch_get_call_filter (&info, TRUE);
6323 emit_trampoline (acfg, acfg->got_offset, info);
6324 mono_arch_get_throw_exception (&info, TRUE);
6325 emit_trampoline (acfg, acfg->got_offset, info);
6326 mono_arch_get_rethrow_exception (&info, TRUE);
6327 emit_trampoline (acfg, acfg->got_offset, info);
6328 mono_arch_get_throw_corlib_exception (&info, TRUE);
6329 emit_trampoline (acfg, acfg->got_offset, info);
6331 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6332 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6333 emit_trampoline (acfg, acfg->got_offset, info);
6334 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6335 emit_trampoline (acfg, acfg->got_offset, info);
6338 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6339 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6341 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6343 /* Create a separate out trampoline for more information in stack traces */
6344 info->name = g_strdup ("gsharedvt_out_trampoline");
6345 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6349 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6351 GSList *l = mono_arch_get_trampolines (TRUE);
6354 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6356 emit_trampoline (acfg, acfg->got_offset, info);
6362 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6365 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6366 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6367 emit_trampoline (acfg, acfg->got_offset, info);
6369 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6370 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6371 emit_trampoline (acfg, acfg->got_offset, info);
6374 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6375 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6376 emit_trampoline (acfg, acfg->got_offset, info);
6382 /* delegate_invoke_impl trampolines */
6383 l = mono_arch_get_delegate_invoke_impls ();
6385 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6387 emit_trampoline (acfg, acfg->got_offset, info);
6392 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6394 /* Emit trampolines which are numerous */
6397 * These include the following:
6398 * - specific trampolines
6399 * - static rgctx invoke trampolines
6401 * These trampolines have the same code, they are parameterized by GOT
6403 * They are defined in this file, in the arch_... routines instead of
6404 * in tramp-<ARCH>.c, since it is easier to do it this way.
6408 * When running in aot-only mode, we can't create specific trampolines at
6409 * runtime, so we create a few, and save them in the AOT file.
6410 * Normal trampolines embed their argument as a literal inside the
6411 * trampoline code, we can't do that here, so instead we embed an offset
6412 * which needs to be added to the trampoline address to get the address of
6413 * the GOT slot which contains the argument value.
6414 * The generated trampolines jump to the generic trampolines using another
6415 * GOT slot, which will be setup by the AOT loader to point to the
6416 * generic trampoline code of the given type.
6420 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6424 emit_section_change (acfg, ".text", 0);
6426 tramp_got_offset = acfg->got_offset;
6428 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6430 case MONO_AOT_TRAMP_SPECIFIC:
6431 sprintf (symbol, "specific_trampolines");
6433 case MONO_AOT_TRAMP_STATIC_RGCTX:
6434 sprintf (symbol, "static_rgctx_trampolines");
6436 case MONO_AOT_TRAMP_IMT_THUNK:
6437 sprintf (symbol, "imt_thunks");
6439 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6440 sprintf (symbol, "gsharedvt_arg_trampolines");
6443 g_assert_not_reached ();
6446 sprintf (end_symbol, "%s_e", symbol);
6448 if (acfg->aot_opts.write_symbols)
6449 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6451 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6452 emit_info_symbol (acfg, symbol);
6454 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6456 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6460 case MONO_AOT_TRAMP_SPECIFIC:
6461 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6462 tramp_got_offset += 2;
6464 case MONO_AOT_TRAMP_STATIC_RGCTX:
6465 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6466 tramp_got_offset += 2;
6468 case MONO_AOT_TRAMP_IMT_THUNK:
6469 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6470 tramp_got_offset += 1;
6472 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6473 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6474 tramp_got_offset += 2;
6477 g_assert_not_reached ();
6479 #ifdef __native_client_codegen__
6480 /* align to avoid 32-byte boundary crossings */
6481 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6484 if (!acfg->trampoline_size [ntype]) {
6485 g_assert (tramp_size);
6486 acfg->trampoline_size [ntype] = tramp_size;
6490 emit_label (acfg, end_symbol);
6491 emit_int32 (acfg, 0);
6494 arch_emit_specific_trampoline_pages (acfg);
6496 /* Reserve some entries at the end of the GOT for our use */
6497 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6500 acfg->got_offset += acfg->num_trampoline_got_entries;
6504 str_begins_with (const char *str1, const char *str2)
6506 int len = strlen (str2);
6507 return strncmp (str1, str2, len) == 0;
6511 mono_aot_readonly_field_override (MonoClassField *field)
6514 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6515 char *p = rdv->name;
6517 len = strlen (field->parent->name_space);
6518 if (strncmp (p, field->parent->name_space, len))
6523 len = strlen (field->parent->name);
6524 if (strncmp (p, field->parent->name, len))
6529 if (strcmp (p, field->name))
6531 switch (rdv->type) {
6533 return &rdv->value.i1;
6535 return &rdv->value.i2;
6537 return &rdv->value.i4;
6546 add_readonly_value (MonoAotOptions *opts, const char *val)
6551 /* the format of val is:
6552 * namespace.typename.fieldname=type/value
6553 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6555 fval = strrchr (val, '/');
6557 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6560 tval = strrchr (val, '=');
6562 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6565 rdv = g_new0 (ReadOnlyValue, 1);
6566 rdv->name = (char *)g_malloc0 (tval - val + 1);
6567 memcpy (rdv->name, val, tval - val);
6570 if (strncmp (tval, "i1", 2) == 0) {
6571 rdv->value.i1 = atoi (fval);
6572 rdv->type = MONO_TYPE_I1;
6573 } else if (strncmp (tval, "i2", 2) == 0) {
6574 rdv->value.i2 = atoi (fval);
6575 rdv->type = MONO_TYPE_I2;
6576 } else if (strncmp (tval, "i4", 2) == 0) {
6577 rdv->value.i4 = atoi (fval);
6578 rdv->type = MONO_TYPE_I4;
6580 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6583 rdv->next = readonly_values;
6584 readonly_values = rdv;
6588 clean_path (gchar * path)
6593 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6596 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6603 mono_aot_split_options (const char *aot_options)
6605 enum MonoAotOptionState {
6606 MONO_AOT_OPTION_STATE_DEFAULT,
6607 MONO_AOT_OPTION_STATE_STRING,
6608 MONO_AOT_OPTION_STATE_ESCAPE,
6611 GPtrArray *args = g_ptr_array_new ();
6612 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6613 gchar const *opt_start = aot_options;
6614 gboolean end_of_string = FALSE;
6617 g_return_val_if_fail (aot_options != NULL, NULL);
6619 while ((cur = *aot_options) != '\0') {
6620 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6625 // If we find a quote, then if we're in the default case then
6626 // it means we've found the start of a string, if not then it
6627 // means we've found the end of the string and should switch
6628 // back to the default case.
6630 case MONO_AOT_OPTION_STATE_DEFAULT:
6631 state = MONO_AOT_OPTION_STATE_STRING;
6633 case MONO_AOT_OPTION_STATE_STRING:
6634 state = MONO_AOT_OPTION_STATE_DEFAULT;
6636 case MONO_AOT_OPTION_STATE_ESCAPE:
6637 g_assert_not_reached ();
6642 // If we've found an escaping operator, then this means we
6643 // should not process the next character if inside a string.
6644 if (state == MONO_AOT_OPTION_STATE_STRING)
6645 state = MONO_AOT_OPTION_STATE_ESCAPE;
6648 // If we're in the default state then this means we've found
6649 // an option, store it for later processing.
6650 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6657 // If the next character is end of string, then process the last option.
6658 if (*(aot_options) == '\0') {
6659 end_of_string = TRUE;
6665 g_ptr_array_add (args, g_strndup (opt_start, aot_options - opt_start));
6666 opt_start = ++aot_options;
6676 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6680 args = mono_aot_split_options (aot_options ? aot_options : "");
6681 for (int i = 0; i < args->len; ++i) {
6682 const char *arg = (const char *)g_ptr_array_index (args, i);
6684 if (str_begins_with (arg, "outfile=")) {
6685 opts->outfile = g_strdup (arg + strlen ("outfile="));
6686 } else if (str_begins_with (arg, "llvm-outfile=")) {
6687 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6688 } else if (str_begins_with (arg, "temp-path=")) {
6689 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
6690 } else if (str_begins_with (arg, "save-temps")) {
6691 opts->save_temps = TRUE;
6692 } else if (str_begins_with (arg, "keep-temps")) {
6693 opts->save_temps = TRUE;
6694 } else if (str_begins_with (arg, "write-symbols")) {
6695 opts->write_symbols = TRUE;
6696 } else if (str_begins_with (arg, "no-write-symbols")) {
6697 opts->write_symbols = FALSE;
6698 } else if (str_begins_with (arg, "metadata-only")) {
6699 opts->metadata_only = TRUE;
6700 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6701 opts->bind_to_runtime_version = TRUE;
6702 } else if (str_begins_with (arg, "full")) {
6703 opts->mode = MONO_AOT_MODE_FULL;
6704 } else if (str_begins_with (arg, "hybrid")) {
6705 opts->mode = MONO_AOT_MODE_HYBRID;
6706 } else if (str_begins_with (arg, "threads=")) {
6707 opts->nthreads = atoi (arg + strlen ("threads="));
6708 } else if (str_begins_with (arg, "static")) {
6709 opts->static_link = TRUE;
6710 opts->no_dlsym = TRUE;
6711 } else if (str_begins_with (arg, "asmonly")) {
6712 opts->asm_only = TRUE;
6713 } else if (str_begins_with (arg, "asmwriter")) {
6714 opts->asm_writer = TRUE;
6715 } else if (str_begins_with (arg, "nodebug")) {
6716 opts->nodebug = TRUE;
6717 } else if (str_begins_with (arg, "dwarfdebug")) {
6718 opts->dwarf_debug = TRUE;
6719 } else if (str_begins_with (arg, "nopagetrampolines")) {
6720 opts->use_trampolines_page = FALSE;
6721 } else if (str_begins_with (arg, "ntrampolines=")) {
6722 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6723 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6724 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6725 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6726 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6727 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6728 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6729 } else if (str_begins_with (arg, "tool-prefix=")) {
6730 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6731 } else if (str_begins_with (arg, "ld-flags=")) {
6732 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6733 } else if (str_begins_with (arg, "soft-debug")) {
6734 opts->soft_debug = TRUE;
6735 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6736 opts->gen_seq_points_file = TRUE;
6737 } else if (str_begins_with (arg, "direct-pinvoke")) {
6738 opts->direct_pinvoke = TRUE;
6739 } else if (str_begins_with (arg, "direct-icalls")) {
6740 opts->direct_icalls = TRUE;
6741 } else if (str_begins_with (arg, "no-direct-calls")) {
6742 opts->no_direct_calls = TRUE;
6743 } else if (str_begins_with (arg, "print-skipped")) {
6744 opts->print_skipped_methods = TRUE;
6745 } else if (str_begins_with (arg, "stats")) {
6747 } else if (str_begins_with (arg, "no-instances")) {
6748 opts->no_instances = TRUE;
6749 } else if (str_begins_with (arg, "log-generics")) {
6750 opts->log_generics = TRUE;
6751 } else if (str_begins_with (arg, "log-instances=")) {
6752 opts->log_instances = TRUE;
6753 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6754 } else if (str_begins_with (arg, "log-instances")) {
6755 opts->log_instances = TRUE;
6756 } else if (str_begins_with (arg, "internal-logfile=")) {
6757 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6758 } else if (str_begins_with (arg, "mtriple=")) {
6759 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6760 } else if (str_begins_with (arg, "llvm-path=")) {
6761 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
6762 } else if (!strcmp (arg, "llvm")) {
6764 } else if (str_begins_with (arg, "readonly-value=")) {
6765 add_readonly_value (opts, arg + strlen ("readonly-value="));
6766 } else if (str_begins_with (arg, "info")) {
6767 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6769 } else if (str_begins_with (arg, "gc-maps")) {
6770 mini_gc_enable_gc_maps_for_aot ();
6771 } else if (str_begins_with (arg, "dump")) {
6772 opts->dump_json = TRUE;
6773 } else if (str_begins_with (arg, "llvmonly")) {
6774 opts->mode = MONO_AOT_MODE_FULL;
6776 opts->llvm_only = TRUE;
6777 } else if (str_begins_with (arg, "data-outfile=")) {
6778 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
6779 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6780 printf ("Supported options for --aot:\n");
6781 printf (" outfile=\n");
6782 printf (" llvm-outfile=\n");
6783 printf (" llvm-path=\n");
6784 printf (" temp-path=\n");
6785 printf (" save-temps\n");
6786 printf (" keep-temps\n");
6787 printf (" write-symbols\n");
6788 printf (" metadata-only\n");
6789 printf (" bind-to-runtime-version\n");
6791 printf (" threads=\n");
6792 printf (" static\n");
6793 printf (" asmonly\n");
6794 printf (" asmwriter\n");
6795 printf (" nodebug\n");
6796 printf (" dwarfdebug\n");
6797 printf (" ntrampolines=\n");
6798 printf (" nrgctx-trampolines=\n");
6799 printf (" nimt-trampolines=\n");
6800 printf (" ngsharedvt-trampolines=\n");
6801 printf (" tool-prefix=\n");
6802 printf (" readonly-value=\n");
6803 printf (" soft-debug\n");
6804 printf (" gen-seq-points-file\n");
6805 printf (" gc-maps\n");
6806 printf (" print-skipped\n");
6807 printf (" no-instances\n");
6808 printf (" stats\n");
6811 printf (" help/?\n");
6814 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6818 g_free ((gpointer) arg);
6821 if (opts->use_trampolines_page) {
6822 opts->ntrampolines = 0;
6823 opts->nrgctx_trampolines = 0;
6824 opts->nimt_trampolines = 0;
6825 opts->ngsharedvt_arg_trampolines = 0;
6828 g_ptr_array_free (args, /*free_seg=*/TRUE);
6832 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6834 MonoMethod *method = (MonoMethod*)key;
6835 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6836 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
6837 MonoJumpInfoToken *new_ji;
6839 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6840 new_ji->image = ji->image;
6841 new_ji->token = ji->token;
6842 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6846 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6848 if (klass->type_token)
6850 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6853 return can_encode_class (acfg, klass->element_class);
6858 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6860 if (method->wrapper_type) {
6861 switch (method->wrapper_type) {
6862 case MONO_WRAPPER_NONE:
6863 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6864 case MONO_WRAPPER_XDOMAIN_INVOKE:
6865 case MONO_WRAPPER_STFLD:
6866 case MONO_WRAPPER_LDFLD:
6867 case MONO_WRAPPER_LDFLDA:
6868 case MONO_WRAPPER_LDFLD_REMOTE:
6869 case MONO_WRAPPER_STFLD_REMOTE:
6870 case MONO_WRAPPER_STELEMREF:
6871 case MONO_WRAPPER_ISINST:
6872 case MONO_WRAPPER_PROXY_ISINST:
6873 case MONO_WRAPPER_ALLOC:
6874 case MONO_WRAPPER_REMOTING_INVOKE:
6875 case MONO_WRAPPER_UNKNOWN:
6876 case MONO_WRAPPER_WRITE_BARRIER:
6877 case MONO_WRAPPER_DELEGATE_INVOKE:
6878 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6879 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6880 case MONO_WRAPPER_SYNCHRONIZED:
6882 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6883 case MONO_WRAPPER_CASTCLASS: {
6884 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6893 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6897 if (!method->token) {
6898 /* The method is part of a constructed type like Int[,].Set (). */
6899 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6900 if (method->klass->rank)
6910 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6912 switch (patch_info->type) {
6913 case MONO_PATCH_INFO_METHOD:
6914 case MONO_PATCH_INFO_METHODCONST:
6915 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6916 MonoMethod *method = patch_info->data.method;
6918 return can_encode_method (acfg, method);
6920 case MONO_PATCH_INFO_VTABLE:
6921 case MONO_PATCH_INFO_CLASS:
6922 case MONO_PATCH_INFO_IID:
6923 case MONO_PATCH_INFO_ADJUSTED_IID:
6924 if (!can_encode_class (acfg, patch_info->data.klass)) {
6925 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6929 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6930 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6931 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6936 case MONO_PATCH_INFO_RGCTX_FETCH:
6937 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6938 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6940 if (!can_encode_method (acfg, entry->method))
6942 if (!can_encode_patch (acfg, entry->data))
6954 is_concrete_type (MonoType *t)
6959 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
6961 if (t->type == MONO_TYPE_GENERICINST) {
6962 MonoGenericContext *orig_ctx;
6963 MonoGenericInst *inst;
6966 if (!MONO_TYPE_ISSTRUCT (t))
6968 klass = mono_class_from_mono_type (t);
6969 orig_ctx = &klass->generic_class->context;
6971 inst = orig_ctx->class_inst;
6973 for (i = 0; i < inst->type_argc; ++i) {
6974 arg = mini_get_underlying_type (inst->type_argv [i]);
6975 if (!is_concrete_type (arg))
6979 inst = orig_ctx->method_inst;
6981 for (i = 0; i < inst->type_argc; ++i) {
6982 arg = mini_get_underlying_type (inst->type_argv [i]);
6983 if (!is_concrete_type (arg))
6991 /* LOCKING: Assumes the loader lock is held */
6993 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
6995 MonoMethod *wrapper;
6996 gboolean concrete = TRUE;
6997 gboolean add_in = gsharedvt_in;
6998 gboolean add_out = gsharedvt_out;
7000 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7002 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7005 if (!add_in && !add_out)
7008 if (mini_is_gsharedvt_variable_signature (sig))
7012 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7014 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7016 if (!sig->has_type_parameters) {
7017 //printf ("%s\n", mono_signature_full_name (sig));
7020 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7021 add_extra_method (acfg, wrapper);
7023 if (gsharedvt_out) {
7024 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7025 add_extra_method (acfg, wrapper);
7028 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7029 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7032 //printf ("%s\n", mono_signature_full_name (sig));
7034 copy->ret = mini_get_underlying_type (sig->ret);
7035 if (!is_concrete_type (copy->ret))
7037 for (i = 0; i < sig->param_count; ++i) {
7038 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7039 if (!is_concrete_type (copy->params [i]))
7043 copy->has_type_parameters = 0;
7046 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7047 add_extra_method (acfg, wrapper);
7050 if (gsharedvt_out) {
7051 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7052 add_extra_method (acfg, wrapper);
7055 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7063 * AOT compile a given method.
7064 * This function might be called by multiple threads, so it must be thread-safe.
7067 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7070 MonoJumpInfo *patch_info;
7073 MonoMethod *wrapped;
7076 if (acfg->aot_opts.metadata_only)
7079 mono_acfg_lock (acfg);
7080 index = get_method_index (acfg, method);
7081 mono_acfg_unlock (acfg);
7083 /* fixme: maybe we can also precompile wrapper methods */
7084 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7085 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7086 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7087 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7091 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7094 wrapped = mono_marshal_method_from_wrapper (method);
7095 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7096 // FIXME: The wrapper should be generic too, but it is not
7099 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7102 InterlockedIncrement (&acfg->stats.mcount);
7105 if (method->is_generic || method->klass->generic_container) {
7106 InterlockedIncrement (&acfg->stats.genericcount);
7111 //acfg->aot_opts.print_skipped_methods = TRUE;
7114 * Since these methods are the only ones which are compiled with
7115 * AOT support, and they are not used by runtime startup/shutdown code,
7116 * the runtime will not see AOT methods during AOT compilation,so it
7117 * does not need to support them by creating a fake GOT etc.
7119 flags = JIT_FLAG_AOT;
7120 if (mono_aot_mode_is_full (&acfg->aot_opts))
7121 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7123 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7124 if (acfg->aot_opts.llvm_only)
7125 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7126 if (acfg->aot_opts.no_direct_calls)
7127 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7128 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7129 mono_loader_clear_error ();
7131 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7132 if (acfg->aot_opts.print_skipped_methods)
7133 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7134 InterlockedIncrement (&acfg->stats.genericcount);
7137 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7138 if (acfg->aot_opts.print_skipped_methods)
7139 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7140 /* Let the exception happen at runtime */
7144 if (cfg->disable_aot) {
7145 if (acfg->aot_opts.print_skipped_methods)
7146 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7147 InterlockedIncrement (&acfg->stats.ocount);
7148 mono_destroy_compile (cfg);
7151 cfg->method_index = index;
7153 /* Nullify patches which need no aot processing */
7154 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7155 switch (patch_info->type) {
7156 case MONO_PATCH_INFO_LABEL:
7157 case MONO_PATCH_INFO_BB:
7158 patch_info->type = MONO_PATCH_INFO_NONE;
7165 /* Collect method->token associations from the cfg */
7166 mono_acfg_lock (acfg);
7167 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7168 mono_acfg_unlock (acfg);
7169 g_hash_table_destroy (cfg->token_info_hash);
7170 cfg->token_info_hash = NULL;
7173 * Check for absolute addresses.
7176 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7177 switch (patch_info->type) {
7178 case MONO_PATCH_INFO_ABS:
7179 /* unable to handle this */
7188 if (acfg->aot_opts.print_skipped_methods)
7189 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7190 InterlockedIncrement (&acfg->stats.abscount);
7191 mono_destroy_compile (cfg);
7195 /* Lock for the rest of the code */
7196 mono_acfg_lock (acfg);
7199 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7200 else if (cfg->gshared)
7201 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7202 else if (cfg->method->wrapper_type)
7203 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7205 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7208 * Check for methods/klasses we can't encode.
7211 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7212 if (!can_encode_patch (acfg, patch_info))
7217 if (acfg->aot_opts.print_skipped_methods)
7218 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7219 acfg->stats.ocount++;
7220 mono_destroy_compile (cfg);
7221 mono_acfg_unlock (acfg);
7225 if (!cfg->compile_llvm)
7226 acfg->has_jitted_code = TRUE;
7228 if (method->is_inflated && acfg->aot_opts.log_instances) {
7229 if (acfg->instances_logfile)
7230 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7232 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7235 /* Adds generic instances referenced by this method */
7237 * The depth is used to avoid infinite loops when generic virtual recursion is
7240 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7241 if (!acfg->aot_opts.no_instances && depth < 32) {
7242 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7243 switch (patch_info->type) {
7244 case MONO_PATCH_INFO_RGCTX_FETCH:
7245 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7246 case MONO_PATCH_INFO_METHOD: {
7247 MonoMethod *m = NULL;
7249 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7250 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7252 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7253 m = e->data->data.method;
7255 m = patch_info->data.method;
7260 if (m->is_inflated) {
7261 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7262 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7263 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7264 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7265 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7266 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7268 add_extra_method_with_depth (acfg, m, depth + 1);
7269 add_types_from_method_header (acfg, m);
7272 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7274 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7275 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7277 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7278 add_extra_method_with_depth (acfg, m, depth + 1);
7282 case MONO_PATCH_INFO_VTABLE: {
7283 MonoClass *klass = patch_info->data.klass;
7285 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7286 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7289 case MONO_PATCH_INFO_SFLDA: {
7290 MonoClass *klass = patch_info->data.field->parent;
7292 /* The .cctor needs to run at runtime. */
7293 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
7294 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7303 /* Determine whenever the method has GOT slots */
7304 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7305 switch (patch_info->type) {
7306 case MONO_PATCH_INFO_GOT_OFFSET:
7307 case MONO_PATCH_INFO_NONE:
7308 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7309 case MONO_PATCH_INFO_GC_NURSERY_START:
7310 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7312 case MONO_PATCH_INFO_IMAGE:
7313 /* The assembly is stored in GOT slot 0 */
7314 if (patch_info->data.image != acfg->image)
7315 cfg->has_got_slots = TRUE;
7318 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7319 cfg->has_got_slots = TRUE;
7324 if (!cfg->has_got_slots)
7325 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7327 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7328 /* These only need out wrappers */
7329 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7331 /* Add gsharedvt wrappers for signatures used by the method */
7332 if (acfg->aot_opts.llvm_only) {
7335 for (l = cfg->signatures; l; l = l->next) {
7336 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7338 /* These only need in wrappers */
7339 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7344 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7346 /* Make a copy of the patch info which is in the mempool */
7348 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7350 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7351 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7354 patches = new_patch_info;
7356 patches_end->next = new_patch_info;
7357 patches_end = new_patch_info;
7359 cfg->patch_info = patches;
7361 /* Make a copy of the unwind info */
7363 GSList *l, *unwind_ops;
7367 for (l = cfg->unwind_ops; l; l = l->next) {
7368 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7369 memcpy (op, l->data, sizeof (MonoUnwindOp));
7370 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7372 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7374 /* Make a copy of the argument/local info */
7376 MonoInst **args, **locals;
7377 MonoMethodSignature *sig;
7378 MonoMethodHeader *header;
7381 sig = mono_method_signature (method);
7382 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7383 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7384 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7385 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7389 header = mono_method_get_header (method);
7390 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7391 for (i = 0; i < header->num_locals; ++i) {
7392 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7393 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7395 cfg->locals = locals;
7398 /* Free some fields used by cfg to conserve memory */
7399 mono_mempool_destroy (cfg->mempool);
7400 cfg->mempool = NULL;
7401 g_free (cfg->varinfo);
7402 cfg->varinfo = NULL;
7406 mono_regstate_free (cfg->rs);
7410 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7412 while (index >= acfg->cfgs_size) {
7413 MonoCompile **new_cfgs;
7416 new_size = acfg->cfgs_size * 2;
7417 new_cfgs = g_new0 (MonoCompile*, new_size);
7418 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7419 g_free (acfg->cfgs);
7420 acfg->cfgs = new_cfgs;
7421 acfg->cfgs_size = new_size;
7423 acfg->cfgs [index] = cfg;
7425 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7428 if (cfg->orig_method->wrapper_type)
7429 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7432 mono_acfg_unlock (acfg);
7434 InterlockedIncrement (&acfg->stats.ccount);
7438 compile_thread_main (gpointer *user_data)
7440 MonoDomain *domain = (MonoDomain *)user_data [0];
7441 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7442 GPtrArray *methods = (GPtrArray *)user_data [2];
7445 mono_thread_attach (domain);
7447 for (i = 0; i < methods->len; ++i)
7448 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7452 load_profile_files (MonoAotCompile *acfg)
7456 int file_index, res, method_index, i;
7459 GList *unordered, *l;
7464 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7466 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7471 infile = fopen (tmp, "r");
7474 printf ("Using profile data file '%s'\n", tmp);
7479 res = fscanf (infile, "%32s\n", ver);
7480 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7481 printf ("Profile file has wrong version or invalid.\n");
7488 MonoMethodDesc *desc;
7491 if (fgets (name, 1023, infile) == NULL)
7494 /* Kill the newline */
7495 if (strlen (name) > 0)
7496 name [strlen (name) - 1] = '\0';
7498 desc = mono_method_desc_new (name, TRUE);
7500 method = mono_method_desc_search_in_image (desc, acfg->image);
7502 if (method && mono_method_get_token (method)) {
7503 token = mono_method_get_token (method);
7504 method_index = mono_metadata_token_index (token) - 1;
7507 for (i = 0; i < acfg->method_order->len; ++i) {
7508 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7514 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7516 //printf ("No method found matching '%s'.\n", name);
7522 /* Add missing methods */
7524 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7526 for (i = 0; i < acfg->method_order->len; ++i) {
7527 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7533 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7535 unordered = g_list_reverse (unordered);
7536 for (l = unordered; l; l = l->next)
7537 g_ptr_array_add (acfg->method_order, l->data);
7540 /* Used by the LLVM backend */
7542 mono_aot_get_got_offset (MonoJumpInfo *ji)
7544 return get_got_offset (llvm_acfg, TRUE, ji);
7548 * mono_aot_is_shared_got_offset:
7550 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7551 * when the AOT image is loaded.
7554 mono_aot_is_shared_got_offset (int offset)
7556 return offset < llvm_acfg->nshared_got_entries;
7560 mono_aot_get_method_name (MonoCompile *cfg)
7562 if (llvm_acfg->aot_opts.static_link)
7563 /* Include the assembly name too to avoid duplicate symbol errors */
7564 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7566 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7570 * mono_aot_is_linkonce_method:
7572 * Return whenever METHOD should be emitted with linkonce linkage,
7573 * eliminating duplicate copies when compiling in static mode.
7576 mono_aot_is_linkonce_method (MonoMethod *method)
7580 // FIXME: Add more cases
7581 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7583 info = mono_marshal_get_wrapper_info (method);
7584 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7590 append_mangled_type (GString *s, MonoType *t)
7593 g_string_append_printf (s, "b");
7595 case MONO_TYPE_VOID:
7596 g_string_append_printf (s, "void_");
7599 g_string_append_printf (s, "i1");
7602 g_string_append_printf (s, "u1");
7605 g_string_append_printf (s, "i2");
7608 g_string_append_printf (s, "u2");
7611 g_string_append_printf (s, "i4");
7614 g_string_append_printf (s, "u4");
7617 g_string_append_printf (s, "i8");
7620 g_string_append_printf (s, "u8");
7623 g_string_append_printf (s, "ii");
7626 g_string_append_printf (s, "ui");
7629 g_string_append_printf (s, "fl");
7632 g_string_append_printf (s, "do");
7635 char *fullname = mono_type_full_name (t);
7641 * Have to create a mangled name which is:
7645 temp = g_string_new ("");
7646 len = strlen (fullname);
7647 for (i = 0; i < len; ++i) {
7648 char c = fullname [i];
7650 g_string_append_c (temp, c);
7651 } else if (c == '_') {
7652 g_string_append_c (temp, '_');
7653 g_string_append_c (temp, '_');
7655 g_string_append_c (temp, '_');
7656 g_string_append_printf (temp, "%x", (int)c);
7659 temps = g_string_free (temp, FALSE);
7660 /* Include the length to avoid different length type names aliasing each other */
7661 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
7670 append_mangled_signature (GString *s, MonoMethodSignature *sig)
7675 supported = append_mangled_type (s, sig->ret);
7679 g_string_append_printf (s, "this_");
7680 for (i = 0; i < sig->param_count; ++i) {
7681 supported = append_mangled_type (s, sig->params [i]);
7690 * mono_aot_get_mangled_method_name:
7692 * Return a unique mangled name for METHOD, or NULL.
7695 mono_aot_get_mangled_method_name (MonoMethod *method)
7701 // FIXME: Add more cases
7702 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7704 info = mono_marshal_get_wrapper_info (method);
7705 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7708 s = g_string_new ("");
7710 g_string_append_printf (s, "aot_method_w_");
7712 switch (info->subtype) {
7713 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
7714 g_string_append_printf (s, "gsharedvt_in_");
7716 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
7717 g_string_append_printf (s, "gsharedvt_out_");
7720 g_assert_not_reached ();
7724 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
7726 g_string_free (s, TRUE);
7730 return g_string_free (s, FALSE);
7734 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7736 return is_direct_callable (llvm_acfg, NULL, patch_info);
7740 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7742 MonoPltEntry *plt_entry;
7744 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7745 plt_entry->llvm_used = FALSE;
7749 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
7751 const char *sym = NULL;
7753 if (llvm_acfg->aot_opts.direct_icalls) {
7754 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7755 /* Call to a C function implementing a jit icall */
7756 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7757 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7758 MonoMethod *method = (MonoMethod *)data;
7759 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7760 sym = mono_lookup_icall_symbol (method);
7763 return g_strdup (sym);
7769 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7771 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7772 MonoPltEntry *plt_entry;
7773 const char *sym = NULL;
7776 ji->data.target = data;
7778 if (!can_encode_patch (llvm_acfg, ji))
7781 if (llvm_acfg->aot_opts.direct_icalls) {
7782 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7783 /* Call to a C function implementing a jit icall */
7784 sym = mono_lookup_jit_icall_symbol ((const char *)data);
7785 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7786 MonoMethod *method = (MonoMethod *)data;
7787 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7788 sym = mono_lookup_icall_symbol (method);
7791 return g_strdup (sym);
7794 plt_entry = get_plt_entry (llvm_acfg, ji);
7795 plt_entry->llvm_used = TRUE;
7797 #if defined(TARGET_MACH)
7798 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7800 return g_strdup_printf (plt_entry->llvm_symbol);
7805 mono_aot_get_method_index (MonoMethod *method)
7807 g_assert (llvm_acfg);
7808 return get_method_index (llvm_acfg, method);
7812 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7816 mono_acfg_lock (llvm_acfg);
7817 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7818 mono_acfg_unlock (llvm_acfg);
7824 execute_system (const char * command)
7829 // We need an extra set of quotes around the whole command to properly handle commands
7830 // with spaces since internally the command is called through "cmd /c.
7831 command = g_strdup_printf ("\"%s\"", command);
7833 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7834 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7835 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7836 status = _wsystem (wstr);
7840 #elif defined (HAVE_SYSTEM)
7841 status = system (command);
7843 g_assert_not_reached ();
7854 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7858 emit_llvm_file (MonoAotCompile *acfg)
7860 char *command, *opts, *tempbc, *optbc, *output_fname;
7862 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
7863 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7864 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
7866 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7867 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
7870 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7873 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7874 * a lot of time, and doesn't seem to save much space.
7875 * The following optimizations cannot be enabled:
7877 * - 'jump-threading' changes our blockaddress references to int constants.
7878 * - 'basiccg' fails because it contains:
7879 * if (CS && !isa<IntrinsicInst>(II)) {
7880 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7881 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7882 * The opt list below was produced by taking the output of:
7883 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7884 * then removing tailcallelim + the global opts.
7885 * strip-dead-prototypes deletes unused intrinsics definitions.
7887 //opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -domtree -verify");
7888 /* The dse pass is disabled because of #13734 and #17616 */
7890 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7891 * // If we have no DataLayout information around, then the size of the store
7892 * // is inferrable from the pointee type. If they are the same type, then
7893 * // we know that the store is safe.
7894 * if (AA.getDataLayout() == 0 &&
7895 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7896 * return OverwriteComplete;
7897 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7899 if (acfg->aot_opts.llvm_only)
7900 // FIXME: This doesn't work yet
7901 opts = g_strdup ("");
7903 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");
7904 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
7905 aot_printf (acfg, "Executing opt: %s\n", command);
7906 if (execute_system (command) != 0)
7910 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
7911 /* Nothing else to do */
7914 if (acfg->aot_opts.llvm_only) {
7915 /* Use the stock clang from xcode */
7918 // FIXME: llc/opt flags
7919 command = g_strdup_printf ("clang -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O0 -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
7920 //command = g_strdup_printf ("/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk -Qunused-arguments -miphoneos-version-min=8.2 -arch arm64 -fpic -O0 -c -o \"%s\" \"%s.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
7922 aot_printf (acfg, "Executing clang: %s\n", command);
7923 if (execute_system (command) != 0)
7928 if (!acfg->llc_args)
7929 acfg->llc_args = g_string_new ("");
7931 /* Verbose asm slows down llc greatly */
7932 g_string_append (acfg->llc_args, " -asm-verbose=false");
7934 if (acfg->aot_opts.mtriple)
7935 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7937 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7939 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
7941 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7942 /* ios requires PIC code now */
7943 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7945 if (llvm_acfg->aot_opts.static_link)
7946 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7948 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7951 if (acfg->llvm_owriter) {
7952 /* Emit an object file directly */
7953 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7954 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7956 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7958 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7959 g_free (output_fname);
7961 aot_printf (acfg, "Executing llc: %s\n", command);
7963 if (execute_system (command) != 0)
7970 emit_code (MonoAotCompile *acfg)
7972 int oindex, i, prev_index;
7973 gboolean saved_unbox_info = FALSE;
7976 if (acfg->aot_opts.llvm_only)
7979 #if defined(TARGET_POWERPC64)
7980 sprintf (symbol, ".Lgot_addr");
7981 emit_section_change (acfg, ".text", 0);
7982 emit_alignment (acfg, 8);
7983 emit_label (acfg, symbol);
7984 emit_pointer (acfg, acfg->got_symbol);
7988 * This global symbol is used to compute the address of each method using the
7989 * code_offsets array. It is also used to compute the memory ranges occupied by
7990 * AOT code, so it must be equal to the address of the first emitted method.
7992 emit_section_change (acfg, ".text", 0);
7993 emit_alignment_code (acfg, 8);
7994 emit_info_symbol (acfg, "jit_code_start");
7997 * Emit some padding so the local symbol for the first method doesn't have the
7998 * same address as 'methods'.
8000 #if defined(__default_codegen__)
8001 emit_padding (acfg, 16);
8002 #elif defined(__native_client_codegen__)
8004 const int kPaddingSize = 16;
8005 guint8 pad_buffer[kPaddingSize];
8006 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
8007 emit_bytes (acfg, pad_buffer, kPaddingSize);
8011 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8015 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8017 cfg = acfg->cfgs [i];
8022 method = cfg->orig_method;
8024 /* Emit unbox trampoline */
8025 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8026 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8028 emit_section_change (acfg, ".text", 0);
8029 #ifdef __native_client_codegen__
8030 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
8033 if (acfg->thumb_mixed && cfg->compile_llvm) {
8034 emit_set_thumb_mode (acfg);
8035 fprintf (acfg->fp, "\n.thumb_func\n");
8038 emit_label (acfg, symbol);
8040 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8042 if (acfg->thumb_mixed && cfg->compile_llvm)
8043 emit_set_arm_mode (acfg);
8045 if (!saved_unbox_info) {
8046 char user_symbol [128];
8048 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8050 emit_label (acfg, "ut_end");
8052 unwind_ops = mono_unwind_get_cie_program ();
8053 save_unwind_info (acfg, user_symbol, unwind_ops);
8054 mono_free_unwind_info (unwind_ops);
8056 /* Save the unbox trampoline size */
8057 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8059 saved_unbox_info = TRUE;
8063 if (cfg->compile_llvm)
8064 acfg->stats.llvm_count ++;
8066 emit_method_code (acfg, cfg);
8069 emit_section_change (acfg, ".text", 0);
8070 emit_alignment_code (acfg, 8);
8071 emit_info_symbol (acfg, "jit_code_end");
8073 /* To distinguish it from the next symbol */
8074 emit_padding (acfg, 4);
8077 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8078 * from optimizing them away, since it doesn't see that code_offsets references them.
8079 * JITted methods don't need this since they are referenced using assembler local
8081 * FIXME: This is why write-symbols doesn't work on OSX ?
8083 if (acfg->llvm && acfg->need_no_dead_strip) {
8084 fprintf (acfg->fp, "\n");
8085 for (i = 0; i < acfg->nmethods; ++i) {
8086 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8087 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8092 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8093 * This is PIE code, and the linker can update it if needed.
8095 sprintf (symbol, "method_addresses");
8096 emit_section_change (acfg, ".text", 1);
8097 emit_alignment_code (acfg, 8);
8098 emit_info_symbol (acfg, symbol);
8099 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8100 emit_unset_mode (acfg);
8101 if (acfg->need_no_dead_strip)
8102 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8104 for (i = 0; i < acfg->nmethods; ++i) {
8105 #ifdef MONO_ARCH_AOT_SUPPORTED
8108 if (acfg->cfgs [i]) {
8109 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
8110 /* Obtained by calling a generated function in the LLVM image */
8111 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8113 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8115 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
8120 sprintf (symbol, "method_addresses_end");
8121 emit_label (acfg, symbol);
8124 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8125 sprintf (symbol, "unbox_trampolines");
8126 emit_section_change (acfg, RODATA_SECT, 0);
8127 emit_alignment (acfg, 8);
8128 emit_info_symbol (acfg, symbol);
8131 for (i = 0; i < acfg->nmethods; ++i) {
8136 cfg = acfg->cfgs [i];
8140 method = cfg->orig_method;
8142 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8143 index = get_method_index (acfg, method);
8145 emit_int32 (acfg, index);
8146 /* Make sure the table is sorted by index */
8147 g_assert (index > prev_index);
8151 sprintf (symbol, "unbox_trampolines_end");
8152 emit_info_symbol (acfg, symbol);
8153 emit_int32 (acfg, 0);
8155 /* Emit a separate table with the trampoline addresses/offsets */
8156 sprintf (symbol, "unbox_trampoline_addresses");
8157 emit_section_change (acfg, ".text", 0);
8158 emit_alignment_code (acfg, 8);
8159 emit_info_symbol (acfg, symbol);
8161 for (i = 0; i < acfg->nmethods; ++i) {
8166 cfg = acfg->cfgs [i];
8170 method = cfg->orig_method;
8172 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8173 #ifdef MONO_ARCH_AOT_SUPPORTED
8176 index = get_method_index (acfg, method);
8177 sprintf (symbol, "ut_%d", index);
8179 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8183 emit_int32 (acfg, 0);
8187 emit_info (MonoAotCompile *acfg)
8192 offsets = g_new0 (gint32, acfg->nmethods);
8194 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8195 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8197 if (acfg->cfgs [i]) {
8198 emit_method_info (acfg, acfg->cfgs [i]);
8199 offsets [i] = acfg->cfgs [i]->method_info_offset;
8205 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8210 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8212 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8213 #define mix(a,b,c) { \
8214 a -= c; a ^= rot(c, 4); c += b; \
8215 b -= a; b ^= rot(a, 6); a += c; \
8216 c -= b; c ^= rot(b, 8); b += a; \
8217 a -= c; a ^= rot(c,16); c += b; \
8218 b -= a; b ^= rot(a,19); a += c; \
8219 c -= b; c ^= rot(b, 4); b += a; \
8221 #define final(a,b,c) { \
8222 c ^= b; c -= rot(b,14); \
8223 a ^= c; a -= rot(c,11); \
8224 b ^= a; b -= rot(a,25); \
8225 c ^= b; c -= rot(b,16); \
8226 a ^= c; a -= rot(c,4); \
8227 b ^= a; b -= rot(a,14); \
8228 c ^= b; c -= rot(b,24); \
8232 mono_aot_type_hash (MonoType *t1)
8234 guint hash = t1->type;
8236 hash |= t1->byref << 6; /* do not collide with t1->type values */
8238 case MONO_TYPE_VALUETYPE:
8239 case MONO_TYPE_CLASS:
8240 case MONO_TYPE_SZARRAY:
8241 /* check if the distribution is good enough */
8242 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8244 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8245 case MONO_TYPE_ARRAY:
8246 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8247 case MONO_TYPE_GENERICINST:
8248 return ((hash << 5) - hash) ^ 0;
8255 * mono_aot_method_hash:
8257 * Return a hash code for methods which only depends on metadata.
8260 mono_aot_method_hash (MonoMethod *method)
8262 MonoMethodSignature *sig;
8266 guint32 *hashes_start, *hashes;
8268 MonoGenericInst *class_ginst = NULL;
8269 MonoGenericInst *ginst = NULL;
8271 /* Similar to the hash in mono_method_get_imt_slot () */
8273 sig = mono_method_signature (method);
8275 if (method->klass->generic_class)
8276 class_ginst = method->klass->generic_class->context.class_inst;
8277 if (method->is_inflated)
8278 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8280 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8281 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8282 hashes = hashes_start;
8284 /* Some wrappers are assigned to random classes */
8285 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8286 klass = method->klass;
8288 klass = mono_defaults.object_class;
8290 if (!method->wrapper_type) {
8293 if (klass->generic_class)
8294 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8296 full_name = mono_type_full_name (&klass->byval_arg);
8298 hashes [0] = mono_metadata_str_hash (full_name);
8302 hashes [0] = mono_metadata_str_hash (klass->name);
8303 hashes [1] = mono_metadata_str_hash (klass->name_space);
8305 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8306 /* The method name includes a stringified pointer */
8309 hashes [2] = mono_metadata_str_hash (method->name);
8310 hashes [3] = method->wrapper_type;
8311 hashes [4] = mono_aot_type_hash (sig->ret);
8313 for (i = 0; i < sig->param_count; i++) {
8314 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8317 for (i = 0; i < class_ginst->type_argc; ++i)
8318 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8321 for (i = 0; i < ginst->type_argc; ++i)
8322 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8324 g_assert (hindex == hashes_count);
8326 /* Setup internal state */
8327 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8329 /* Handle most of the hashes */
8330 while (hashes_count > 3) {
8339 /* Handle the last 3 hashes (all the case statements fall through) */
8340 switch (hashes_count) {
8341 case 3 : c += hashes [2];
8342 case 2 : b += hashes [1];
8343 case 1 : a += hashes [0];
8345 case 0: /* nothing left to add */
8349 free (hashes_start);
8358 * mono_aot_get_array_helper_from_wrapper;
8360 * Get the helper method in Array called by an array wrapper method.
8363 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8367 MonoGenericContext ctx;
8368 MonoType *args [16];
8369 char *mname, *iname, *s, *s2, *helper_name = NULL;
8371 prefix = "System.Collections.Generic";
8372 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8373 s2 = strstr (s, "`1.");
8379 //printf ("X: %s %s\n", iname, mname);
8381 if (!strcmp (iname, "IList"))
8382 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8384 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8385 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8387 g_free (helper_name);
8390 if (m->is_generic) {
8392 memset (&ctx, 0, sizeof (ctx));
8393 args [0] = &method->klass->element_class->byval_arg;
8394 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8395 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8396 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8402 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8404 typedef struct HashEntry {
8405 guint32 key, value, index;
8406 struct HashEntry *next;
8410 * emit_extra_methods:
8412 * Emit methods which are not in the METHOD table, like wrappers.
8415 emit_extra_methods (MonoAotCompile *acfg)
8417 int i, table_size, buf_size;
8419 guint32 *info_offsets;
8422 HashEntry *entry, *new_entry;
8423 int nmethods, max_chain_length;
8426 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8428 /* Emit method info */
8430 for (i = 0; i < acfg->extra_methods->len; ++i) {
8431 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8432 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8438 p = buf = (guint8 *)g_malloc (buf_size);
8442 method = cfg->method_to_register;
8444 encode_method_ref (acfg, method, p, &p);
8446 g_assert ((p - buf) < buf_size);
8448 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8453 * Construct a chained hash table for mapping indexes in extra_method_info to
8456 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8457 table = g_ptr_array_sized_new (table_size);
8458 for (i = 0; i < table_size; ++i)
8459 g_ptr_array_add (table, NULL);
8460 chain_lengths = g_new0 (int, table_size);
8461 max_chain_length = 0;
8462 for (i = 0; i < acfg->extra_methods->len; ++i) {
8463 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8464 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8470 key = info_offsets [i];
8471 value = get_method_index (acfg, method);
8473 hash = mono_aot_method_hash (method) % table_size;
8474 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8476 chain_lengths [hash] ++;
8477 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8479 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8480 new_entry->key = key;
8481 new_entry->value = value;
8483 entry = (HashEntry *)g_ptr_array_index (table, hash);
8484 if (entry == NULL) {
8485 new_entry->index = hash;
8486 g_ptr_array_index (table, hash) = new_entry;
8489 entry = entry->next;
8491 entry->next = new_entry;
8492 new_entry->index = table->len;
8493 g_ptr_array_add (table, new_entry);
8497 //printf ("MAX: %d\n", max_chain_length);
8499 buf_size = table->len * 12 + 4;
8500 p = buf = (guint8 *)g_malloc (buf_size);
8501 encode_int (table_size, p, &p);
8503 for (i = 0; i < table->len; ++i) {
8504 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8506 if (entry == NULL) {
8507 encode_int (0, p, &p);
8508 encode_int (0, p, &p);
8509 encode_int (0, p, &p);
8511 //g_assert (entry->key > 0);
8512 encode_int (entry->key, p, &p);
8513 encode_int (entry->value, p, &p);
8515 encode_int (entry->next->index, p, &p);
8517 encode_int (0, p, &p);
8520 g_assert (p - buf <= buf_size);
8522 /* Emit the table */
8523 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8526 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8527 * This is used by mono_aot_find_jit_info ().
8529 buf_size = acfg->extra_methods->len * 8 + 4;
8530 p = buf = (guint8 *)g_malloc (buf_size);
8531 encode_int (acfg->extra_methods->len, p, &p);
8532 for (i = 0; i < acfg->extra_methods->len; ++i) {
8533 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8535 encode_int (get_method_index (acfg, method), p, &p);
8536 encode_int (info_offsets [i], p, &p);
8538 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8542 emit_exception_info (MonoAotCompile *acfg)
8546 SeqPointData sp_data;
8547 gboolean seq_points_to_file = FALSE;
8549 offsets = g_new0 (gint32, acfg->nmethods);
8550 for (i = 0; i < acfg->nmethods; ++i) {
8551 if (acfg->cfgs [i]) {
8552 MonoCompile *cfg = acfg->cfgs [i];
8554 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8555 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8556 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
8557 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8558 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8560 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8561 offsets [i] = cfg->ex_info_offset;
8563 if (method_seq_points_to_file) {
8564 if (!seq_points_to_file) {
8565 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8566 seq_points_to_file = TRUE;
8568 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8575 if (seq_points_to_file) {
8576 char *seq_points_aot_file;
8577 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
8578 mono_seq_point_data_write (&sp_data, seq_points_aot_file);
8579 mono_seq_point_data_free (&sp_data);
8580 g_free (seq_points_aot_file);
8583 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8588 emit_unwind_info (MonoAotCompile *acfg)
8593 if (acfg->aot_opts.llvm_only) {
8594 g_assert (acfg->unwind_ops->len == 0);
8599 * The unwind info contains a lot of duplicates so we emit each unique
8600 * entry once, and only store the offset from the start of the table in the
8604 sprintf (symbol, "unwind_info");
8605 emit_section_change (acfg, RODATA_SECT, 1);
8606 emit_alignment (acfg, 8);
8607 emit_info_symbol (acfg, symbol);
8609 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8610 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8611 guint8 *unwind_info;
8612 guint32 unwind_info_len;
8616 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8619 encode_value (unwind_info_len, p, &p);
8620 emit_bytes (acfg, buf, p - buf);
8621 emit_bytes (acfg, unwind_info, unwind_info_len);
8623 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
8628 emit_class_info (MonoAotCompile *acfg)
8633 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8634 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8635 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8637 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);
8641 typedef struct ClassNameTableEntry {
8642 guint32 token, index;
8643 struct ClassNameTableEntry *next;
8644 } ClassNameTableEntry;
8647 emit_class_name_table (MonoAotCompile *acfg)
8649 int i, table_size, buf_size;
8650 guint32 token, hash;
8655 ClassNameTableEntry *entry, *new_entry;
8658 * Construct a chained hash table for mapping class names to typedef tokens.
8660 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8661 table = g_ptr_array_sized_new (table_size);
8662 for (i = 0; i < table_size; ++i)
8663 g_ptr_array_add (table, NULL);
8664 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8666 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8667 klass = mono_class_get_checked (acfg->image, token, &error);
8669 mono_error_cleanup (&error);
8672 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8673 hash = mono_metadata_str_hash (full_name) % table_size;
8676 /* FIXME: Allocate from the mempool */
8677 new_entry = g_new0 (ClassNameTableEntry, 1);
8678 new_entry->token = token;
8680 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
8681 if (entry == NULL) {
8682 new_entry->index = hash;
8683 g_ptr_array_index (table, hash) = new_entry;
8686 entry = entry->next;
8688 entry->next = new_entry;
8689 new_entry->index = table->len;
8690 g_ptr_array_add (table, new_entry);
8694 /* Emit the table */
8695 buf_size = table->len * 4 + 4;
8696 p = buf = (guint8 *)g_malloc0 (buf_size);
8698 /* FIXME: Optimize memory usage */
8699 g_assert (table_size < 65000);
8700 encode_int16 (table_size, p, &p);
8701 g_assert (table->len < 65000);
8702 for (i = 0; i < table->len; ++i) {
8703 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
8705 if (entry == NULL) {
8706 encode_int16 (0, p, &p);
8707 encode_int16 (0, p, &p);
8709 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
8711 encode_int16 (entry->next->index, p, &p);
8713 encode_int16 (0, p, &p);
8716 g_assert (p - buf <= buf_size);
8718 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
8722 emit_image_table (MonoAotCompile *acfg)
8728 * The image table is small but referenced in a lot of places.
8729 * So we emit it at once, and reference its elements by an index.
8731 buf_size = acfg->image_table->len * 28 + 4;
8732 for (i = 0; i < acfg->image_table->len; i++) {
8733 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8734 MonoAssemblyName *aname = &image->assembly->aname;
8736 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
8739 buf = p = (guint8 *)g_malloc0 (buf_size);
8740 encode_int (acfg->image_table->len, p, &p);
8741 for (i = 0; i < acfg->image_table->len; i++) {
8742 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8743 MonoAssemblyName *aname = &image->assembly->aname;
8745 /* FIXME: Support multi-module assemblies */
8746 g_assert (image->assembly->image == image);
8748 encode_string (image->assembly_name, p, &p);
8749 encode_string (image->guid, p, &p);
8750 encode_string (aname->culture ? aname->culture : "", p, &p);
8751 encode_string ((const char*)aname->public_key_token, p, &p);
8753 while (GPOINTER_TO_UINT (p) % 8 != 0)
8756 encode_int (aname->flags, p, &p);
8757 encode_int (aname->major, p, &p);
8758 encode_int (aname->minor, p, &p);
8759 encode_int (aname->build, p, &p);
8760 encode_int (aname->revision, p, &p);
8762 g_assert (p - buf <= buf_size);
8764 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
8770 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8772 int i, first_plt_got_patch = 0, buf_size;
8774 guint32 *got_info_offsets;
8775 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8777 /* Add the patches needed by the PLT to the GOT */
8779 acfg->plt_got_offset_base = acfg->got_offset;
8780 first_plt_got_patch = info->got_patches->len;
8781 for (i = 1; i < acfg->plt_offset; ++i) {
8782 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8784 g_ptr_array_add (info->got_patches, plt_entry->ji);
8786 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8789 acfg->got_offset += acfg->plt_offset;
8794 * - optimize offsets table.
8795 * - reduce number of exported symbols.
8796 * - emit info for a klass only once.
8797 * - determine when a method uses a GOT slot which is guaranteed to be already
8799 * - clean up and document the code.
8800 * - use String.Empty in class libs.
8803 /* Encode info required to decode shared GOT entries */
8804 buf_size = info->got_patches->len * 128;
8805 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
8806 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8808 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8810 if (acfg->plt_offset)
8811 acfg->plt_got_info_offsets [0] = 0;
8813 for (i = 0; i < info->got_patches->len; ++i) {
8814 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
8819 encode_value (ji->type, p, &p);
8821 encode_patch (acfg, ji, p, &p);
8822 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8823 g_assert (p - buf <= buf_size);
8824 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8826 if (!llvm && i >= first_plt_got_patch)
8827 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8828 acfg->stats.got_info_size += p - buf;
8831 /* Emit got_info_offsets table */
8833 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8834 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);
8838 emit_got (MonoAotCompile *acfg)
8842 if (acfg->aot_opts.llvm_only)
8845 /* Don't make GOT global so accesses to it don't need relocations */
8846 sprintf (symbol, "%s", acfg->got_symbol);
8849 emit_unset_mode (acfg);
8850 fprintf (acfg->fp, ".section __DATA, __bss\n");
8851 emit_alignment (acfg, 8);
8853 emit_info_symbol (acfg, "jit_got");
8854 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
8856 emit_section_change (acfg, ".bss", 0);
8857 emit_alignment (acfg, 8);
8858 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8859 emit_label (acfg, symbol);
8861 emit_info_symbol (acfg, "jit_got");
8862 if (acfg->got_offset > 0)
8863 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8866 sprintf (symbol, "got_end");
8867 emit_label (acfg, symbol);
8870 typedef struct GlobalsTableEntry {
8871 guint32 value, index;
8872 struct GlobalsTableEntry *next;
8873 } GlobalsTableEntry;
8876 emit_globals (MonoAotCompile *acfg)
8882 GlobalsTableEntry *entry, *new_entry;
8884 if (!acfg->aot_opts.static_link)
8886 if (acfg->aot_opts.llvm_only) {
8887 g_assert (acfg->globals->len == 0);
8892 * When static linking, we emit a table containing our globals.
8896 * Construct a chained hash table for mapping global names to their index in
8897 * the globals table.
8899 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8900 table = g_ptr_array_sized_new (table_size);
8901 for (i = 0; i < table_size; ++i)
8902 g_ptr_array_add (table, NULL);
8903 for (i = 0; i < acfg->globals->len; ++i) {
8904 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8906 hash = mono_metadata_str_hash (name) % table_size;
8908 /* FIXME: Allocate from the mempool */
8909 new_entry = g_new0 (GlobalsTableEntry, 1);
8910 new_entry->value = i;
8912 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
8913 if (entry == NULL) {
8914 new_entry->index = hash;
8915 g_ptr_array_index (table, hash) = new_entry;
8918 entry = entry->next;
8920 entry->next = new_entry;
8921 new_entry->index = table->len;
8922 g_ptr_array_add (table, new_entry);
8926 /* Emit the table */
8927 sprintf (symbol, ".Lglobals_hash");
8928 emit_section_change (acfg, RODATA_SECT, 0);
8929 emit_alignment (acfg, 8);
8930 emit_label (acfg, symbol);
8932 /* FIXME: Optimize memory usage */
8933 g_assert (table_size < 65000);
8934 emit_int16 (acfg, table_size);
8935 for (i = 0; i < table->len; ++i) {
8936 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
8938 if (entry == NULL) {
8939 emit_int16 (acfg, 0);
8940 emit_int16 (acfg, 0);
8942 emit_int16 (acfg, entry->value + 1);
8944 emit_int16 (acfg, entry->next->index);
8946 emit_int16 (acfg, 0);
8950 /* Emit the names */
8951 for (i = 0; i < acfg->globals->len; ++i) {
8952 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8954 sprintf (symbol, "name_%d", i);
8955 emit_section_change (acfg, RODATA_SECT, 1);
8957 emit_alignment (acfg, 4);
8959 emit_label (acfg, symbol);
8960 emit_string (acfg, name);
8963 /* Emit the globals table */
8964 sprintf (symbol, "globals");
8965 emit_section_change (acfg, ".data", 0);
8966 /* This is not a global, since it is accessed by the init function */
8967 emit_alignment (acfg, 8);
8968 emit_info_symbol (acfg, symbol);
8970 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8971 emit_pointer (acfg, symbol);
8973 for (i = 0; i < acfg->globals->len; ++i) {
8974 char *name = (char *)g_ptr_array_index (acfg->globals, i);
8976 sprintf (symbol, "name_%d", i);
8977 emit_pointer (acfg, symbol);
8979 g_assert (strlen (name) < sizeof (symbol));
8980 sprintf (symbol, "%s", name);
8981 emit_pointer (acfg, symbol);
8983 /* Null terminate the table */
8984 emit_int32 (acfg, 0);
8985 emit_int32 (acfg, 0);
8989 emit_mem_end (MonoAotCompile *acfg)
8993 if (acfg->aot_opts.llvm_only)
8996 sprintf (symbol, "mem_end");
8997 emit_section_change (acfg, ".text", 1);
8998 emit_alignment_code (acfg, 8);
8999 emit_label (acfg, symbol);
9003 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9007 info->version = MONO_AOT_FILE_VERSION;
9008 info->plt_got_offset_base = acfg->plt_got_offset_base;
9009 info->got_size = acfg->got_offset * sizeof (gpointer);
9010 info->plt_size = acfg->plt_offset;
9011 info->nmethods = acfg->nmethods;
9012 info->flags = acfg->flags;
9013 info->opts = acfg->opts;
9014 info->simd_opts = acfg->simd_opts;
9015 info->gc_name_index = acfg->gc_name_offset;
9016 info->datafile_size = acfg->datafile_offset;
9017 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9018 info->table_offsets [i] = acfg->table_offsets [i];
9019 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9020 info->num_trampolines [i] = acfg->num_trampolines [i];
9021 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9022 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9023 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9024 info->trampoline_size [i] = acfg->trampoline_size [i];
9025 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9027 info->double_align = MONO_ABI_ALIGNOF (double);
9028 info->long_align = MONO_ABI_ALIGNOF (gint64);
9029 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9030 info->tramp_page_size = acfg->tramp_page_size;
9031 info->nshared_got_entries = acfg->nshared_got_entries;
9032 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9033 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9037 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9041 const char **symbols;
9043 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9045 symbols [sindex ++] = acfg->got_symbol;
9047 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9048 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9050 symbols [sindex ++] = NULL;
9051 symbols [sindex ++] = NULL;
9053 /* llvm_get_method */
9054 symbols [sindex ++] = NULL;
9055 /* llvm_get_unbox_tramp */
9056 symbols [sindex ++] = NULL;
9057 if (!acfg->aot_opts.llvm_only) {
9058 symbols [sindex ++] = "jit_code_start";
9059 symbols [sindex ++] = "jit_code_end";
9060 symbols [sindex ++] = "method_addresses";
9062 symbols [sindex ++] = NULL;
9063 symbols [sindex ++] = NULL;
9064 symbols [sindex ++] = NULL;
9066 if (acfg->data_outfile) {
9067 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9068 symbols [sindex ++] = NULL;
9070 symbols [sindex ++] = "blob";
9071 symbols [sindex ++] = "class_name_table";
9072 symbols [sindex ++] = "class_info_offsets";
9073 symbols [sindex ++] = "method_info_offsets";
9074 symbols [sindex ++] = "ex_info_offsets";
9075 symbols [sindex ++] = "extra_method_info_offsets";
9076 symbols [sindex ++] = "extra_method_table";
9077 symbols [sindex ++] = "got_info_offsets";
9079 symbols [sindex ++] = "llvm_got_info_offsets";
9081 symbols [sindex ++] = NULL;
9082 symbols [sindex ++] = "image_table";
9084 symbols [sindex ++] = "mem_end";
9085 symbols [sindex ++] = "assembly_guid";
9086 symbols [sindex ++] = "runtime_version";
9087 if (acfg->num_trampoline_got_entries) {
9088 symbols [sindex ++] = "specific_trampolines";
9089 symbols [sindex ++] = "static_rgctx_trampolines";
9090 symbols [sindex ++] = "imt_thunks";
9091 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9093 symbols [sindex ++] = NULL;
9094 symbols [sindex ++] = NULL;
9095 symbols [sindex ++] = NULL;
9096 symbols [sindex ++] = NULL;
9098 if (acfg->aot_opts.static_link) {
9099 symbols [sindex ++] = "globals";
9101 symbols [sindex ++] = NULL;
9103 symbols [sindex ++] = "assembly_name";
9104 symbols [sindex ++] = "plt";
9105 symbols [sindex ++] = "plt_end";
9106 symbols [sindex ++] = "unwind_info";
9107 if (!acfg->aot_opts.llvm_only) {
9108 symbols [sindex ++] = "unbox_trampolines";
9109 symbols [sindex ++] = "unbox_trampolines_end";
9110 symbols [sindex ++] = "unbox_trampoline_addresses";
9112 symbols [sindex ++] = NULL;
9113 symbols [sindex ++] = NULL;
9114 symbols [sindex ++] = NULL;
9117 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9119 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9120 emit_section_change (acfg, ".data", 0);
9121 emit_alignment (acfg, 8);
9122 emit_label (acfg, symbol);
9123 if (!acfg->aot_opts.static_link)
9124 emit_global (acfg, symbol, FALSE);
9126 /* The data emitted here must match MonoAotFileInfo. */
9128 emit_int32 (acfg, info->version);
9129 emit_int32 (acfg, info->dummy);
9132 * We emit pointers to our data structures instead of emitting global symbols which
9133 * point to them, to reduce the number of globals, and because using globals leads to
9134 * various problems (i.e. arm/thumb).
9136 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9137 emit_pointer (acfg, symbols [i]);
9139 emit_int32 (acfg, info->plt_got_offset_base);
9140 emit_int32 (acfg, info->got_size);
9141 emit_int32 (acfg, info->plt_size);
9142 emit_int32 (acfg, info->nmethods);
9143 emit_int32 (acfg, info->flags);
9144 emit_int32 (acfg, info->opts);
9145 emit_int32 (acfg, info->simd_opts);
9146 emit_int32 (acfg, info->gc_name_index);
9147 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9148 emit_int32 (acfg, info->double_align);
9149 emit_int32 (acfg, info->long_align);
9150 emit_int32 (acfg, info->generic_tramp_num);
9151 emit_int32 (acfg, info->tramp_page_size);
9152 emit_int32 (acfg, info->nshared_got_entries);
9153 emit_int32 (acfg, info->datafile_size);
9155 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9156 emit_int32 (acfg, info->table_offsets [i]);
9157 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9158 emit_int32 (acfg, info->num_trampolines [i]);
9159 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9160 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9161 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9162 emit_int32 (acfg, info->trampoline_size [i]);
9163 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9164 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9166 if (acfg->aot_opts.static_link) {
9167 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9168 emit_alignment (acfg, sizeof (gpointer));
9169 emit_label (acfg, acfg->static_linking_symbol);
9170 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9175 * Emit a structure containing all the information not stored elsewhere.
9178 emit_file_info (MonoAotCompile *acfg)
9181 MonoAotFileInfo *info;
9183 if (acfg->aot_opts.bind_to_runtime_version) {
9184 build_info = mono_get_runtime_build_info ();
9185 emit_string_symbol (acfg, "runtime_version", build_info);
9186 g_free (build_info);
9188 emit_string_symbol (acfg, "runtime_version", "");
9191 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9193 /* Emit a string holding the assembly name */
9194 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9196 info = g_new0 (MonoAotFileInfo, 1);
9197 init_aot_file_info (acfg, info);
9199 if (acfg->aot_opts.static_link) {
9204 * Emit a global symbol which can be passed by an embedding app to
9205 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9208 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9210 /* Get rid of characters which cannot occur in symbols */
9212 for (p = symbol; *p; ++p) {
9213 if (!(isalnum (*p) || *p == '_'))
9216 acfg->static_linking_symbol = g_strdup (symbol);
9220 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9222 emit_aot_file_info (acfg, info);
9226 emit_blob (MonoAotCompile *acfg)
9228 acfg->blob_closed = TRUE;
9230 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9234 emit_objc_selectors (MonoAotCompile *acfg)
9239 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9244 * cat > foo.m << EOF
9247 * return @selector(print:);
9252 mono_img_writer_emit_unset_mode (acfg->w);
9253 g_assert (acfg->fp);
9254 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9255 fprintf (acfg->fp, ".align 3\n");
9256 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9257 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9258 emit_label (acfg, symbol);
9259 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9260 emit_pointer (acfg, symbol);
9263 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9264 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9265 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9266 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9269 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9270 fprintf (acfg->fp, ".align 3\n");
9271 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9272 fprintf (acfg->fp, ".long 0\n");
9273 fprintf (acfg->fp, ".long 16\n");
9277 emit_dwarf_info (MonoAotCompile *acfg)
9279 #ifdef EMIT_DWARF_INFO
9283 /* DIEs for methods */
9284 for (i = 0; i < acfg->nmethods; ++i) {
9285 MonoCompile *cfg = acfg->cfgs [i];
9290 // FIXME: LLVM doesn't define .Lme_...
9291 if (cfg->compile_llvm)
9294 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9296 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 ()));
9302 collect_methods (MonoAotCompile *acfg)
9305 MonoImage *image = acfg->image;
9307 /* Collect methods */
9308 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9311 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9313 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9316 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9317 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9318 mono_error_cleanup (&error);
9322 /* Load all methods eagerly to skip the slower lazy loading code */
9323 mono_class_setup_methods (method->klass);
9325 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9326 /* Compile the wrapper instead */
9327 /* We do this here instead of add_wrappers () because it is easy to do it here */
9328 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9332 /* FIXME: Some mscorlib methods don't have debug info */
9334 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9335 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9336 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9337 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9338 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9339 if (!mono_debug_lookup_method (method)) {
9340 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9347 if (method->is_generic || method->klass->generic_container)
9348 /* Compile the ref shared version instead */
9349 method = mini_get_shared_method (method);
9351 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9352 add_method_with_index (acfg, method, i, FALSE);
9353 acfg->method_index ++;
9356 /* gsharedvt methods */
9357 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9360 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9362 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9365 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9366 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9368 if (method->is_generic || method->klass->generic_container) {
9369 MonoMethod *gshared;
9371 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9372 add_extra_method (acfg, gshared);
9376 add_generic_instances (acfg);
9378 if (mono_aot_mode_is_full (&acfg->aot_opts))
9379 add_wrappers (acfg);
9384 compile_methods (MonoAotCompile *acfg)
9388 if (acfg->aot_opts.nthreads > 0) {
9393 gpointer *user_data;
9394 MonoMethod **methods;
9396 methods_len = acfg->methods->len;
9398 len = acfg->methods->len / acfg->aot_opts.nthreads;
9401 * Partition the list of methods into fragments, and hand it to threads to
9404 threads = g_ptr_array_new ();
9405 /* Make a copy since acfg->methods is modified by compile_method () */
9406 methods = g_new0 (MonoMethod*, methods_len);
9407 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9408 for (i = 0; i < methods_len; ++i)
9409 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9411 while (i < methods_len) {
9412 frag = g_ptr_array_new ();
9413 for (j = 0; j < len; ++j) {
9414 if (i < methods_len) {
9415 g_ptr_array_add (frag, methods [i]);
9420 user_data = g_new0 (gpointer, 3);
9421 user_data [0] = mono_domain_get ();
9422 user_data [1] = acfg;
9423 user_data [2] = frag;
9425 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, 0, 0, NULL);
9426 g_ptr_array_add (threads, handle);
9430 for (i = 0; i < threads->len; ++i) {
9431 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9437 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9438 for (i = methods_len; i < acfg->methods->len; ++i) {
9439 /* This can new methods to acfg->methods */
9440 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9445 compile_asm (MonoAotCompile *acfg)
9447 char *command, *objfile;
9448 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9449 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9450 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9452 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9453 #define AS_OPTIONS "--64"
9454 #elif defined(TARGET_POWERPC64)
9455 #define AS_OPTIONS "-a64 -mppc64"
9456 #define LD_OPTIONS "-m elf64ppc"
9457 #elif defined(sparc) && SIZEOF_VOID_P == 8
9458 #define AS_OPTIONS "-xarch=v9"
9459 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9460 #define AS_OPTIONS "-arch i386"
9462 #define AS_OPTIONS ""
9465 #ifdef __native_client_codegen__
9466 #if defined(TARGET_AMD64)
9467 #define AS_NAME "nacl64-as"
9469 #define AS_NAME "nacl-as"
9471 #elif defined(TARGET_OSX)
9472 #define AS_NAME "clang"
9474 #define AS_NAME "as"
9478 #define LD_OPTIONS ""
9482 #define LD_NAME "ld -shared -G"
9483 #elif defined(__ppc__) && defined(TARGET_MACH)
9484 #define LD_NAME "gcc -dynamiclib"
9485 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9486 #define LD_NAME "clang --shared"
9487 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9488 #define LD_NAME "gcc -shared --dll"
9489 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9490 #define LD_NAME "clang -m32 -dynamiclib"
9491 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9492 #define LD_NAME "gcc --shared"
9495 if (acfg->aot_opts.asm_only) {
9496 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9497 if (acfg->aot_opts.static_link)
9498 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9500 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9504 if (acfg->aot_opts.static_link) {
9505 if (acfg->aot_opts.outfile)
9506 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9508 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9510 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9514 g_string_append (acfg->as_args, "-c -x assembler");
9517 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
9518 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9519 if (execute_system (command) != 0) {
9525 if (acfg->llvm && !acfg->llvm_owriter) {
9526 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", acfg->llvm_ofile, acfg->llvm_sfile);
9527 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9528 if (execute_system (command) != 0) {
9537 if (acfg->aot_opts.static_link) {
9538 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9539 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9544 if (acfg->aot_opts.outfile)
9545 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9547 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9549 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9552 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9554 llvm_ofile = g_strdup ("");
9557 /* replace the ; flags separators with spaces */
9558 g_strdelimit (ld_flags, ";", ' ');
9560 if (acfg->aot_opts.llvm_only)
9561 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9564 command = g_strdup_printf ("%s -o \"%s\" %s \"%s.o\" %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
9566 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
9567 acfg->tmpfname, ld_flags);
9569 aot_printf (acfg, "Executing the native linker: %s\n", command);
9570 if (execute_system (command) != 0) {
9571 g_free (tmp_outfile_name);
9572 g_free (outfile_name);
9581 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9582 printf ("Stripping the binary: %s\n", com);
9583 execute_system (com);
9586 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9588 * gas generates 'mapping symbols' each time code and data is mixed, which
9589 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9591 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
9592 aot_printf (acfg, "Stripping the binary: %s\n", command);
9593 if (execute_system (command) != 0) {
9594 g_free (tmp_outfile_name);
9595 g_free (outfile_name);
9602 rename (tmp_outfile_name, outfile_name);
9604 #if defined(TARGET_MACH)
9605 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
9606 aot_printf (acfg, "Executing dsymutil: %s\n", command);
9607 if (execute_system (command) != 0) {
9612 if (!acfg->aot_opts.save_temps)
9615 g_free (tmp_outfile_name);
9616 g_free (outfile_name);
9619 if (acfg->aot_opts.save_temps)
9620 aot_printf (acfg, "Retained input file.\n");
9622 unlink (acfg->tmpfname);
9627 static void init_got_info (GotInfo *info)
9631 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9632 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9633 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9634 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
9635 info->got_patches = g_ptr_array_new ();
9638 static MonoAotCompile*
9639 acfg_create (MonoAssembly *ass, guint32 opts)
9641 MonoImage *image = ass->image;
9642 MonoAotCompile *acfg;
9644 acfg = g_new0 (MonoAotCompile, 1);
9645 acfg->methods = g_ptr_array_new ();
9646 acfg->method_indexes = g_hash_table_new (NULL, NULL);
9647 acfg->method_depth = g_hash_table_new (NULL, NULL);
9648 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
9649 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
9650 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
9651 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
9652 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
9653 acfg->image_hash = g_hash_table_new (NULL, NULL);
9654 acfg->image_table = g_ptr_array_new ();
9655 acfg->globals = g_ptr_array_new ();
9656 acfg->image = image;
9658 /* TODO: Write out set of SIMD instructions used, rather than just those available */
9659 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
9660 acfg->mempool = mono_mempool_new ();
9661 acfg->extra_methods = g_ptr_array_new ();
9662 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
9663 acfg->unwind_ops = g_ptr_array_new ();
9664 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
9665 acfg->method_order = g_ptr_array_new ();
9666 acfg->export_names = g_hash_table_new (NULL, NULL);
9667 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
9668 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
9669 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
9670 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9671 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
9672 mono_os_mutex_init_recursive (&acfg->mutex);
9674 init_got_info (&acfg->got_info);
9675 init_got_info (&acfg->llvm_got_info);
9681 got_info_free (GotInfo *info)
9685 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9686 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9687 g_free (info->patch_to_got_offset_by_type);
9688 g_hash_table_destroy (info->patch_to_got_offset);
9689 g_ptr_array_free (info->got_patches, TRUE);
9693 acfg_free (MonoAotCompile *acfg)
9697 mono_img_writer_destroy (acfg->w);
9698 for (i = 0; i < acfg->nmethods; ++i)
9700 g_free (acfg->cfgs [i]);
9701 g_free (acfg->cfgs);
9702 g_free (acfg->static_linking_symbol);
9703 g_free (acfg->got_symbol);
9704 g_free (acfg->plt_symbol);
9705 g_ptr_array_free (acfg->methods, TRUE);
9706 g_ptr_array_free (acfg->image_table, TRUE);
9707 g_ptr_array_free (acfg->globals, TRUE);
9708 g_ptr_array_free (acfg->unwind_ops, TRUE);
9709 g_hash_table_destroy (acfg->method_indexes);
9710 g_hash_table_destroy (acfg->method_depth);
9711 g_hash_table_destroy (acfg->plt_offset_to_entry);
9712 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9713 if (acfg->patch_to_plt_entry [i])
9714 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9716 g_free (acfg->patch_to_plt_entry);
9717 g_hash_table_destroy (acfg->method_to_cfg);
9718 g_hash_table_destroy (acfg->token_info_hash);
9719 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9720 g_hash_table_destroy (acfg->image_hash);
9721 g_hash_table_destroy (acfg->unwind_info_offsets);
9722 g_hash_table_destroy (acfg->method_label_hash);
9723 g_hash_table_destroy (acfg->export_names);
9724 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9725 g_hash_table_destroy (acfg->klass_blob_hash);
9726 g_hash_table_destroy (acfg->method_blob_hash);
9727 got_info_free (&acfg->got_info);
9728 got_info_free (&acfg->llvm_got_info);
9729 mono_mempool_destroy (acfg->mempool);
9733 #define WRAPPER(e,n) n,
9734 static const char* const
9735 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9736 #include "mono/metadata/wrapper-types.h"
9740 static G_GNUC_UNUSED const char*
9741 get_wrapper_type_name (int type)
9743 return wrapper_type_names [type];
9749 static void aot_dump (MonoAotCompile *acfg)
9755 mono_json_writer_init (&writer);
9757 mono_json_writer_object_begin(&writer);
9760 mono_json_writer_indent (&writer);
9761 mono_json_writer_object_key(&writer, "methods");
9762 mono_json_writer_array_begin (&writer);
9765 for (i = 0; i < acfg->nmethods; ++i) {
9770 cfg = acfg->cfgs [i];
9774 method = cfg->orig_method;
9776 mono_json_writer_indent (&writer);
9777 mono_json_writer_object_begin(&writer);
9779 mono_json_writer_indent (&writer);
9780 mono_json_writer_object_key(&writer, "name");
9781 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
9783 mono_json_writer_indent (&writer);
9784 mono_json_writer_object_key(&writer, "signature");
9785 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
9787 mono_json_writer_indent (&writer);
9788 mono_json_writer_object_key(&writer, "code_size");
9789 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9791 klass = method->klass;
9793 mono_json_writer_indent (&writer);
9794 mono_json_writer_object_key(&writer, "class");
9795 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
9797 mono_json_writer_indent (&writer);
9798 mono_json_writer_object_key(&writer, "namespace");
9799 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9801 mono_json_writer_indent (&writer);
9802 mono_json_writer_object_key(&writer, "wrapper_type");
9803 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9805 mono_json_writer_indent_pop (&writer);
9806 mono_json_writer_indent (&writer);
9807 mono_json_writer_object_end (&writer);
9808 mono_json_writer_printf (&writer, ",\n");
9811 mono_json_writer_indent_pop (&writer);
9812 mono_json_writer_indent (&writer);
9813 mono_json_writer_array_end (&writer);
9814 mono_json_writer_printf (&writer, ",\n");
9818 mono_json_writer_indent_push (&writer);
9819 mono_json_writer_indent (&writer);
9820 mono_json_writer_object_key(&writer, "plt");
9821 mono_json_writer_array_begin (&writer);
9823 for (i = 0; i < acfg->plt_offset; ++i) {
9824 MonoPltEntry *plt_entry = NULL;
9829 * The first plt entry is unused.
9833 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9836 mono_json_writer_indent (&writer);
9837 mono_json_writer_printf (&writer, "{ ");
9838 mono_json_writer_object_key(&writer, "symbol");
9839 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9842 mono_json_writer_indent_pop (&writer);
9843 mono_json_writer_indent (&writer);
9844 mono_json_writer_array_end (&writer);
9845 mono_json_writer_printf (&writer, ",\n");
9850 mono_json_writer_indent_push (&writer);
9851 mono_json_writer_indent (&writer);
9852 mono_json_writer_object_key(&writer, "got");
9853 mono_json_writer_array_begin (&writer);
9855 mono_json_writer_indent_push (&writer);
9856 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9857 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9859 mono_json_writer_indent (&writer);
9860 mono_json_writer_printf (&writer, "{ ");
9861 mono_json_writer_object_key(&writer, "patch_name");
9862 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9865 mono_json_writer_indent_pop (&writer);
9866 mono_json_writer_indent (&writer);
9867 mono_json_writer_array_end (&writer);
9868 mono_json_writer_printf (&writer, ",\n");
9871 mono_json_writer_indent_pop (&writer);
9872 mono_json_writer_indent (&writer);
9873 mono_json_writer_object_end (&writer);
9875 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9876 dumpfile = fopen (dumpname, "w+");
9879 fprintf (dumpfile, "%s", writer.text->str);
9882 mono_json_writer_destroy (&writer);
9885 static const char *preinited_jit_icalls[] = {
9886 "mono_aot_init_llvm_method",
9887 "mono_aot_init_gshared_method_this",
9888 "mono_aot_init_gshared_method_mrgctx",
9889 "mono_aot_init_gshared_method_vtable",
9890 "mono_llvm_throw_corlib_exception",
9891 "mono_init_vtable_slot",
9892 "mono_helper_ldstr_mscorlib"
9896 add_preinit_got_slots (MonoAotCompile *acfg)
9902 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
9903 * during method initialization etc.
9906 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9907 ji->type = MONO_PATCH_INFO_IMAGE;
9908 ji->data.image = acfg->image;
9909 get_got_offset (acfg, FALSE, ji);
9910 get_got_offset (acfg, TRUE, ji);
9912 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9913 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9914 get_got_offset (acfg, FALSE, ji);
9915 get_got_offset (acfg, TRUE, ji);
9917 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9918 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9919 get_got_offset (acfg, FALSE, ji);
9920 get_got_offset (acfg, TRUE, ji);
9922 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9923 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9924 get_got_offset (acfg, FALSE, ji);
9925 get_got_offset (acfg, TRUE, ji);
9927 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9928 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9929 get_got_offset (acfg, FALSE, ji);
9930 get_got_offset (acfg, TRUE, ji);
9932 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9933 ji->type = MONO_PATCH_INFO_AOT_MODULE;
9934 get_got_offset (acfg, FALSE, ji);
9935 get_got_offset (acfg, TRUE, ji);
9937 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9938 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
9939 get_got_offset (acfg, FALSE, ji);
9940 get_got_offset (acfg, TRUE, ji);
9942 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
9943 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
9944 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9945 ji->data.name = preinited_jit_icalls [i];
9946 get_got_offset (acfg, FALSE, ji);
9947 get_got_offset (acfg, TRUE, ji);
9950 acfg->nshared_got_entries = acfg->got_offset;
9954 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9956 MonoImage *image = ass->image;
9959 MonoAotCompile *acfg;
9960 char *outfile_name, *tmp_outfile_name, *p;
9961 char llvm_stats_msg [256];
9965 acfg = acfg_create (ass, opts);
9967 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9968 acfg->aot_opts.write_symbols = TRUE;
9969 acfg->aot_opts.ntrampolines = 1024;
9970 acfg->aot_opts.nrgctx_trampolines = 1024;
9971 acfg->aot_opts.nimt_trampolines = 128;
9972 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9973 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9974 acfg->aot_opts.llvm_path = g_strdup ("");
9975 acfg->aot_opts.temp_path = g_strdup ("");
9977 acfg->aot_opts.use_trampolines_page = TRUE;
9980 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9982 if (acfg->aot_opts.logfile) {
9983 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9986 if (acfg->aot_opts.data_outfile) {
9987 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
9988 if (!acfg->data_outfile) {
9989 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
9992 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
9995 //acfg->aot_opts.print_skipped_methods = TRUE;
9997 #if !defined(ENABLE_GSHAREDVT)
9998 if (opts & MONO_OPT_GSHAREDVT) {
9999 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10004 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10005 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10006 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10011 if (acfg->aot_opts.llvm_only) {
10012 #ifndef ENABLE_GSHAREDVT
10013 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with --enable-gsharedvt.\n");
10018 #if defined(ENABLE_GSHAREDVT) && defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10019 acfg->opts |= MONO_OPT_GSHAREDVT;
10020 opts |= MONO_OPT_GSHAREDVT;
10023 if (opts & MONO_OPT_GSHAREDVT)
10024 mono_set_generic_sharing_vt_supported (TRUE);
10026 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10028 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10029 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10030 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10035 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10036 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10040 if (acfg->aot_opts.static_link)
10041 acfg->aot_opts.asm_writer = TRUE;
10043 if (acfg->aot_opts.soft_debug) {
10044 MonoDebugOptions *opt = mini_get_debug_options ();
10046 opt->mdb_optimizations = TRUE;
10047 opt->gen_sdb_seq_points = TRUE;
10049 if (!mono_debug_enabled ()) {
10050 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10053 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10056 if (mono_use_llvm || acfg->aot_opts.llvm) {
10058 acfg->aot_opts.asm_writer = TRUE;
10059 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10061 if (acfg->aot_opts.soft_debug) {
10062 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10068 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10069 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10074 * Emit all LLVM code into a separate assembly/object file and link with it
10077 if (!acfg->aot_opts.asm_only) {
10078 acfg->llvm_owriter = TRUE;
10079 } else if (acfg->aot_opts.llvm_outfile) {
10080 int len = strlen (acfg->aot_opts.llvm_outfile);
10082 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10083 acfg->llvm_owriter = TRUE;
10087 if (mono_aot_mode_is_full (&acfg->aot_opts))
10088 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10090 if (mono_threads_is_coop_enabled ())
10091 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10093 if (acfg->aot_opts.instances_logfile_path) {
10094 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10095 if (!acfg->instances_logfile) {
10096 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10101 load_profile_files (acfg);
10103 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10104 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10105 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10107 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10108 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10109 if (acfg->opts & MONO_OPT_GSHAREDVT)
10110 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10113 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10117 if (acfg->llvm && acfg->thumb_mixed)
10118 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10119 if (acfg->aot_opts.llvm_only)
10120 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10122 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10123 /* Get rid of characters which cannot occur in symbols */
10124 for (p = acfg->assembly_name_sym; *p; ++p) {
10125 if (!(isalnum (*p) || *p == '_'))
10129 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10130 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10131 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10133 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10134 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10137 acfg->method_index = 1;
10139 if (mono_aot_mode_is_full (&acfg->aot_opts))
10140 mono_set_partial_sharing_supported (TRUE);
10142 res = collect_methods (acfg);
10146 acfg->cfgs_size = acfg->methods->len + 32;
10147 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10149 /* PLT offset 0 is reserved for the PLT trampoline */
10150 acfg->plt_offset = 1;
10151 add_preinit_got_slots (acfg);
10156 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10162 compile_methods (acfg);
10166 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10172 if (acfg->aot_opts.asm_only) {
10173 if (acfg->aot_opts.outfile) {
10174 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10175 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10177 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10178 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10180 g_assert (acfg->aot_opts.llvm_outfile);
10181 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10182 if (acfg->llvm_owriter)
10183 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10185 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10187 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10188 g_strdup_printf ("%s", "temp") :
10189 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10191 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10192 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10193 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10198 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10199 if (acfg->aot_opts.outfile)
10200 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10202 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10203 acfg->fp = fopen (acfg->tmpfname, "w+");
10205 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10206 acfg->fp = fdopen (i, "w+");
10208 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10209 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10213 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10215 tmp_outfile_name = NULL;
10216 outfile_name = NULL;
10218 /* Compute symbols for methods */
10219 for (i = 0; i < acfg->nmethods; ++i) {
10220 if (acfg->cfgs [i]) {
10221 MonoCompile *cfg = acfg->cfgs [i];
10222 int method_index = get_method_index (acfg, cfg->orig_method);
10224 if (COMPILE_LLVM (cfg))
10225 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10226 else if (acfg->global_symbols || acfg->llvm)
10227 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10229 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10230 cfg->asm_debug_symbol = cfg->asm_symbol;
10234 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
10236 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10237 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
10238 * .byte directives.
10240 //acfg->gas_line_numbers = TRUE;
10243 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10244 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10245 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10248 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
10252 mono_img_writer_emit_start (acfg->w);
10255 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10261 emit_extra_methods (acfg);
10263 emit_trampolines (acfg);
10265 emit_class_name_table (acfg);
10267 emit_got_info (acfg, FALSE);
10269 emit_got_info (acfg, TRUE);
10271 emit_exception_info (acfg);
10273 emit_unwind_info (acfg);
10275 emit_class_info (acfg);
10279 emit_image_table (acfg);
10285 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10288 const char *gc_name = mono_gc_get_gc_name ();
10289 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10294 emit_objc_selectors (acfg);
10296 emit_globals (acfg);
10298 emit_file_info (acfg);
10301 emit_dwarf_info (acfg);
10302 mono_dwarf_writer_close (acfg->dwarf);
10305 emit_mem_end (acfg);
10307 if (acfg->need_pt_gnu_stack) {
10308 /* This is required so the .so doesn't have an executable stack */
10309 /* The bin writer already emits this */
10310 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10313 if (acfg->aot_opts.data_outfile)
10314 fclose (acfg->data_outfile);
10320 res = emit_llvm_file (acfg);
10328 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10331 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10333 strcpy (llvm_stats_msg, "");
10335 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;
10337 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",
10338 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10339 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10340 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10341 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10342 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10343 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,
10344 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10345 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10346 (int)(acfg->got_offset * sizeof (gpointer)));
10347 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10348 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10350 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10351 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10352 if (acfg->stats.genericcount)
10353 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10354 if (acfg->stats.abscount)
10355 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10356 if (acfg->stats.lmfcount)
10357 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10358 if (acfg->stats.ocount)
10359 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10363 res = mono_img_writer_emit_writeout (acfg->w);
10368 res = compile_asm (acfg);
10375 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10377 if (acfg->aot_opts.stats) {
10380 aot_printf (acfg, "GOT slot distribution:\n");
10381 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
10382 if (acfg->stats.got_slot_types [i])
10383 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]);
10384 aot_printf (acfg, "\nMethod stats:\n");
10385 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10386 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10387 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10388 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10391 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);
10393 if (acfg->aot_opts.dump_json)
10406 mono_aot_readonly_field_override (MonoClassField *field)
10412 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10418 mono_aot_is_shared_got_offset (int offset)