3 * mono Ahead of Time compiler
6 * Dietmar Maurer (dietmar@ximian.com)
7 * Zoltan Varga (vargaz@gmail.com)
8 * Johan Lorensson (lateralusx.github@gmail.com)
10 * (C) 2002 Ximian, Inc.
11 * Copyright 2003-2011 Novell, Inc
12 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
17 #include <sys/types.h>
37 #include <mono/metadata/abi-details.h>
38 #include <mono/metadata/tabledefs.h>
39 #include <mono/metadata/class.h>
40 #include <mono/metadata/object.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/appdomain.h>
43 #include <mono/metadata/debug-helpers.h>
44 #include <mono/metadata/assembly.h>
45 #include <mono/metadata/metadata-internals.h>
46 #include <mono/metadata/reflection-internals.h>
47 #include <mono/metadata/marshal.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/mempool-internals.h>
50 #include <mono/metadata/mono-endian.h>
51 #include <mono/metadata/threads-types.h>
52 #include <mono/utils/mono-logger-internals.h>
53 #include <mono/utils/mono-compiler.h>
54 #include <mono/utils/mono-time.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/mono-rand.h>
57 #include <mono/utils/json.h>
58 #include <mono/utils/mono-threads-coop.h>
59 #include <mono/profiler/mono-profiler-aot.h>
60 #include <mono/utils/w32api.h>
62 #include "aot-compiler.h"
63 #include "seq-points.h"
64 #include "image-writer.h"
65 #include "dwarfwriter.h"
67 #include "mini-llvm.h"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
72 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
73 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
74 #define TARGET_X86_64_WIN32_MSVC
77 #if defined(TARGET_X86_64_WIN32_MSVC)
78 #define TARGET_WIN32_MSVC
81 #if defined(__linux__)
82 #define RODATA_SECT ".rodata"
83 #elif defined(TARGET_MACH)
84 #define RODATA_SECT ".section __TEXT, __const"
85 #elif defined(TARGET_WIN32_MSVC)
86 #define RODATA_SECT ".rdata"
88 #define RODATA_SECT ".text"
91 #define TV_DECLARE(name) gint64 name
92 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
93 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
95 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
96 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
97 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
104 typedef struct ClassProfileData ClassProfileData;
108 ClassProfileData **argv;
109 MonoGenericInst *inst;
112 struct ClassProfileData {
113 ImageProfileData *image;
115 GInstProfileData *inst;
120 ClassProfileData *klass;
125 GInstProfileData *inst;
130 GHashTable *images, *classes, *ginsts, *methods;
133 /* predefined values for static readonly fields without needed to run the .cctor */
134 typedef struct _ReadOnlyValue ReadOnlyValue;
135 struct _ReadOnlyValue {
138 int type; /* to be used later for typechecking to prevent user errors */
147 static ReadOnlyValue *readonly_values;
149 typedef struct MonoAotOptions {
153 GList *profile_files;
155 gboolean write_symbols;
156 gboolean metadata_only;
157 gboolean bind_to_runtime_version;
160 gboolean static_link;
164 gboolean dwarf_debug;
166 gboolean log_generics;
167 gboolean log_instances;
168 gboolean gen_msym_dir;
169 char *gen_msym_dir_path;
170 gboolean direct_pinvoke;
171 gboolean direct_icalls;
172 gboolean no_direct_calls;
173 gboolean use_trampolines_page;
174 gboolean no_instances;
180 int nrgctx_trampolines;
181 int nimt_trampolines;
182 int ngsharedvt_arg_trampolines;
183 int nrgctx_fetch_trampolines;
184 gboolean print_skipped_methods;
192 char *instances_logfile_path;
195 gboolean profile_only;
200 METHOD_CAT_GSHAREDVT,
206 typedef struct MonoAotStats {
207 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
208 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
209 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
210 int got_slots, offsets_size;
211 int method_categories [METHOD_CAT_NUM];
212 int got_slot_types [MONO_PATCH_INFO_NUM];
213 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
214 int jit_time, gen_time, link_time;
217 typedef struct GotInfo {
218 GHashTable *patch_to_got_offset;
219 GHashTable **patch_to_got_offset_by_type;
220 GPtrArray *got_patches;
223 typedef struct MonoAotCompile {
226 GHashTable *method_indexes;
227 GHashTable *method_depth;
230 GHashTable **patch_to_plt_entry;
231 GHashTable *plt_offset_to_entry;
232 //GHashTable *patch_to_got_offset;
233 //GHashTable **patch_to_got_offset_by_type;
234 //GPtrArray *got_patches;
235 GotInfo got_info, llvm_got_info;
236 GHashTable *image_hash;
237 GHashTable *method_to_cfg;
238 GHashTable *token_info_hash;
239 GHashTable *method_to_pinvoke_import;
240 GPtrArray *extra_methods;
241 GPtrArray *image_table;
243 GPtrArray *method_order;
244 GHashTable *export_names;
245 /* Maps MonoClass* -> blob offset */
246 GHashTable *klass_blob_hash;
247 /* Maps MonoMethod* -> blob offset */
248 GHashTable *method_blob_hash;
249 GHashTable *gsharedvt_in_signatures;
250 GHashTable *gsharedvt_out_signatures;
251 guint32 *plt_got_info_offsets;
252 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
253 /* Number of GOT entries reserved for trampolines */
254 guint32 num_trampoline_got_entries;
255 guint32 tramp_page_size;
257 guint32 table_offsets [MONO_AOT_TABLE_NUM];
258 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
259 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
260 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
261 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
263 MonoAotOptions aot_opts;
267 MonoMemPool *mempool;
270 char *static_linking_symbol;
272 gboolean gas_line_numbers;
273 /* Whenever to emit an object file directly from llc */
274 gboolean llvm_owriter;
275 gboolean llvm_owriter_supported;
277 MonoDwarfWriter *dwarf;
284 GHashTable *unwind_info_offsets;
285 GPtrArray *unwind_ops;
286 guint32 unwind_info_offset;
289 char *llvm_got_symbol;
291 char *llvm_eh_frame_symbol;
292 GHashTable *method_label_hash;
293 const char *temp_prefix;
294 const char *user_symbol_prefix;
295 const char *llvm_label_prefix;
296 const char *inst_directive;
298 guint32 label_generator;
300 gboolean has_jitted_code;
301 gboolean is_full_aot;
302 MonoAotFileFlags flags;
303 MonoDynamicStream blob;
304 gboolean blob_closed;
305 GHashTable *typespec_classes;
308 char *assembly_name_sym;
309 GHashTable *plt_entry_debug_sym_cache;
310 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
311 GHashTable *ginst_hash;
312 GHashTable *dwarf_ln_filenames;
313 gboolean global_symbols;
314 int objc_selector_index, objc_selector_index_2;
315 GPtrArray *objc_selectors;
316 GHashTable *objc_selector_to_index;
318 GHashTable *profile_methods;
320 FILE *instances_logfile;
328 char *symbol, *llvm_symbol, *debug_sym;
330 gboolean jit_used, llvm_used;
333 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
334 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
336 /* This points to the current acfg in LLVM mode */
337 static MonoAotCompile *llvm_acfg;
339 #ifdef HAVE_ARRAY_ELEM_INIT
340 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
341 #define MSGSTRFIELD1(line) str##line
342 static const struct msgstr_t {
343 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
344 #include "patch-info.h"
347 #define PATCH_INFO(a,b) b,
348 #include "patch-info.h"
351 static const gint16 opidx [] = {
352 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
353 #include "patch-info.h"
357 static G_GNUC_UNUSED const char*
358 get_patch_name (int info)
360 return (const char*)&opstr + opidx [info];
364 #define PATCH_INFO(a,b) b,
365 static const char* const
366 patch_types [MONO_PATCH_INFO_NUM + 1] = {
367 #include "patch-info.h"
371 static G_GNUC_UNUSED const char*
372 get_patch_name (int info)
374 return patch_types [info];
380 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
383 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
386 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out);
389 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
392 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
398 output = acfg->logfile;
402 va_start (args, format);
403 vfprintf (output, format, args);
408 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
414 output = acfg->logfile;
418 va_start (args, format);
419 vfprintf (output, format, args);
424 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
429 if (mono_error_ok (error))
433 output = acfg->logfile;
437 va_start (args, format);
438 vfprintf (output, format, args);
440 mono_error_cleanup (error);
442 if (acfg->is_full_aot) {
443 fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
448 /* Wrappers around the image writer functions */
450 #define MAX_SYMBOL_SIZE 256
452 static inline const char *
453 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
455 gsize needed_size = length;
457 g_assert (NULL != symbol);
458 g_assert (NULL != mangled_symbol);
459 g_assert (0 != length);
461 #if defined(TARGET_WIN32) && defined(TARGET_X86)
462 if (symbol && '_' != symbol [0]) {
463 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
465 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
468 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
471 g_assert (0 <= needed_size && needed_size < length);
472 return mangled_symbol;
476 mangle_symbol_alloc (const char * symbol)
478 g_assert (NULL != symbol);
480 #if defined(TARGET_WIN32) && defined(TARGET_X86)
481 if (symbol && '_' != symbol [0]) {
482 return g_strdup_printf ("_%s", symbol);
485 return g_strdup_printf ("%s", symbol);
488 return g_strdup_printf ("%s", symbol);
493 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
495 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
498 #if defined(TARGET_WIN32) && defined(TARGET_X86)
501 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
503 const char * mangled_symbol_name = name;
504 char * mangled_symbol_name_alloc = NULL;
507 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
508 mangled_symbol_name = mangled_symbol_name_alloc;
511 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
512 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
514 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
516 if (NULL != mangled_symbol_name_alloc) {
517 g_free (mangled_symbol_name_alloc);
524 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
526 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
532 emit_label (MonoAotCompile *acfg, const char *name)
534 mono_img_writer_emit_label (acfg->w, name);
538 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
540 mono_img_writer_emit_bytes (acfg->w, buf, size);
544 emit_string (MonoAotCompile *acfg, const char *value)
546 mono_img_writer_emit_string (acfg->w, value);
550 emit_line (MonoAotCompile *acfg)
552 mono_img_writer_emit_line (acfg->w);
556 emit_alignment (MonoAotCompile *acfg, int size)
558 mono_img_writer_emit_alignment (acfg->w, size);
562 emit_alignment_code (MonoAotCompile *acfg, int size)
564 if (acfg->align_pad_value)
565 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
567 mono_img_writer_emit_alignment (acfg->w, size);
571 emit_padding (MonoAotCompile *acfg, int size)
576 if (acfg->align_pad_value) {
577 for (i = 0; i < 16; ++i)
578 buf [i] = acfg->align_pad_value;
580 memset (buf, 0, sizeof (buf));
583 for (i = 0; i < size; i += 16) {
585 emit_bytes (acfg, buf, size - i);
587 emit_bytes (acfg, buf, 16);
592 emit_pointer (MonoAotCompile *acfg, const char *target)
594 mono_img_writer_emit_pointer (acfg->w, target);
598 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
600 if (prefix [0] != '\0') {
601 char *s = g_strdup_printf ("%s%s", prefix, target);
602 mono_img_writer_emit_pointer (acfg->w, s);
605 mono_img_writer_emit_pointer (acfg->w, target);
610 emit_int16 (MonoAotCompile *acfg, int value)
612 mono_img_writer_emit_int16 (acfg->w, value);
616 emit_int32 (MonoAotCompile *acfg, int value)
618 mono_img_writer_emit_int32 (acfg->w, value);
622 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
624 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
628 emit_zero_bytes (MonoAotCompile *acfg, int num)
630 mono_img_writer_emit_zero_bytes (acfg->w, num);
634 emit_byte (MonoAotCompile *acfg, guint8 val)
636 mono_img_writer_emit_byte (acfg->w, val);
639 #if defined(TARGET_WIN32) && defined(TARGET_X86)
641 static G_GNUC_UNUSED void
642 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
644 const char * mangled_symbol_name = name;
645 char * mangled_symbol_name_alloc = NULL;
647 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
648 mangled_symbol_name = mangled_symbol_name_alloc;
650 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
651 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
653 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
655 if (NULL != mangled_symbol_name_alloc) {
656 g_free (mangled_symbol_name_alloc);
662 static G_GNUC_UNUSED void
663 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
665 mono_img_writer_emit_global (acfg->w, name, func);
670 static inline gboolean
671 link_shared_library (MonoAotCompile *acfg)
673 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
676 static inline gboolean
677 add_to_global_symbol_table (MonoAotCompile *acfg)
679 #ifdef TARGET_WIN32_MSVC
680 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
682 return acfg->aot_opts.no_dlsym;
687 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
689 if (add_to_global_symbol_table (acfg))
690 g_ptr_array_add (acfg->globals, g_strdup (name));
692 if (acfg->aot_opts.no_dlsym) {
693 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
695 emit_global_inner (acfg, name, func);
700 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
702 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
705 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
707 emit_info_symbol (MonoAotCompile *acfg, const char *name)
709 char symbol [MAX_SYMBOL_SIZE];
712 emit_label (acfg, name);
713 /* LLVM generated code references this */
714 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
715 emit_label (acfg, symbol);
716 emit_global_inner (acfg, symbol, FALSE);
718 emit_label (acfg, name);
723 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
726 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
730 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
732 /* On apple, all symbols need to be aligned to avoid warnings from ld */
733 emit_alignment (acfg, 4);
735 mono_img_writer_emit_label (acfg->w, name);
736 mono_img_writer_emit_string (acfg->w, value);
739 static G_GNUC_UNUSED void
740 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
743 guint8 b = value & 0x7f;
745 if (value != 0) /* more bytes to come */
751 static G_GNUC_UNUSED void
752 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
755 gboolean negative = (value < 0);
762 /* the following is unnecessary if the
763 * implementation of >>= uses an arithmetic rather
764 * than logical shift for a signed left operand
768 value |= - ((gint64)1 <<(size - 7));
769 /* sign bit of byte is second high order bit (0x40) */
770 if ((value == 0 && !(byte & 0x40)) ||
771 (value == -1 && (byte & 0x40)))
775 emit_byte (acfg, byte);
779 static G_GNUC_UNUSED void
780 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
785 guint8 b = value & 0x7f;
787 if (value != 0) /* more bytes to come */
795 static G_GNUC_UNUSED void
796 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
799 gboolean negative = (value < 0);
807 /* the following is unnecessary if the
808 * implementation of >>= uses an arithmetic rather
809 * than logical shift for a signed left operand
813 value |= - (1 <<(size - 7));
814 /* sign bit of byte is second high order bit (0x40) */
815 if ((value == 0 && !(byte & 0x40)) ||
816 (value == -1 && (byte & 0x40)))
827 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
830 buf [0] = (val >> 0) & 0xff;
831 buf [1] = (val >> 8) & 0xff;
832 buf [2] = (val >> 16) & 0xff;
833 buf [3] = (val >> 24) & 0xff;
839 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
841 buf [0] = (val >> 0) & 0xff;
842 buf [1] = (val >> 8) & 0xff;
848 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
850 int len = strlen (s);
852 memcpy (buf, s, len + 1);
853 *endbuf = buf + len + 1;
857 emit_unset_mode (MonoAotCompile *acfg)
859 mono_img_writer_emit_unset_mode (acfg->w);
862 static G_GNUC_UNUSED void
863 emit_set_thumb_mode (MonoAotCompile *acfg)
865 emit_unset_mode (acfg);
866 fprintf (acfg->fp, ".code 16\n");
869 static G_GNUC_UNUSED void
870 emit_set_arm_mode (MonoAotCompile *acfg)
872 emit_unset_mode (acfg);
873 fprintf (acfg->fp, ".code 32\n");
877 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
882 g_assert (size % 4 == 0);
883 emit_unset_mode (acfg);
884 for (i = 0; i < size; i += 4)
885 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
887 emit_bytes (acfg, buf, size);
891 /* ARCHITECTURE SPECIFIC CODE */
893 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
894 #define EMIT_DWARF_INFO 1
897 #ifdef TARGET_WIN32_MSVC
898 #undef EMIT_DWARF_INFO
901 #if defined(TARGET_ARM)
902 #define AOT_FUNC_ALIGNMENT 4
904 #define AOT_FUNC_ALIGNMENT 16
907 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
908 #define PPC_LD_OP "ld"
909 #define PPC_LDX_OP "ldx"
911 #define PPC_LD_OP "lwz"
912 #define PPC_LDX_OP "lwzx"
915 #ifdef TARGET_X86_64_WIN32_MSVC
916 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
918 #define AOT_TARGET_STR "AMD64"
923 #define AOT_TARGET_STR "ARM (MACH)"
925 #define AOT_TARGET_STR "ARM (!MACH)"
931 #define AOT_TARGET_STR "ARM64 (MACH)"
933 #define AOT_TARGET_STR "ARM64 (!MACH)"
937 #ifdef TARGET_POWERPC64
938 #ifdef __mono_ilp32__
939 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
941 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
944 #ifdef TARGET_POWERPC
945 #ifdef __mono_ilp32__
946 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
948 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
955 #define AOT_TARGET_STR "X86 (WIN32)"
957 #define AOT_TARGET_STR "X86"
961 #ifndef AOT_TARGET_STR
962 #define AOT_TARGET_STR ""
966 arch_init (MonoAotCompile *acfg)
968 acfg->llc_args = g_string_new ("");
969 acfg->as_args = g_string_new ("");
970 acfg->llvm_owriter_supported = TRUE;
973 * The prefix LLVM likes to put in front of symbol names on darwin.
974 * The mach-os specs require this for globals, but LLVM puts them in front of all
975 * symbols. We need to handle this, since we need to refer to LLVM generated
978 acfg->llvm_label_prefix = "";
979 acfg->user_symbol_prefix = "";
981 #if defined(TARGET_X86)
982 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
985 #if defined(TARGET_AMD64)
986 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
988 acfg->align_pad_value = 0x90;
992 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
993 g_string_append (acfg->llc_args, "-mattr=+v6");
995 #if defined(ARM_FPU_VFP_HARD)
996 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
997 g_string_append (acfg->as_args, " -mfpu=vfp3");
998 #elif defined(ARM_FPU_VFP)
999 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1000 g_string_append (acfg->as_args, " -mfpu=vfp3");
1002 g_string_append (acfg->llc_args, " -soft-float");
1005 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1006 acfg->thumb_mixed = TRUE;
1008 if (acfg->aot_opts.mtriple)
1009 mono_arch_set_target (acfg->aot_opts.mtriple);
1013 acfg->inst_directive = ".inst";
1014 if (acfg->aot_opts.mtriple)
1015 mono_arch_set_target (acfg->aot_opts.mtriple);
1019 acfg->user_symbol_prefix = "_";
1020 acfg->llvm_label_prefix = "_";
1021 acfg->inst_directive = ".word";
1022 acfg->need_no_dead_strip = TRUE;
1023 acfg->aot_opts.gnu_asm = TRUE;
1026 #if defined(__linux__) && !defined(TARGET_ARM)
1027 acfg->need_pt_gnu_stack = TRUE;
1031 acfg->global_symbols = TRUE;
1034 #ifdef TARGET_ANDROID
1035 acfg->llvm_owriter_supported = FALSE;
1042 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1044 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1048 g_assert (acfg->fp);
1049 emit_unset_mode (acfg);
1051 offset = (int)(got_slot * sizeof (gpointer));
1053 /* clang's integrated assembler */
1054 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1055 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1056 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1059 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1060 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1061 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1066 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1070 g_assert (acfg->fp);
1071 emit_unset_mode (acfg);
1073 /* ldr rt, target */
1074 reg = arm_get_ldr_lit_reg (code);
1076 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1077 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1078 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1084 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1086 g_assert (acfg->fp);
1087 emit_unset_mode (acfg);
1088 if (ji && ji->relocation == MONO_R_ARM64_B) {
1089 fprintf (acfg->fp, "b %s\n", target);
1092 g_assert (ji->relocation == MONO_R_ARM64_BL);
1093 fprintf (acfg->fp, "bl %s\n", target);
1099 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1103 /* ldr rt, target */
1104 reg = arm_get_ldr_lit_reg (code);
1105 arm64_emit_load_got_slot (acfg, reg, got_slot);
1110 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1112 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1113 fprintf (acfg->fp, "br x16\n");
1114 /* Used by mono_aot_get_plt_info_offset () */
1115 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1119 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1125 /* The common code */
1128 /* The trampoline address is in IP0 */
1129 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1130 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1131 /* Compute the data slot address */
1132 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1133 /* Trampoline argument */
1134 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1136 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1137 arm_brx (code, ARMREG_IP0);
1140 emit_code_bytes (acfg, buf, code - buf);
1146 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1152 count = (pagesize - common_tramp_size) / specific_tramp_size;
1153 for (i = 0; i < count; ++i) {
1155 arm_adrx (code, ARMREG_IP0, code);
1156 /* Branch to the generic code */
1157 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1158 /* This has to be 2 pointers long */
1161 g_assert (code - buf == specific_tramp_size);
1162 emit_code_bytes (acfg, buf, code - buf);
1167 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1171 guint8 *labels [16];
1172 int common_tramp_size;
1173 int specific_tramp_size = 2 * 8;
1177 if (!acfg->aot_opts.use_trampolines_page)
1181 /* Have to match the target pagesize */
1184 pagesize = mono_pagesize ();
1186 acfg->tramp_page_size = pagesize;
1188 /* The specific trampolines */
1189 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1190 emit_alignment (acfg, pagesize);
1191 emit_global (acfg, symbol, TRUE);
1192 emit_label (acfg, symbol);
1194 /* The common code */
1195 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1196 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1198 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1200 /* The rgctx trampolines */
1201 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1202 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1203 emit_alignment (acfg, pagesize);
1204 emit_global (acfg, symbol, TRUE);
1205 emit_label (acfg, symbol);
1207 /* The common code */
1208 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1209 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1211 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1213 /* The gsharedvt arg trampolines */
1214 /* These are the same as the specific trampolines */
1215 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1216 emit_alignment (acfg, pagesize);
1217 emit_global (acfg, symbol, TRUE);
1218 emit_label (acfg, symbol);
1220 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1221 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1223 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1225 /* The IMT trampolines */
1226 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1227 emit_alignment (acfg, pagesize);
1228 emit_global (acfg, symbol, TRUE);
1229 emit_label (acfg, symbol);
1233 /* The trampoline address is in IP0 */
1234 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1235 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1236 /* Compute the data slot address */
1237 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1238 /* Trampoline argument */
1239 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1241 /* Same as arch_emit_imt_trampoline () */
1243 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1244 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1246 arm_bcc (code, ARMCOND_EQ, 0);
1248 /* End-of-loop check */
1250 arm_cbzx (code, ARMREG_IP0, 0);
1253 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1254 arm_b (code, labels [0]);
1257 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1258 /* Load vtable slot addr */
1259 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1260 /* Load vtable slot */
1261 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1262 arm_brx (code, ARMREG_IP0);
1265 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1266 /* Load fail addr */
1267 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1268 arm_brx (code, ARMREG_IP0);
1270 emit_code_bytes (acfg, buf, code - buf);
1272 common_tramp_size = code - buf;
1273 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1275 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1279 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1281 /* Load argument from second GOT slot */
1282 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1283 /* Load generic trampoline address from first GOT slot */
1284 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1285 fprintf (acfg->fp, "br x16\n");
1286 *tramp_size = 7 * 4;
1290 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1292 emit_unset_mode (acfg);
1293 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1294 fprintf (acfg->fp, "b %s\n", call_target);
1298 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1300 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1302 /* Load argument from first GOT slot */
1303 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1304 /* Load generic trampoline address from second GOT slot */
1305 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1306 fprintf (acfg->fp, "br x16\n");
1307 *tramp_size = 7 * 4;
1311 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1314 guint8 *code, *labels [16];
1316 /* Load parameter from GOT slot into ip1 */
1317 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1321 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1322 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1324 arm_bcc (code, ARMCOND_EQ, 0);
1326 /* End-of-loop check */
1328 arm_cbzx (code, ARMREG_IP0, 0);
1331 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1332 arm_b (code, labels [0]);
1335 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1336 /* Load vtable slot addr */
1337 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1338 /* Load vtable slot */
1339 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1340 arm_brx (code, ARMREG_IP0);
1343 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1344 /* Load fail addr */
1345 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1346 arm_brx (code, ARMREG_IP0);
1348 emit_code_bytes (acfg, buf, code - buf);
1350 *tramp_size = code - buf + (3 * 4);
1354 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1356 /* Similar to the specific trampolines, but the address is in the second slot */
1357 /* Load argument from first GOT slot */
1358 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1359 /* Load generic trampoline address from second GOT slot */
1360 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1361 fprintf (acfg->fp, "br x16\n");
1362 *tramp_size = 7 * 4;
1368 #ifdef MONO_ARCH_AOT_SUPPORTED
1370 * arch_emit_direct_call:
1372 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1376 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1378 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1379 /* Need to make sure this is exactly 5 bytes long */
1380 emit_unset_mode (acfg);
1381 fprintf (acfg->fp, "call %s\n", target);
1383 #elif defined(TARGET_ARM)
1384 emit_unset_mode (acfg);
1386 fprintf (acfg->fp, "blx %s\n", target);
1388 fprintf (acfg->fp, "bl %s\n", target);
1390 #elif defined(TARGET_ARM64)
1391 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1392 #elif defined(TARGET_POWERPC)
1393 emit_unset_mode (acfg);
1394 fprintf (acfg->fp, "bl %s\n", target);
1397 g_assert_not_reached ();
1404 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1406 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1407 * in in the 2. slot of every GOT, and require every method to place the GOT
1408 * address in r30, even when it doesn't access the GOT otherwise. This way,
1409 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1414 * PPC64 uses function descriptors which greatly complicate all code, since
1415 * these are used very inconsistently in the runtime. Some functions like
1416 * mono_compile_method () return ftn descriptors, while others like the
1417 * trampoline creation functions do not.
1418 * We assume that all GOT slots contain function descriptors, and create
1419 * descriptors in aot-runtime.c when needed.
1420 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1421 * from function descriptors, we could do the same, but it would require
1422 * rewriting all the ppc/aot code to handle function descriptors properly.
1423 * So instead, we use the same approach as on PPC32.
1424 * This is a horrible mess, but fixing it would probably lead to an even bigger
1430 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1433 #ifdef MONO_ARCH_AOT_SUPPORTED
1435 * arch_emit_got_offset:
1437 * The memory pointed to by CODE should hold native code for computing the GOT
1438 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1439 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1442 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1444 #if defined(TARGET_POWERPC64)
1445 emit_unset_mode (acfg);
1447 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1448 * unsupported relocations. So we store the got address into the .Lgot_addr
1449 * symbol which is in the text segment, compute its address, and load it.
1451 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1452 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1453 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1454 fprintf (acfg->fp, "add 30, 30, 0\n");
1455 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1456 acfg->label_generator ++;
1458 #elif defined(TARGET_POWERPC)
1459 emit_unset_mode (acfg);
1460 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1461 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1462 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1463 acfg->label_generator ++;
1466 guint32 offset = mono_arch_get_patch_offset (code);
1467 emit_bytes (acfg, code, offset);
1468 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1470 *code_size = offset + 4;
1475 * arch_emit_got_access:
1477 * The memory pointed to by CODE should hold native code for loading a GOT
1478 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1479 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1482 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1485 /* mov reg, got+offset(%rip) */
1487 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1491 /* Decode reg, see amd64_mov_reg_membase () */
1492 rex_r = code [0] & AMD64_REX_R;
1493 g_assert (code [0] == 0x49 + rex_r);
1494 g_assert (code [1] == 0x8b);
1495 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1497 emit_unset_mode (acfg);
1498 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1501 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1502 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1503 *code_size = mono_arch_get_patch_offset (code) + 4;
1505 #elif defined(TARGET_X86)
1506 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1507 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1508 *code_size = mono_arch_get_patch_offset (code) + 4;
1509 #elif defined(TARGET_ARM)
1510 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1511 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1512 *code_size = mono_arch_get_patch_offset (code) + 4;
1513 #elif defined(TARGET_ARM64)
1514 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1515 arm64_emit_got_access (acfg, code, got_slot, code_size);
1516 #elif defined(TARGET_POWERPC)
1520 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1522 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1523 g_assert (code - buf == 8);
1524 emit_bytes (acfg, buf, code - buf);
1525 *code_size = code - buf;
1528 g_assert_not_reached ();
1534 #ifdef MONO_ARCH_AOT_SUPPORTED
1536 * arch_emit_objc_selector_ref:
1538 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1541 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1543 #if defined(TARGET_ARM)
1544 char symbol1 [MAX_SYMBOL_SIZE];
1545 char symbol2 [MAX_SYMBOL_SIZE];
1546 int lindex = acfg->objc_selector_index_2 ++;
1548 /* Emit ldr.imm/b */
1549 emit_bytes (acfg, code, 8);
1551 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1552 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1554 emit_label (acfg, symbol1);
1555 mono_img_writer_emit_unset_mode (acfg->w);
1556 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1559 #elif defined(TARGET_ARM64)
1560 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1562 g_assert_not_reached ();
1568 * arch_emit_plt_entry:
1570 * Emit code for the PLT entry.
1571 * The plt entry should look like this:
1572 * <indirect jump to GOT_SYMBOL + OFFSET>
1573 * <INFO_OFFSET embedded into the instruction stream>
1576 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1578 #if defined(TARGET_X86)
1579 /* jmp *<offset>(%ebx) */
1580 emit_byte (acfg, 0xff);
1581 emit_byte (acfg, 0xa3);
1582 emit_int32 (acfg, offset);
1583 /* Used by mono_aot_get_plt_info_offset */
1584 emit_int32 (acfg, info_offset);
1585 #elif defined(TARGET_AMD64)
1586 emit_unset_mode (acfg);
1587 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1588 /* Used by mono_aot_get_plt_info_offset */
1589 emit_int32 (acfg, info_offset);
1590 acfg->stats.plt_size += 10;
1591 #elif defined(TARGET_ARM)
1596 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1597 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1598 emit_bytes (acfg, buf, code - buf);
1599 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1600 /* Used by mono_aot_get_plt_info_offset */
1601 emit_int32 (acfg, info_offset);
1602 #elif defined(TARGET_ARM64)
1603 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1604 #elif defined(TARGET_POWERPC)
1605 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1606 emit_unset_mode (acfg);
1607 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1608 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1609 fprintf (acfg->fp, "add 11, 11, 30\n");
1610 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1611 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1612 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1613 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1615 fprintf (acfg->fp, "mtctr 11\n");
1616 fprintf (acfg->fp, "bctr\n");
1617 emit_int32 (acfg, info_offset);
1619 g_assert_not_reached ();
1624 * arch_emit_llvm_plt_entry:
1626 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1627 * This is only needed on arm to handle thumb interop.
1630 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1632 #if defined(TARGET_ARM)
1633 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1634 /* The caller already transitioned to thumb */
1635 /* The code below should be 12 bytes long */
1636 /* clang has trouble encoding these instructions, so emit the binary */
1638 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1639 /* thumb can't encode ld pc, [pc, ip] */
1640 fprintf (acfg->fp, "add ip, pc, ip\n");
1641 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1642 fprintf (acfg->fp, "bx ip\n");
1644 emit_set_thumb_mode (acfg);
1645 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1646 fprintf (acfg->fp, ".2byte 0x44fc\n");
1647 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1648 fprintf (acfg->fp, ".2byte 0x4760\n");
1649 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1650 emit_int32 (acfg, info_offset);
1651 emit_unset_mode (acfg);
1652 emit_set_arm_mode (acfg);
1654 g_assert_not_reached ();
1658 /* Save unwind_info in the module and emit the offset to the information at symbol */
1659 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1661 guint32 uw_offset, encoded_len;
1664 emit_section_change (acfg, RODATA_SECT, 0);
1665 emit_global (acfg, symbol, FALSE);
1666 emit_label (acfg, symbol);
1668 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1669 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1671 emit_int32 (acfg, uw_offset);
1675 * arch_emit_specific_trampoline_pages:
1677 * Emits a page full of trampolines: each trampoline uses its own address to
1678 * lookup both the generic trampoline code and the data argument.
1679 * This page can be remapped in process multiple times so we can get an
1680 * unlimited number of trampolines.
1681 * Specifically this implementation uses the following trick: two memory pages
1682 * are allocated, with the first containing the data and the second containing the trampolines.
1683 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1684 * implementation does all the lifting.
1685 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1686 * on the arm 32 bit system.
1689 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1691 #if defined(TARGET_ARM)
1694 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1696 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1697 GSList *unwind_ops = NULL;
1698 #define COMMON_TRAMP_SIZE 16
1699 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1700 int imm8, rot_amount;
1703 if (!acfg->aot_opts.use_trampolines_page)
1706 acfg->tramp_page_size = pagesize;
1708 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1709 emit_alignment (acfg, pagesize);
1710 emit_global (acfg, symbol, TRUE);
1711 emit_label (acfg, symbol);
1713 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1715 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1716 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1717 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1718 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1720 g_assert (code - buf == COMMON_TRAMP_SIZE);
1723 emit_bytes (acfg, buf, code - buf);
1725 for (i = 0; i < count; ++i) {
1727 ARM_PUSH (code, 0x5fff);
1729 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1730 g_assert (code - buf == 8);
1731 emit_bytes (acfg, buf, code - buf);
1734 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1735 * the instruction pointer address, so the generic trampoline at the start of the page
1736 * subtracts 4096 to get to the data page and loads the values
1737 * We again fit the generic trampiline in 16 bytes.
1739 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1740 emit_global (acfg, symbol, TRUE);
1741 emit_label (acfg, symbol);
1743 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1744 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1745 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1746 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1748 g_assert (code - buf == COMMON_TRAMP_SIZE);
1751 emit_bytes (acfg, buf, code - buf);
1753 for (i = 0; i < count; ++i) {
1755 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1757 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1758 g_assert (code - buf == 8);
1759 emit_bytes (acfg, buf, code - buf);
1763 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1765 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1766 emit_global (acfg, symbol, TRUE);
1767 emit_label (acfg, symbol);
1769 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1770 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1771 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1772 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1773 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1774 g_assert (code - buf == COMMON_TRAMP_SIZE);
1776 emit_bytes (acfg, buf, code - buf);
1778 for (i = 0; i < count; ++i) {
1780 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1782 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1783 g_assert (code - buf == 8);
1784 emit_bytes (acfg, buf, code - buf);
1787 /* now the imt trampolines: each specific trampolines puts in the ip register
1788 * the instruction pointer address, so the generic trampoline at the start of the page
1789 * subtracts 4096 to get to the data page and loads the values
1791 #define IMT_TRAMP_SIZE 72
1792 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1793 emit_global (acfg, symbol, TRUE);
1794 emit_label (acfg, symbol);
1796 /* Need at least two free registers, plus a slot for storing the pc */
1797 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1799 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1800 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1801 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1803 /* The IMT method is in v5, r0 has the imt array address */
1806 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1807 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1808 imt_found_check = code;
1809 ARM_B_COND (code, ARMCOND_EQ, 0);
1811 /* End-of-loop check */
1812 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1813 loop_end_check = code;
1814 ARM_B_COND (code, ARMCOND_EQ, 0);
1817 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1818 loop_branch_back = code;
1820 arm_patch (loop_branch_back, loop_start);
1823 arm_patch (imt_found_check, code);
1824 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1825 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1826 /* Save it to the third stack slot */
1827 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1828 /* Restore the registers and branch */
1829 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1832 arm_patch (loop_end_check, code);
1833 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1834 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1835 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1839 g_assert (code - buf == IMT_TRAMP_SIZE);
1840 emit_bytes (acfg, buf, code - buf);
1842 for (i = 0; i < count; ++i) {
1844 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1846 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1847 g_assert (code - buf == 8);
1848 emit_bytes (acfg, buf, code - buf);
1851 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1852 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1853 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1854 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1856 /* Unwind info for specifc trampolines */
1857 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1858 /* We unwind to the original caller, from the stack, since lr is clobbered */
1859 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1860 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1861 save_unwind_info (acfg, symbol, unwind_ops);
1862 mono_free_unwind_info (unwind_ops);
1864 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1865 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1866 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1867 save_unwind_info (acfg, symbol, unwind_ops);
1868 mono_free_unwind_info (unwind_ops);
1870 /* Unwind info for rgctx trampolines */
1871 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1872 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1873 save_unwind_info (acfg, symbol, unwind_ops);
1875 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1876 save_unwind_info (acfg, symbol, unwind_ops);
1877 mono_free_unwind_info (unwind_ops);
1879 /* Unwind info for gsharedvt trampolines */
1880 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1881 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1882 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1883 save_unwind_info (acfg, symbol, unwind_ops);
1884 mono_free_unwind_info (unwind_ops);
1886 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1887 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1888 save_unwind_info (acfg, symbol, unwind_ops);
1889 mono_free_unwind_info (unwind_ops);
1891 /* Unwind info for imt trampolines */
1892 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1893 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1894 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1895 save_unwind_info (acfg, symbol, unwind_ops);
1896 mono_free_unwind_info (unwind_ops);
1898 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1899 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1900 save_unwind_info (acfg, symbol, unwind_ops);
1901 mono_free_unwind_info (unwind_ops);
1902 #elif defined(TARGET_ARM64)
1903 arm64_emit_specific_trampoline_pages (acfg);
1908 * arch_emit_specific_trampoline:
1910 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1911 * two GOT slots which contain the generic trampoline address and the trampoline
1912 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1915 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1918 * The trampolines created here are variations of the specific
1919 * trampolines created in mono_arch_create_specific_trampoline (). The
1921 * - the generic trampoline address is taken from a got slot.
1922 * - the offset of the got slot where the trampoline argument is stored
1923 * is embedded in the instruction stream, and the generic trampoline
1924 * can load the argument by loading the offset, adding it to the
1925 * address of the trampoline to get the address of the got slot, and
1926 * loading the argument from there.
1927 * - all the trampolines should be of the same length.
1929 #if defined(TARGET_AMD64)
1930 /* This should be exactly 8 bytes long */
1932 /* call *<offset>(%rip) */
1934 emit_unset_mode (acfg);
1935 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1936 emit_zero_bytes (acfg, 2);
1938 emit_byte (acfg, '\x41');
1939 emit_byte (acfg, '\xff');
1940 emit_byte (acfg, '\x15');
1941 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1942 emit_zero_bytes (acfg, 1);
1944 #elif defined(TARGET_ARM)
1948 /* This should be exactly 20 bytes long */
1951 ARM_PUSH (code, 0x5fff);
1952 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1953 /* Load the value from the GOT */
1954 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1956 ARM_BLX_REG (code, ARMREG_R1);
1958 g_assert (code - buf == 16);
1961 emit_bytes (acfg, buf, code - buf);
1963 * Only one offset is needed, since the second one would be equal to the
1966 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1967 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1968 #elif defined(TARGET_ARM64)
1969 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1970 #elif defined(TARGET_POWERPC)
1978 * PPC has no ip relative addressing, so we need to compute the address
1979 * of the mscorlib got. That is slow and complex, so instead, we store it
1980 * in the second got slot of every aot image. The caller already computed
1981 * the address of its got and placed it into r30.
1983 emit_unset_mode (acfg);
1984 /* Load mscorlib got address */
1985 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1986 /* Load generic trampoline address */
1987 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1988 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1989 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1990 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1991 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1993 fprintf (acfg->fp, "mtctr 11\n");
1994 /* Load trampoline argument */
1995 /* On ppc, we pass it normally to the generic trampoline */
1996 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1997 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1998 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1999 /* Branch to generic trampoline */
2000 fprintf (acfg->fp, "bctr\n");
2002 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2003 *tramp_size = 10 * 4;
2005 *tramp_size = 9 * 4;
2007 #elif defined(TARGET_X86)
2011 /* Similar to the PPC code above */
2013 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2016 /* Load mscorlib got address */
2017 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2018 /* Push trampoline argument */
2019 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2020 /* Load generic trampoline address */
2021 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2022 /* Branch to generic trampoline */
2023 x86_jump_reg (code, X86_ECX);
2025 emit_bytes (acfg, buf, code - buf);
2028 g_assert (code - buf == *tramp_size);
2030 g_assert_not_reached ();
2035 * arch_emit_unbox_trampoline:
2037 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2038 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2041 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2043 #if defined(TARGET_AMD64)
2048 this_reg = mono_arch_get_this_arg_reg (NULL);
2050 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2052 emit_bytes (acfg, buf, code - buf);
2055 emit_unset_mode (acfg);
2056 fprintf (acfg->fp, "jmp %s\n", call_target);
2058 emit_byte (acfg, '\xe9');
2059 emit_symbol_diff (acfg, call_target, ".", -4);
2061 #elif defined(TARGET_X86)
2068 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2070 emit_bytes (acfg, buf, code - buf);
2073 emit_byte (acfg, '\xe9');
2074 emit_symbol_diff (acfg, call_target, ".", -4);
2075 #elif defined(TARGET_ARM)
2079 if (acfg->thumb_mixed && cfg->compile_llvm) {
2080 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2081 fprintf (acfg->fp, "b %s\n", call_target);
2082 fprintf (acfg->fp, ".arm\n");
2083 fprintf (acfg->fp, ".align 2\n");
2089 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2091 emit_bytes (acfg, buf, code - buf);
2092 /* jump to method */
2093 if (acfg->thumb_mixed && cfg->compile_llvm)
2094 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2096 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2097 #elif defined(TARGET_ARM64)
2098 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2099 #elif defined(TARGET_POWERPC)
2102 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2103 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2105 g_assert_not_reached ();
2110 * arch_emit_static_rgctx_trampoline:
2112 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2113 * two GOT slots which contain the rgctx argument, and the method to jump to.
2114 * TRAMP_SIZE is set to the size of the emitted trampoline.
2115 * These kinds of trampolines cannot be enumerated statically, since there could
2116 * be one trampoline per method instantiation, so we emit the same code for all
2117 * trampolines, and parameterize them using two GOT slots.
2120 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2122 #if defined(TARGET_AMD64)
2123 /* This should be exactly 13 bytes long */
2127 emit_unset_mode (acfg);
2128 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2129 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2131 /* mov <OFFSET>(%rip), %r10 */
2132 emit_byte (acfg, '\x4d');
2133 emit_byte (acfg, '\x8b');
2134 emit_byte (acfg, '\x15');
2135 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2137 /* jmp *<offset>(%rip) */
2138 emit_byte (acfg, '\xff');
2139 emit_byte (acfg, '\x25');
2140 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2142 #elif defined(TARGET_ARM)
2146 /* This should be exactly 24 bytes long */
2149 /* Load rgctx value */
2150 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2151 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2152 /* Load branch addr + branch */
2153 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2154 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2156 g_assert (code - buf == 16);
2159 emit_bytes (acfg, buf, code - buf);
2160 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2161 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2162 #elif defined(TARGET_ARM64)
2163 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2164 #elif defined(TARGET_POWERPC)
2172 * PPC has no ip relative addressing, so we need to compute the address
2173 * of the mscorlib got. That is slow and complex, so instead, we store it
2174 * in the second got slot of every aot image. The caller already computed
2175 * the address of its got and placed it into r30.
2177 emit_unset_mode (acfg);
2178 /* Load mscorlib got address */
2179 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2181 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2182 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2183 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2184 /* Load target address */
2185 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2186 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2187 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2188 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2189 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2190 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2192 fprintf (acfg->fp, "mtctr 11\n");
2193 /* Branch to the target address */
2194 fprintf (acfg->fp, "bctr\n");
2196 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2197 *tramp_size = 11 * 4;
2199 *tramp_size = 9 * 4;
2202 #elif defined(TARGET_X86)
2206 /* Similar to the PPC code above */
2208 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2211 /* Load mscorlib got address */
2212 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2214 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2215 /* Branch to the target address */
2216 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2218 emit_bytes (acfg, buf, code - buf);
2221 g_assert (code - buf == *tramp_size);
2223 g_assert_not_reached ();
2228 * arch_emit_imt_trampoline:
2230 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2231 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2232 * key is the IMT key, and ptr holds the address of a memory location holding
2233 * the address to branch to if the IMT arg matches the key. The array is
2234 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2236 * TRAMP_SIZE is set to the size of the emitted trampoline.
2239 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2241 #if defined(TARGET_AMD64)
2243 guint8 *labels [16];
2245 guint8 *mov_buf_ptr = mov_buf;
2247 const int kSizeOfMove = 7;
2249 code = buf = (guint8 *)g_malloc (256);
2251 /* FIXME: Optimize this, i.e. use binary search etc. */
2252 /* Maybe move the body into a separate function (slower, but much smaller) */
2254 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2257 emit_unset_mode (acfg);
2258 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2262 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2264 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2267 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2269 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2272 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2273 amd64_jump_code (code, labels [0]);
2276 mono_amd64_patch (labels [2], code);
2277 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2278 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2281 mono_amd64_patch (labels [1], code);
2282 /* Load fail tramp */
2283 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2284 /* Check if there is a fail tramp */
2285 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2287 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2288 /* Jump to fail tramp */
2289 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2292 mono_amd64_patch (labels [3], code);
2293 x86_breakpoint (code);
2296 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2297 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2298 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2299 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2300 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2301 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2303 emit_bytes (acfg, buf, code - buf);
2305 *tramp_size = code - buf + kSizeOfMove;
2309 #elif defined(TARGET_X86)
2311 guint8 *labels [16];
2313 code = buf = g_malloc (256);
2315 /* Allocate a temporary stack slot */
2316 x86_push_reg (code, X86_EAX);
2318 x86_push_reg (code, X86_EAX);
2320 /* Load mscorlib got address */
2321 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2323 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2326 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2328 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2331 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2333 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2336 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2337 x86_jump_code (code, labels [0]);
2340 mono_x86_patch (labels [2], code);
2341 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2342 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2343 /* Save the target address to the temporary stack location */
2344 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2346 x86_pop_reg (code, X86_EAX);
2347 /* Jump to the target address */
2351 mono_x86_patch (labels [1], code);
2352 /* Load fail tramp */
2353 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2354 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2356 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2357 /* Jump to fail tramp */
2358 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2359 x86_pop_reg (code, X86_EAX);
2363 mono_x86_patch (labels [3], code);
2364 x86_breakpoint (code);
2366 emit_bytes (acfg, buf, code - buf);
2368 *tramp_size = code - buf;
2372 #elif defined(TARGET_ARM)
2374 guint8 *code, *code2, *labels [16];
2378 /* The IMT method is in v5 */
2380 /* Need at least two free registers, plus a slot for storing the pc */
2381 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2383 /* Load the parameter from the GOT */
2384 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2385 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2388 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2389 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2391 ARM_B_COND (code, ARMCOND_EQ, 0);
2393 /* End-of-loop check */
2394 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2396 ARM_B_COND (code, ARMCOND_EQ, 0);
2399 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2402 arm_patch (labels [4], labels [1]);
2405 arm_patch (labels [2], code);
2406 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2407 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2408 /* Save it to the third stack slot */
2409 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2410 /* Restore the registers and branch */
2411 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2414 arm_patch (labels [3], code);
2415 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2416 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2417 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2421 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2423 emit_bytes (acfg, buf, code - buf);
2424 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2426 *tramp_size = code - buf + 4;
2427 #elif defined(TARGET_ARM64)
2428 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2429 #elif defined(TARGET_POWERPC)
2431 guint8 *code, *labels [16];
2435 /* Load the mscorlib got address */
2436 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2437 /* Load the parameter from the GOT */
2438 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2439 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2441 /* Load and check key */
2443 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2444 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2446 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2448 /* End-of-loop check */
2449 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2451 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2454 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2457 mono_ppc_patch (labels [4], labels [1]);
2460 mono_ppc_patch (labels [2], code);
2461 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2462 /* r12 now contains the value of the vtable slot */
2463 /* this is not a function descriptor on ppc64 */
2464 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2465 ppc_mtctr (code, ppc_r12);
2466 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2469 mono_ppc_patch (labels [3], code);
2473 *tramp_size = code - buf;
2475 emit_bytes (acfg, buf, code - buf);
2477 g_assert_not_reached ();
2482 #if defined (TARGET_AMD64)
2485 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2488 g_assert (acfg->fp);
2489 emit_unset_mode (acfg);
2491 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2498 * arch_emit_gsharedvt_arg_trampoline:
2500 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2501 * two GOT slots which contain the argument, and the code to jump to.
2502 * TRAMP_SIZE is set to the size of the emitted trampoline.
2503 * These kinds of trampolines cannot be enumerated statically, since there could
2504 * be one trampoline per method instantiation, so we emit the same code for all
2505 * trampolines, and parameterize them using two GOT slots.
2508 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2510 #if defined(TARGET_X86)
2514 /* Similar to the PPC code above */
2516 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2519 /* Load mscorlib got address */
2520 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2522 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2523 /* Branch to the target address */
2524 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2526 emit_bytes (acfg, buf, code - buf);
2529 g_assert (code - buf == *tramp_size);
2530 #elif defined(TARGET_ARM)
2534 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2535 /* Similar to arch_emit_specific_trampoline () */
2538 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2539 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2540 /* Load the arg value from the GOT */
2541 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2542 /* Load the addr from the GOT */
2543 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2545 ARM_BX (code, ARMREG_R1);
2547 g_assert (code - buf == 20);
2550 emit_bytes (acfg, buf, code - buf);
2551 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2552 #elif defined(TARGET_ARM64)
2553 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2554 #elif defined (TARGET_AMD64)
2556 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2557 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2558 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2559 fprintf (acfg->fp, "jmp *%%r11\n");
2563 g_assert_not_reached ();
2567 /* END OF ARCH SPECIFIC CODE */
2570 mono_get_field_token (MonoClassField *field)
2572 MonoClass *klass = field->parent;
2575 int fcount = mono_class_get_field_count (klass);
2576 for (i = 0; i < fcount; ++i) {
2577 if (field == &klass->fields [i])
2578 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2581 g_assert_not_reached ();
2586 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2590 //printf ("ENCODE: %d 0x%x.\n", value, value);
2593 * Same encoding as the one used in the metadata, extended to handle values
2594 * greater than 0x1fffffff.
2596 if ((value >= 0) && (value <= 127))
2598 else if ((value >= 0) && (value <= 16383)) {
2599 p [0] = 0x80 | (value >> 8);
2600 p [1] = value & 0xff;
2602 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2603 p [0] = (value >> 24) | 0xc0;
2604 p [1] = (value >> 16) & 0xff;
2605 p [2] = (value >> 8) & 0xff;
2606 p [3] = value & 0xff;
2611 p [1] = (value >> 24) & 0xff;
2612 p [2] = (value >> 16) & 0xff;
2613 p [3] = (value >> 8) & 0xff;
2614 p [4] = value & 0xff;
2622 stream_init (MonoDynamicStream *sh)
2625 sh->alloc_size = 4096;
2626 sh->data = (char *)g_malloc (4096);
2628 /* So offsets are > 0 */
2634 make_room_in_stream (MonoDynamicStream *stream, int size)
2636 if (size <= stream->alloc_size)
2639 while (stream->alloc_size <= size) {
2640 if (stream->alloc_size < 4096)
2641 stream->alloc_size = 4096;
2643 stream->alloc_size *= 2;
2646 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2650 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2654 make_room_in_stream (stream, stream->index + len);
2655 memcpy (stream->data + stream->index, data, len);
2656 idx = stream->index;
2657 stream->index += len;
2664 * Add data to the binary blob inside the aot image. Returns the offset inside the
2665 * blob where the data was stored.
2668 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2670 g_assert (!acfg->blob_closed);
2672 if (acfg->blob.alloc_size == 0)
2673 stream_init (&acfg->blob);
2675 return add_stream_data (&acfg->blob, (char*)data, data_len);
2679 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2684 if (acfg->blob.alloc_size == 0)
2685 stream_init (&acfg->blob);
2687 count = acfg->blob.index % align;
2689 /* we assume the stream data will be aligned */
2691 add_stream_data (&acfg->blob, buf, 4 - count);
2693 return add_stream_data (&acfg->blob, (char*)data, data_len);
2696 /* Emit a table of data into the aot image */
2698 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2700 if (acfg->data_outfile) {
2701 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2702 fwrite (data,1, size, acfg->data_outfile);
2703 acfg->datafile_offset += size;
2704 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2705 int align = 8 - size % 8;
2706 acfg->datafile_offset += align;
2707 guint8 align_buf [16];
2708 memset (&align_buf, 0, sizeof (align_buf));
2709 fwrite (align_buf, align, 1, acfg->data_outfile);
2710 } else if (acfg->llvm) {
2711 mono_llvm_emit_aot_data (symbol, data, size);
2713 emit_section_change (acfg, RODATA_SECT, 0);
2714 emit_alignment (acfg, 8);
2715 emit_label (acfg, symbol);
2716 emit_bytes (acfg, data, size);
2721 * emit_offset_table:
2723 * Emit a table of increasing offsets in a compact form using differential encoding.
2724 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2725 * group size, the more compact the table becomes, but the slower it becomes to compute
2726 * a given entry. Returns the size of the table.
2729 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2731 gint32 current_offset;
2732 int i, buf_size, ngroups, index_entry_size;
2734 guint8 *data_p, *data_buf;
2735 guint32 *index_offsets;
2737 ngroups = (noffsets + (group_size - 1)) / group_size;
2739 index_offsets = g_new0 (guint32, ngroups);
2741 buf_size = noffsets * 4;
2742 p = buf = (guint8 *)g_malloc0 (buf_size);
2745 for (i = 0; i < noffsets; ++i) {
2746 //printf ("D: %d -> %d\n", i, offsets [i]);
2747 if ((i % group_size) == 0) {
2748 index_offsets [i / group_size] = p - buf;
2749 /* Emit the full value for these entries */
2750 encode_value (offsets [i], p, &p);
2752 /* The offsets are allowed to be non-increasing */
2753 //g_assert (offsets [i] >= current_offset);
2754 encode_value (offsets [i] - current_offset, p, &p);
2756 current_offset = offsets [i];
2761 if (ngroups && index_offsets [ngroups - 1] < 65000)
2762 index_entry_size = 2;
2764 index_entry_size = 4;
2766 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2767 p = buf = (guint8 *)g_malloc0 (buf_size);
2769 /* Emit the header */
2770 encode_int (noffsets, p, &p);
2771 encode_int (group_size, p, &p);
2772 encode_int (ngroups, p, &p);
2773 encode_int (index_entry_size, p, &p);
2775 /* Emit the index */
2776 for (i = 0; i < ngroups; ++i) {
2777 if (index_entry_size == 2)
2778 encode_int16 (index_offsets [i], p, &p);
2780 encode_int (index_offsets [i], p, &p);
2783 memcpy (p, data_buf, data_p - data_buf);
2784 p += data_p - data_buf;
2786 g_assert (p - buf <= buf_size);
2788 emit_aot_data (acfg, table, symbol, buf, p - buf);
2793 return (int)(p - buf);
2797 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2801 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2805 index = g_hash_table_size (cfg->image_hash);
2806 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2807 g_ptr_array_add (cfg->image_table, image);
2813 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2816 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2818 /* FIXME: Search referenced images as well */
2819 if (!acfg->typespec_classes) {
2820 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2821 for (i = 0; i < len; i++) {
2823 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2824 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2825 if (!is_ok (&error)) {
2826 mono_error_cleanup (&error);
2829 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2832 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2836 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2839 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2842 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2845 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2848 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2853 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2857 if (mono_class_is_ginst (klass)) {
2859 g_assert (klass->type_token);
2861 /* Find a typespec for a class if possible */
2862 token = find_typespec_for_class (acfg, klass);
2864 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2865 encode_value (token, p, &p);
2867 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2868 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2869 static int count = 0;
2872 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2873 encode_klass_ref (acfg, gclass, p, &p);
2874 encode_ginst (acfg, inst, p, &p);
2878 } else if (klass->type_token) {
2879 int iindex = get_image_index (acfg, klass->image);
2881 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2883 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2884 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2886 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2887 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2888 encode_value (get_image_index (acfg, klass->image), p, &p);
2890 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2891 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2892 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2894 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2896 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2897 if (par->gshared_constraint) {
2898 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2899 encode_type (acfg, par->gshared_constraint, p, &p);
2900 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2902 encode_value (klass->byval_arg.type, p, &p);
2903 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2905 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2907 if (!container->is_anonymous) {
2908 encode_value (container->is_method, p, &p);
2909 if (container->is_method)
2910 encode_method_ref (acfg, container->owner.method, p, &p);
2912 encode_klass_ref (acfg, container->owner.klass, p, &p);
2915 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2916 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2917 encode_type (acfg, &klass->byval_arg, p, &p);
2920 g_assert (klass->rank > 0);
2921 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2922 encode_value (klass->rank, p, &p);
2923 encode_klass_ref (acfg, klass->element_class, p, &p);
2931 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2932 * standard metadata encoding.
2935 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2937 gboolean shared = FALSE;
2940 * The encoding of generic instances is large so emit them only once.
2942 if (mono_class_is_ginst (klass)) {
2944 g_assert (klass->type_token);
2946 /* Find a typespec for a class if possible */
2947 token = find_typespec_for_class (acfg, klass);
2950 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2955 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2959 buf2 = (guint8 *)g_malloc (1024);
2962 encode_klass_ref_inner (acfg, klass, p, &p);
2963 g_assert (p - buf2 < 1024);
2965 offset = add_to_blob (acfg, buf2, p - buf2);
2968 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2974 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2975 encode_value (offset, p, &p);
2980 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2984 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2986 guint32 token = mono_get_field_token (field);
2989 encode_klass_ref (cfg, field->parent, p, &p);
2990 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2991 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2996 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3001 encode_value (inst->type_argc, p, &p);
3002 for (i = 0; i < inst->type_argc; ++i)
3003 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3008 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3011 MonoGenericInst *inst;
3013 inst = context->class_inst;
3015 g_assert (inst->type_argc);
3016 encode_ginst (acfg, inst, p, &p);
3018 encode_value (0, p, &p);
3020 inst = context->method_inst;
3022 g_assert (inst->type_argc);
3023 encode_ginst (acfg, inst, p, &p);
3025 encode_value (0, p, &p);
3031 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3035 g_assert (t->num_mods == 0);
3036 /* t->attrs can be ignored */
3037 //g_assert (t->attrs == 0);
3040 *p = MONO_TYPE_PINNED;
3044 *p = MONO_TYPE_BYREF;
3052 case MONO_TYPE_VOID:
3053 case MONO_TYPE_BOOLEAN:
3054 case MONO_TYPE_CHAR:
3067 case MONO_TYPE_STRING:
3068 case MONO_TYPE_OBJECT:
3069 case MONO_TYPE_TYPEDBYREF:
3071 case MONO_TYPE_VALUETYPE:
3072 case MONO_TYPE_CLASS:
3073 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3075 case MONO_TYPE_SZARRAY:
3076 encode_klass_ref (acfg, t->data.klass, p, &p);
3079 encode_type (acfg, t->data.type, p, &p);
3081 case MONO_TYPE_GENERICINST: {
3082 MonoClass *gclass = t->data.generic_class->container_class;
3083 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3085 encode_klass_ref (acfg, gclass, p, &p);
3086 encode_ginst (acfg, inst, p, &p);
3089 case MONO_TYPE_ARRAY: {
3090 MonoArrayType *array = t->data.array;
3093 encode_klass_ref (acfg, array->eklass, p, &p);
3094 encode_value (array->rank, p, &p);
3095 encode_value (array->numsizes, p, &p);
3096 for (i = 0; i < array->numsizes; ++i)
3097 encode_value (array->sizes [i], p, &p);
3098 encode_value (array->numlobounds, p, &p);
3099 for (i = 0; i < array->numlobounds; ++i)
3100 encode_value (array->lobounds [i], p, &p);
3104 case MONO_TYPE_MVAR:
3105 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3108 g_assert_not_reached ();
3115 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3121 /* Similar to the metadata encoding */
3122 if (sig->generic_param_count)
3126 if (sig->explicit_this)
3128 flags |= (sig->call_convention & 0x0F);
3132 if (sig->generic_param_count)
3133 encode_value (sig->generic_param_count, p, &p);
3134 encode_value (sig->param_count, p, &p);
3136 encode_type (acfg, sig->ret, p, &p);
3137 for (i = 0; i < sig->param_count; ++i) {
3138 if (sig->sentinelpos == i) {
3139 *p = MONO_TYPE_SENTINEL;
3142 encode_type (acfg, sig->params [i], p, &p);
3148 #define MAX_IMAGE_INDEX 250
3151 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3153 guint32 image_index = get_image_index (acfg, method->klass->image);
3154 guint32 token = method->token;
3155 MonoJumpInfoToken *ji;
3159 * The encoding for most methods is as follows:
3160 * - image index encoded as a leb128
3161 * - token index encoded as a leb128
3162 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3163 * types of method encodings.
3166 /* Mark methods which can't use aot trampolines because they need the further
3167 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3169 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3170 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3171 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3173 if (method->wrapper_type) {
3174 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3176 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3178 encode_value (method->wrapper_type, p, &p);
3180 switch (method->wrapper_type) {
3181 case MONO_WRAPPER_REMOTING_INVOKE:
3182 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3183 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3186 m = mono_marshal_method_from_wrapper (method);
3188 encode_method_ref (acfg, m, p, &p);
3191 case MONO_WRAPPER_PROXY_ISINST:
3192 case MONO_WRAPPER_LDFLD:
3193 case MONO_WRAPPER_LDFLDA:
3194 case MONO_WRAPPER_STFLD: {
3196 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3199 case MONO_WRAPPER_ALLOC: {
3200 /* The GC name is saved once in MonoAotFileInfo */
3201 g_assert (info->d.alloc.alloc_type != -1);
3202 encode_value (info->d.alloc.alloc_type, p, &p);
3205 case MONO_WRAPPER_WRITE_BARRIER: {
3209 case MONO_WRAPPER_STELEMREF: {
3211 encode_value (info->subtype, p, &p);
3212 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3213 encode_value (info->d.virtual_stelemref.kind, p, &p);
3216 case MONO_WRAPPER_UNKNOWN: {
3218 encode_value (info->subtype, p, &p);
3219 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3220 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3221 encode_klass_ref (acfg, method->klass, p, &p);
3222 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3223 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3224 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3225 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3226 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3227 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3228 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3229 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3232 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3234 encode_value (info->subtype, p, &p);
3235 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3236 strcpy ((char*)p, method->name);
3237 p += strlen (method->name) + 1;
3238 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3239 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3241 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3242 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3246 case MONO_WRAPPER_SYNCHRONIZED: {
3249 m = mono_marshal_method_from_wrapper (method);
3251 g_assert (m != method);
3252 encode_method_ref (acfg, m, p, &p);
3255 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3257 encode_value (info->subtype, p, &p);
3259 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3260 encode_value (info->d.element_addr.rank, p, &p);
3261 encode_value (info->d.element_addr.elem_size, p, &p);
3262 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3263 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3265 g_assert_not_reached ();
3269 case MONO_WRAPPER_CASTCLASS: {
3271 encode_value (info->subtype, p, &p);
3274 case MONO_WRAPPER_RUNTIME_INVOKE: {
3276 encode_value (info->subtype, p, &p);
3277 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3278 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3279 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3280 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3283 case MONO_WRAPPER_DELEGATE_INVOKE:
3284 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3285 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3286 if (method->is_inflated) {
3287 /* These wrappers are identified by their class */
3288 encode_value (1, p, &p);
3289 encode_klass_ref (acfg, method->klass, p, &p);
3291 MonoMethodSignature *sig = mono_method_signature (method);
3292 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3294 encode_value (0, p, &p);
3295 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3296 encode_value (info ? info->subtype : 0, p, &p);
3297 encode_signature (acfg, sig, p, &p);
3301 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3303 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3304 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3308 g_assert_not_reached ();
3310 } else if (mono_method_signature (method)->is_inflated) {
3312 * This is a generic method, find the original token which referenced it and
3314 * Obtain the token from information recorded by the JIT.
3316 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3318 image_index = get_image_index (acfg, ji->image);
3319 g_assert (image_index < MAX_IMAGE_INDEX);
3322 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3323 encode_value (image_index, p, &p);
3324 encode_value (token, p, &p);
3326 MonoMethod *declaring;
3327 MonoGenericContext *context = mono_method_get_context (method);
3329 g_assert (method->is_inflated);
3330 declaring = ((MonoMethodInflated*)method)->declaring;
3333 * This might be a non-generic method of a generic instance, which
3334 * doesn't have a token since the reference is generated by the JIT
3335 * like Nullable:Box/Unbox, or by generic sharing.
3337 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3338 /* Encode the klass */
3339 encode_klass_ref (acfg, method->klass, p, &p);
3340 /* Encode the method */
3341 image_index = get_image_index (acfg, method->klass->image);
3342 g_assert (image_index < MAX_IMAGE_INDEX);
3343 g_assert (declaring->token);
3344 token = declaring->token;
3345 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3346 encode_value (image_index, p, &p);
3347 encode_value (token, p, &p);
3348 encode_generic_context (acfg, context, p, &p);
3350 } else if (token == 0) {
3351 /* This might be a method of a constructed type like int[,].Set */
3352 /* Obtain the token from information recorded by the JIT */
3353 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3355 image_index = get_image_index (acfg, ji->image);
3356 g_assert (image_index < MAX_IMAGE_INDEX);
3359 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3360 encode_value (image_index, p, &p);
3361 encode_value (token, p, &p);
3364 g_assert (method->klass->rank);
3366 /* Encode directly */
3367 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3368 encode_klass_ref (acfg, method->klass, p, &p);
3369 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3370 encode_value (0, p, &p);
3371 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3372 encode_value (1, p, &p);
3373 else if (!strcmp (method->name, "Get"))
3374 encode_value (2, p, &p);
3375 else if (!strcmp (method->name, "Address"))
3376 encode_value (3, p, &p);
3377 else if (!strcmp (method->name, "Set"))
3378 encode_value (4, p, &p);
3380 g_assert_not_reached ();
3383 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3385 if (image_index >= MONO_AOT_METHODREF_MIN) {
3386 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3387 encode_value (image_index, p, &p);
3388 encode_value (mono_metadata_token_index (token), p, &p);
3390 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3397 compare_patches (gconstpointer a, gconstpointer b)
3401 i = (*(MonoJumpInfo**)a)->ip.i;
3402 j = (*(MonoJumpInfo**)b)->ip.i;
3413 static G_GNUC_UNUSED char*
3414 patch_to_string (MonoJumpInfo *patch_info)
3418 str = g_string_new ("");
3420 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3422 switch (patch_info->type) {
3423 case MONO_PATCH_INFO_VTABLE:
3424 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3429 g_string_append_printf (str, ")");
3430 return g_string_free (str, FALSE);
3436 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3439 static inline gboolean
3440 is_plt_patch (MonoJumpInfo *patch_info)
3442 switch (patch_info->type) {
3443 case MONO_PATCH_INFO_METHOD:
3444 case MONO_PATCH_INFO_INTERNAL_METHOD:
3445 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3446 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3447 case MONO_PATCH_INFO_RGCTX_FETCH:
3457 * Return the symbol identifying the plt entry PLT_OFFSET.
3460 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3464 * The Apple linker reorganizes object files, so it doesn't like branches to local
3465 * labels, since those have no relocations.
3467 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3469 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3476 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3478 static MonoPltEntry*
3479 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3482 gboolean synchronized = FALSE;
3483 static int synchronized_symbol_idx;
3485 if (!is_plt_patch (patch_info))
3488 if (!acfg->patch_to_plt_entry [patch_info->type])
3489 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3490 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3492 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3494 * Allocate a separate PLT slot for each such patch, since some plt
3495 * entries will refer to the method itself, and some will refer to the
3499 synchronized = TRUE;
3503 MonoJumpInfo *new_ji;
3505 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3507 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3508 res->plt_offset = acfg->plt_offset;
3510 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3511 if (acfg->aot_opts.write_symbols)
3512 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3514 /* Avoid duplicate symbols because we don't cache */
3515 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3517 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3518 synchronized_symbol_idx ++;
3521 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3523 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3525 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3527 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3529 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3530 //mono_print_ji (patch_info); printf ("\n");
3531 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3533 acfg->plt_offset ++;
3542 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3543 * JI could be found if it exists, otherwise allocates a new one.
3546 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3549 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3551 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3553 return got_offset - 1;
3556 got_offset = acfg->llvm_got_offset;
3557 acfg->llvm_got_offset ++;
3559 got_offset = acfg->got_offset;
3560 acfg->got_offset ++;
3563 acfg->stats.got_slots ++;
3564 acfg->stats.got_slot_types [ji->type] ++;
3566 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3567 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3568 g_ptr_array_add (info->got_patches, ji);
3573 /* Add a method to the list of methods which need to be emitted */
3575 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3578 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3579 g_ptr_array_add (acfg->methods, method);
3580 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3581 acfg->nmethods = acfg->methods->len + 1;
3584 if (method->wrapper_type || extra)
3585 g_ptr_array_add (acfg->extra_methods, method);
3589 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3591 /* One instantiation with valuetypes is generated for each async method */
3592 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3599 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3601 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3609 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3613 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3617 index = acfg->method_index;
3618 add_method_with_index (acfg, method, index, extra);
3620 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3622 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3624 acfg->method_index ++;
3630 add_method (MonoAotCompile *acfg, MonoMethod *method)
3632 return add_method_full (acfg, method, FALSE, 0);
3636 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3638 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3639 method = mini_get_shared_method (method);
3640 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3641 /* Use the gsharedvt version */
3642 method = mini_get_shared_method_full (method, TRUE, TRUE);
3644 if (acfg->aot_opts.log_generics)
3645 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3647 add_method_full (acfg, method, TRUE, depth);
3651 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3653 add_extra_method_with_depth (acfg, method, 0);
3657 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3659 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3660 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3661 MonoMethod *wrapper;
3667 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3668 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3671 add_method (acfg, wrapper);
3675 get_runtime_invoke_sig (MonoMethodSignature *sig)
3677 MonoMethodBuilder *mb;
3680 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3681 m = mono_mb_create_method (mb, sig, 16);
3682 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3688 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3690 return mono_marshal_get_runtime_invoke (method, virtual_);
3694 can_marshal_struct (MonoClass *klass)
3696 MonoClassField *field;
3697 gboolean can_marshal = TRUE;
3698 gpointer iter = NULL;
3699 MonoMarshalType *info;
3702 if (mono_class_is_auto_layout (klass))
3705 info = mono_marshal_load_type_info (klass);
3707 /* Only allow a few field types to avoid asserts in the marshalling code */
3708 while ((field = mono_class_get_fields (klass, &iter))) {
3709 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3712 switch (field->type->type) {
3717 case MONO_TYPE_BOOLEAN:
3720 case MONO_TYPE_CHAR:
3728 case MONO_TYPE_STRING:
3730 case MONO_TYPE_VALUETYPE:
3731 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3732 can_marshal = FALSE;
3734 case MONO_TYPE_SZARRAY: {
3735 gboolean has_mspec = FALSE;
3738 for (i = 0; i < info->num_fields; ++i) {
3739 if (info->fields [i].field == field && info->fields [i].mspec)
3744 can_marshal = FALSE;
3748 can_marshal = FALSE;
3754 /* Its hard to compute whenever these can be marshalled or not */
3755 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3762 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3764 /* Create a vtype instantiation */
3765 MonoGenericContext shared_context;
3767 MonoGenericInst *inst;
3768 MonoGenericContainer *container;
3769 MonoClass **constraints;
3772 memset (ctx, 0, sizeof (MonoGenericContext));
3774 if (mono_class_is_gtd (method->klass)) {
3775 shared_context = mono_class_get_generic_container (method->klass)->context;
3776 inst = shared_context.class_inst;
3778 args = g_new0 (MonoType*, inst->type_argc);
3779 for (i = 0; i < inst->type_argc; ++i) {
3780 args [i] = &mono_defaults.int_class->byval_arg;
3782 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3784 if (method->is_generic) {
3785 container = mono_method_get_generic_container (method);
3786 shared_context = container->context;
3787 inst = shared_context.method_inst;
3789 args = g_new0 (MonoType*, inst->type_argc);
3790 for (i = 0; i < container->type_argc; ++i) {
3791 MonoGenericParamInfo *info = &container->type_params [i].info;
3792 gboolean ref_only = FALSE;
3794 if (info && info->constraints) {
3795 constraints = info->constraints;
3797 while (*constraints) {
3798 MonoClass *cklass = *constraints;
3799 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3800 /* Inflaring the method with our vtype would not be valid */
3807 args [i] = &mono_defaults.object_class->byval_arg;
3809 args [i] = &mono_defaults.int_class->byval_arg;
3811 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3816 add_wrappers (MonoAotCompile *acfg)
3818 MonoMethod *method, *m;
3820 MonoMethodSignature *sig, *csig;
3824 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3825 * so there is only one wrapper of a given type, or inlining their contents into their
3828 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3831 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3832 gboolean skip = FALSE;
3834 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3835 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3837 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3838 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3839 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3842 /* Skip methods which can not be handled by get_runtime_invoke () */
3843 sig = mono_method_signature (method);
3846 if ((sig->ret->type == MONO_TYPE_PTR) ||
3847 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3849 if (mono_class_is_open_constructed_type (sig->ret))
3852 for (j = 0; j < sig->param_count; j++) {
3853 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3855 if (mono_class_is_open_constructed_type (sig->params [j]))
3859 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3860 if (!mono_class_is_contextbound (method->klass)) {
3861 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3862 gboolean has_nullable = FALSE;
3864 for (j = 0; j < sig->param_count; j++) {
3865 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3866 has_nullable = TRUE;
3869 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3870 /* Supported by the dynamic runtime-invoke wrapper */
3874 mono_arch_dyn_call_free (info);
3878 if (acfg->aot_opts.llvm_only)
3879 /* Supported by the gsharedvt based runtime-invoke wrapper */
3883 //printf ("%s\n", mono_method_full_name (method, TRUE));
3884 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3888 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3891 /* Runtime invoke wrappers */
3893 /* void runtime-invoke () [.cctor] */
3894 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3895 csig->ret = &mono_defaults.void_class->byval_arg;
3896 add_method (acfg, get_runtime_invoke_sig (csig));
3898 /* void runtime-invoke () [Finalize] */
3899 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3901 csig->ret = &mono_defaults.void_class->byval_arg;
3902 add_method (acfg, get_runtime_invoke_sig (csig));
3904 /* void runtime-invoke (string) [exception ctor] */
3905 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3907 csig->ret = &mono_defaults.void_class->byval_arg;
3908 csig->params [0] = &mono_defaults.string_class->byval_arg;
3909 add_method (acfg, get_runtime_invoke_sig (csig));
3911 /* void runtime-invoke (string, string) [exception ctor] */
3912 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3914 csig->ret = &mono_defaults.void_class->byval_arg;
3915 csig->params [0] = &mono_defaults.string_class->byval_arg;
3916 csig->params [1] = &mono_defaults.string_class->byval_arg;
3917 add_method (acfg, get_runtime_invoke_sig (csig));
3919 /* string runtime-invoke () [Exception.ToString ()] */
3920 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3922 csig->ret = &mono_defaults.string_class->byval_arg;
3923 add_method (acfg, get_runtime_invoke_sig (csig));
3925 /* void runtime-invoke (string, Exception) [exception ctor] */
3926 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3928 csig->ret = &mono_defaults.void_class->byval_arg;
3929 csig->params [0] = &mono_defaults.string_class->byval_arg;
3930 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3931 add_method (acfg, get_runtime_invoke_sig (csig));
3933 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
3934 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
3936 csig->ret = &(mono_class_load_from_name (
3937 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3938 csig->params [0] = &mono_defaults.string_class->byval_arg;
3939 csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3940 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
3941 add_method (acfg, get_runtime_invoke_sig (csig));
3943 /* runtime-invoke used by finalizers */
3944 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3946 /* This is used by mono_runtime_capture_context () */
3947 method = mono_get_context_capture_method ();
3949 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3951 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3952 if (!acfg->aot_opts.llvm_only)
3953 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3956 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3957 if (acfg->aot_opts.llvm_only) {
3960 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3961 for (variants = 0; variants < 4; ++variants) {
3962 for (i = 0; i < 16; ++i) {
3963 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3964 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3972 add_method (acfg, mono_marshal_get_stelemref ());
3974 /* Managed Allocators */
3975 nallocators = mono_gc_get_managed_allocator_types ();
3976 for (i = 0; i < nallocators; ++i) {
3977 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3978 add_method (acfg, m);
3979 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3980 add_method (acfg, m);
3983 /* write barriers */
3984 if (mono_gc_is_moving ()) {
3985 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3986 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3989 /* Stelemref wrappers */
3991 MonoMethod **wrappers;
3994 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3995 for (i = 0; i < nwrappers; ++i)
3996 add_method (acfg, wrappers [i]);
4000 /* castclass_with_check wrapper */
4001 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4002 /* isinst_with_check wrapper */
4003 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4005 /* JIT icall wrappers */
4006 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4007 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4011 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4012 * we use the original method instead at runtime.
4013 * Since full-aot doesn't support remoting, this is not a problem.
4016 /* remoting-invoke wrappers */
4017 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4019 MonoMethodSignature *sig;
4021 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4022 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4023 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4025 sig = mono_method_signature (method);
4027 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4028 m = mono_marshal_get_remoting_invoke_with_check (method);
4030 add_method (acfg, m);
4035 /* delegate-invoke wrappers */
4036 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4039 MonoCustomAttrInfo *cattr;
4041 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4042 klass = mono_class_get_checked (acfg->image, token, &error);
4045 mono_error_cleanup (&error);
4049 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4052 if (!mono_class_is_gtd (klass)) {
4053 method = mono_get_delegate_invoke (klass);
4055 m = mono_marshal_get_delegate_invoke (method, NULL);
4057 add_method (acfg, m);
4059 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4061 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4063 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4065 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4067 cattr = mono_custom_attrs_from_class_checked (klass, &error);
4068 if (!is_ok (&error)) {
4069 mono_error_cleanup (&error);
4076 for (j = 0; j < cattr->num_attrs; ++j)
4077 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4079 if (j < cattr->num_attrs) {
4081 MonoMethod *wrapper;
4082 MonoMethod *del_invoke;
4084 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4085 invoke = mono_get_delegate_invoke (klass);
4086 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4087 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4088 add_method (acfg, wrapper);
4089 add_method (acfg, del_invoke);
4092 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4094 MonoGenericContext ctx;
4095 MonoMethod *inst, *gshared;
4098 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4101 method = mono_get_delegate_invoke (klass);
4102 create_gsharedvt_inst (acfg, method, &ctx);
4104 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4105 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4107 m = mono_marshal_get_delegate_invoke (inst, NULL);
4108 g_assert (m->is_inflated);
4110 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4111 add_extra_method (acfg, gshared);
4114 method = mono_get_delegate_begin_invoke (klass);
4116 create_gsharedvt_inst (acfg, method, &ctx);
4118 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4119 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4121 m = mono_marshal_get_delegate_begin_invoke (inst);
4122 g_assert (m->is_inflated);
4124 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4125 add_extra_method (acfg, gshared);
4129 method = mono_get_delegate_end_invoke (klass);
4131 create_gsharedvt_inst (acfg, method, &ctx);
4133 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4134 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4136 m = mono_marshal_get_delegate_end_invoke (inst);
4137 g_assert (m->is_inflated);
4139 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4140 add_extra_method (acfg, gshared);
4145 /* array access wrappers */
4146 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4150 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4151 klass = mono_class_get_checked (acfg->image, token, &error);
4154 mono_error_cleanup (&error);
4158 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4159 MonoMethod *m, *wrapper;
4161 /* Add runtime-invoke wrappers too */
4163 m = mono_class_get_method_from_name (klass, "Get", -1);
4165 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4166 add_extra_method (acfg, wrapper);
4167 if (!acfg->aot_opts.llvm_only)
4168 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4170 m = mono_class_get_method_from_name (klass, "Set", -1);
4172 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4173 add_extra_method (acfg, wrapper);
4174 if (!acfg->aot_opts.llvm_only)
4175 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4179 /* Synchronized wrappers */
4180 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4182 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4183 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4184 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4186 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4187 if (method->is_generic) {
4189 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4191 MonoGenericContext ctx;
4192 MonoMethod *inst, *gshared, *m;
4195 * Create a generic wrapper for a generic instance, and AOT that.
4197 create_gsharedvt_inst (acfg, method, &ctx);
4198 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4199 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4200 m = mono_marshal_get_synchronized_wrapper (inst);
4201 g_assert (m->is_inflated);
4202 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4203 add_method (acfg, gshared);
4205 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4210 /* pinvoke wrappers */
4211 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4214 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4216 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4217 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4219 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4220 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4221 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4224 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4225 if (acfg->aot_opts.llvm_only) {
4226 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4227 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE);
4232 /* native-to-managed wrappers */
4233 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4236 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4237 MonoCustomAttrInfo *cattr;
4240 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4241 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4244 * Only generate native-to-managed wrappers for methods which have an
4245 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4246 * name to avoid defining a new assembly to contain it.
4248 cattr = mono_custom_attrs_from_method_checked (method, &error);
4249 if (!is_ok (&error)) {
4250 char *name = mono_method_get_full_name (method);
4251 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4256 for (j = 0; j < cattr->num_attrs; ++j)
4257 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4259 if (j < cattr->num_attrs) {
4260 MonoCustomAttrEntry *e = &cattr->attrs [j];
4261 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4262 const char *p = (const char*)e->data;
4264 int slen, num_named, named_type;
4268 char *export_name = NULL;
4269 MonoMethod *wrapper;
4271 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4272 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4273 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4274 mono_method_full_name (method, TRUE));
4278 g_assert (sig->param_count == 1);
4279 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4282 * Decode the cattr manually since we can't create objects
4283 * during aot compilation.
4289 /* From load_cattr_value () in reflection.c */
4290 slen = mono_metadata_decode_value (p, &p);
4291 n = (char *)g_memdup (p, slen + 1);
4293 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4295 mono_error_assert_ok (&error);
4298 klass = mono_class_from_mono_type (t);
4299 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4303 num_named = read16 (p);
4306 g_assert (num_named < 2);
4307 if (num_named == 1) {
4311 /* parse ExportSymbol attribute */
4313 named_type = *named;
4315 /* data_type = *named; */
4318 name_len = mono_metadata_decode_blob_size (named, &named);
4319 name = (char *)g_malloc (name_len + 1);
4320 memcpy (name, named, name_len);
4321 name [name_len] = 0;
4324 g_assert (named_type == 0x54);
4325 g_assert (!strcmp (name, "ExportSymbol"));
4327 /* load_cattr_value (), string case */
4328 g_assert (*named != (char)0xff);
4329 slen = mono_metadata_decode_value (named, &named);
4330 export_name = (char *)g_malloc (slen + 1);
4331 memcpy (export_name, named, slen);
4332 export_name [slen] = 0;
4336 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, &error);
4337 mono_error_assert_ok (&error);
4339 add_method (acfg, wrapper);
4341 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4346 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4347 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4348 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4352 /* StructureToPtr/PtrToStructure wrappers */
4353 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4357 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4358 klass = mono_class_get_checked (acfg->image, token, &error);
4361 mono_error_cleanup (&error);
4365 if (klass->valuetype && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4366 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4367 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4368 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4374 has_type_vars (MonoClass *klass)
4376 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4379 return has_type_vars (klass->element_class);
4380 if (mono_class_is_ginst (klass)) {
4381 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4382 if (context->class_inst) {
4385 for (i = 0; i < context->class_inst->type_argc; ++i)
4386 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4390 if (mono_class_is_gtd (klass))
4396 is_vt_inst (MonoGenericInst *inst)
4400 for (i = 0; i < inst->type_argc; ++i) {
4401 MonoType *t = inst->type_argv [i];
4402 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4409 method_has_type_vars (MonoMethod *method)
4411 if (has_type_vars (method->klass))
4414 if (method->is_inflated) {
4415 MonoGenericContext *context = mono_method_get_context (method);
4416 if (context->method_inst) {
4419 for (i = 0; i < context->method_inst->type_argc; ++i)
4420 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4428 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4430 return opts->mode == MONO_AOT_MODE_FULL;
4434 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4436 return opts->mode == MONO_AOT_MODE_HYBRID;
4439 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4442 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4444 /* This might lead to a huge code blowup so only do it if neccesary */
4445 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4448 add_generic_class_with_depth (acfg, klass, 0, ref);
4452 check_type_depth (MonoType *t, int depth)
4460 case MONO_TYPE_GENERICINST: {
4461 MonoGenericClass *gklass = t->data.generic_class;
4462 MonoGenericInst *ginst = gklass->context.class_inst;
4465 for (i = 0; i < ginst->type_argc; ++i) {
4466 if (check_type_depth (ginst->type_argv [i], depth + 1))
4480 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4483 * add_generic_class:
4485 * Add all methods of a generic class.
4488 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4491 MonoClassField *field;
4493 gboolean use_gsharedvt = FALSE;
4495 if (!acfg->ginst_hash)
4496 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4498 mono_class_init (klass);
4500 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4503 if (has_type_vars (klass))
4506 if (!mono_class_is_ginst (klass) && !klass->rank)
4509 if (mono_class_has_failure (klass))
4512 if (!acfg->ginst_hash)
4513 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4515 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4518 if (check_type_depth (&klass->byval_arg, 0))
4521 if (acfg->aot_opts.log_generics)
4522 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4524 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4527 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4528 * Enable this only for some classes since gsharedvt might not support all methods.
4530 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst (mono_class_get_generic_class (klass)->context.class_inst) &&
4531 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4532 use_gsharedvt = TRUE;
4535 while ((method = mono_class_get_methods (klass, &iter))) {
4536 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4538 * This is partial sharing, and we can't handle it yet
4543 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4545 add_types_from_method_header (acfg, method);
4549 if (method->is_generic)
4554 * FIXME: Instances which are referenced by these methods are not added,
4555 * for example Array.Resize<int> for List<int>.Add ().
4557 add_extra_method_with_depth (acfg, method, depth + 1);
4561 while ((field = mono_class_get_fields (klass, &iter))) {
4562 if (field->type->type == MONO_TYPE_GENERICINST)
4563 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4566 if (klass->delegate) {
4567 method = mono_get_delegate_invoke (klass);
4569 method = mono_marshal_get_delegate_invoke (method, NULL);
4571 if (acfg->aot_opts.log_generics)
4572 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4574 add_method (acfg, method);
4577 /* Add superclasses */
4579 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4582 * For ICollection<T>, add instances of the helper methods
4583 * in Array, since a T[] could be cast to ICollection<T>.
4585 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4586 (!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"))) {
4587 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4588 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4592 if (!strcmp (klass->name, "IEnumerator`1"))
4593 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4595 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4597 /* Add the T[]/InternalEnumerator class */
4598 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4603 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4604 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4608 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), &error);
4609 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4610 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4614 while ((method = mono_class_get_methods (array_class, &iter))) {
4615 if (strstr (method->name, name_prefix)) {
4616 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4618 add_extra_method_with_depth (acfg, m, depth);
4622 g_free (name_prefix);
4625 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4626 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4628 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4629 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4630 MonoGenericContext ctx;
4631 MonoType *args [16];
4633 memset (&ctx, 0, sizeof (ctx));
4635 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4637 args [0] = &tclass->byval_arg;
4638 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4640 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4641 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4643 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4644 MonoClass *gcomparer_inst;
4645 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4646 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4647 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4649 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4653 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4654 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4656 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4657 MonoClass *iface, *gcomparer, *iface_inst;
4658 MonoGenericContext ctx;
4659 MonoType *args [16];
4661 memset (&ctx, 0, sizeof (ctx));
4663 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4665 args [0] = &tclass->byval_arg;
4666 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4668 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4669 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4671 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4672 MonoClass *gcomparer_inst;
4675 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4676 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4677 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4678 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4682 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4683 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4684 MonoClass *enum_comparer;
4685 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4686 MonoGenericContext ctx;
4687 MonoType *args [16];
4689 if (mono_class_is_enum (tclass)) {
4690 MonoClass *enum_comparer_inst;
4693 memset (&ctx, 0, sizeof (ctx));
4694 args [0] = &tclass->byval_arg;
4695 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4697 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4698 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4699 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4700 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4704 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4705 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4706 MonoClass *comparer;
4707 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4708 MonoGenericContext ctx;
4709 MonoType *args [16];
4711 if (mono_class_is_enum (tclass)) {
4712 MonoClass *comparer_inst;
4715 memset (&ctx, 0, sizeof (ctx));
4716 args [0] = &tclass->byval_arg;
4717 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4719 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4720 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4721 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4722 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4728 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4731 MonoGenericContext ctx;
4732 MonoType *args [16];
4734 if (acfg->aot_opts.no_instances)
4737 memset (&ctx, 0, sizeof (ctx));
4739 for (i = 0; i < ninsts; ++i) {
4741 MonoClass *generic_inst;
4742 args [0] = insts [i];
4743 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4744 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4745 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4746 add_generic_class (acfg, generic_inst, force, "");
4751 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4754 MonoMethodHeader *header;
4755 MonoMethodSignature *sig;
4758 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4760 sig = mono_method_signature (method);
4763 for (j = 0; j < sig->param_count; ++j)
4764 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4765 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4768 header = mono_method_get_header_checked (method, &error);
4771 for (j = 0; j < header->num_locals; ++j)
4772 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4773 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4774 mono_metadata_free_mh (header);
4776 mono_error_cleanup (&error); /* FIXME report the error */
4782 * add_generic_instances:
4784 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4787 add_generic_instances (MonoAotCompile *acfg)
4792 MonoGenericContext *context;
4794 if (acfg->aot_opts.no_instances)
4797 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4799 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4800 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4803 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4804 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4805 mono_error_cleanup (&error);
4809 if (method->klass->image != acfg->image)
4812 context = mono_method_get_context (method);
4814 if (context && ((context->class_inst && context->class_inst->is_open)))
4818 * For open methods, create an instantiation which can be passed to the JIT.
4819 * FIXME: Handle class_inst as well.
4821 if (context && context->method_inst && context->method_inst->is_open) {
4823 MonoGenericContext shared_context;
4824 MonoGenericInst *inst;
4825 MonoType **type_argv;
4827 MonoMethod *declaring_method;
4828 gboolean supported = TRUE;
4830 /* Check that the context doesn't contain open constructed types */
4831 if (context->class_inst) {
4832 inst = context->class_inst;
4833 for (i = 0; i < inst->type_argc; ++i) {
4834 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)
4836 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4840 if (context->method_inst) {
4841 inst = context->method_inst;
4842 for (i = 0; i < inst->type_argc; ++i) {
4843 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)
4845 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4853 memset (&shared_context, 0, sizeof (MonoGenericContext));
4855 inst = context->class_inst;
4857 type_argv = g_new0 (MonoType*, inst->type_argc);
4858 for (i = 0; i < inst->type_argc; ++i) {
4859 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)
4860 type_argv [i] = &mono_defaults.object_class->byval_arg;
4862 type_argv [i] = inst->type_argv [i];
4865 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4869 inst = context->method_inst;
4871 type_argv = g_new0 (MonoType*, inst->type_argc);
4872 for (i = 0; i < inst->type_argc; ++i) {
4873 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)
4874 type_argv [i] = &mono_defaults.object_class->byval_arg;
4876 type_argv [i] = inst->type_argv [i];
4879 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4883 if (method->is_generic || mono_class_is_gtd (method->klass))
4884 declaring_method = method;
4886 declaring_method = mono_method_get_declaring_generic_method (method);
4888 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4889 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4893 * If the method is fully sharable, it was already added in place of its
4894 * generic definition.
4896 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4900 * FIXME: Partially shared methods are not shared here, so we end up with
4901 * many identical methods.
4903 add_extra_method (acfg, method);
4906 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4910 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4912 klass = mono_class_get_checked (acfg->image, token, &error);
4913 if (!klass || klass->rank) {
4914 mono_error_cleanup (&error);
4918 add_generic_class (acfg, klass, FALSE, "typespec");
4921 /* Add types of args/locals */
4922 for (i = 0; i < acfg->methods->len; ++i) {
4923 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4924 add_types_from_method_header (acfg, method);
4927 if (acfg->image == mono_defaults.corlib) {
4929 MonoType *insts [256];
4932 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4933 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4934 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4935 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4936 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4937 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4938 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4939 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4940 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4941 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4942 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4943 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4945 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4946 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4948 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4949 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4951 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4953 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4955 MonoClass *enum_comparer;
4956 MonoType *insts [16];
4960 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4961 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4962 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4963 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4964 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4965 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4968 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4969 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4970 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4973 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4974 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4975 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4977 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4979 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4980 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4981 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4984 /* Add instances of the array generic interfaces for primitive types */
4985 /* This will add instances of the InternalArray_ helper methods in Array too */
4986 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4988 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4990 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4992 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4994 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4996 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4999 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5000 * used for all instances of GetGenericValueImpl by the AOT runtime.
5003 MonoGenericContext ctx;
5004 MonoType *args [16];
5005 MonoMethod *get_method;
5006 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
5008 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5012 memset (&ctx, 0, sizeof (ctx));
5013 args [0] = &mono_defaults.object_class->byval_arg;
5014 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5015 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
5016 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5020 /* Same for CompareExchange<T>/Exchange<T> */
5022 MonoGenericContext ctx;
5023 MonoType *args [16];
5025 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5026 gpointer iter = NULL;
5028 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5029 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5031 memset (&ctx, 0, sizeof (ctx));
5032 args [0] = &mono_defaults.object_class->byval_arg;
5033 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5034 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5035 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5040 /* Same for Volatile.Read/Write<T> */
5042 MonoGenericContext ctx;
5043 MonoType *args [16];
5045 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5046 gpointer iter = NULL;
5048 if (volatile_klass) {
5049 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5050 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5052 memset (&ctx, 0, sizeof (ctx));
5053 args [0] = &mono_defaults.object_class->byval_arg;
5054 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5055 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5056 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5062 /* object[] accessor wrappers. */
5063 for (i = 1; i < 4; ++i) {
5064 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
5067 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5070 m = mono_marshal_get_array_accessor_wrapper (m);
5071 add_extra_method (acfg, m);
5073 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5076 m = mono_marshal_get_array_accessor_wrapper (m);
5077 add_extra_method (acfg, m);
5079 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5082 m = mono_marshal_get_array_accessor_wrapper (m);
5083 add_extra_method (acfg, m);
5089 * is_direct_callable:
5091 * Return whenever the method identified by JI is directly callable without
5092 * going through the PLT.
5095 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5097 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5098 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5100 gboolean direct_callable = TRUE;
5102 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5103 direct_callable = FALSE;
5104 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5105 // FIXME: Maybe call the wrapper directly ?
5106 direct_callable = FALSE;
5108 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5109 /* Disable this so all calls go through load_method (), see the
5110 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5111 * mono_debugger_agent_init ().
5113 direct_callable = FALSE;
5116 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5117 /* sgen does some initialization when the allocator method is created */
5118 direct_callable = FALSE;
5119 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5120 /* we don't know at compile time whether sgen is concurrent or not */
5121 direct_callable = FALSE;
5123 if (direct_callable)
5126 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5127 if (acfg->aot_opts.direct_pinvoke)
5129 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5130 if (acfg->aot_opts.direct_icalls)
5138 #ifdef MONO_ARCH_AOT_SUPPORTED
5140 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5142 MonoImage *image = method->klass->image;
5143 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5144 MonoTableInfo *tables = image->tables;
5145 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5146 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5147 guint32 im_cols [MONO_IMPLMAP_SIZE];
5150 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5154 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5157 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5159 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5162 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5164 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5170 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5177 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5179 if (a->native_offset == b->native_offset)
5180 return a->il_offset - b->il_offset;
5182 return a->native_offset - b->native_offset;
5186 * compute_line_numbers:
5188 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5191 static MonoDebugSourceLocation**
5192 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5194 MonoDebugMethodInfo *minfo;
5195 MonoDebugLineNumberEntry *ln_array;
5196 MonoDebugSourceLocation *loc;
5197 int i, prev_line, prev_il_offset;
5198 int *native_to_il_offset = NULL;
5199 MonoDebugSourceLocation **res;
5202 minfo = mono_debug_lookup_method (method);
5205 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5206 if (debug_info->code_size != code_size)
5209 g_assert (code_size);
5211 /* Compute the native->IL offset mapping */
5213 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5214 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5216 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5218 native_to_il_offset = g_new0 (int, code_size + 1);
5220 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5222 MonoDebugLineNumberEntry *lne = &ln_array [i];
5225 for (j = 0; j < lne->native_offset; ++j)
5226 native_to_il_offset [j] = -1;
5229 if (i < debug_info->num_line_numbers - 1) {
5230 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5232 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5233 native_to_il_offset [j] = lne->il_offset;
5235 for (j = lne->native_offset; j < code_size; ++j)
5236 native_to_il_offset [j] = lne->il_offset;
5241 /* Compute the native->line number mapping */
5242 res = g_new0 (MonoDebugSourceLocation*, code_size);
5243 prev_il_offset = -1;
5246 for (i = 0; i < code_size; ++i) {
5247 int il_offset = native_to_il_offset [i];
5249 if (il_offset == -1 || il_offset == prev_il_offset)
5251 prev_il_offset = il_offset;
5252 loc = mono_debug_method_lookup_location (minfo, il_offset);
5253 if (!(loc && loc->source_file))
5255 if (loc->row == prev_line) {
5256 mono_debug_free_source_location (loc);
5259 prev_line = loc->row;
5260 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5262 /* This will cover the prolog too */
5272 get_file_index (MonoAotCompile *acfg, const char *source_file)
5276 // FIXME: Free these
5277 if (!acfg->dwarf_ln_filenames)
5278 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5279 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5281 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5282 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5283 emit_unset_mode (acfg);
5284 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5296 * emit_and_reloc_code:
5298 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5299 * is true, calls are made through the GOT too. This is used for emitting trampolines
5300 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5301 * since trampolines are needed to make PTL work.
5304 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5306 int i, pindex, start_index;
5308 MonoJumpInfo *patch_info;
5309 MonoDebugSourceLocation **locs = NULL;
5310 gboolean skip, prologue_end = FALSE;
5311 #ifdef MONO_ARCH_AOT_SUPPORTED
5312 gboolean direct_call, external_call;
5314 const char *direct_call_target = 0;
5315 const char *direct_pinvoke;
5318 if (acfg->gas_line_numbers && method && debug_info) {
5319 locs = compute_line_numbers (method, code_len, debug_info);
5321 int findex = get_file_index (acfg, "<unknown>");
5322 emit_unset_mode (acfg);
5323 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5327 /* Collect and sort relocations */
5328 patches = g_ptr_array_new ();
5329 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5330 g_ptr_array_add (patches, patch_info);
5331 g_ptr_array_sort (patches, compare_patches);
5334 for (i = 0; i < code_len; i += INST_LEN) {
5336 for (pindex = start_index; pindex < patches->len; ++pindex) {
5337 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5338 if (patch_info->ip.i >= i)
5342 if (locs && locs [i]) {
5343 MonoDebugSourceLocation *loc = locs [i];
5345 const char *options;
5347 findex = get_file_index (acfg, loc->source_file);
5348 emit_unset_mode (acfg);
5350 options = " prologue_end";
5353 prologue_end = TRUE;
5354 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5355 mono_debug_free_source_location (loc);
5359 #ifdef MONO_ARCH_AOT_SUPPORTED
5360 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5361 start_index = pindex;
5363 switch (patch_info->type) {
5364 case MONO_PATCH_INFO_NONE:
5366 case MONO_PATCH_INFO_GOT_OFFSET: {
5369 arch_emit_got_offset (acfg, code + i, &code_size);
5370 i += code_size - INST_LEN;
5372 patch_info->type = MONO_PATCH_INFO_NONE;
5375 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5376 int code_size, index;
5377 char *selector = (char *)patch_info->data.target;
5379 if (!acfg->objc_selector_to_index)
5380 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5381 if (!acfg->objc_selectors)
5382 acfg->objc_selectors = g_ptr_array_new ();
5383 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5387 index = acfg->objc_selector_index;
5388 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5389 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5390 acfg->objc_selector_index ++;
5393 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5394 i += code_size - INST_LEN;
5396 patch_info->type = MONO_PATCH_INFO_NONE;
5401 * If this patch is a call, try emitting a direct call instead of
5402 * through a PLT entry. This is possible if the called method is in
5403 * the same assembly and requires no initialization.
5405 direct_call = FALSE;
5406 external_call = FALSE;
5407 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5408 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5409 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5410 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5412 direct_call_target = callee_cfg->asm_symbol;
5413 patch_info->type = MONO_PATCH_INFO_NONE;
5414 acfg->stats.direct_calls ++;
5417 acfg->stats.all_calls ++;
5418 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5419 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5420 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5421 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5423 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5424 if (direct_pinvoke) {
5426 g_assert (strlen (direct_pinvoke) < 1000);
5427 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5430 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5431 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5432 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5433 /* Call to a C function implementing a jit icall */
5435 external_call = TRUE;
5436 g_assert (strlen (sym) < 1000);
5437 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5439 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5440 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5441 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5442 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5443 /* Call to a jit icall without a wrapper */
5445 external_call = TRUE;
5446 g_assert (strlen (sym) < 1000);
5447 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5452 patch_info->type = MONO_PATCH_INFO_NONE;
5453 acfg->stats.direct_calls ++;
5456 if (!got_only && !direct_call) {
5457 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5459 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5461 direct_call_target = plt_entry->symbol;
5463 /* Nullify the patch */
5464 patch_info->type = MONO_PATCH_INFO_NONE;
5465 plt_entry->jit_used = TRUE;
5472 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5473 i += call_size - INST_LEN;
5477 got_slot = get_got_offset (acfg, FALSE, patch_info);
5479 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5480 i += code_size - INST_LEN;
5486 #endif /* MONO_ARCH_AOT_SUPPORTED */
5489 /* Find next patch */
5491 for (pindex = start_index; pindex < patches->len; ++pindex) {
5492 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5493 if (patch_info->ip.i >= i)
5497 /* Try to emit multiple bytes at once */
5498 if (pindex < patches->len && patch_info->ip.i > i) {
5501 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5502 if (locs && locs [limit])
5506 emit_code_bytes (acfg, code + i, limit - i);
5507 i = limit - INST_LEN;
5509 emit_code_bytes (acfg, code + i, INST_LEN);
5514 g_ptr_array_free (patches, TRUE);
5521 * Return a modified version of S which only includes characters permissible in symbols.
5524 sanitize_symbol (MonoAotCompile *acfg, char *s)
5526 gboolean process = FALSE;
5535 for (i = 0; i < len; ++i)
5536 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5541 gs = g_string_sized_new (len);
5542 for (i = 0; i < len; ++i) {
5544 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5545 g_string_append_c (gs, c);
5546 } else if (c > 0x7f) {
5547 /* multi-byte utf8 */
5548 g_string_append_printf (gs, "_0x%x", c);
5551 while (c >> 6 == 0x2) {
5552 g_string_append_printf (gs, "%x", c);
5556 g_string_append_printf (gs, "_");
5559 g_string_append_c (gs, '_');
5563 res = mono_mempool_strdup (acfg->mempool, gs->str);
5564 g_string_free (gs, TRUE);
5569 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5571 char *name1, *name2, *cached;
5572 int i, j, len, count;
5573 MonoMethod *cached_method;
5575 name1 = mono_method_full_name (method, TRUE);
5578 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5579 if ((!prefix || !*prefix) && name1 [0] == 'L')
5583 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5584 char adjustedPrefix [MAX_SYMBOL_SIZE];
5585 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5588 len = strlen (name1);
5589 name2 = (char *)malloc (strlen (prefix) + len + 16);
5590 memcpy (name2, prefix, strlen (prefix));
5591 j = strlen (prefix);
5592 for (i = 0; i < len; ++i) {
5593 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5595 } else if (isalnum (name1 [i])) {
5596 name2 [j ++] = name1 [i];
5597 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5599 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5602 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5612 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5613 if (!(cached_method && cached_method != method))
5615 sprintf (name2 + j, "_%d", count);
5619 cached = g_strdup (name2);
5620 g_hash_table_insert (cache, cached, method);
5626 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5631 char *debug_sym = NULL;
5632 char *symbol = NULL;
5633 int func_alignment = AOT_FUNC_ALIGNMENT;
5636 method = cfg->orig_method;
5637 code = cfg->native_code;
5639 method_index = get_method_index (acfg, method);
5640 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5642 /* Make the labels local */
5643 emit_section_change (acfg, ".text", 0);
5644 emit_alignment_code (acfg, func_alignment);
5646 if (acfg->global_symbols && acfg->need_no_dead_strip)
5647 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5649 emit_label (acfg, cfg->asm_symbol);
5651 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5653 * Write a C style symbol for every method, this has two uses:
5654 * - it works on platforms where the dwarf debugging info is not
5656 * - it allows the setting of breakpoints of aot-ed methods.
5658 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5659 cfg->asm_debug_symbol = g_strdup (debug_sym);
5661 if (acfg->need_no_dead_strip)
5662 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5663 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5664 emit_label (acfg, debug_sym);
5667 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5669 /* Emit a global symbol for the method */
5670 emit_global_inner (acfg, export_name, TRUE);
5671 emit_label (acfg, export_name);
5674 if (cfg->verbose_level > 0)
5675 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5677 acfg->stats.code_size += cfg->code_len;
5679 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5681 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 ()));
5685 if (acfg->aot_opts.write_symbols) {
5687 emit_symbol_size (acfg, debug_sym, ".");
5689 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5693 emit_label (acfg, symbol);
5700 * Encode PATCH_INFO into its disk representation.
5703 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5707 switch (patch_info->type) {
5708 case MONO_PATCH_INFO_NONE:
5710 case MONO_PATCH_INFO_IMAGE:
5711 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5713 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5714 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5715 case MONO_PATCH_INFO_GC_NURSERY_START:
5716 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5718 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5719 encode_value (patch_info->data.index, p, &p);
5721 case MONO_PATCH_INFO_METHOD_REL:
5722 encode_value ((gint)patch_info->data.offset, p, &p);
5724 case MONO_PATCH_INFO_SWITCH: {
5725 gpointer *table = (gpointer *)patch_info->data.table->table;
5728 encode_value (patch_info->data.table->table_size, p, &p);
5729 for (k = 0; k < patch_info->data.table->table_size; k++)
5730 encode_value ((int)(gssize)table [k], p, &p);
5733 case MONO_PATCH_INFO_METHODCONST:
5734 case MONO_PATCH_INFO_METHOD:
5735 case MONO_PATCH_INFO_METHOD_JUMP:
5736 case MONO_PATCH_INFO_ICALL_ADDR:
5737 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5738 case MONO_PATCH_INFO_METHOD_RGCTX:
5739 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5740 encode_method_ref (acfg, patch_info->data.method, p, &p);
5742 case MONO_PATCH_INFO_AOT_JIT_INFO:
5743 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5744 case MONO_PATCH_INFO_SET_TLS_TRAMP:
5745 encode_value (patch_info->data.index, p, &p);
5747 case MONO_PATCH_INFO_INTERNAL_METHOD:
5748 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5749 guint32 len = strlen (patch_info->data.name);
5751 encode_value (len, p, &p);
5753 memcpy (p, patch_info->data.name, len);
5758 case MONO_PATCH_INFO_LDSTR: {
5759 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5760 guint32 token = patch_info->data.token->token;
5761 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5762 encode_value (image_index, p, &p);
5763 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5766 case MONO_PATCH_INFO_RVA:
5767 case MONO_PATCH_INFO_DECLSEC:
5768 case MONO_PATCH_INFO_LDTOKEN:
5769 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5770 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5771 encode_value (patch_info->data.token->token, p, &p);
5772 encode_value (patch_info->data.token->has_context, p, &p);
5773 if (patch_info->data.token->has_context)
5774 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5776 case MONO_PATCH_INFO_EXC_NAME: {
5777 MonoClass *ex_class;
5780 mono_class_load_from_name (mono_defaults.exception_class->image,
5781 "System", (const char *)patch_info->data.target);
5782 encode_klass_ref (acfg, ex_class, p, &p);
5785 case MONO_PATCH_INFO_R4:
5786 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5788 case MONO_PATCH_INFO_R8:
5789 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5790 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5792 case MONO_PATCH_INFO_VTABLE:
5793 case MONO_PATCH_INFO_CLASS:
5794 case MONO_PATCH_INFO_IID:
5795 case MONO_PATCH_INFO_ADJUSTED_IID:
5796 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5798 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5799 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5800 if (patch_info->data.del_tramp->method) {
5801 encode_value (1, p, &p);
5802 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5804 encode_value (0, p, &p);
5806 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5808 case MONO_PATCH_INFO_FIELD:
5809 case MONO_PATCH_INFO_SFLDA:
5810 encode_field_info (acfg, patch_info->data.field, p, &p);
5812 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5814 case MONO_PATCH_INFO_RGCTX_FETCH:
5815 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5816 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5821 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5822 * reference the same method, so encode the method only once.
5824 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5826 buf2 = (guint8 *)g_malloc (1024);
5829 encode_method_ref (acfg, entry->method, p2, &p2);
5830 g_assert (p2 - buf2 < 1024);
5832 offset = add_to_blob (acfg, buf2, p2 - buf2);
5835 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5840 encode_value (offset, p, &p);
5841 g_assert ((int)entry->info_type < 256);
5842 g_assert (entry->data->type < 256);
5843 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5844 encode_patch (acfg, entry->data, p, &p);
5847 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5848 case MONO_PATCH_INFO_AOT_MODULE:
5850 case MONO_PATCH_INFO_SIGNATURE:
5851 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5852 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5854 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5855 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5856 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5858 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5859 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5862 encode_method_ref (acfg, info->method, p, &p);
5863 encode_value (info->num_entries, p, &p);
5864 for (i = 0; i < info->num_entries; ++i) {
5865 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5867 encode_value (template_->info_type, p, &p);
5868 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5869 case MONO_PATCH_INFO_CLASS:
5870 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5872 case MONO_PATCH_INFO_FIELD:
5873 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5876 g_assert_not_reached ();
5882 case MONO_PATCH_INFO_LDSTR_LIT: {
5883 const char *s = (const char *)patch_info->data.target;
5884 int len = strlen (s);
5886 encode_value (len, p, &p);
5887 memcpy (p, s, len + 1);
5891 case MONO_PATCH_INFO_VIRT_METHOD:
5892 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5893 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5895 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5896 case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
5899 g_warning ("unable to handle jump info %d", patch_info->type);
5900 g_assert_not_reached ();
5907 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5910 guint32 pindex, offset;
5911 MonoJumpInfo *patch_info;
5913 encode_value (n_patches, p, &p);
5915 for (pindex = 0; pindex < patches->len; ++pindex) {
5916 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5918 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5922 offset = get_got_offset (acfg, llvm, patch_info);
5923 encode_value (offset, p, &p);
5930 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5933 int pindex, buf_size, n_patches;
5935 MonoJumpInfo *patch_info;
5936 guint32 method_index;
5938 guint32 first_got_offset;
5940 method = cfg->orig_method;
5942 method_index = get_method_index (acfg, method);
5944 /* Sort relocations */
5945 patches = g_ptr_array_new ();
5946 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5947 g_ptr_array_add (patches, patch_info);
5948 g_ptr_array_sort (patches, compare_patches);
5950 first_got_offset = acfg->cfgs [method_index]->got_offset;
5952 /**********************/
5953 /* Encode method info */
5954 /**********************/
5956 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5957 p = buf = (guint8 *)g_malloc (buf_size);
5959 if (mono_class_get_cctor (method->klass)) {
5960 encode_value (1, p, &p);
5961 encode_klass_ref (acfg, method->klass, p, &p);
5963 /* Not needed when loading the method */
5964 encode_value (0, p, &p);
5967 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5970 for (pindex = 0; pindex < patches->len; ++pindex) {
5971 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5973 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5974 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5975 patch_info->type = MONO_PATCH_INFO_NONE;
5980 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5981 /* Stored in a GOT slot initialized at module load time */
5982 patch_info->type = MONO_PATCH_INFO_NONE;
5986 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5987 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5988 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5989 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5990 /* Stored in a GOT slot initialized at module load time */
5991 patch_info->type = MONO_PATCH_INFO_NONE;
5995 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5996 /* Calls are made through the PLT */
5997 patch_info->type = MONO_PATCH_INFO_NONE;
6005 g_assert (cfg->has_got_slots);
6007 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6009 g_ptr_array_free (patches, TRUE);
6011 acfg->stats.info_size += p - buf;
6013 g_assert (p - buf < buf_size);
6015 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6020 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6022 guint32 cache_index;
6025 /* Reuse the unwind module to canonize and store unwind info entries */
6026 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6028 /* Use +/- 1 to distinguish 0s from missing entries */
6029 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6037 * It would be easier to use assembler symbols, but the caller needs an
6040 offset = acfg->unwind_info_offset;
6041 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6042 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6045 encode_value (encoded_len, p, &p);
6047 acfg->unwind_info_offset += encoded_len + (p - buf);
6053 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6056 guint32 debug_info_size, seq_points_size;
6058 MonoMethodHeader *header;
6059 guint8 *p, *buf, *debug_info;
6060 MonoJitInfo *jinfo = cfg->jit_info;
6062 gboolean use_unwind_ops = FALSE;
6063 MonoSeqPointInfo *seq_points;
6065 code = cfg->native_code;
6066 header = cfg->header;
6068 if (!acfg->aot_opts.nodebug) {
6069 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6072 debug_info_size = 0;
6075 seq_points = cfg->seq_point_info;
6076 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6078 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6080 p = buf = (guint8 *)g_malloc (buf_size);
6082 use_unwind_ops = cfg->unwind_ops != NULL;
6084 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);
6086 encode_value (flags, p, &p);
6088 if (use_unwind_ops) {
6089 guint32 encoded_len;
6091 guint32 unwind_desc;
6093 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6095 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6096 encode_value (unwind_desc, p, &p);
6100 encode_value (jinfo->unwind_info, p, &p);
6103 /*Encode the number of holes before the number of clauses to make decoding easier*/
6104 if (jinfo->has_try_block_holes) {
6105 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6106 encode_value (table->num_holes, p, &p);
6109 if (jinfo->has_arch_eh_info) {
6111 * In AOT mode, the code length is calculated from the address of the previous method,
6112 * which could include alignment padding, so calculating the start of the epilog as
6113 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6115 encode_value (jinfo->code_size, p, &p);
6118 /* Exception table */
6119 if (cfg->compile_llvm) {
6121 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6122 * since the information is only available to llc. Instead, we let llc save the data
6123 * into the LSDA, and read it from there at runtime.
6125 /* The assembly might be CIL stripped so emit the data ourselves */
6126 if (header->num_clauses)
6127 encode_value (header->num_clauses, p, &p);
6129 for (k = 0; k < header->num_clauses; ++k) {
6130 MonoExceptionClause *clause;
6132 clause = &header->clauses [k];
6134 encode_value (clause->flags, p, &p);
6135 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6136 if (clause->data.catch_class) {
6140 buf2 = (guint8 *)g_malloc (4096);
6142 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6144 g_assert (len < 4096);
6145 encode_value (len, p, &p);
6146 memcpy (p, buf2, len);
6150 encode_value (0, p, &p);
6154 /* Emit the IL ranges too, since they might not be available at runtime */
6155 encode_value (clause->try_offset, p, &p);
6156 encode_value (clause->try_len, p, &p);
6157 encode_value (clause->handler_offset, p, &p);
6158 encode_value (clause->handler_len, p, &p);
6160 /* Emit a list of nesting clauses */
6161 for (i = 0; i < header->num_clauses; ++i) {
6163 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6165 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6167 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6168 encode_value (i, p, &p);
6170 encode_value (-1, p, &p);
6173 if (jinfo->num_clauses)
6174 encode_value (jinfo->num_clauses, p, &p);
6176 for (k = 0; k < jinfo->num_clauses; ++k) {
6177 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6179 encode_value (ei->flags, p, &p);
6180 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6181 /* Not used for catch clauses */
6182 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6183 encode_value (ei->exvar_offset, p, &p);
6185 encode_value (ei->exvar_offset, p, &p);
6188 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6189 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6191 if (ei->data.catch_class) {
6195 buf2 = (guint8 *)g_malloc (4096);
6197 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6199 g_assert (len < 4096);
6200 encode_value (len, p, &p);
6201 memcpy (p, buf2, len);
6205 encode_value (0, p, &p);
6209 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6210 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6211 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6215 if (jinfo->has_try_block_holes) {
6216 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6217 for (i = 0; i < table->num_holes; ++i) {
6218 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6219 encode_value (hole->clause, p, &p);
6220 encode_value (hole->length, p, &p);
6221 encode_value (hole->offset, p, &p);
6225 if (jinfo->has_arch_eh_info) {
6226 MonoArchEHJitInfo *eh_info;
6228 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6229 encode_value (eh_info->stack_size, p, &p);
6230 encode_value (eh_info->epilog_size, p, &p);
6233 if (jinfo->has_generic_jit_info) {
6234 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6235 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6239 encode_value (gi->nlocs, p, &p);
6241 for (i = 0; i < gi->nlocs; ++i) {
6242 MonoDwarfLocListEntry *entry = &gi->locations [i];
6244 encode_value (entry->is_reg ? 1 : 0, p, &p);
6245 encode_value (entry->reg, p, &p);
6247 encode_value (entry->offset, p, &p);
6249 g_assert (entry->from == 0);
6251 encode_value (entry->from, p, &p);
6252 encode_value (entry->to, p, &p);
6255 if (!cfg->compile_llvm) {
6256 encode_value (gi->has_this ? 1 : 0, p, &p);
6257 encode_value (gi->this_reg, p, &p);
6258 encode_value (gi->this_offset, p, &p);
6263 * Need to encode jinfo->method too, since it is not equal to 'method'
6264 * when using generic sharing.
6266 buf2 = (guint8 *)g_malloc (4096);
6268 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6270 g_assert (len < 4096);
6271 encode_value (len, p, &p);
6272 memcpy (p, buf2, len);
6276 if (gsctx && gsctx->is_gsharedvt) {
6277 encode_value (1, p, &p);
6279 encode_value (0, p, &p);
6283 if (seq_points_size)
6284 p += mono_seq_point_info_write (seq_points, p);
6286 g_assert (debug_info_size < buf_size);
6288 encode_value (debug_info_size, p, &p);
6289 if (debug_info_size) {
6290 memcpy (p, debug_info, debug_info_size);
6291 p += debug_info_size;
6292 g_free (debug_info);
6297 encode_value (cfg->gc_map_size, p, &p);
6298 /* The GC map requires 4 bytes of alignment */
6299 while ((gsize)p % 4)
6301 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6302 p += cfg->gc_map_size;
6305 acfg->stats.ex_info_size += p - buf;
6307 g_assert (p - buf < buf_size);
6310 /* The GC Map requires 4 byte alignment */
6311 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6316 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6319 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6321 int i, buf_size, res;
6322 gboolean no_special_static, cant_encode;
6323 gpointer iter = NULL;
6326 mono_error_cleanup (&error);
6330 p = buf = (guint8 *)g_malloc (buf_size);
6332 /* Mark as unusable */
6333 encode_value (-1, p, &p);
6335 res = add_to_blob (acfg, buf, p - buf);
6341 buf_size = 10240 + (klass->vtable_size * 16);
6342 p = buf = (guint8 *)g_malloc (buf_size);
6346 mono_class_init (klass);
6348 mono_class_get_nested_types (klass, &iter);
6349 g_assert (klass->nested_classes_inited);
6351 mono_class_setup_vtable (klass);
6354 * Emit all the information which is required for creating vtables so
6355 * the runtime does not need to create the MonoMethod structures which
6356 * take up a lot of space.
6359 no_special_static = !mono_class_has_special_static_fields (klass);
6361 /* Check whenever we have enough info to encode the vtable */
6362 cant_encode = FALSE;
6363 for (i = 0; i < klass->vtable_size; ++i) {
6364 MonoMethod *cm = klass->vtable [i];
6366 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6370 mono_class_has_finalizer (klass);
6371 if (mono_class_has_failure (klass))
6374 if (mono_class_is_gtd (klass) || cant_encode) {
6375 encode_value (-1, p, &p);
6377 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6378 encode_value (klass->vtable_size, p, &p);
6379 encode_value ((mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | (has_nested ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
6380 if (klass->has_cctor)
6381 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6382 if (klass->has_finalize)
6383 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6385 encode_value (klass->instance_size, p, &p);
6386 encode_value (mono_class_data_size (klass), p, &p);
6387 encode_value (klass->packing_size, p, &p);
6388 encode_value (klass->min_align, p, &p);
6390 for (i = 0; i < klass->vtable_size; ++i) {
6391 MonoMethod *cm = klass->vtable [i];
6394 encode_method_ref (acfg, cm, p, &p);
6396 encode_value (0, p, &p);
6400 acfg->stats.class_info_size += p - buf;
6402 g_assert (p - buf < buf_size);
6403 res = add_to_blob (acfg, buf, p - buf);
6410 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6412 char *debug_sym = NULL;
6415 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6416 /* Need to add a prefix to create unique symbols */
6417 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6419 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6420 prefix = mangle_symbol_alloc ("plt_");
6422 prefix = g_strdup ("plt_");
6427 case MONO_PATCH_INFO_METHOD:
6428 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6430 case MONO_PATCH_INFO_INTERNAL_METHOD:
6431 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6433 case MONO_PATCH_INFO_RGCTX_FETCH:
6434 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6436 case MONO_PATCH_INFO_ICALL_ADDR:
6437 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6438 char *s = get_debug_sym (ji->data.method, "", cache);
6440 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6444 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6445 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6453 return sanitize_symbol (acfg, debug_sym);
6457 * Calls made from AOTed code are routed through a table of jumps similar to the
6458 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6459 * control to the AOT runtime through a trampoline.
6462 emit_plt (MonoAotCompile *acfg)
6466 if (acfg->aot_opts.llvm_only) {
6467 g_assert (acfg->plt_offset == 1);
6473 emit_section_change (acfg, ".text", 0);
6474 emit_alignment_code (acfg, 16);
6475 emit_info_symbol (acfg, "plt");
6476 emit_label (acfg, acfg->plt_symbol);
6478 for (i = 0; i < acfg->plt_offset; ++i) {
6479 char *debug_sym = NULL;
6480 MonoPltEntry *plt_entry = NULL;
6484 * The first plt entry is unused.
6488 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6490 debug_sym = plt_entry->debug_sym;
6492 if (acfg->thumb_mixed && !plt_entry->jit_used)
6493 /* Emit only a thumb version */
6496 /* Skip plt entries not actually called */
6497 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6500 if (acfg->llvm && !acfg->thumb_mixed) {
6501 emit_label (acfg, plt_entry->llvm_symbol);
6503 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6504 #if defined(TARGET_MACH)
6505 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6511 if (acfg->need_no_dead_strip) {
6512 emit_unset_mode (acfg);
6513 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6515 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6516 emit_label (acfg, debug_sym);
6519 emit_label (acfg, plt_entry->symbol);
6521 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6524 emit_symbol_size (acfg, debug_sym, ".");
6527 if (acfg->thumb_mixed) {
6528 /* Make sure the ARM symbols don't alias the thumb ones */
6529 emit_zero_bytes (acfg, 16);
6532 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6535 for (i = 0; i < acfg->plt_offset; ++i) {
6536 char *debug_sym = NULL;
6537 MonoPltEntry *plt_entry = NULL;
6542 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6544 /* Skip plt entries not actually called by LLVM code */
6545 if (!plt_entry->llvm_used)
6548 if (acfg->aot_opts.write_symbols) {
6549 if (plt_entry->debug_sym)
6550 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6554 #if defined(TARGET_MACH)
6555 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6556 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6558 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6559 emit_label (acfg, debug_sym);
6561 fprintf (acfg->fp, "\n.thumb_func\n");
6563 emit_label (acfg, plt_entry->llvm_symbol);
6566 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6568 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6571 emit_symbol_size (acfg, debug_sym, ".");
6577 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6579 emit_info_symbol (acfg, "plt_end");
6583 * emit_trampoline_full:
6585 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6586 * create_jit_info_for_trampoline ().
6588 static G_GNUC_UNUSED void
6589 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6591 char start_symbol [MAX_SYMBOL_SIZE];
6592 char end_symbol [MAX_SYMBOL_SIZE];
6593 char symbol [MAX_SYMBOL_SIZE];
6594 guint32 buf_size, info_offset;
6595 MonoJumpInfo *patch_info;
6608 code_size = info->code_size;
6610 unwind_ops = info->unwind_ops;
6614 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6616 emit_section_change (acfg, ".text", 0);
6617 emit_global (acfg, start_symbol, TRUE);
6618 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6619 emit_label (acfg, start_symbol);
6621 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6622 emit_label (acfg, symbol);
6625 * The code should access everything through the GOT, so we pass
6628 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6630 emit_symbol_size (acfg, start_symbol, ".");
6633 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6634 emit_label (acfg, end_symbol);
6639 /* Sort relocations */
6640 patches = g_ptr_array_new ();
6641 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6642 if (patch_info->type != MONO_PATCH_INFO_NONE)
6643 g_ptr_array_add (patches, patch_info);
6644 g_ptr_array_sort (patches, compare_patches);
6646 buf_size = patches->len * 128 + 128;
6647 buf = (guint8 *)g_malloc (buf_size);
6650 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6651 g_assert (p - buf < buf_size);
6652 g_ptr_array_free (patches, TRUE);
6654 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6656 info_offset = add_to_blob (acfg, buf, p - buf);
6658 emit_section_change (acfg, RODATA_SECT, 0);
6659 emit_global (acfg, symbol, FALSE);
6660 emit_label (acfg, symbol);
6662 emit_int32 (acfg, info_offset);
6666 guint32 encoded_len;
6670 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6672 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6673 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6676 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6677 emit_int32 (acfg, uw_offset);
6680 /* Emit debug info */
6682 char symbol2 [MAX_SYMBOL_SIZE];
6684 sprintf (symbol, "%s", name);
6685 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6688 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6694 static G_GNUC_UNUSED void
6695 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6697 emit_trampoline_full (acfg, got_offset, info, TRUE);
6701 emit_trampolines (MonoAotCompile *acfg)
6703 char symbol [MAX_SYMBOL_SIZE];
6704 char end_symbol [MAX_SYMBOL_SIZE];
6705 int i, tramp_got_offset;
6707 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6711 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6714 g_assert (acfg->image->assembly);
6716 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6717 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6718 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6719 MonoTrampInfo *info;
6722 * Emit the generic trampolines.
6724 * We could save some code by treating the generic trampolines as a wrapper
6725 * method, but that approach has its own complexities, so we choose the simpler
6728 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6729 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6730 #ifdef DISABLE_REMOTING
6731 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6734 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6735 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6738 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6739 emit_trampoline (acfg, acfg->got_offset, info);
6742 /* Emit the exception related code pieces */
6743 mono_arch_get_restore_context (&info, TRUE);
6744 emit_trampoline (acfg, acfg->got_offset, info);
6745 mono_arch_get_call_filter (&info, TRUE);
6746 emit_trampoline (acfg, acfg->got_offset, info);
6747 mono_arch_get_throw_exception (&info, TRUE);
6748 emit_trampoline (acfg, acfg->got_offset, info);
6749 mono_arch_get_rethrow_exception (&info, TRUE);
6750 emit_trampoline (acfg, acfg->got_offset, info);
6751 mono_arch_get_throw_corlib_exception (&info, TRUE);
6752 emit_trampoline (acfg, acfg->got_offset, info);
6754 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6755 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6756 emit_trampoline (acfg, acfg->got_offset, info);
6757 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6758 emit_trampoline (acfg, acfg->got_offset, info);
6761 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6762 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6764 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6766 /* Create a separate out trampoline for more information in stack traces */
6767 info->name = g_strdup ("gsharedvt_out_trampoline");
6768 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6772 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6774 GSList *l = mono_arch_get_trampolines (TRUE);
6777 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6779 emit_trampoline (acfg, acfg->got_offset, info);
6785 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6788 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6789 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6790 emit_trampoline (acfg, acfg->got_offset, info);
6793 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6794 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6795 emit_trampoline (acfg, acfg->got_offset, info);
6799 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6800 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6801 emit_trampoline (acfg, acfg->got_offset, info);
6807 /* delegate_invoke_impl trampolines */
6808 l = mono_arch_get_delegate_invoke_impls ();
6810 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6812 emit_trampoline (acfg, acfg->got_offset, info);
6817 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6818 mono_arch_create_handler_block_trampoline (&info, TRUE);
6819 emit_trampoline (acfg, acfg->got_offset, info);
6822 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6824 /* Emit trampolines which are numerous */
6827 * These include the following:
6828 * - specific trampolines
6829 * - static rgctx invoke trampolines
6831 * These trampolines have the same code, they are parameterized by GOT
6833 * They are defined in this file, in the arch_... routines instead of
6834 * in tramp-<ARCH>.c, since it is easier to do it this way.
6838 * When running in aot-only mode, we can't create specific trampolines at
6839 * runtime, so we create a few, and save them in the AOT file.
6840 * Normal trampolines embed their argument as a literal inside the
6841 * trampoline code, we can't do that here, so instead we embed an offset
6842 * which needs to be added to the trampoline address to get the address of
6843 * the GOT slot which contains the argument value.
6844 * The generated trampolines jump to the generic trampolines using another
6845 * GOT slot, which will be setup by the AOT loader to point to the
6846 * generic trampoline code of the given type.
6850 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6854 emit_section_change (acfg, ".text", 0);
6856 tramp_got_offset = acfg->got_offset;
6858 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6860 case MONO_AOT_TRAMP_SPECIFIC:
6861 sprintf (symbol, "specific_trampolines");
6863 case MONO_AOT_TRAMP_STATIC_RGCTX:
6864 sprintf (symbol, "static_rgctx_trampolines");
6866 case MONO_AOT_TRAMP_IMT:
6867 sprintf (symbol, "imt_trampolines");
6869 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6870 sprintf (symbol, "gsharedvt_arg_trampolines");
6873 g_assert_not_reached ();
6876 sprintf (end_symbol, "%s_e", symbol);
6878 if (acfg->aot_opts.write_symbols)
6879 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6881 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6882 emit_info_symbol (acfg, symbol);
6884 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6886 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6890 case MONO_AOT_TRAMP_SPECIFIC:
6891 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6892 tramp_got_offset += 2;
6894 case MONO_AOT_TRAMP_STATIC_RGCTX:
6895 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6896 tramp_got_offset += 2;
6898 case MONO_AOT_TRAMP_IMT:
6899 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6900 tramp_got_offset += 1;
6902 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6903 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6904 tramp_got_offset += 2;
6907 g_assert_not_reached ();
6909 if (!acfg->trampoline_size [ntype]) {
6910 g_assert (tramp_size);
6911 acfg->trampoline_size [ntype] = tramp_size;
6915 emit_label (acfg, end_symbol);
6916 emit_int32 (acfg, 0);
6919 arch_emit_specific_trampoline_pages (acfg);
6921 /* Reserve some entries at the end of the GOT for our use */
6922 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6925 acfg->got_offset += acfg->num_trampoline_got_entries;
6929 str_begins_with (const char *str1, const char *str2)
6931 int len = strlen (str2);
6932 return strncmp (str1, str2, len) == 0;
6936 mono_aot_readonly_field_override (MonoClassField *field)
6939 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6940 char *p = rdv->name;
6942 len = strlen (field->parent->name_space);
6943 if (strncmp (p, field->parent->name_space, len))
6948 len = strlen (field->parent->name);
6949 if (strncmp (p, field->parent->name, len))
6954 if (strcmp (p, field->name))
6956 switch (rdv->type) {
6958 return &rdv->value.i1;
6960 return &rdv->value.i2;
6962 return &rdv->value.i4;
6971 add_readonly_value (MonoAotOptions *opts, const char *val)
6976 /* the format of val is:
6977 * namespace.typename.fieldname=type/value
6978 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6980 fval = strrchr (val, '/');
6982 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6985 tval = strrchr (val, '=');
6987 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6990 rdv = g_new0 (ReadOnlyValue, 1);
6991 rdv->name = (char *)g_malloc0 (tval - val + 1);
6992 memcpy (rdv->name, val, tval - val);
6995 if (strncmp (tval, "i1", 2) == 0) {
6996 rdv->value.i1 = atoi (fval);
6997 rdv->type = MONO_TYPE_I1;
6998 } else if (strncmp (tval, "i2", 2) == 0) {
6999 rdv->value.i2 = atoi (fval);
7000 rdv->type = MONO_TYPE_I2;
7001 } else if (strncmp (tval, "i4", 2) == 0) {
7002 rdv->value.i4 = atoi (fval);
7003 rdv->type = MONO_TYPE_I4;
7005 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7008 rdv->next = readonly_values;
7009 readonly_values = rdv;
7013 clean_path (gchar * path)
7018 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7021 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7028 wrap_path (gchar * path)
7034 // If the string contains no spaces, just return the original string.
7035 if (strstr (path, " ") == NULL)
7038 // If the string is already wrapped in quotes, return it.
7039 len = strlen (path);
7040 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7043 // If the string contains spaces, then wrap it in quotes.
7044 gchar *clean = g_strdup_printf ("\"%s\"", path);
7049 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7051 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7053 ptrdiff_t len = end-start;
7055 g_ptr_array_add (args, g_strndup (start, len));
7059 mono_aot_split_options (const char *aot_options)
7061 enum MonoAotOptionState {
7062 MONO_AOT_OPTION_STATE_DEFAULT,
7063 MONO_AOT_OPTION_STATE_STRING,
7064 MONO_AOT_OPTION_STATE_ESCAPE,
7067 GPtrArray *args = g_ptr_array_new ();
7068 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7069 gchar const *opt_start = aot_options;
7070 gboolean end_of_string = FALSE;
7073 g_return_val_if_fail (aot_options != NULL, NULL);
7075 while ((cur = *aot_options) != '\0') {
7076 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7081 // If we find a quote, then if we're in the default case then
7082 // it means we've found the start of a string, if not then it
7083 // means we've found the end of the string and should switch
7084 // back to the default case.
7086 case MONO_AOT_OPTION_STATE_DEFAULT:
7087 state = MONO_AOT_OPTION_STATE_STRING;
7089 case MONO_AOT_OPTION_STATE_STRING:
7090 state = MONO_AOT_OPTION_STATE_DEFAULT;
7092 case MONO_AOT_OPTION_STATE_ESCAPE:
7093 g_assert_not_reached ();
7098 // If we've found an escaping operator, then this means we
7099 // should not process the next character if inside a string.
7100 if (state == MONO_AOT_OPTION_STATE_STRING)
7101 state = MONO_AOT_OPTION_STATE_ESCAPE;
7104 // If we're in the default state then this means we've found
7105 // an option, store it for later processing.
7106 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7114 // If the next character is end of string, then process the last option.
7115 if (*(aot_options) == '\0') {
7116 end_of_string = TRUE;
7122 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7123 opt_start = ++aot_options;
7126 goto restart; // Check for null and continue loop
7133 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7137 args = mono_aot_split_options (aot_options ? aot_options : "");
7138 for (int i = 0; i < args->len; ++i) {
7139 const char *arg = (const char *)g_ptr_array_index (args, i);
7141 if (str_begins_with (arg, "outfile=")) {
7142 opts->outfile = g_strdup (arg + strlen ("outfile="));
7143 } else if (str_begins_with (arg, "llvm-outfile=")) {
7144 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7145 } else if (str_begins_with (arg, "temp-path=")) {
7146 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7147 } else if (str_begins_with (arg, "save-temps")) {
7148 opts->save_temps = TRUE;
7149 } else if (str_begins_with (arg, "keep-temps")) {
7150 opts->save_temps = TRUE;
7151 } else if (str_begins_with (arg, "write-symbols")) {
7152 opts->write_symbols = TRUE;
7153 } else if (str_begins_with (arg, "no-write-symbols")) {
7154 opts->write_symbols = FALSE;
7155 // Intentionally undocumented -- one-off experiment
7156 } else if (str_begins_with (arg, "metadata-only")) {
7157 opts->metadata_only = TRUE;
7158 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7159 opts->bind_to_runtime_version = TRUE;
7160 } else if (str_begins_with (arg, "full")) {
7161 opts->mode = MONO_AOT_MODE_FULL;
7162 } else if (str_begins_with (arg, "hybrid")) {
7163 opts->mode = MONO_AOT_MODE_HYBRID;
7164 } else if (str_begins_with (arg, "threads=")) {
7165 opts->nthreads = atoi (arg + strlen ("threads="));
7166 } else if (str_begins_with (arg, "static")) {
7167 opts->static_link = TRUE;
7168 opts->no_dlsym = TRUE;
7169 } else if (str_begins_with (arg, "asmonly")) {
7170 opts->asm_only = TRUE;
7171 } else if (str_begins_with (arg, "asmwriter")) {
7172 opts->asm_writer = TRUE;
7173 } else if (str_begins_with (arg, "nodebug")) {
7174 opts->nodebug = TRUE;
7175 } else if (str_begins_with (arg, "dwarfdebug")) {
7176 opts->dwarf_debug = TRUE;
7177 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7178 } else if (str_begins_with (arg, "nopagetrampolines")) {
7179 opts->use_trampolines_page = FALSE;
7180 } else if (str_begins_with (arg, "ntrampolines=")) {
7181 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7182 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7183 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7184 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7185 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7186 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7187 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7188 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7189 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7190 } else if (str_begins_with (arg, "tool-prefix=")) {
7191 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7192 } else if (str_begins_with (arg, "ld-flags=")) {
7193 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7194 } else if (str_begins_with (arg, "soft-debug")) {
7195 opts->soft_debug = TRUE;
7196 // Intentionally undocumented x2-- deprecated
7197 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7198 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7199 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7200 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7201 } else if (str_begins_with (arg, "msym-dir=")) {
7202 debug_options.no_seq_points_compact_data = FALSE;
7203 opts->gen_msym_dir = TRUE;
7204 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7205 } else if (str_begins_with (arg, "direct-pinvoke")) {
7206 opts->direct_pinvoke = TRUE;
7207 } else if (str_begins_with (arg, "direct-icalls")) {
7208 opts->direct_icalls = TRUE;
7209 } else if (str_begins_with (arg, "no-direct-calls")) {
7210 opts->no_direct_calls = TRUE;
7211 } else if (str_begins_with (arg, "print-skipped")) {
7212 opts->print_skipped_methods = TRUE;
7213 } else if (str_begins_with (arg, "stats")) {
7215 // Intentionally undocumented-- has no known function other than to debug the compiler
7216 } else if (str_begins_with (arg, "no-instances")) {
7217 opts->no_instances = TRUE;
7218 // Intentionally undocumented x4-- Used for internal debugging of compiler
7219 } else if (str_begins_with (arg, "log-generics")) {
7220 opts->log_generics = TRUE;
7221 } else if (str_begins_with (arg, "log-instances=")) {
7222 opts->log_instances = TRUE;
7223 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7224 } else if (str_begins_with (arg, "log-instances")) {
7225 opts->log_instances = TRUE;
7226 } else if (str_begins_with (arg, "internal-logfile=")) {
7227 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7228 } else if (str_begins_with (arg, "mtriple=")) {
7229 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7230 } else if (str_begins_with (arg, "llvm-path=")) {
7231 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7232 } else if (!strcmp (arg, "llvm")) {
7234 } else if (str_begins_with (arg, "readonly-value=")) {
7235 add_readonly_value (opts, arg + strlen ("readonly-value="));
7236 } else if (str_begins_with (arg, "info")) {
7237 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7239 // Intentionally undocumented: Used for precise stack maps, which are not available yet
7240 } else if (str_begins_with (arg, "gc-maps")) {
7241 mini_gc_enable_gc_maps_for_aot ();
7242 // Intentionally undocumented: Used for internal debugging
7243 } else if (str_begins_with (arg, "dump")) {
7244 opts->dump_json = TRUE;
7245 } else if (str_begins_with (arg, "llvmonly")) {
7246 opts->mode = MONO_AOT_MODE_FULL;
7248 opts->llvm_only = TRUE;
7249 } else if (str_begins_with (arg, "data-outfile=")) {
7250 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7251 } else if (str_begins_with (arg, "profile=")) {
7252 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7253 } else if (!strcmp (arg, "profile-only")) {
7254 opts->profile_only = TRUE;
7255 } else if (!strcmp (arg, "verbose")) {
7256 opts->verbose = TRUE;
7257 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7258 printf ("Supported options for --aot:\n");
7259 printf (" asmonly\n");
7260 printf (" bind-to-runtime-version\n");
7261 printf (" bitcode\n");
7262 printf (" data-outfile=\n");
7263 printf (" direct-icalls\n");
7264 printf (" direct-pinvoke\n");
7265 printf (" dwarfdebug\n");
7267 printf (" hybrid\n");
7269 printf (" keep-temps\n");
7271 printf (" llvmonly\n");
7272 printf (" llvm-outfile=\n");
7273 printf (" llvm-path=\n");
7274 printf (" msym-dir=\n");
7275 printf (" mtriple\n");
7276 printf (" nimt-trampolines=\n");
7277 printf (" nodebug\n");
7278 printf (" no-direct-calls\n");
7279 printf (" no-write-symbols\n");
7280 printf (" nrgctx-trampolines=\n");
7281 printf (" nrgctx-fetch-trampolines=\n");
7282 printf (" ngsharedvt-trampolines=\n");
7283 printf (" ntrampolines=\n");
7284 printf (" outfile=\n");
7285 printf (" profile=\n");
7286 printf (" profile-only\n");
7287 printf (" print-skipped-methods\n");
7288 printf (" readonly-value=\n");
7289 printf (" save-temps\n");
7290 printf (" soft-debug\n");
7291 printf (" static\n");
7292 printf (" stats\n");
7293 printf (" temp-path=\n");
7294 printf (" tool-prefix=\n");
7295 printf (" threads=\n");
7296 printf (" write-symbols\n");
7297 printf (" verbose\n");
7298 printf (" help/?\n");
7301 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7305 g_free ((gpointer) arg);
7308 if (opts->use_trampolines_page) {
7309 opts->ntrampolines = 0;
7310 opts->nrgctx_trampolines = 0;
7311 opts->nimt_trampolines = 0;
7312 opts->ngsharedvt_arg_trampolines = 0;
7315 g_ptr_array_free (args, /*free_seg=*/TRUE);
7319 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7321 MonoMethod *method = (MonoMethod*)key;
7322 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7323 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7324 MonoJumpInfoToken *new_ji;
7326 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7327 new_ji->image = ji->image;
7328 new_ji->token = ji->token;
7329 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7333 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7335 if (klass->type_token)
7337 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7340 return can_encode_class (acfg, klass->element_class);
7345 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7347 if (method->wrapper_type) {
7348 switch (method->wrapper_type) {
7349 case MONO_WRAPPER_NONE:
7350 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7351 case MONO_WRAPPER_XDOMAIN_INVOKE:
7352 case MONO_WRAPPER_STFLD:
7353 case MONO_WRAPPER_LDFLD:
7354 case MONO_WRAPPER_LDFLDA:
7355 case MONO_WRAPPER_STELEMREF:
7356 case MONO_WRAPPER_PROXY_ISINST:
7357 case MONO_WRAPPER_ALLOC:
7358 case MONO_WRAPPER_REMOTING_INVOKE:
7359 case MONO_WRAPPER_UNKNOWN:
7360 case MONO_WRAPPER_WRITE_BARRIER:
7361 case MONO_WRAPPER_DELEGATE_INVOKE:
7362 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7363 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7364 case MONO_WRAPPER_SYNCHRONIZED:
7366 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7367 case MONO_WRAPPER_CASTCLASS: {
7368 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7377 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7381 if (!method->token) {
7382 /* The method is part of a constructed type like Int[,].Set (). */
7383 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7384 if (method->klass->rank)
7394 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7396 switch (patch_info->type) {
7397 case MONO_PATCH_INFO_METHOD:
7398 case MONO_PATCH_INFO_METHODCONST:
7399 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7400 MonoMethod *method = patch_info->data.method;
7402 return can_encode_method (acfg, method);
7404 case MONO_PATCH_INFO_VTABLE:
7405 case MONO_PATCH_INFO_CLASS:
7406 case MONO_PATCH_INFO_IID:
7407 case MONO_PATCH_INFO_ADJUSTED_IID:
7408 if (!can_encode_class (acfg, patch_info->data.klass)) {
7409 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7413 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7414 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7415 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7420 case MONO_PATCH_INFO_RGCTX_FETCH:
7421 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7422 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7424 if (!can_encode_method (acfg, entry->method))
7426 if (!can_encode_patch (acfg, entry->data))
7438 is_concrete_type (MonoType *t)
7443 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7445 if (t->type == MONO_TYPE_GENERICINST) {
7446 MonoGenericContext *orig_ctx;
7447 MonoGenericInst *inst;
7450 if (!MONO_TYPE_ISSTRUCT (t))
7452 klass = mono_class_from_mono_type (t);
7453 orig_ctx = &mono_class_get_generic_class (klass)->context;
7455 inst = orig_ctx->class_inst;
7457 for (i = 0; i < inst->type_argc; ++i) {
7458 arg = mini_get_underlying_type (inst->type_argv [i]);
7459 if (!is_concrete_type (arg))
7463 inst = orig_ctx->method_inst;
7465 for (i = 0; i < inst->type_argc; ++i) {
7466 arg = mini_get_underlying_type (inst->type_argv [i]);
7467 if (!is_concrete_type (arg))
7475 /* LOCKING: Assumes the loader lock is held */
7477 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7479 MonoMethod *wrapper;
7480 gboolean concrete = TRUE;
7481 gboolean add_in = gsharedvt_in;
7482 gboolean add_out = gsharedvt_out;
7484 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7486 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7489 if (!add_in && !add_out)
7492 if (mini_is_gsharedvt_variable_signature (sig))
7496 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7498 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7500 if (!sig->has_type_parameters) {
7501 //printf ("%s\n", mono_signature_full_name (sig));
7504 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7505 add_extra_method (acfg, wrapper);
7507 if (gsharedvt_out) {
7508 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7509 add_extra_method (acfg, wrapper);
7512 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7513 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7516 //printf ("%s\n", mono_signature_full_name (sig));
7518 copy->ret = mini_get_underlying_type (sig->ret);
7519 if (!is_concrete_type (copy->ret))
7521 for (i = 0; i < sig->param_count; ++i) {
7522 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7523 if (!is_concrete_type (copy->params [i]))
7527 copy->has_type_parameters = 0;
7530 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7531 add_extra_method (acfg, wrapper);
7534 if (gsharedvt_out) {
7535 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7536 add_extra_method (acfg, wrapper);
7539 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7547 * AOT compile a given method.
7548 * This function might be called by multiple threads, so it must be thread-safe.
7551 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7554 MonoJumpInfo *patch_info;
7557 MonoMethod *wrapped;
7561 if (acfg->aot_opts.metadata_only)
7564 mono_acfg_lock (acfg);
7565 index = get_method_index (acfg, method);
7566 mono_acfg_unlock (acfg);
7568 /* fixme: maybe we can also precompile wrapper methods */
7569 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7570 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7571 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7572 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7576 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7579 wrapped = mono_marshal_method_from_wrapper (method);
7580 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7581 // FIXME: The wrapper should be generic too, but it is not
7584 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7587 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7590 InterlockedIncrement (&acfg->stats.mcount);
7593 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7594 InterlockedIncrement (&acfg->stats.genericcount);
7599 //acfg->aot_opts.print_skipped_methods = TRUE;
7602 * Since these methods are the only ones which are compiled with
7603 * AOT support, and they are not used by runtime startup/shutdown code,
7604 * the runtime will not see AOT methods during AOT compilation,so it
7605 * does not need to support them by creating a fake GOT etc.
7607 flags = JIT_FLAG_AOT;
7608 if (mono_aot_mode_is_full (&acfg->aot_opts))
7609 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7611 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7612 if (acfg->aot_opts.llvm_only)
7613 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7614 if (acfg->aot_opts.no_direct_calls)
7615 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7616 if (acfg->aot_opts.direct_pinvoke)
7617 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7619 jit_timer = mono_time_track_start ();
7620 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7621 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7623 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7624 if (acfg->aot_opts.print_skipped_methods)
7625 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7626 InterlockedIncrement (&acfg->stats.genericcount);
7629 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7630 /* Some instances cannot be JITted due to constraints etc. */
7631 if (!method->is_inflated)
7632 report_loader_error (acfg, &cfg->error, "Unable to compile method '%s' due to: '%s'.\n", mono_method_get_full_name (method), mono_error_get_message (&cfg->error));
7633 /* Let the exception happen at runtime */
7637 if (cfg->disable_aot) {
7638 if (acfg->aot_opts.print_skipped_methods)
7639 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7640 InterlockedIncrement (&acfg->stats.ocount);
7643 cfg->method_index = index;
7645 /* Nullify patches which need no aot processing */
7646 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7647 switch (patch_info->type) {
7648 case MONO_PATCH_INFO_LABEL:
7649 case MONO_PATCH_INFO_BB:
7650 patch_info->type = MONO_PATCH_INFO_NONE;
7657 /* Collect method->token associations from the cfg */
7658 mono_acfg_lock (acfg);
7659 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7660 mono_acfg_unlock (acfg);
7661 g_hash_table_destroy (cfg->token_info_hash);
7662 cfg->token_info_hash = NULL;
7665 * Check for absolute addresses.
7668 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7669 switch (patch_info->type) {
7670 case MONO_PATCH_INFO_ABS:
7671 /* unable to handle this */
7680 if (acfg->aot_opts.print_skipped_methods)
7681 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7682 InterlockedIncrement (&acfg->stats.abscount);
7686 /* Lock for the rest of the code */
7687 mono_acfg_lock (acfg);
7690 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7691 else if (cfg->gshared)
7692 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7693 else if (cfg->method->wrapper_type)
7694 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7696 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7699 * Check for methods/klasses we can't encode.
7702 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7703 if (!can_encode_patch (acfg, patch_info))
7708 if (acfg->aot_opts.print_skipped_methods)
7709 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7710 acfg->stats.ocount++;
7711 mono_acfg_unlock (acfg);
7715 if (!cfg->compile_llvm)
7716 acfg->has_jitted_code = TRUE;
7718 if (method->is_inflated && acfg->aot_opts.log_instances) {
7719 if (acfg->instances_logfile)
7720 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7722 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7725 /* Adds generic instances referenced by this method */
7727 * The depth is used to avoid infinite loops when generic virtual recursion is
7730 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7731 if (!acfg->aot_opts.no_instances && depth < 32 && mono_aot_mode_is_full (&acfg->aot_opts)) {
7732 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7733 switch (patch_info->type) {
7734 case MONO_PATCH_INFO_RGCTX_FETCH:
7735 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7736 case MONO_PATCH_INFO_METHOD: {
7737 MonoMethod *m = NULL;
7739 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7740 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7742 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7743 m = e->data->data.method;
7745 m = patch_info->data.method;
7750 if (m->is_inflated && mono_aot_mode_is_full (&acfg->aot_opts)) {
7751 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7752 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7753 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7754 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7755 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7756 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7758 add_extra_method_with_depth (acfg, m, depth + 1);
7759 add_types_from_method_header (acfg, m);
7762 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7764 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7765 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7767 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7768 add_extra_method_with_depth (acfg, m, depth + 1);
7772 case MONO_PATCH_INFO_VTABLE: {
7773 MonoClass *klass = patch_info->data.klass;
7775 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7776 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7779 case MONO_PATCH_INFO_SFLDA: {
7780 MonoClass *klass = patch_info->data.field->parent;
7782 /* The .cctor needs to run at runtime. */
7783 if (mono_class_is_ginst (klass) && !mono_generic_context_is_sharable_full (&mono_class_get_generic_class (klass)->context, FALSE, FALSE) && mono_class_get_cctor (klass))
7784 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7793 /* Determine whenever the method has GOT slots */
7794 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7795 switch (patch_info->type) {
7796 case MONO_PATCH_INFO_GOT_OFFSET:
7797 case MONO_PATCH_INFO_NONE:
7798 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7799 case MONO_PATCH_INFO_GC_NURSERY_START:
7800 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7802 case MONO_PATCH_INFO_IMAGE:
7803 /* The assembly is stored in GOT slot 0 */
7804 if (patch_info->data.image != acfg->image)
7805 cfg->has_got_slots = TRUE;
7808 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7809 cfg->has_got_slots = TRUE;
7814 if (!cfg->has_got_slots)
7815 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7817 /* Add gsharedvt wrappers for signatures used by the method */
7818 if (acfg->aot_opts.llvm_only) {
7821 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7822 /* These only need out wrappers */
7823 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7825 for (l = cfg->signatures; l; l = l->next) {
7826 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7828 /* These only need in wrappers */
7829 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7834 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7836 /* Make a copy of the patch info which is in the mempool */
7838 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7840 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7841 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7844 patches = new_patch_info;
7846 patches_end->next = new_patch_info;
7847 patches_end = new_patch_info;
7849 cfg->patch_info = patches;
7851 /* Make a copy of the unwind info */
7853 GSList *l, *unwind_ops;
7857 for (l = cfg->unwind_ops; l; l = l->next) {
7858 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7859 memcpy (op, l->data, sizeof (MonoUnwindOp));
7860 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7862 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7864 /* Make a copy of the argument/local info */
7867 MonoInst **args, **locals;
7868 MonoMethodSignature *sig;
7869 MonoMethodHeader *header;
7872 sig = mono_method_signature (method);
7873 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7874 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7875 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7876 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7880 header = mono_method_get_header_checked (method, &error);
7881 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7882 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7883 for (i = 0; i < header->num_locals; ++i) {
7884 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7885 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7887 mono_metadata_free_mh (header);
7888 cfg->locals = locals;
7891 /* Free some fields used by cfg to conserve memory */
7892 mono_empty_compile (cfg);
7894 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7896 while (index >= acfg->cfgs_size) {
7897 MonoCompile **new_cfgs;
7900 new_size = acfg->cfgs_size * 2;
7901 new_cfgs = g_new0 (MonoCompile*, new_size);
7902 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7903 g_free (acfg->cfgs);
7904 acfg->cfgs = new_cfgs;
7905 acfg->cfgs_size = new_size;
7907 acfg->cfgs [index] = cfg;
7909 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7911 mono_update_jit_stats (cfg);
7914 if (cfg->orig_method->wrapper_type)
7915 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7918 mono_acfg_unlock (acfg);
7920 InterlockedIncrement (&acfg->stats.ccount);
7923 static mono_thread_start_return_t WINAPI
7924 compile_thread_main (gpointer user_data)
7926 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
7927 GPtrArray *methods = ((GPtrArray **)user_data) [1];
7931 MonoInternalThread *internal = mono_thread_internal_current ();
7932 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", &error);
7933 mono_error_assert_ok (&error);
7934 mono_thread_set_name_internal (internal, str, TRUE, FALSE, &error);
7935 mono_error_assert_ok (&error);
7937 for (i = 0; i < methods->len; ++i)
7938 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7943 /* Used by the LLVM backend */
7945 mono_aot_get_got_offset (MonoJumpInfo *ji)
7947 return get_got_offset (llvm_acfg, TRUE, ji);
7951 * mono_aot_is_shared_got_offset:
7953 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7954 * when the AOT image is loaded.
7957 mono_aot_is_shared_got_offset (int offset)
7959 return offset < llvm_acfg->nshared_got_entries;
7963 mono_aot_get_method_name (MonoCompile *cfg)
7965 if (llvm_acfg->aot_opts.static_link)
7966 /* Include the assembly name too to avoid duplicate symbol errors */
7967 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7969 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7973 * mono_aot_is_linkonce_method:
7975 * Return whenever METHOD should be emitted with linkonce linkage,
7976 * eliminating duplicate copies when compiling in static mode.
7979 mono_aot_is_linkonce_method (MonoMethod *method)
7985 // FIXME: Add more cases
7986 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7988 info = mono_marshal_get_wrapper_info (method);
7989 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7996 append_mangled_type (GString *s, MonoType *t)
7999 g_string_append_printf (s, "b");
8001 case MONO_TYPE_VOID:
8002 g_string_append_printf (s, "void_");
8005 g_string_append_printf (s, "i1");
8008 g_string_append_printf (s, "u1");
8011 g_string_append_printf (s, "i2");
8014 g_string_append_printf (s, "u2");
8017 g_string_append_printf (s, "i4");
8020 g_string_append_printf (s, "u4");
8023 g_string_append_printf (s, "i8");
8026 g_string_append_printf (s, "u8");
8029 g_string_append_printf (s, "ii");
8032 g_string_append_printf (s, "ui");
8035 g_string_append_printf (s, "fl");
8038 g_string_append_printf (s, "do");
8041 char *fullname = mono_type_full_name (t);
8047 * Have to create a mangled name which is:
8051 temp = g_string_new ("");
8052 len = strlen (fullname);
8053 for (i = 0; i < len; ++i) {
8054 char c = fullname [i];
8056 g_string_append_c (temp, c);
8057 } else if (c == '_') {
8058 g_string_append_c (temp, '_');
8059 g_string_append_c (temp, '_');
8061 g_string_append_c (temp, '_');
8062 g_string_append_printf (temp, "%x", (int)c);
8065 temps = g_string_free (temp, FALSE);
8066 /* Include the length to avoid different length type names aliasing each other */
8067 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8076 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8081 supported = append_mangled_type (s, sig->ret);
8085 g_string_append_printf (s, "this_");
8086 for (i = 0; i < sig->param_count; ++i) {
8087 supported = append_mangled_type (s, sig->params [i]);
8096 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8100 switch (wrapper_type) {
8101 case MONO_WRAPPER_REMOTING_INVOKE:
8102 label = "remoting_invoke";
8104 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8105 label = "remoting_invoke_check";
8107 case MONO_WRAPPER_XDOMAIN_INVOKE:
8108 label = "remoting_invoke_xdomain";
8110 case MONO_WRAPPER_PROXY_ISINST:
8111 label = "proxy_isinst";
8113 case MONO_WRAPPER_LDFLD:
8116 case MONO_WRAPPER_LDFLDA:
8119 case MONO_WRAPPER_STFLD:
8122 case MONO_WRAPPER_ALLOC:
8125 case MONO_WRAPPER_WRITE_BARRIER:
8126 label = "write_barrier";
8128 case MONO_WRAPPER_STELEMREF:
8129 label = "stelemref";
8131 case MONO_WRAPPER_UNKNOWN:
8134 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8135 label = "man2native";
8137 case MONO_WRAPPER_SYNCHRONIZED:
8140 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8143 case MONO_WRAPPER_CASTCLASS:
8144 label = "castclass";
8146 case MONO_WRAPPER_RUNTIME_INVOKE:
8147 label = "run_invoke";
8149 case MONO_WRAPPER_DELEGATE_INVOKE:
8152 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8153 label = "del_beg_inv";
8155 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8156 label = "del_end_inv";
8158 case MONO_WRAPPER_NATIVE_TO_MANAGED:
8159 label = "native2man";
8162 g_assert_not_reached ();
8165 g_string_append_printf (s, "%s_", label);
8169 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
8175 case WRAPPER_SUBTYPE_NONE:
8177 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8178 label = "elem_addr";
8180 case WRAPPER_SUBTYPE_STRING_CTOR:
8183 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8184 label = "virt_stelem";
8186 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8187 label = "fast_mon_enter";
8189 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8190 label = "fast_mon_enter_4";
8192 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8193 label = "fast_monitor_exit";
8195 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8196 label = "ptr2struct";
8198 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8199 label = "struct2ptr";
8201 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8202 label = "castclass_w_cache";
8204 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8205 label = "isinst_w_cache";
8207 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8208 label = "run_inv_norm";
8210 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8211 label = "run_inv_dyn";
8213 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8214 label = "run_inv_dir";
8216 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8217 label = "run_inv_vir";
8219 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8222 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8223 label = "native_func_aot";
8225 case WRAPPER_SUBTYPE_PINVOKE:
8228 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8229 label = "synch_inner";
8231 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8232 label = "gshared_in";
8234 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8235 label = "gshared_out";
8237 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8238 label = "array_acc";
8240 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8241 label = "generic_arry_help";
8243 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8244 label = "del_inv_virt";
8246 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8247 label = "del_inv_bound";
8249 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8250 label = "gsharedvt_in_sig";
8252 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8253 label = "gsharedvt_out_sig";
8256 g_assert_not_reached ();
8259 g_string_append_printf (s, "%s_", label);
8263 sanitize_mangled_string (const char *input)
8265 GString *s = g_string_new ("");
8267 for (int i=0; input [i] != '\0'; i++) {
8271 g_string_append (s, "_dot_");
8274 g_string_append (s, "_");
8277 g_string_append (s, "_bt_");
8280 g_string_append (s, "_le_");
8283 g_string_append (s, "_gt_");
8286 g_string_append (s, "_sl_");
8289 g_string_append (s, "_lbrack_");
8292 g_string_append (s, "_rbrack_");
8295 g_string_append (s, "_lparen_");
8298 g_string_append (s, "_dash_");
8301 g_string_append (s, "_rparen_");
8304 g_string_append (s, "_comma_");
8307 g_string_append_c (s, c);
8311 return g_string_free (s, FALSE);
8315 append_mangled_klass (GString *s, MonoClass *klass)
8317 char *klass_desc = mono_class_full_name (klass);
8318 g_string_append_printf (s, "_%s_%s_", klass->name_space, klass_desc);
8319 g_free (klass_desc);
8326 append_mangled_method (GString *s, MonoMethod *method);
8329 append_mangled_wrapper (GString *s, MonoMethod *method)
8331 gboolean success = TRUE;
8332 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8333 g_string_append_printf (s, "wrapper_");
8335 append_mangled_wrapper_type (s, method->wrapper_type);
8337 switch (method->wrapper_type) {
8338 case MONO_WRAPPER_REMOTING_INVOKE:
8339 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8340 case MONO_WRAPPER_XDOMAIN_INVOKE: {
8341 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8343 success = success && append_mangled_method (s, m);
8346 case MONO_WRAPPER_PROXY_ISINST:
8347 case MONO_WRAPPER_LDFLD:
8348 case MONO_WRAPPER_LDFLDA:
8349 case MONO_WRAPPER_STFLD: {
8351 success = success && append_mangled_klass (s, info->d.proxy.klass);
8354 case MONO_WRAPPER_ALLOC: {
8355 /* The GC name is saved once in MonoAotFileInfo */
8356 g_assert (info->d.alloc.alloc_type != -1);
8357 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8359 g_string_append_printf (s, "%s_", method->name);
8362 case MONO_WRAPPER_WRITE_BARRIER: {
8365 case MONO_WRAPPER_STELEMREF: {
8366 append_mangled_wrapper_subtype (s, info->subtype);
8367 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8368 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8371 case MONO_WRAPPER_UNKNOWN: {
8372 append_mangled_wrapper_subtype (s, info->subtype);
8373 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8374 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8375 success = success && append_mangled_klass (s, method->klass);
8376 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8377 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8378 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8379 success = success && append_mangled_method (s, info->d.array_accessor.method);
8380 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
8381 append_mangled_signature (s, info->d.gsharedvt.sig);
8382 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8383 append_mangled_signature (s, info->d.gsharedvt.sig);
8386 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8387 append_mangled_wrapper_subtype (s, info->subtype);
8388 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8389 g_string_append_printf (s, "%s", method->name);
8390 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8391 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8393 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8394 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8398 case MONO_WRAPPER_SYNCHRONIZED: {
8401 m = mono_marshal_method_from_wrapper (method);
8403 g_assert (m != method);
8404 success = success && append_mangled_method (s, m);
8407 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8408 append_mangled_wrapper_subtype (s, info->subtype);
8410 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8411 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8412 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8413 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8414 success = success && append_mangled_method (s, info->d.string_ctor.method);
8416 g_assert_not_reached ();
8420 case MONO_WRAPPER_CASTCLASS: {
8421 append_mangled_wrapper_subtype (s, info->subtype);
8424 case MONO_WRAPPER_RUNTIME_INVOKE: {
8425 append_mangled_wrapper_subtype (s, info->subtype);
8426 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
8427 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
8428 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
8429 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
8432 case MONO_WRAPPER_DELEGATE_INVOKE:
8433 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8434 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
8435 if (method->is_inflated) {
8436 /* These wrappers are identified by their class */
8437 g_string_append_printf (s, "i_");
8438 success = success && append_mangled_klass (s, method->klass);
8440 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8442 g_string_append_printf (s, "u_");
8443 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8444 append_mangled_wrapper_subtype (s, info->subtype);
8445 g_string_append_printf (s, "u_sigstart");
8449 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
8451 success = success && append_mangled_method (s, info->d.native_to_managed.method);
8452 success = success && append_mangled_klass (s, method->klass);
8456 g_assert_not_reached ();
8458 return success && append_mangled_signature (s, mono_method_signature (method));
8462 append_mangled_context (GString *str, MonoGenericContext *context)
8464 GString *res = g_string_new ("");
8466 g_string_append_printf (res, "gens_");
8467 g_string_append (res, "00");
8469 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
8470 good = good || (context->method_inst && context->method_inst->type_argc > 0);
8473 if (context->class_inst)
8474 mono_ginst_get_desc (res, context->class_inst);
8475 if (context->method_inst) {
8476 if (context->class_inst)
8477 g_string_append (res, "11");
8478 mono_ginst_get_desc (res, context->method_inst);
8480 g_string_append_printf (str, "gens_%s", res->str);
8484 append_mangled_method (GString *s, MonoMethod *method)
8486 if (method->wrapper_type)
8487 return append_mangled_wrapper (s, method);
8489 g_string_append_printf (s, "%s_", method->klass->image->assembly->aname.name);
8491 if (method->is_inflated) {
8492 g_string_append_printf (s, "inflated_");
8493 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
8494 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
8496 append_mangled_context (s, &imethod->context);
8497 g_string_append_printf (s, "_declared_by_");
8498 append_mangled_method (s, imethod->declaring);
8499 } else if (method->is_generic) {
8500 g_string_append_printf (s, "generic_");
8501 append_mangled_klass (s, method->klass);
8502 g_string_append_printf (s, "_%s_", method->name);
8504 MonoGenericContainer *container = mono_method_get_generic_container (method);
8505 g_string_append_printf (s, "_%s");
8506 append_mangled_context (s, &container->context);
8508 return append_mangled_signature (s, mono_method_signature (method));
8510 g_string_append_printf (s, "_");
8511 append_mangled_klass (s, method->klass);
8512 g_string_append_printf (s, "_%s_", method->name);
8513 if (!append_mangled_signature (s, mono_method_signature (method))) {
8514 g_string_free (s, TRUE);
8523 * mono_aot_get_mangled_method_name:
8525 * Return a unique mangled name for METHOD, or NULL.
8528 mono_aot_get_mangled_method_name (MonoMethod *method)
8530 GString *s = g_string_new ("aot_");
8531 if (!append_mangled_method (s, method)) {
8532 g_string_free (s, TRUE);
8535 char *out = g_string_free (s, FALSE);
8536 // Scrub method and class names
8537 char *cleaned = sanitize_mangled_string (out);
8544 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8546 return is_direct_callable (llvm_acfg, NULL, patch_info);
8550 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8552 MonoPltEntry *plt_entry;
8554 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8555 plt_entry->llvm_used = FALSE;
8559 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8561 const char *sym = NULL;
8563 if (llvm_acfg->aot_opts.direct_icalls) {
8564 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8565 /* Call to a C function implementing a jit icall */
8566 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8567 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8568 MonoMethod *method = (MonoMethod *)data;
8569 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8570 sym = mono_lookup_icall_symbol (method);
8571 else if (llvm_acfg->aot_opts.direct_pinvoke)
8572 sym = get_pinvoke_import (llvm_acfg, method);
8575 return g_strdup (sym);
8581 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8583 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8584 MonoPltEntry *plt_entry;
8585 const char *sym = NULL;
8588 ji->data.target = data;
8590 if (!can_encode_patch (llvm_acfg, ji))
8593 if (llvm_acfg->aot_opts.direct_icalls) {
8594 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8595 /* Call to a C function implementing a jit icall */
8596 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8597 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8598 MonoMethod *method = (MonoMethod *)data;
8599 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8600 sym = mono_lookup_icall_symbol (method);
8603 return g_strdup (sym);
8606 plt_entry = get_plt_entry (llvm_acfg, ji);
8607 plt_entry->llvm_used = TRUE;
8609 #if defined(TARGET_MACH)
8610 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8612 return g_strdup_printf (plt_entry->llvm_symbol);
8617 mono_aot_get_method_index (MonoMethod *method)
8619 g_assert (llvm_acfg);
8620 return get_method_index (llvm_acfg, method);
8624 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8628 mono_acfg_lock (llvm_acfg);
8629 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8630 mono_acfg_unlock (llvm_acfg);
8636 execute_system (const char * command)
8640 #if defined(HOST_WIN32)
8641 // We need an extra set of quotes around the whole command to properly handle commands
8642 // with spaces since internally the command is called through "cmd /c.
8643 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8645 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8646 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8647 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8648 status = _wsystem (wstr);
8651 g_free (quoted_command);
8652 #elif defined (HAVE_SYSTEM)
8653 status = system (command);
8655 g_assert_not_reached ();
8666 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8670 emit_llvm_file (MonoAotCompile *acfg)
8672 char *command, *opts, *tempbc, *optbc, *output_fname;
8674 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8675 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8676 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8678 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8679 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8682 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8685 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8686 * a lot of time, and doesn't seem to save much space.
8687 * The following optimizations cannot be enabled:
8689 * - 'jump-threading' changes our blockaddress references to int constants.
8690 * - 'basiccg' fails because it contains:
8691 * if (CS && !isa<IntrinsicInst>(II)) {
8692 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8693 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8694 * The opt list below was produced by taking the output of:
8695 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8696 * then removing tailcallelim + the global opts.
8697 * strip-dead-prototypes deletes unused intrinsics definitions.
8699 /* The dse pass is disabled because of #13734 and #17616 */
8701 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8702 * // If we have no DataLayout information around, then the size of the store
8703 * // is inferrable from the pointee type. If they are the same type, then
8704 * // we know that the store is safe.
8705 * if (AA.getDataLayout() == 0 &&
8706 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8707 * return OverwriteComplete;
8708 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8710 if (acfg->aot_opts.llvm_only)
8711 // FIXME: This doesn't work yet
8712 opts = g_strdup ("");
8714 #if LLVM_API_VERSION > 100
8715 opts = g_strdup ("-O2 -disable-tail-calls");
8717 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");
8719 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8720 aot_printf (acfg, "Executing opt: %s\n", command);
8721 if (execute_system (command) != 0)
8725 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8726 /* Nothing else to do */
8729 if (acfg->aot_opts.llvm_only) {
8730 /* Use the stock clang from xcode */
8732 command = g_strdup_printf ("clang++ -fexceptions -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
8734 aot_printf (acfg, "Executing clang: %s\n", command);
8735 if (execute_system (command) != 0)
8740 if (!acfg->llc_args)
8741 acfg->llc_args = g_string_new ("");
8743 /* Verbose asm slows down llc greatly */
8744 g_string_append (acfg->llc_args, " -asm-verbose=false");
8746 if (acfg->aot_opts.mtriple)
8747 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8749 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8751 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8753 #if LLVM_API_VERSION > 100
8754 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8757 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS)
8758 /* ios requires PIC code now */
8759 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8761 if (llvm_acfg->aot_opts.static_link)
8762 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8764 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8767 if (acfg->llvm_owriter) {
8768 /* Emit an object file directly */
8769 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8770 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8772 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8774 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8775 g_free (output_fname);
8777 aot_printf (acfg, "Executing llc: %s\n", command);
8779 if (execute_system (command) != 0)
8786 emit_code (MonoAotCompile *acfg)
8788 int oindex, i, prev_index;
8789 gboolean saved_unbox_info = FALSE;
8790 char symbol [MAX_SYMBOL_SIZE];
8792 if (acfg->aot_opts.llvm_only)
8795 #if defined(TARGET_POWERPC64)
8796 sprintf (symbol, ".Lgot_addr");
8797 emit_section_change (acfg, ".text", 0);
8798 emit_alignment (acfg, 8);
8799 emit_label (acfg, symbol);
8800 emit_pointer (acfg, acfg->got_symbol);
8804 * This global symbol is used to compute the address of each method using the
8805 * code_offsets array. It is also used to compute the memory ranges occupied by
8806 * AOT code, so it must be equal to the address of the first emitted method.
8808 emit_section_change (acfg, ".text", 0);
8809 emit_alignment_code (acfg, 8);
8810 emit_info_symbol (acfg, "jit_code_start");
8813 * Emit some padding so the local symbol for the first method doesn't have the
8814 * same address as 'methods'.
8816 emit_padding (acfg, 16);
8818 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8822 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8824 cfg = acfg->cfgs [i];
8829 method = cfg->orig_method;
8831 /* Emit unbox trampoline */
8832 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8833 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8835 emit_section_change (acfg, ".text", 0);
8837 if (acfg->thumb_mixed && cfg->compile_llvm) {
8838 emit_set_thumb_mode (acfg);
8839 fprintf (acfg->fp, "\n.thumb_func\n");
8842 emit_label (acfg, symbol);
8844 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8846 if (acfg->thumb_mixed && cfg->compile_llvm)
8847 emit_set_arm_mode (acfg);
8849 if (!saved_unbox_info) {
8850 char user_symbol [128];
8852 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8854 emit_label (acfg, "ut_end");
8856 unwind_ops = mono_unwind_get_cie_program ();
8857 save_unwind_info (acfg, user_symbol, unwind_ops);
8858 mono_free_unwind_info (unwind_ops);
8860 /* Save the unbox trampoline size */
8861 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8863 saved_unbox_info = TRUE;
8867 if (cfg->compile_llvm)
8868 acfg->stats.llvm_count ++;
8870 emit_method_code (acfg, cfg);
8873 emit_section_change (acfg, ".text", 0);
8874 emit_alignment_code (acfg, 8);
8875 emit_info_symbol (acfg, "jit_code_end");
8877 /* To distinguish it from the next symbol */
8878 emit_padding (acfg, 4);
8881 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8882 * from optimizing them away, since it doesn't see that code_offsets references them.
8883 * JITted methods don't need this since they are referenced using assembler local
8885 * FIXME: This is why write-symbols doesn't work on OSX ?
8887 if (acfg->llvm && acfg->need_no_dead_strip) {
8888 fprintf (acfg->fp, "\n");
8889 for (i = 0; i < acfg->nmethods; ++i) {
8890 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8891 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8896 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8897 * This is PIE code, and the linker can update it if needed.
8900 sprintf (symbol, "method_addresses");
8901 emit_section_change (acfg, ".text", 1);
8902 emit_alignment_code (acfg, 8);
8903 emit_info_symbol (acfg, symbol);
8904 if (acfg->aot_opts.write_symbols)
8905 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8906 emit_unset_mode (acfg);
8907 if (acfg->need_no_dead_strip)
8908 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8910 for (i = 0; i < acfg->nmethods; ++i) {
8911 #ifdef MONO_ARCH_AOT_SUPPORTED
8914 if (acfg->cfgs [i]) {
8915 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8917 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8922 sprintf (symbol, "method_addresses_end");
8923 emit_label (acfg, symbol);
8926 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8927 sprintf (symbol, "unbox_trampolines");
8928 emit_section_change (acfg, RODATA_SECT, 0);
8929 emit_alignment (acfg, 8);
8930 emit_info_symbol (acfg, symbol);
8933 for (i = 0; i < acfg->nmethods; ++i) {
8938 cfg = acfg->cfgs [i];
8942 method = cfg->orig_method;
8944 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8945 index = get_method_index (acfg, method);
8947 emit_int32 (acfg, index);
8948 /* Make sure the table is sorted by index */
8949 g_assert (index > prev_index);
8953 sprintf (symbol, "unbox_trampolines_end");
8954 emit_info_symbol (acfg, symbol);
8955 emit_int32 (acfg, 0);
8957 /* Emit a separate table with the trampoline addresses/offsets */
8958 sprintf (symbol, "unbox_trampoline_addresses");
8959 emit_section_change (acfg, ".text", 0);
8960 emit_alignment_code (acfg, 8);
8961 emit_info_symbol (acfg, symbol);
8963 for (i = 0; i < acfg->nmethods; ++i) {
8968 cfg = acfg->cfgs [i];
8972 method = cfg->orig_method;
8974 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8975 #ifdef MONO_ARCH_AOT_SUPPORTED
8978 index = get_method_index (acfg, method);
8979 sprintf (symbol, "ut_%d", index);
8981 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8985 emit_int32 (acfg, 0);
8989 emit_info (MonoAotCompile *acfg)
8994 offsets = g_new0 (gint32, acfg->nmethods);
8996 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8997 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8999 if (acfg->cfgs [i]) {
9000 emit_method_info (acfg, acfg->cfgs [i]);
9001 offsets [i] = acfg->cfgs [i]->method_info_offset;
9007 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9012 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
9014 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
9015 #define mix(a,b,c) { \
9016 a -= c; a ^= rot(c, 4); c += b; \
9017 b -= a; b ^= rot(a, 6); a += c; \
9018 c -= b; c ^= rot(b, 8); b += a; \
9019 a -= c; a ^= rot(c,16); c += b; \
9020 b -= a; b ^= rot(a,19); a += c; \
9021 c -= b; c ^= rot(b, 4); b += a; \
9023 #define final(a,b,c) { \
9024 c ^= b; c -= rot(b,14); \
9025 a ^= c; a -= rot(c,11); \
9026 b ^= a; b -= rot(a,25); \
9027 c ^= b; c -= rot(b,16); \
9028 a ^= c; a -= rot(c,4); \
9029 b ^= a; b -= rot(a,14); \
9030 c ^= b; c -= rot(b,24); \
9034 mono_aot_type_hash (MonoType *t1)
9036 guint hash = t1->type;
9038 hash |= t1->byref << 6; /* do not collide with t1->type values */
9040 case MONO_TYPE_VALUETYPE:
9041 case MONO_TYPE_CLASS:
9042 case MONO_TYPE_SZARRAY:
9043 /* check if the distribution is good enough */
9044 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
9046 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9047 case MONO_TYPE_ARRAY:
9048 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
9049 case MONO_TYPE_GENERICINST:
9050 return ((hash << 5) - hash) ^ 0;
9057 * mono_aot_method_hash:
9059 * Return a hash code for methods which only depends on metadata.
9062 mono_aot_method_hash (MonoMethod *method)
9064 MonoMethodSignature *sig;
9068 guint32 *hashes_start, *hashes;
9070 MonoGenericInst *class_ginst = NULL;
9071 MonoGenericInst *ginst = NULL;
9073 /* Similar to the hash in mono_method_get_imt_slot () */
9075 sig = mono_method_signature (method);
9077 if (mono_class_is_ginst (method->klass))
9078 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9079 if (method->is_inflated)
9080 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9082 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9083 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9084 hashes = hashes_start;
9086 /* Some wrappers are assigned to random classes */
9087 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9088 klass = method->klass;
9090 klass = mono_defaults.object_class;
9092 if (!method->wrapper_type) {
9095 if (mono_class_is_ginst (klass))
9096 full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
9098 full_name = mono_type_full_name (&klass->byval_arg);
9100 hashes [0] = mono_metadata_str_hash (full_name);
9104 hashes [0] = mono_metadata_str_hash (klass->name);
9105 hashes [1] = mono_metadata_str_hash (klass->name_space);
9107 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9108 /* The method name includes a stringified pointer */
9111 hashes [2] = mono_metadata_str_hash (method->name);
9112 hashes [3] = method->wrapper_type;
9113 hashes [4] = mono_aot_type_hash (sig->ret);
9115 for (i = 0; i < sig->param_count; i++) {
9116 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9119 for (i = 0; i < class_ginst->type_argc; ++i)
9120 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9123 for (i = 0; i < ginst->type_argc; ++i)
9124 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9126 g_assert (hindex == hashes_count);
9128 /* Setup internal state */
9129 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9131 /* Handle most of the hashes */
9132 while (hashes_count > 3) {
9141 /* Handle the last 3 hashes (all the case statements fall through) */
9142 switch (hashes_count) {
9143 case 3 : c += hashes [2];
9144 case 2 : b += hashes [1];
9145 case 1 : a += hashes [0];
9147 case 0: /* nothing left to add */
9151 g_free (hashes_start);
9160 * mono_aot_get_array_helper_from_wrapper;
9162 * Get the helper method in Array called by an array wrapper method.
9165 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9169 MonoGenericContext ctx;
9170 MonoType *args [16];
9171 char *mname, *iname, *s, *s2, *helper_name = NULL;
9173 prefix = "System.Collections.Generic";
9174 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9175 s2 = strstr (s, "`1.");
9181 //printf ("X: %s %s\n", iname, mname);
9183 if (!strcmp (iname, "IList"))
9184 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9186 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9187 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
9189 g_free (helper_name);
9192 if (m->is_generic) {
9194 memset (&ctx, 0, sizeof (ctx));
9195 args [0] = &method->klass->element_class->byval_arg;
9196 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9197 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
9198 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9204 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9206 typedef struct HashEntry {
9207 guint32 key, value, index;
9208 struct HashEntry *next;
9212 * emit_extra_methods:
9214 * Emit methods which are not in the METHOD table, like wrappers.
9217 emit_extra_methods (MonoAotCompile *acfg)
9219 int i, table_size, buf_size;
9221 guint32 *info_offsets;
9224 HashEntry *entry, *new_entry;
9225 int nmethods, max_chain_length;
9228 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9230 /* Emit method info */
9232 for (i = 0; i < acfg->extra_methods->len; ++i) {
9233 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9234 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9240 p = buf = (guint8 *)g_malloc (buf_size);
9244 method = cfg->method_to_register;
9246 encode_method_ref (acfg, method, p, &p);
9248 g_assert ((p - buf) < buf_size);
9250 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9255 * Construct a chained hash table for mapping indexes in extra_method_info to
9258 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9259 table = g_ptr_array_sized_new (table_size);
9260 for (i = 0; i < table_size; ++i)
9261 g_ptr_array_add (table, NULL);
9262 chain_lengths = g_new0 (int, table_size);
9263 max_chain_length = 0;
9264 for (i = 0; i < acfg->extra_methods->len; ++i) {
9265 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9266 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9272 key = info_offsets [i];
9273 value = get_method_index (acfg, method);
9275 hash = mono_aot_method_hash (method) % table_size;
9276 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9278 chain_lengths [hash] ++;
9279 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9281 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9282 new_entry->key = key;
9283 new_entry->value = value;
9285 entry = (HashEntry *)g_ptr_array_index (table, hash);
9286 if (entry == NULL) {
9287 new_entry->index = hash;
9288 g_ptr_array_index (table, hash) = new_entry;
9291 entry = entry->next;
9293 entry->next = new_entry;
9294 new_entry->index = table->len;
9295 g_ptr_array_add (table, new_entry);
9298 g_free (chain_lengths);
9300 //printf ("MAX: %d\n", max_chain_length);
9302 buf_size = table->len * 12 + 4;
9303 p = buf = (guint8 *)g_malloc (buf_size);
9304 encode_int (table_size, p, &p);
9306 for (i = 0; i < table->len; ++i) {
9307 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9309 if (entry == NULL) {
9310 encode_int (0, p, &p);
9311 encode_int (0, p, &p);
9312 encode_int (0, p, &p);
9314 //g_assert (entry->key > 0);
9315 encode_int (entry->key, p, &p);
9316 encode_int (entry->value, p, &p);
9318 encode_int (entry->next->index, p, &p);
9320 encode_int (0, p, &p);
9323 g_assert (p - buf <= buf_size);
9325 /* Emit the table */
9326 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9331 * Emit a table reverse mapping method indexes to their index in extra_method_info.
9332 * This is used by mono_aot_find_jit_info ().
9334 buf_size = acfg->extra_methods->len * 8 + 4;
9335 p = buf = (guint8 *)g_malloc (buf_size);
9336 encode_int (acfg->extra_methods->len, p, &p);
9337 for (i = 0; i < acfg->extra_methods->len; ++i) {
9338 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9340 encode_int (get_method_index (acfg, method), p, &p);
9341 encode_int (info_offsets [i], p, &p);
9343 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9346 g_free (info_offsets);
9347 g_ptr_array_free (table, TRUE);
9351 generate_aotid (guint8* aotid)
9353 gpointer rand_handle;
9357 rand_handle = mono_rand_init (NULL, 0);
9359 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
9360 mono_error_assert_ok (&error);
9362 mono_rand_close (rand_handle);
9366 emit_exception_info (MonoAotCompile *acfg)
9370 SeqPointData sp_data;
9371 gboolean seq_points_to_file = FALSE;
9373 offsets = g_new0 (gint32, acfg->nmethods);
9374 for (i = 0; i < acfg->nmethods; ++i) {
9375 if (acfg->cfgs [i]) {
9376 MonoCompile *cfg = acfg->cfgs [i];
9378 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
9379 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
9380 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
9381 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
9382 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
9384 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
9385 offsets [i] = cfg->ex_info_offset;
9387 if (method_seq_points_to_file) {
9388 if (!seq_points_to_file) {
9389 mono_seq_point_data_init (&sp_data, acfg->nmethods);
9390 seq_points_to_file = TRUE;
9392 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
9399 if (seq_points_to_file) {
9400 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
9401 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
9402 char *image_basename = g_path_get_basename (acfg->image->name);
9403 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
9404 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
9406 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
9407 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
9411 mono_seq_point_data_write (&sp_data, aot_file_path);
9412 mono_seq_point_data_free (&sp_data);
9416 g_free (image_basename);
9418 g_free (aot_file_path);
9421 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9426 emit_unwind_info (MonoAotCompile *acfg)
9431 if (acfg->aot_opts.llvm_only) {
9432 g_assert (acfg->unwind_ops->len == 0);
9437 * The unwind info contains a lot of duplicates so we emit each unique
9438 * entry once, and only store the offset from the start of the table in the
9442 sprintf (symbol, "unwind_info");
9443 emit_section_change (acfg, RODATA_SECT, 1);
9444 emit_alignment (acfg, 8);
9445 emit_info_symbol (acfg, symbol);
9447 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9448 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9449 guint8 *unwind_info;
9450 guint32 unwind_info_len;
9454 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9457 encode_value (unwind_info_len, p, &p);
9458 emit_bytes (acfg, buf, p - buf);
9459 emit_bytes (acfg, unwind_info, unwind_info_len);
9461 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9466 emit_class_info (MonoAotCompile *acfg)
9471 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9472 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9473 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9475 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);
9479 typedef struct ClassNameTableEntry {
9480 guint32 token, index;
9481 struct ClassNameTableEntry *next;
9482 } ClassNameTableEntry;
9485 emit_class_name_table (MonoAotCompile *acfg)
9487 int i, table_size, buf_size;
9488 guint32 token, hash;
9493 ClassNameTableEntry *entry, *new_entry;
9496 * Construct a chained hash table for mapping class names to typedef tokens.
9498 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9499 table = g_ptr_array_sized_new (table_size);
9500 for (i = 0; i < table_size; ++i)
9501 g_ptr_array_add (table, NULL);
9502 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9504 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9505 klass = mono_class_get_checked (acfg->image, token, &error);
9507 mono_error_cleanup (&error);
9510 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9511 hash = mono_metadata_str_hash (full_name) % table_size;
9514 /* FIXME: Allocate from the mempool */
9515 new_entry = g_new0 (ClassNameTableEntry, 1);
9516 new_entry->token = token;
9518 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9519 if (entry == NULL) {
9520 new_entry->index = hash;
9521 g_ptr_array_index (table, hash) = new_entry;
9524 entry = entry->next;
9526 entry->next = new_entry;
9527 new_entry->index = table->len;
9528 g_ptr_array_add (table, new_entry);
9532 /* Emit the table */
9533 buf_size = table->len * 4 + 4;
9534 p = buf = (guint8 *)g_malloc0 (buf_size);
9536 /* FIXME: Optimize memory usage */
9537 g_assert (table_size < 65000);
9538 encode_int16 (table_size, p, &p);
9539 g_assert (table->len < 65000);
9540 for (i = 0; i < table->len; ++i) {
9541 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9543 if (entry == NULL) {
9544 encode_int16 (0, p, &p);
9545 encode_int16 (0, p, &p);
9547 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9549 encode_int16 (entry->next->index, p, &p);
9551 encode_int16 (0, p, &p);
9555 g_assert (p - buf <= buf_size);
9556 g_ptr_array_free (table, TRUE);
9558 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9564 emit_image_table (MonoAotCompile *acfg)
9570 * The image table is small but referenced in a lot of places.
9571 * So we emit it at once, and reference its elements by an index.
9573 buf_size = acfg->image_table->len * 28 + 4;
9574 for (i = 0; i < acfg->image_table->len; i++) {
9575 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9576 MonoAssemblyName *aname = &image->assembly->aname;
9578 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9581 buf = p = (guint8 *)g_malloc0 (buf_size);
9582 encode_int (acfg->image_table->len, p, &p);
9583 for (i = 0; i < acfg->image_table->len; i++) {
9584 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9585 MonoAssemblyName *aname = &image->assembly->aname;
9587 /* FIXME: Support multi-module assemblies */
9588 g_assert (image->assembly->image == image);
9590 encode_string (image->assembly_name, p, &p);
9591 encode_string (image->guid, p, &p);
9592 encode_string (aname->culture ? aname->culture : "", p, &p);
9593 encode_string ((const char*)aname->public_key_token, p, &p);
9595 while (GPOINTER_TO_UINT (p) % 8 != 0)
9598 encode_int (aname->flags, p, &p);
9599 encode_int (aname->major, p, &p);
9600 encode_int (aname->minor, p, &p);
9601 encode_int (aname->build, p, &p);
9602 encode_int (aname->revision, p, &p);
9604 g_assert (p - buf <= buf_size);
9606 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9612 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9614 int i, first_plt_got_patch = 0, buf_size;
9616 guint32 *got_info_offsets;
9617 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9619 /* Add the patches needed by the PLT to the GOT */
9621 acfg->plt_got_offset_base = acfg->got_offset;
9622 first_plt_got_patch = info->got_patches->len;
9623 for (i = 1; i < acfg->plt_offset; ++i) {
9624 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9626 g_ptr_array_add (info->got_patches, plt_entry->ji);
9628 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9631 acfg->got_offset += acfg->plt_offset;
9636 * - optimize offsets table.
9637 * - reduce number of exported symbols.
9638 * - emit info for a klass only once.
9639 * - determine when a method uses a GOT slot which is guaranteed to be already
9641 * - clean up and document the code.
9642 * - use String.Empty in class libs.
9645 /* Encode info required to decode shared GOT entries */
9646 buf_size = info->got_patches->len * 128;
9647 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9648 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9650 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9652 if (acfg->plt_offset)
9653 acfg->plt_got_info_offsets [0] = 0;
9655 for (i = 0; i < info->got_patches->len; ++i) {
9656 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9661 encode_value (ji->type, p, &p);
9663 encode_patch (acfg, ji, p, &p);
9664 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9665 g_assert (p - buf <= buf_size);
9666 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9668 if (!llvm && i >= first_plt_got_patch)
9669 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9670 acfg->stats.got_info_size += p - buf;
9673 /* Emit got_info_offsets table */
9675 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9676 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);
9680 emit_got (MonoAotCompile *acfg)
9682 char symbol [MAX_SYMBOL_SIZE];
9684 if (acfg->aot_opts.llvm_only)
9687 /* Don't make GOT global so accesses to it don't need relocations */
9688 sprintf (symbol, "%s", acfg->got_symbol);
9691 emit_unset_mode (acfg);
9692 fprintf (acfg->fp, ".section __DATA, __bss\n");
9693 emit_alignment (acfg, 8);
9695 emit_info_symbol (acfg, "jit_got");
9696 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9698 emit_section_change (acfg, ".bss", 0);
9699 emit_alignment (acfg, 8);
9700 if (acfg->aot_opts.write_symbols)
9701 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9702 emit_label (acfg, symbol);
9704 emit_info_symbol (acfg, "jit_got");
9705 if (acfg->got_offset > 0)
9706 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9709 sprintf (symbol, "got_end");
9710 emit_label (acfg, symbol);
9713 typedef struct GlobalsTableEntry {
9714 guint32 value, index;
9715 struct GlobalsTableEntry *next;
9716 } GlobalsTableEntry;
9718 #ifdef TARGET_WIN32_MSVC
9719 #define DLL_ENTRY_POINT "DllMain"
9722 emit_library_info (MonoAotCompile *acfg)
9724 // Only include for shared libraries linked directly from generated object.
9725 if (link_shared_library (acfg)) {
9727 char symbol [MAX_SYMBOL_SIZE];
9729 // Ask linker to export all global symbols.
9730 emit_section_change (acfg, ".drectve", 0);
9731 for (guint i = 0; i < acfg->globals->len; ++i) {
9732 name = (char *)g_ptr_array_index (acfg->globals, i);
9733 g_assert (name != NULL);
9734 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
9735 emit_string (acfg, symbol);
9738 // Emit DLLMain function, needed by MSVC linker for DLL's.
9739 // NOTE, DllMain should not go into exports above.
9740 emit_section_change (acfg, ".text", 0);
9741 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
9742 emit_label (acfg, DLL_ENTRY_POINT);
9744 // Simple implementation of DLLMain, just returning TRUE.
9745 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
9746 fprintf (acfg->fp, "movl $1, %%eax\n");
9747 fprintf (acfg->fp, "ret\n");
9749 // Inform linker about our dll entry function.
9750 emit_section_change (acfg, ".drectve", 0);
9751 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
9759 emit_library_info (MonoAotCompile *acfg)
9766 emit_globals (MonoAotCompile *acfg)
9772 GlobalsTableEntry *entry, *new_entry;
9774 if (!acfg->aot_opts.static_link)
9777 if (acfg->aot_opts.llvm_only) {
9778 g_assert (acfg->globals->len == 0);
9783 * When static linking, we emit a table containing our globals.
9787 * Construct a chained hash table for mapping global names to their index in
9788 * the globals table.
9790 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9791 table = g_ptr_array_sized_new (table_size);
9792 for (i = 0; i < table_size; ++i)
9793 g_ptr_array_add (table, NULL);
9794 for (i = 0; i < acfg->globals->len; ++i) {
9795 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9797 hash = mono_metadata_str_hash (name) % table_size;
9799 /* FIXME: Allocate from the mempool */
9800 new_entry = g_new0 (GlobalsTableEntry, 1);
9801 new_entry->value = i;
9803 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9804 if (entry == NULL) {
9805 new_entry->index = hash;
9806 g_ptr_array_index (table, hash) = new_entry;
9809 entry = entry->next;
9811 entry->next = new_entry;
9812 new_entry->index = table->len;
9813 g_ptr_array_add (table, new_entry);
9817 /* Emit the table */
9818 sprintf (symbol, ".Lglobals_hash");
9819 emit_section_change (acfg, RODATA_SECT, 0);
9820 emit_alignment (acfg, 8);
9821 emit_label (acfg, symbol);
9823 /* FIXME: Optimize memory usage */
9824 g_assert (table_size < 65000);
9825 emit_int16 (acfg, table_size);
9826 for (i = 0; i < table->len; ++i) {
9827 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9829 if (entry == NULL) {
9830 emit_int16 (acfg, 0);
9831 emit_int16 (acfg, 0);
9833 emit_int16 (acfg, entry->value + 1);
9835 emit_int16 (acfg, entry->next->index);
9837 emit_int16 (acfg, 0);
9841 /* Emit the names */
9842 for (i = 0; i < acfg->globals->len; ++i) {
9843 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9845 sprintf (symbol, "name_%d", i);
9846 emit_section_change (acfg, RODATA_SECT, 1);
9848 emit_alignment (acfg, 4);
9850 emit_label (acfg, symbol);
9851 emit_string (acfg, name);
9854 /* Emit the globals table */
9855 sprintf (symbol, "globals");
9856 emit_section_change (acfg, ".data", 0);
9857 /* This is not a global, since it is accessed by the init function */
9858 emit_alignment (acfg, 8);
9859 emit_info_symbol (acfg, symbol);
9861 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9862 emit_pointer (acfg, symbol);
9864 for (i = 0; i < acfg->globals->len; ++i) {
9865 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9867 sprintf (symbol, "name_%d", i);
9868 emit_pointer (acfg, symbol);
9870 g_assert (strlen (name) < sizeof (symbol));
9871 sprintf (symbol, "%s", name);
9872 emit_pointer (acfg, symbol);
9874 /* Null terminate the table */
9875 emit_int32 (acfg, 0);
9876 emit_int32 (acfg, 0);
9880 emit_mem_end (MonoAotCompile *acfg)
9884 if (acfg->aot_opts.llvm_only)
9887 sprintf (symbol, "mem_end");
9888 emit_section_change (acfg, ".text", 1);
9889 emit_alignment_code (acfg, 8);
9890 emit_label (acfg, symbol);
9894 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9898 info->version = MONO_AOT_FILE_VERSION;
9899 info->plt_got_offset_base = acfg->plt_got_offset_base;
9900 info->got_size = acfg->got_offset * sizeof (gpointer);
9901 info->plt_size = acfg->plt_offset;
9902 info->nmethods = acfg->nmethods;
9903 info->flags = acfg->flags;
9904 info->opts = acfg->opts;
9905 info->simd_opts = acfg->simd_opts;
9906 info->gc_name_index = acfg->gc_name_offset;
9907 info->datafile_size = acfg->datafile_offset;
9908 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9909 info->table_offsets [i] = acfg->table_offsets [i];
9910 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9911 info->num_trampolines [i] = acfg->num_trampolines [i];
9912 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9913 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9914 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9915 info->trampoline_size [i] = acfg->trampoline_size [i];
9916 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9918 info->double_align = MONO_ABI_ALIGNOF (double);
9919 info->long_align = MONO_ABI_ALIGNOF (gint64);
9920 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9921 info->tramp_page_size = acfg->tramp_page_size;
9922 info->nshared_got_entries = acfg->nshared_got_entries;
9923 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9924 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9926 memcpy(&info->aotid, acfg->image->aotid, 16);
9930 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9932 char symbol [MAX_SYMBOL_SIZE];
9934 const char **symbols;
9936 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9938 symbols [sindex ++] = acfg->got_symbol;
9940 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9941 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9943 symbols [sindex ++] = NULL;
9944 symbols [sindex ++] = NULL;
9946 /* llvm_get_method */
9947 symbols [sindex ++] = NULL;
9948 /* llvm_get_unbox_tramp */
9949 symbols [sindex ++] = NULL;
9950 if (!acfg->aot_opts.llvm_only) {
9951 symbols [sindex ++] = "jit_code_start";
9952 symbols [sindex ++] = "jit_code_end";
9953 symbols [sindex ++] = "method_addresses";
9955 symbols [sindex ++] = NULL;
9956 symbols [sindex ++] = NULL;
9957 symbols [sindex ++] = NULL;
9959 if (acfg->data_outfile) {
9960 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9961 symbols [sindex ++] = NULL;
9963 symbols [sindex ++] = "blob";
9964 symbols [sindex ++] = "class_name_table";
9965 symbols [sindex ++] = "class_info_offsets";
9966 symbols [sindex ++] = "method_info_offsets";
9967 symbols [sindex ++] = "ex_info_offsets";
9968 symbols [sindex ++] = "extra_method_info_offsets";
9969 symbols [sindex ++] = "extra_method_table";
9970 symbols [sindex ++] = "got_info_offsets";
9972 symbols [sindex ++] = "llvm_got_info_offsets";
9974 symbols [sindex ++] = NULL;
9975 symbols [sindex ++] = "image_table";
9977 symbols [sindex ++] = "mem_end";
9978 symbols [sindex ++] = "assembly_guid";
9979 symbols [sindex ++] = "runtime_version";
9980 if (acfg->num_trampoline_got_entries) {
9981 symbols [sindex ++] = "specific_trampolines";
9982 symbols [sindex ++] = "static_rgctx_trampolines";
9983 symbols [sindex ++] = "imt_trampolines";
9984 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9986 symbols [sindex ++] = NULL;
9987 symbols [sindex ++] = NULL;
9988 symbols [sindex ++] = NULL;
9989 symbols [sindex ++] = NULL;
9991 if (acfg->aot_opts.static_link) {
9992 symbols [sindex ++] = "globals";
9994 symbols [sindex ++] = NULL;
9996 symbols [sindex ++] = "assembly_name";
9997 symbols [sindex ++] = "plt";
9998 symbols [sindex ++] = "plt_end";
9999 symbols [sindex ++] = "unwind_info";
10000 if (!acfg->aot_opts.llvm_only) {
10001 symbols [sindex ++] = "unbox_trampolines";
10002 symbols [sindex ++] = "unbox_trampolines_end";
10003 symbols [sindex ++] = "unbox_trampoline_addresses";
10005 symbols [sindex ++] = NULL;
10006 symbols [sindex ++] = NULL;
10007 symbols [sindex ++] = NULL;
10010 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10012 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
10013 emit_section_change (acfg, ".data", 0);
10014 emit_alignment (acfg, 8);
10015 emit_label (acfg, symbol);
10016 if (!acfg->aot_opts.static_link)
10017 emit_global (acfg, symbol, FALSE);
10019 /* The data emitted here must match MonoAotFileInfo. */
10021 emit_int32 (acfg, info->version);
10022 emit_int32 (acfg, info->dummy);
10025 * We emit pointers to our data structures instead of emitting global symbols which
10026 * point to them, to reduce the number of globals, and because using globals leads to
10027 * various problems (i.e. arm/thumb).
10029 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10030 emit_pointer (acfg, symbols [i]);
10032 emit_int32 (acfg, info->plt_got_offset_base);
10033 emit_int32 (acfg, info->got_size);
10034 emit_int32 (acfg, info->plt_size);
10035 emit_int32 (acfg, info->nmethods);
10036 emit_int32 (acfg, info->flags);
10037 emit_int32 (acfg, info->opts);
10038 emit_int32 (acfg, info->simd_opts);
10039 emit_int32 (acfg, info->gc_name_index);
10040 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10041 emit_int32 (acfg, info->double_align);
10042 emit_int32 (acfg, info->long_align);
10043 emit_int32 (acfg, info->generic_tramp_num);
10044 emit_int32 (acfg, info->tramp_page_size);
10045 emit_int32 (acfg, info->nshared_got_entries);
10046 emit_int32 (acfg, info->datafile_size);
10048 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10049 emit_int32 (acfg, info->table_offsets [i]);
10050 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10051 emit_int32 (acfg, info->num_trampolines [i]);
10052 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10053 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10054 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10055 emit_int32 (acfg, info->trampoline_size [i]);
10056 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10057 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10059 emit_bytes (acfg, info->aotid, 16);
10061 if (acfg->aot_opts.static_link) {
10062 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10063 emit_alignment (acfg, sizeof (gpointer));
10064 emit_label (acfg, acfg->static_linking_symbol);
10065 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10070 * Emit a structure containing all the information not stored elsewhere.
10073 emit_file_info (MonoAotCompile *acfg)
10076 MonoAotFileInfo *info;
10078 if (acfg->aot_opts.bind_to_runtime_version) {
10079 build_info = mono_get_runtime_build_info ();
10080 emit_string_symbol (acfg, "runtime_version", build_info);
10081 g_free (build_info);
10083 emit_string_symbol (acfg, "runtime_version", "");
10086 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10088 /* Emit a string holding the assembly name */
10089 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10091 info = g_new0 (MonoAotFileInfo, 1);
10092 init_aot_file_info (acfg, info);
10094 if (acfg->aot_opts.static_link) {
10095 char symbol [MAX_SYMBOL_SIZE];
10099 * Emit a global symbol which can be passed by an embedding app to
10100 * mono_aot_register_module (). The symbol points to a pointer to the the file info
10103 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10105 /* Get rid of characters which cannot occur in symbols */
10107 for (p = symbol; *p; ++p) {
10108 if (!(isalnum (*p) || *p == '_'))
10111 acfg->static_linking_symbol = g_strdup (symbol);
10115 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10117 emit_aot_file_info (acfg, info);
10121 emit_blob (MonoAotCompile *acfg)
10123 acfg->blob_closed = TRUE;
10125 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10129 emit_objc_selectors (MonoAotCompile *acfg)
10134 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10139 * cat > foo.m << EOF
10142 * return @selector(print:);
10147 mono_img_writer_emit_unset_mode (acfg->w);
10148 g_assert (acfg->fp);
10149 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10150 fprintf (acfg->fp, ".align 3\n");
10151 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10152 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10153 emit_label (acfg, symbol);
10154 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10155 emit_pointer (acfg, symbol);
10158 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
10159 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10160 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10161 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10164 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10165 fprintf (acfg->fp, ".align 3\n");
10166 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10167 fprintf (acfg->fp, ".long 0\n");
10168 fprintf (acfg->fp, ".long 16\n");
10172 emit_dwarf_info (MonoAotCompile *acfg)
10174 #ifdef EMIT_DWARF_INFO
10176 char symbol2 [128];
10178 /* DIEs for methods */
10179 for (i = 0; i < acfg->nmethods; ++i) {
10180 MonoCompile *cfg = acfg->cfgs [i];
10185 // FIXME: LLVM doesn't define .Lme_...
10186 if (cfg->compile_llvm)
10189 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10191 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 ()));
10197 collect_methods (MonoAotCompile *acfg)
10200 MonoImage *image = acfg->image;
10202 /* Collect methods */
10203 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
10205 MonoMethod *method;
10206 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
10208 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10211 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
10212 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
10213 mono_error_cleanup (&error);
10217 /* Load all methods eagerly to skip the slower lazy loading code */
10218 mono_class_setup_methods (method->klass);
10220 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
10221 /* Compile the wrapper instead */
10222 /* We do this here instead of add_wrappers () because it is easy to do it here */
10223 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
10227 /* FIXME: Some mscorlib methods don't have debug info */
10229 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
10230 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
10231 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
10232 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10233 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
10234 if (!mono_debug_lookup_method (method)) {
10235 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
10242 if (method->is_generic || mono_class_is_gtd (method->klass))
10243 /* Compile the ref shared version instead */
10244 method = mini_get_shared_method (method);
10246 /* Since we add the normal methods first, their index will be equal to their zero based token index */
10247 add_method_with_index (acfg, method, i, FALSE);
10248 acfg->method_index ++;
10251 /* gsharedvt methods */
10252 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
10254 MonoMethod *method;
10255 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
10257 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
10260 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10261 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
10263 if (method->is_generic || mono_class_is_gtd (method->klass)) {
10264 MonoMethod *gshared;
10266 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
10267 add_extra_method (acfg, gshared);
10271 if (mono_aot_mode_is_full (&acfg->aot_opts))
10272 add_generic_instances (acfg);
10274 if (mono_aot_mode_is_full (&acfg->aot_opts))
10275 add_wrappers (acfg);
10280 compile_methods (MonoAotCompile *acfg)
10282 int i, methods_len;
10284 if (acfg->aot_opts.nthreads > 0) {
10287 GPtrArray *threads;
10288 MonoThreadHandle *thread_handle;
10289 gpointer *user_data;
10290 MonoMethod **methods;
10292 methods_len = acfg->methods->len;
10294 len = acfg->methods->len / acfg->aot_opts.nthreads;
10295 g_assert (len > 0);
10297 * Partition the list of methods into fragments, and hand it to threads to
10300 threads = g_ptr_array_new ();
10301 /* Make a copy since acfg->methods is modified by compile_method () */
10302 methods = g_new0 (MonoMethod*, methods_len);
10303 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
10304 for (i = 0; i < methods_len; ++i)
10305 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
10307 while (i < methods_len) {
10309 MonoInternalThread *thread;
10311 frag = g_ptr_array_new ();
10312 for (j = 0; j < len; ++j) {
10313 if (i < methods_len) {
10314 g_ptr_array_add (frag, methods [i]);
10319 user_data = g_new0 (gpointer, 3);
10320 user_data [0] = acfg;
10321 user_data [1] = frag;
10323 thread = mono_thread_create_internal (mono_domain_get (), compile_thread_main, (gpointer) user_data, MONO_THREAD_CREATE_FLAGS_NONE, &error);
10324 mono_error_assert_ok (&error);
10326 thread_handle = mono_threads_open_thread_handle (thread->handle);
10327 g_ptr_array_add (threads, thread_handle);
10331 for (i = 0; i < threads->len; ++i) {
10332 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
10333 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
10339 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
10340 for (i = methods_len; i < acfg->methods->len; ++i) {
10341 /* This can add new methods to acfg->methods */
10342 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
10347 compile_asm (MonoAotCompile *acfg)
10349 char *command, *objfile;
10350 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
10351 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
10352 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
10354 #ifdef TARGET_WIN32_MSVC
10355 #define AS_OPTIONS "-c -x assembler"
10356 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
10357 #define AS_OPTIONS "--64"
10358 #elif defined(TARGET_POWERPC64)
10359 #define AS_OPTIONS "-a64 -mppc64"
10360 #elif defined(sparc) && SIZEOF_VOID_P == 8
10361 #define AS_OPTIONS "-xarch=v9"
10362 #elif defined(TARGET_X86) && defined(TARGET_MACH)
10363 #define AS_OPTIONS "-arch i386"
10365 #define AS_OPTIONS ""
10368 #if defined(TARGET_OSX)
10369 #define AS_NAME "clang"
10370 #elif defined(TARGET_WIN32_MSVC)
10371 #define AS_NAME "clang.exe"
10373 #define AS_NAME "as"
10376 #ifdef TARGET_WIN32_MSVC
10377 #define AS_OBJECT_FILE_SUFFIX "obj"
10379 #define AS_OBJECT_FILE_SUFFIX "o"
10383 #define LD_NAME "ld"
10384 #define LD_OPTIONS "-shared -G"
10385 #elif defined(__ppc__) && defined(TARGET_MACH)
10386 #define LD_NAME "gcc"
10387 #define LD_OPTIONS "-dynamiclib"
10388 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
10389 #define LD_NAME "clang"
10390 #define LD_OPTIONS "--shared"
10391 #elif defined(TARGET_WIN32_MSVC)
10392 #define LD_NAME "link.exe"
10393 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO"
10394 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
10395 #define LD_NAME "gcc"
10396 #define LD_OPTIONS "-shared"
10397 #elif defined(TARGET_X86) && defined(TARGET_MACH)
10398 #define LD_NAME "clang"
10399 #define LD_OPTIONS "-m32 -dynamiclib"
10400 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
10401 #define LD_NAME "gcc"
10402 #define LD_OPTIONS "--shared"
10403 #elif defined(TARGET_POWERPC64)
10404 #define LD_OPTIONS "-m elf64ppc"
10408 #define LD_OPTIONS ""
10411 if (acfg->aot_opts.asm_only) {
10412 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
10413 if (acfg->aot_opts.static_link)
10414 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10416 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
10420 if (acfg->aot_opts.static_link) {
10421 if (acfg->aot_opts.outfile)
10422 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10424 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
10426 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
10430 g_string_append (acfg->as_args, "-c -x assembler");
10433 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10434 acfg->as_args ? acfg->as_args->str : "",
10435 wrap_path (objfile), wrap_path (acfg->tmpfname));
10436 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10437 if (execute_system (command) != 0) {
10443 if (acfg->llvm && !acfg->llvm_owriter) {
10444 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10445 acfg->as_args ? acfg->as_args->str : "",
10446 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
10447 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10448 if (execute_system (command) != 0) {
10457 if (acfg->aot_opts.static_link) {
10458 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10459 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10464 if (acfg->aot_opts.outfile)
10465 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10467 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10469 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10472 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10474 llvm_ofile = g_strdup ("");
10477 /* replace the ; flags separators with spaces */
10478 g_strdelimit (ld_flags, ";", ' ');
10480 if (acfg->aot_opts.llvm_only)
10481 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10483 #ifdef TARGET_WIN32_MSVC
10484 g_assert (tmp_outfile_name != NULL);
10485 g_assert (objfile != NULL);
10486 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME, LD_OPTIONS,
10487 ld_flags, tmp_outfile_name, objfile);
10488 #elif defined(LD_NAME)
10489 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10490 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10491 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10494 if (acfg->aot_opts.tool_prefix) {
10495 /* Cross compiling */
10496 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10497 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10498 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10500 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
10501 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10502 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10504 if (acfg->aot_opts.llvm_only) {
10505 command = g_strdup_printf ("clang++ %s", args);
10507 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
10512 aot_printf (acfg, "Executing the native linker: %s\n", command);
10513 if (execute_system (command) != 0) {
10514 g_free (tmp_outfile_name);
10515 g_free (outfile_name);
10524 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10525 printf ("Stripping the binary: %s\n", com);
10526 execute_system (com);
10529 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10531 * gas generates 'mapping symbols' each time code and data is mixed, which
10532 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10534 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10535 aot_printf (acfg, "Stripping the binary: %s\n", command);
10536 if (execute_system (command) != 0) {
10537 g_free (tmp_outfile_name);
10538 g_free (outfile_name);
10545 if (0 != rename (tmp_outfile_name, outfile_name)) {
10546 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10547 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10548 unlink (outfile_name);
10549 rename (tmp_outfile_name, outfile_name);
10553 #if defined(TARGET_MACH)
10554 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10555 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10556 if (execute_system (command) != 0) {
10561 if (!acfg->aot_opts.save_temps)
10564 g_free (tmp_outfile_name);
10565 g_free (outfile_name);
10568 if (acfg->aot_opts.save_temps)
10569 aot_printf (acfg, "Retained input file.\n");
10571 unlink (acfg->tmpfname);
10577 profread_byte (FILE *infile)
10582 res = fread (&i, 1, 1, infile);
10583 g_assert (res == 1);
10588 profread_int (FILE *infile)
10592 res = fread (&i, 4, 1, infile);
10593 g_assert (res == 1);
10598 profread_string (FILE *infile)
10604 len = profread_int (infile);
10605 if (len + 1 > 1024)
10606 pbuf = g_malloc (len + 1);
10609 res = fread (pbuf, 1, len, infile);
10610 g_assert (res == len);
10613 return g_strdup (buf);
10619 load_profile_file (MonoAotCompile *acfg, char *filename)
10623 int res, len, version;
10626 infile = fopen (filename, "r");
10628 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
10632 printf ("Using profile data file '%s'\n", filename);
10634 sprintf (magic, AOT_PROFILER_MAGIC);
10635 len = strlen (magic);
10636 res = fread (buf, 1, len, infile);
10637 magic [len] = '\0';
10639 if ((res != len) || strcmp (buf, magic) != 0) {
10640 printf ("Profile file has wrong header: '%s'.\n", buf);
10644 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
10645 version = profread_int (infile);
10646 if (version != expected_version) {
10647 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
10652 ProfileData *data = g_new0 (ProfileData, 1);
10653 data->images = g_hash_table_new (NULL, NULL);
10654 data->classes = g_hash_table_new (NULL, NULL);
10655 data->ginsts = g_hash_table_new (NULL, NULL);
10656 data->methods = g_hash_table_new (NULL, NULL);
10659 int type = profread_byte (infile);
10660 int id = profread_int (infile);
10662 if (type == AOTPROF_RECORD_NONE)
10666 case AOTPROF_RECORD_IMAGE: {
10667 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
10668 idata->name = profread_string (infile);
10669 char *mvid = profread_string (infile);
10671 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
10674 case AOTPROF_RECORD_GINST: {
10676 int len = profread_int (infile);
10678 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
10680 gdata->argv = g_new0 (ClassProfileData*, len);
10682 for (i = 0; i < len; ++i) {
10683 int class_id = profread_int (infile);
10685 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10686 g_assert (gdata->argv [i]);
10688 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
10691 case AOTPROF_RECORD_TYPE: {
10692 int type = profread_byte (infile);
10695 case MONO_TYPE_CLASS: {
10696 int image_id = profread_int (infile);
10697 int ginst_id = profread_int (infile);
10698 char *class_name = profread_string (infile);
10700 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
10703 char *p = strrchr (class_name, '.');
10707 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
10708 cdata->image = image;
10709 cdata->ns = g_strdup (class_name);
10710 cdata->name = g_strdup (p + 1);
10712 if (ginst_id != -1) {
10713 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10714 g_assert (cdata->inst);
10716 g_free (class_name);
10718 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
10722 case MONO_TYPE_SZARRAY: {
10723 int elem_id = profread_int (infile);
10729 g_assert_not_reached ();
10734 case AOTPROF_RECORD_METHOD: {
10735 int class_id = profread_int (infile);
10736 int ginst_id = profread_int (infile);
10737 int param_count = profread_int (infile);
10738 char *method_name = profread_string (infile);
10739 char *sig = profread_string (infile);
10741 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10744 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
10746 mdata->klass = klass;
10747 mdata->name = method_name;
10748 mdata->signature = sig;
10749 mdata->param_count = param_count;
10751 if (ginst_id != -1) {
10752 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10753 g_assert (mdata->inst);
10755 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
10759 printf ("%d\n", type);
10760 g_assert_not_reached ();
10766 acfg->profile_data = g_list_append (acfg->profile_data, data);
10770 resolve_class (ClassProfileData *cdata);
10773 resolve_ginst (GInstProfileData *inst_data)
10777 if (inst_data->inst)
10780 for (i = 0; i < inst_data->argc; ++i) {
10781 resolve_class (inst_data->argv [i]);
10782 if (!inst_data->argv [i]->klass)
10785 MonoType **args = g_new0 (MonoType*, inst_data->argc);
10786 for (i = 0; i < inst_data->argc; ++i)
10787 args [i] = &inst_data->argv [i]->klass->byval_arg;
10789 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
10793 resolve_class (ClassProfileData *cdata)
10798 if (!cdata->image->image)
10801 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, &error);
10803 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
10807 resolve_ginst (cdata->inst);
10808 if (!cdata->inst->inst)
10810 MonoGenericContext ctx;
10812 memset (&ctx, 0, sizeof (ctx));
10813 ctx.class_inst = cdata->inst->inst;
10814 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
10816 cdata->klass = klass;
10821 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
10824 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
10826 GHashTableIter iter;
10827 gpointer key, value;
10834 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
10835 g_hash_table_iter_init (&iter, data->images);
10836 while (g_hash_table_iter_next (&iter, &key, &value)) {
10837 ImageProfileData *idata = (ImageProfileData*)value;
10839 for (i = 0; i < assemblies->len; ++i) {
10840 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
10842 if (!strcmp (ass->aname.name, idata->name)) {
10843 idata->image = ass->image;
10848 g_ptr_array_free (assemblies, TRUE);
10851 g_hash_table_iter_init (&iter, data->classes);
10852 while (g_hash_table_iter_next (&iter, &key, &value)) {
10853 ClassProfileData *cdata = (ClassProfileData*)value;
10855 if (!cdata->image->image) {
10856 if (acfg->aot_opts.verbose)
10857 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
10861 resolve_class (cdata);
10864 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
10869 g_hash_table_iter_init (&iter, data->methods);
10870 while (g_hash_table_iter_next (&iter, &key, &value)) {
10871 MethodProfileData *mdata = (MethodProfileData*)value;
10876 resolve_class (mdata->klass);
10877 klass = mdata->klass->klass;
10879 if (acfg->aot_opts.verbose)
10880 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
10884 while ((m = mono_class_get_methods (klass, &miter))) {
10887 if (strcmp (m->name, mdata->name))
10889 MonoMethodSignature *sig = mono_method_signature (m);
10892 if (sig->param_count != mdata->param_count)
10895 resolve_ginst (mdata->inst);
10896 if (!mdata->inst->inst)
10898 MonoGenericContext ctx;
10900 memset (&ctx, 0, sizeof (ctx));
10901 ctx.method_inst = mdata->inst->inst;
10903 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
10906 sig = mono_method_signature_checked (m, &error);
10907 if (!is_ok (&error)) {
10908 mono_error_cleanup (&error);
10912 char *sig_str = mono_signature_full_name (sig);
10913 gboolean match = !strcmp (sig_str, mdata->signature);
10918 //printf ("%s\n", mono_method_full_name (m, 1));
10922 if (!mdata->method) {
10923 if (acfg->aot_opts.verbose)
10924 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
10930 inst_references_image (MonoGenericInst *inst, MonoImage *image)
10934 for (i = 0; i < inst->type_argc; ++i) {
10935 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10936 if (k->image == image)
10938 if (mono_class_is_ginst (k)) {
10939 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
10940 if (inst_references_image (kinst, image))
10948 is_local_inst (MonoGenericInst *inst, MonoImage *image)
10952 for (i = 0; i < inst->type_argc; ++i) {
10953 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10954 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
10961 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
10963 GHashTableIter iter;
10964 gpointer key, value;
10970 if (acfg->aot_opts.profile_only) {
10971 /* Add methods referenced by the profile */
10972 g_hash_table_iter_init (&iter, data->methods);
10973 while (g_hash_table_iter_next (&iter, &key, &value)) {
10974 MethodProfileData *mdata = (MethodProfileData*)value;
10975 MonoMethod *m = mdata->method;
10979 if (m->is_inflated)
10981 add_extra_method (acfg, m);
10982 g_hash_table_insert (acfg->profile_methods, m, m);
10988 * Add method instances 'related' to this assembly to the AOT image.
10990 g_hash_table_iter_init (&iter, data->methods);
10991 while (g_hash_table_iter_next (&iter, &key, &value)) {
10992 MethodProfileData *mdata = (MethodProfileData*)value;
10993 MonoMethod *m = mdata->method;
10994 MonoGenericContext *ctx;
10998 if (!m->is_inflated)
11001 ctx = mono_method_get_context (m);
11002 /* For simplicity, add instances which reference the assembly we are compiling */
11003 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
11004 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
11005 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11006 //printf ("%s\n", mono_method_full_name (m, TRUE));
11007 add_extra_method (acfg, m);
11009 } else if (m->klass->image == acfg->image &&
11010 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
11011 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
11012 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11013 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
11014 //printf ("%s\n", mono_method_full_name (m, TRUE));
11015 add_extra_method (acfg, m);
11019 * FIXME: We might skip some instances, for example:
11020 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
11021 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
11025 printf ("Added %d methods from profile.\n", count);
11029 init_got_info (GotInfo *info)
11033 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11034 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11035 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11036 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11037 info->got_patches = g_ptr_array_new ();
11040 static MonoAotCompile*
11041 acfg_create (MonoAssembly *ass, guint32 opts)
11043 MonoImage *image = ass->image;
11044 MonoAotCompile *acfg;
11046 acfg = g_new0 (MonoAotCompile, 1);
11047 acfg->methods = g_ptr_array_new ();
11048 acfg->method_indexes = g_hash_table_new (NULL, NULL);
11049 acfg->method_depth = g_hash_table_new (NULL, NULL);
11050 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
11051 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11052 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
11053 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
11054 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
11055 acfg->image_hash = g_hash_table_new (NULL, NULL);
11056 acfg->image_table = g_ptr_array_new ();
11057 acfg->globals = g_ptr_array_new ();
11058 acfg->image = image;
11060 /* TODO: Write out set of SIMD instructions used, rather than just those available */
11061 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
11062 acfg->mempool = mono_mempool_new ();
11063 acfg->extra_methods = g_ptr_array_new ();
11064 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
11065 acfg->unwind_ops = g_ptr_array_new ();
11066 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
11067 acfg->method_order = g_ptr_array_new ();
11068 acfg->export_names = g_hash_table_new (NULL, NULL);
11069 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
11070 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
11071 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
11072 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11073 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11074 acfg->profile_methods = g_hash_table_new (NULL, NULL);
11075 mono_os_mutex_init_recursive (&acfg->mutex);
11077 init_got_info (&acfg->got_info);
11078 init_got_info (&acfg->llvm_got_info);
11084 got_info_free (GotInfo *info)
11088 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11089 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
11090 g_free (info->patch_to_got_offset_by_type);
11091 g_hash_table_destroy (info->patch_to_got_offset);
11092 g_ptr_array_free (info->got_patches, TRUE);
11096 acfg_free (MonoAotCompile *acfg)
11100 mono_img_writer_destroy (acfg->w);
11101 for (i = 0; i < acfg->nmethods; ++i)
11102 if (acfg->cfgs [i])
11103 mono_destroy_compile (acfg->cfgs [i]);
11105 g_free (acfg->cfgs);
11107 g_free (acfg->static_linking_symbol);
11108 g_free (acfg->got_symbol);
11109 g_free (acfg->plt_symbol);
11110 g_ptr_array_free (acfg->methods, TRUE);
11111 g_ptr_array_free (acfg->image_table, TRUE);
11112 g_ptr_array_free (acfg->globals, TRUE);
11113 g_ptr_array_free (acfg->unwind_ops, TRUE);
11114 g_hash_table_destroy (acfg->method_indexes);
11115 g_hash_table_destroy (acfg->method_depth);
11116 g_hash_table_destroy (acfg->plt_offset_to_entry);
11117 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
11118 if (acfg->patch_to_plt_entry [i])
11119 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
11121 g_free (acfg->patch_to_plt_entry);
11122 g_hash_table_destroy (acfg->method_to_cfg);
11123 g_hash_table_destroy (acfg->token_info_hash);
11124 g_hash_table_destroy (acfg->method_to_pinvoke_import);
11125 g_hash_table_destroy (acfg->image_hash);
11126 g_hash_table_destroy (acfg->unwind_info_offsets);
11127 g_hash_table_destroy (acfg->method_label_hash);
11128 if (acfg->typespec_classes)
11129 g_hash_table_destroy (acfg->typespec_classes);
11130 g_hash_table_destroy (acfg->export_names);
11131 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
11132 g_hash_table_destroy (acfg->klass_blob_hash);
11133 g_hash_table_destroy (acfg->method_blob_hash);
11134 got_info_free (&acfg->got_info);
11135 got_info_free (&acfg->llvm_got_info);
11136 mono_mempool_destroy (acfg->mempool);
11140 #define WRAPPER(e,n) n,
11141 static const char* const
11142 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
11143 #include "mono/metadata/wrapper-types.h"
11147 static G_GNUC_UNUSED const char*
11148 get_wrapper_type_name (int type)
11150 return wrapper_type_names [type];
11156 static void aot_dump (MonoAotCompile *acfg)
11162 mono_json_writer_init (&writer);
11164 mono_json_writer_object_begin(&writer);
11167 mono_json_writer_indent (&writer);
11168 mono_json_writer_object_key(&writer, "methods");
11169 mono_json_writer_array_begin (&writer);
11172 for (i = 0; i < acfg->nmethods; ++i) {
11174 MonoMethod *method;
11177 cfg = acfg->cfgs [i];
11181 method = cfg->orig_method;
11183 mono_json_writer_indent (&writer);
11184 mono_json_writer_object_begin(&writer);
11186 mono_json_writer_indent (&writer);
11187 mono_json_writer_object_key(&writer, "name");
11188 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
11190 mono_json_writer_indent (&writer);
11191 mono_json_writer_object_key(&writer, "signature");
11192 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
11194 mono_json_writer_indent (&writer);
11195 mono_json_writer_object_key(&writer, "code_size");
11196 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
11198 klass = method->klass;
11200 mono_json_writer_indent (&writer);
11201 mono_json_writer_object_key(&writer, "class");
11202 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
11204 mono_json_writer_indent (&writer);
11205 mono_json_writer_object_key(&writer, "namespace");
11206 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
11208 mono_json_writer_indent (&writer);
11209 mono_json_writer_object_key(&writer, "wrapper_type");
11210 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
11212 mono_json_writer_indent_pop (&writer);
11213 mono_json_writer_indent (&writer);
11214 mono_json_writer_object_end (&writer);
11215 mono_json_writer_printf (&writer, ",\n");
11218 mono_json_writer_indent_pop (&writer);
11219 mono_json_writer_indent (&writer);
11220 mono_json_writer_array_end (&writer);
11221 mono_json_writer_printf (&writer, ",\n");
11225 mono_json_writer_indent_push (&writer);
11226 mono_json_writer_indent (&writer);
11227 mono_json_writer_object_key(&writer, "plt");
11228 mono_json_writer_array_begin (&writer);
11230 for (i = 0; i < acfg->plt_offset; ++i) {
11231 MonoPltEntry *plt_entry = NULL;
11236 * The first plt entry is unused.
11240 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
11241 ji = plt_entry->ji;
11243 mono_json_writer_indent (&writer);
11244 mono_json_writer_printf (&writer, "{ ");
11245 mono_json_writer_object_key(&writer, "symbol");
11246 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
11249 mono_json_writer_indent_pop (&writer);
11250 mono_json_writer_indent (&writer);
11251 mono_json_writer_array_end (&writer);
11252 mono_json_writer_printf (&writer, ",\n");
11257 mono_json_writer_indent_push (&writer);
11258 mono_json_writer_indent (&writer);
11259 mono_json_writer_object_key(&writer, "got");
11260 mono_json_writer_array_begin (&writer);
11262 mono_json_writer_indent_push (&writer);
11263 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
11264 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
11266 mono_json_writer_indent (&writer);
11267 mono_json_writer_printf (&writer, "{ ");
11268 mono_json_writer_object_key(&writer, "patch_name");
11269 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
11272 mono_json_writer_indent_pop (&writer);
11273 mono_json_writer_indent (&writer);
11274 mono_json_writer_array_end (&writer);
11275 mono_json_writer_printf (&writer, ",\n");
11278 mono_json_writer_indent_pop (&writer);
11279 mono_json_writer_indent (&writer);
11280 mono_json_writer_object_end (&writer);
11282 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
11283 dumpfile = fopen (dumpname, "w+");
11286 fprintf (dumpfile, "%s", writer.text->str);
11289 mono_json_writer_destroy (&writer);
11292 static const char *preinited_jit_icalls[] = {
11293 "mono_aot_init_llvm_method",
11294 "mono_aot_init_gshared_method_this",
11295 "mono_aot_init_gshared_method_mrgctx",
11296 "mono_aot_init_gshared_method_vtable",
11297 "mono_llvm_throw_corlib_exception",
11298 "mono_init_vtable_slot",
11299 "mono_helper_ldstr_mscorlib"
11303 add_preinit_got_slots (MonoAotCompile *acfg)
11309 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
11310 * during method initialization etc.
11313 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11314 ji->type = MONO_PATCH_INFO_IMAGE;
11315 ji->data.image = acfg->image;
11316 get_got_offset (acfg, FALSE, ji);
11317 get_got_offset (acfg, TRUE, ji);
11319 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11320 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
11321 get_got_offset (acfg, FALSE, ji);
11322 get_got_offset (acfg, TRUE, ji);
11324 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11325 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
11326 get_got_offset (acfg, FALSE, ji);
11327 get_got_offset (acfg, TRUE, ji);
11329 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11330 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
11331 get_got_offset (acfg, FALSE, ji);
11332 get_got_offset (acfg, TRUE, ji);
11334 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11335 ji->type = MONO_PATCH_INFO_AOT_MODULE;
11336 get_got_offset (acfg, FALSE, ji);
11337 get_got_offset (acfg, TRUE, ji);
11339 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11340 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
11341 get_got_offset (acfg, FALSE, ji);
11342 get_got_offset (acfg, TRUE, ji);
11344 for (i = 0; i < TLS_KEY_NUM; i++) {
11345 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11346 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
11347 ji->data.index = i;
11348 get_got_offset (acfg, FALSE, ji);
11349 get_got_offset (acfg, TRUE, ji);
11351 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11352 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
11353 ji->data.index = i;
11354 get_got_offset (acfg, FALSE, ji);
11355 get_got_offset (acfg, TRUE, ji);
11358 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11359 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
11360 get_got_offset (acfg, FALSE, ji);
11361 get_got_offset (acfg, TRUE, ji);
11363 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
11364 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
11365 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11366 ji->data.name = preinited_jit_icalls [i];
11367 get_got_offset (acfg, FALSE, ji);
11368 get_got_offset (acfg, TRUE, ji);
11371 acfg->nshared_got_entries = acfg->got_offset;
11375 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11377 MonoImage *image = ass->image;
11380 MonoAotCompile *acfg;
11381 char *outfile_name, *tmp_outfile_name, *p;
11382 char llvm_stats_msg [256];
11386 acfg = acfg_create (ass, opts);
11388 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
11389 acfg->aot_opts.write_symbols = TRUE;
11390 acfg->aot_opts.ntrampolines = 4096;
11391 acfg->aot_opts.nrgctx_trampolines = 4096;
11392 acfg->aot_opts.nimt_trampolines = 512;
11393 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
11394 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
11395 acfg->aot_opts.llvm_path = g_strdup ("");
11396 acfg->aot_opts.temp_path = g_strdup ("");
11398 acfg->aot_opts.use_trampolines_page = TRUE;
11401 mono_aot_parse_options (aot_options, &acfg->aot_opts);
11403 if (acfg->aot_opts.logfile) {
11404 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
11407 if (acfg->aot_opts.data_outfile) {
11408 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
11409 if (!acfg->data_outfile) {
11410 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
11413 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
11416 //acfg->aot_opts.print_skipped_methods = TRUE;
11418 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
11419 if (acfg->opts & MONO_OPT_GSHAREDVT) {
11420 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
11423 if (acfg->aot_opts.llvm_only) {
11424 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
11428 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11429 acfg->opts |= MONO_OPT_GSHAREDVT;
11432 #if !defined(ENABLE_LLVM)
11433 if (acfg->aot_opts.llvm_only) {
11434 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
11439 if (acfg->opts & MONO_OPT_GSHAREDVT)
11440 mono_set_generic_sharing_vt_supported (TRUE);
11442 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
11444 generate_aotid ((guint8*) &acfg->image->aotid);
11446 char *aotid = mono_guid_to_string (acfg->image->aotid);
11447 aot_printf (acfg, "AOTID %s\n", aotid);
11450 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
11451 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11452 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
11457 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
11458 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
11462 if (acfg->aot_opts.static_link)
11463 acfg->aot_opts.asm_writer = TRUE;
11465 if (acfg->aot_opts.soft_debug) {
11466 MonoDebugOptions *opt = mini_get_debug_options ();
11468 opt->mdb_optimizations = TRUE;
11469 opt->gen_sdb_seq_points = TRUE;
11471 if (!mono_debug_enabled ()) {
11472 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
11475 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
11478 if (mono_use_llvm || acfg->aot_opts.llvm) {
11480 acfg->aot_opts.asm_writer = TRUE;
11481 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
11483 if (acfg->aot_opts.soft_debug) {
11484 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
11490 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
11491 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
11496 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11497 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
11498 acfg->is_full_aot = TRUE;
11501 if (mono_threads_is_coop_enabled ())
11502 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
11504 if (acfg->aot_opts.instances_logfile_path) {
11505 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
11506 if (!acfg->instances_logfile) {
11507 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
11512 if (acfg->aot_opts.profile_files) {
11515 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
11516 load_profile_file (acfg, (char*)l->data);
11523 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
11524 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
11528 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
11529 #ifdef MONO_ARCH_GSHARED_SUPPORTED
11530 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
11532 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
11533 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
11534 if (acfg->opts & MONO_OPT_GSHAREDVT)
11535 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
11538 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
11542 if (mono_use_llvm || acfg->aot_opts.llvm) {
11545 * Emit all LLVM code into a separate assembly/object file and link with it
11548 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
11549 acfg->llvm_owriter = TRUE;
11550 } else if (acfg->aot_opts.llvm_outfile) {
11551 int len = strlen (acfg->aot_opts.llvm_outfile);
11553 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
11554 acfg->llvm_owriter = TRUE;
11558 if (acfg->llvm && acfg->thumb_mixed)
11559 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
11560 if (acfg->aot_opts.llvm_only)
11561 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
11563 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
11564 /* Get rid of characters which cannot occur in symbols */
11565 for (p = acfg->assembly_name_sym; *p; ++p) {
11566 if (!(isalnum (*p) || *p == '_'))
11570 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
11571 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
11572 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
11574 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
11575 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
11578 acfg->method_index = 1;
11580 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11581 mono_set_partial_sharing_supported (TRUE);
11583 res = collect_methods (acfg);
11590 for (l = acfg->profile_data; l; l = l->next)
11591 resolve_profile_data (acfg, (ProfileData*)l->data);
11592 for (l = acfg->profile_data; l; l = l->next)
11593 add_profile_instances (acfg, (ProfileData*)l->data);
11596 acfg->cfgs_size = acfg->methods->len + 32;
11597 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
11599 /* PLT offset 0 is reserved for the PLT trampoline */
11600 acfg->plt_offset = 1;
11601 add_preinit_got_slots (acfg);
11606 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
11612 compile_methods (acfg);
11616 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
11622 if (acfg->aot_opts.asm_only) {
11623 if (acfg->aot_opts.outfile) {
11624 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11625 acfg->tmpbasename = g_strdup (acfg->tmpfname);
11627 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
11628 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11630 g_assert (acfg->aot_opts.llvm_outfile);
11631 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11632 if (acfg->llvm_owriter)
11633 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
11635 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11637 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
11638 g_strdup_printf ("%s", "temp") :
11639 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
11641 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11642 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
11643 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
11648 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
11649 if (acfg->aot_opts.outfile)
11650 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11652 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
11653 acfg->fp = fopen (acfg->tmpfname, "w+");
11655 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
11656 acfg->fp = fdopen (i, "w+");
11658 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
11659 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
11663 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
11665 tmp_outfile_name = NULL;
11666 outfile_name = NULL;
11668 /* Compute symbols for methods */
11669 for (i = 0; i < acfg->nmethods; ++i) {
11670 if (acfg->cfgs [i]) {
11671 MonoCompile *cfg = acfg->cfgs [i];
11672 int method_index = get_method_index (acfg, cfg->orig_method);
11674 if (COMPILE_LLVM (cfg))
11675 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
11676 else if (acfg->global_symbols || acfg->llvm)
11677 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
11679 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
11680 cfg->asm_debug_symbol = cfg->asm_symbol;
11684 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
11686 * CLANG supports GAS .file/.loc directives, so emit line number information this way
11688 acfg->gas_line_numbers = TRUE;
11691 #ifdef EMIT_DWARF_INFO
11692 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
11693 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
11694 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
11697 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
11699 #endif /* EMIT_DWARF_INFO */
11702 mono_img_writer_emit_start (acfg->w);
11705 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
11711 emit_extra_methods (acfg);
11713 emit_trampolines (acfg);
11715 emit_class_name_table (acfg);
11717 emit_got_info (acfg, FALSE);
11719 emit_got_info (acfg, TRUE);
11721 emit_exception_info (acfg);
11723 emit_unwind_info (acfg);
11725 emit_class_info (acfg);
11729 emit_image_table (acfg);
11735 * The managed allocators are GC specific, so can't use an AOT image created by one GC
11738 const char *gc_name = mono_gc_get_gc_name ();
11739 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
11744 emit_objc_selectors (acfg);
11746 emit_globals (acfg);
11748 emit_file_info (acfg);
11750 emit_library_info (acfg);
11753 emit_dwarf_info (acfg);
11754 mono_dwarf_writer_close (acfg->dwarf);
11757 emit_mem_end (acfg);
11759 if (acfg->need_pt_gnu_stack) {
11760 /* This is required so the .so doesn't have an executable stack */
11761 /* The bin writer already emits this */
11762 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
11765 if (acfg->aot_opts.data_outfile)
11766 fclose (acfg->data_outfile);
11772 res = emit_llvm_file (acfg);
11780 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
11783 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
11785 strcpy (llvm_stats_msg, "");
11787 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;
11789 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",
11790 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
11791 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
11792 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
11793 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
11794 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
11795 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,
11796 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
11797 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
11798 (int)(acfg->got_offset * sizeof (gpointer)));
11799 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
11800 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
11802 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
11803 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
11804 if (acfg->stats.genericcount)
11805 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
11806 if (acfg->stats.abscount)
11807 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
11808 if (acfg->stats.lmfcount)
11809 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
11810 if (acfg->stats.ocount)
11811 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
11815 res = mono_img_writer_emit_writeout (acfg->w);
11820 res = compile_asm (acfg);
11827 acfg->stats.link_time = TV_ELAPSED (atv, btv);
11829 if (acfg->aot_opts.stats) {
11832 aot_printf (acfg, "GOT slot distribution:\n");
11833 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11834 if (acfg->stats.got_slot_types [i])
11835 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]);
11836 aot_printf (acfg, "\nMethod stats:\n");
11837 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
11838 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
11839 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
11840 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
11843 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);
11845 if (acfg->aot_opts.dump_json)
11858 mono_aot_readonly_field_override (MonoClassField *field)
11864 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11870 mono_aot_is_shared_got_offset (int offset)