[runtime] Convert more icalls to use handles. (#15862)
[mono-project.git] / mono / mini / aot-compiler.c
blobaaba8b08d8c3c865dd8338f5300bd5f92d06cbf8
1 /**
2 * \file
3 * mono Ahead of Time compiler
5 * Author:
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.
16 #include "config.h"
17 #include <sys/types.h>
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #ifdef HAVE_STDINT_H
22 #include <stdint.h>
23 #endif
24 #include <fcntl.h>
25 #include <ctype.h>
26 #include <string.h>
27 #ifndef HOST_WIN32
28 #include <sys/time.h>
29 #else
30 #include <winsock2.h>
31 #include <windows.h>
32 #endif
34 #include <errno.h>
35 #include <sys/stat.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/metadata/custom-attrs-internals.h>
53 #include <mono/utils/mono-logger-internals.h>
54 #include <mono/utils/mono-compiler.h>
55 #include <mono/utils/mono-time.h>
56 #include <mono/utils/mono-mmap.h>
57 #include <mono/utils/mono-rand.h>
58 #include <mono/utils/json.h>
59 #include <mono/utils/mono-threads-coop.h>
60 #include <mono/profiler/aot.h>
61 #include <mono/utils/w32api.h>
63 #include "aot-compiler.h"
64 #include "aot-runtime.h"
65 #include "seq-points.h"
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
68 #include "mini-gc.h"
69 #include "mini-llvm.h"
70 #include "mini-runtime.h"
72 static MonoMethod*
73 try_get_method_nofail (MonoClass *klass, const char *method_name, int param_count, int flags)
75 MonoMethod *result;
76 ERROR_DECL (error);
77 result = mono_class_get_method_from_name_checked (klass, method_name, param_count, flags, error);
78 mono_error_assert_ok (error);
79 return result;
82 static MonoMethod*
83 get_method_nofail (MonoClass *klass, const char *method_name, int param_count, int flags)
85 MonoMethod *result = try_get_method_nofail (klass, method_name, param_count, flags);
86 g_assertf (result, "Expected to find method %s in klass %s", method_name, m_class_get_name (klass));
87 return result;
90 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
92 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
93 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
94 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
95 #define TARGET_X86_64_WIN32_MSVC
96 #endif
98 #if defined(TARGET_X86_64_WIN32_MSVC)
99 #define TARGET_WIN32_MSVC
100 #endif
102 // Emit native unwind info on Windows platforms (different from DWARF). Emitted unwind info
103 // works when using the MSVC toolchain using Clang for MSVC codegen and linker. Only supported when
104 // compiling for AMD64 (Windows x64 platforms).
105 #if defined(TARGET_WIN32_MSVC) && defined(MONO_ARCH_HAVE_UNWIND_TABLE)
106 #define EMIT_WIN32_UNWIND_INFO
107 #endif
109 #if defined(__linux__)
110 #define RODATA_SECT ".rodata"
111 #elif defined(TARGET_MACH)
112 #define RODATA_SECT ".section __TEXT, __const"
113 #elif defined(TARGET_WIN32_MSVC)
114 #define RODATA_SECT ".rdata"
115 #else
116 #define RODATA_SECT ".text"
117 #endif
119 #define TV_DECLARE(name) gint64 name
120 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
121 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
123 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
125 typedef struct {
126 char *name;
127 MonoImage *image;
128 } ImageProfileData;
130 typedef struct ClassProfileData ClassProfileData;
132 typedef struct {
133 int argc;
134 ClassProfileData **argv;
135 MonoGenericInst *inst;
136 } GInstProfileData;
138 struct ClassProfileData {
139 ImageProfileData *image;
140 char *ns, *name;
141 GInstProfileData *inst;
142 MonoClass *klass;
145 typedef struct {
146 ClassProfileData *klass;
147 int id;
148 char *name;
149 int param_count;
150 char *signature;
151 GInstProfileData *inst;
152 MonoMethod *method;
153 } MethodProfileData;
155 typedef struct {
156 GHashTable *images, *classes, *ginsts, *methods;
157 } ProfileData;
159 /* predefined values for static readonly fields without needed to run the .cctor */
160 typedef struct _ReadOnlyValue ReadOnlyValue;
161 struct _ReadOnlyValue {
162 ReadOnlyValue *next;
163 char *name;
164 int type; /* to be used later for typechecking to prevent user errors */
165 union {
166 guint8 i1;
167 guint16 i2;
168 guint32 i4;
169 guint64 i8;
170 gpointer ptr;
171 } value;
173 static ReadOnlyValue *readonly_values;
175 typedef struct MonoAotOptions {
176 char *outfile;
177 char *llvm_outfile;
178 char *data_outfile;
179 GList *profile_files;
180 gboolean save_temps;
181 gboolean write_symbols;
182 gboolean metadata_only;
183 gboolean bind_to_runtime_version;
184 MonoAotMode mode;
185 gboolean interp;
186 gboolean no_dlsym;
187 gboolean static_link;
188 gboolean asm_only;
189 gboolean asm_writer;
190 gboolean nodebug;
191 gboolean dwarf_debug;
192 gboolean soft_debug;
193 gboolean log_generics;
194 gboolean log_instances;
195 gboolean gen_msym_dir;
196 char *gen_msym_dir_path;
197 gboolean direct_pinvoke;
198 gboolean direct_icalls;
199 gboolean no_direct_calls;
200 gboolean use_trampolines_page;
201 gboolean no_instances;
202 // We are collecting inflated methods and emitting non-inflated
203 gboolean dedup;
204 // The name of the assembly for which the AOT module is going to have all deduped methods moved to.
205 // When set, we are emitting inflated methods only
206 char *dedup_include;
207 gboolean gnu_asm;
208 gboolean try_llvm;
209 gboolean llvm;
210 gboolean llvm_only;
211 gboolean llvm_disable_self_init;
212 int nthreads;
213 int ntrampolines;
214 int nrgctx_trampolines;
215 int nimt_trampolines;
216 int ngsharedvt_arg_trampolines;
217 int nftnptr_arg_trampolines;
218 int nrgctx_fetch_trampolines;
219 int nunbox_arbitrary_trampolines;
220 gboolean print_skipped_methods;
221 gboolean stats;
222 gboolean verbose;
223 gboolean deterministic;
224 char *tool_prefix;
225 char *ld_flags;
226 char *mtriple;
227 char *llvm_path;
228 char *temp_path;
229 char *instances_logfile_path;
230 char *logfile;
231 char *llvm_opts;
232 char *llvm_llc;
233 gboolean dump_json;
234 gboolean profile_only;
235 gboolean no_opt;
236 char *clangxx;
237 char *depfile;
238 } MonoAotOptions;
240 typedef enum {
241 METHOD_CAT_NORMAL,
242 METHOD_CAT_GSHAREDVT,
243 METHOD_CAT_INST,
244 METHOD_CAT_WRAPPER,
245 METHOD_CAT_NUM
246 } MethodCategory;
248 typedef struct MonoAotStats {
249 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
250 gint64 code_size, method_info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size, blob_size;
251 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
252 int got_slots, offsets_size;
253 int method_categories [METHOD_CAT_NUM];
254 int got_slot_types [MONO_PATCH_INFO_NUM];
255 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
256 int jit_time, gen_time, link_time;
257 int method_ref_count, method_ref_size;
258 int class_ref_count, class_ref_size;
259 int ginst_count, ginst_size;
260 } MonoAotStats;
262 typedef struct GotInfo {
263 GHashTable *patch_to_got_offset;
264 GHashTable **patch_to_got_offset_by_type;
265 GPtrArray *got_patches;
266 } GotInfo;
268 #ifdef EMIT_WIN32_UNWIND_INFO
269 typedef struct _UnwindInfoSectionCacheItem {
270 char *xdata_section_label;
271 PUNWIND_INFO unwind_info;
272 gboolean xdata_section_emitted;
273 } UnwindInfoSectionCacheItem;
274 #endif
276 typedef struct MonoAotCompile {
277 MonoImage *image;
278 GPtrArray *methods;
279 GHashTable *method_indexes;
280 GHashTable *method_depth;
281 MonoCompile **cfgs;
282 int cfgs_size;
283 GHashTable **patch_to_plt_entry;
284 GHashTable *plt_offset_to_entry;
285 //GHashTable *patch_to_got_offset;
286 //GHashTable **patch_to_got_offset_by_type;
287 //GPtrArray *got_patches;
288 GotInfo got_info, llvm_got_info;
289 GHashTable *image_hash;
290 GHashTable *method_to_cfg;
291 GHashTable *token_info_hash;
292 GHashTable *method_to_pinvoke_import;
293 GHashTable *method_to_external_icall_symbol_name;
294 GPtrArray *extra_methods;
295 GPtrArray *image_table;
296 GPtrArray *globals;
297 GPtrArray *method_order;
298 GHashTable *dedup_stats;
299 GHashTable *dedup_cache;
300 gboolean dedup_cache_changed;
301 GHashTable *export_names;
302 /* Maps MonoClass* -> blob offset */
303 GHashTable *klass_blob_hash;
304 /* Maps MonoMethod* -> blob offset */
305 GHashTable *method_blob_hash;
306 /* Maps MonoGenericInst* -> blob offset */
307 GHashTable *ginst_blob_hash;
308 GHashTable *gsharedvt_in_signatures;
309 GHashTable *gsharedvt_out_signatures;
310 guint32 *plt_got_info_offsets;
311 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
312 /* Number of GOT entries reserved for trampolines */
313 guint32 num_trampoline_got_entries;
314 guint32 tramp_page_size;
316 guint32 table_offsets [MONO_AOT_TABLE_NUM];
317 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
318 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
319 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
320 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
322 MonoAotOptions aot_opts;
323 guint32 nmethods;
324 guint32 nextra_methods;
325 guint32 opts;
326 guint32 simd_opts;
327 MonoMemPool *mempool;
328 MonoAotStats stats;
329 int method_index;
330 char *static_linking_symbol;
331 mono_mutex_t mutex;
332 gboolean gas_line_numbers;
333 /* Whenever to emit an object file directly from llc */
334 gboolean llvm_owriter;
335 gboolean llvm_owriter_supported;
336 MonoImageWriter *w;
337 MonoDwarfWriter *dwarf;
338 FILE *fp;
339 char *tmpbasename;
340 char *tmpfname;
341 char *temp_dir_to_delete;
342 char *llvm_sfile;
343 char *llvm_ofile;
344 GSList *cie_program;
345 GHashTable *unwind_info_offsets;
346 GPtrArray *unwind_ops;
347 guint32 unwind_info_offset;
348 char *global_prefix;
349 char *got_symbol;
350 char *llvm_got_symbol;
351 char *plt_symbol;
352 char *llvm_eh_frame_symbol;
353 GHashTable *method_label_hash;
354 const char *temp_prefix;
355 const char *user_symbol_prefix;
356 const char *llvm_label_prefix;
357 const char *inst_directive;
358 int align_pad_value;
359 guint32 label_generator;
360 gboolean llvm;
361 gboolean has_jitted_code;
362 gboolean is_full_aot;
363 gboolean dedup_collect_only;
364 MonoAotFileFlags flags;
365 MonoDynamicStream blob;
366 gboolean blob_closed;
367 GHashTable *typespec_classes;
368 GString *llc_args;
369 GString *as_args;
370 char *assembly_name_sym;
371 GHashTable *plt_entry_debug_sym_cache;
372 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
373 GHashTable *ginst_hash;
374 GHashTable *dwarf_ln_filenames;
375 gboolean global_symbols;
376 int objc_selector_index, objc_selector_index_2;
377 GPtrArray *objc_selectors;
378 GHashTable *objc_selector_to_index;
379 GList *profile_data;
380 GHashTable *profile_methods;
381 #ifdef EMIT_WIN32_UNWIND_INFO
382 GList *unwind_info_section_cache;
383 #endif
384 FILE *logfile;
385 FILE *instances_logfile;
386 FILE *data_outfile;
387 int datafile_offset;
388 int gc_name_offset;
389 // In this mode, we are emitting dedupable methods that we encounter
390 gboolean dedup_emit_mode;
391 } MonoAotCompile;
393 typedef struct {
394 int plt_offset;
395 char *symbol, *llvm_symbol, *debug_sym;
396 MonoJumpInfo *ji;
397 gboolean jit_used, llvm_used;
398 } MonoPltEntry;
400 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
401 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
403 /* This points to the current acfg in LLVM mode */
404 static MonoAotCompile *llvm_acfg;
406 /* Cache of decoded method external icall symbol names. */
407 /* Owned by acfg, but kept in this static as well since it is */
408 /* accessed by code paths not having access to acfg. */
409 static GHashTable *method_to_external_icall_symbol_name;
411 // This, instead of an array of pointers, to optimize away a pointer and a relocation per string.
412 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
413 #define MSGSTRFIELD1(line) str##line
414 static const struct msgstr_t {
415 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
416 #include "patch-info.h"
417 #undef PATCH_INFO
418 } opstr = {
419 #define PATCH_INFO(a,b) b,
420 #include "patch-info.h"
421 #undef PATCH_INFO
423 static const gint16 opidx [] = {
424 #define PATCH_INFO(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
425 #include "patch-info.h"
426 #undef PATCH_INFO
429 static G_GNUC_UNUSED const char*
430 get_patch_name (int info)
432 return (const char*)&opstr + opidx [info];
435 static int
436 emit_aot_image (MonoAotCompile *acfg);
438 static void
439 mono_flush_method_cache (MonoAotCompile *acfg);
441 static void
442 mono_read_method_cache (MonoAotCompile *acfg);
444 static guint32
445 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
447 static char*
448 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
450 static void
451 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in);
453 static void
454 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
456 static inline gboolean
457 ignore_cfg (MonoCompile *cfg)
459 return !cfg || cfg->skip;
462 static void
463 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
465 FILE *output;
466 va_list args;
468 if (acfg->logfile)
469 output = acfg->logfile;
470 else
471 output = stdout;
473 va_start (args, format);
474 vfprintf (output, format, args);
475 va_end (args);
478 static void
479 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
481 FILE *output;
482 va_list args;
484 if (acfg->logfile)
485 output = acfg->logfile;
486 else
487 output = stderr;
489 va_start (args, format);
490 vfprintf (output, format, args);
491 va_end (args);
494 static void
495 report_loader_error (MonoAotCompile *acfg, MonoError *error, gboolean fatal, const char *format, ...)
497 FILE *output;
498 va_list args;
500 if (mono_error_ok (error))
501 return;
503 if (acfg->logfile)
504 output = acfg->logfile;
505 else
506 output = stderr;
508 va_start (args, format);
509 vfprintf (output, format, args);
510 va_end (args);
511 mono_error_cleanup (error);
513 if (acfg->is_full_aot && fatal) {
514 fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
515 exit (1);
519 /* Wrappers around the image writer functions */
521 #define MAX_SYMBOL_SIZE 256
523 static inline const char *
524 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
526 gsize needed_size = length;
528 g_assert (NULL != symbol);
529 g_assert (NULL != mangled_symbol);
530 g_assert (0 != length);
532 #if defined(TARGET_WIN32) && defined(TARGET_X86)
533 if (symbol && '_' != symbol [0]) {
534 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
535 } else {
536 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
538 #else
539 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
540 #endif
542 g_assert (0 <= needed_size && needed_size < length);
543 return mangled_symbol;
546 static inline char *
547 mangle_symbol_alloc (const char * symbol)
549 g_assert (NULL != symbol);
551 #if defined(TARGET_WIN32) && defined(TARGET_X86)
552 if (symbol && '_' != symbol [0]) {
553 return g_strdup_printf ("_%s", symbol);
555 else {
556 return g_strdup_printf ("%s", symbol);
558 #else
559 return g_strdup_printf ("%s", symbol);
560 #endif
563 static inline void
564 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
566 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
569 #if defined(TARGET_WIN32) && defined(TARGET_X86)
571 static inline void
572 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
574 const char * mangled_symbol_name = name;
575 char * mangled_symbol_name_alloc = NULL;
577 if (TRUE == func) {
578 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
579 mangled_symbol_name = mangled_symbol_name_alloc;
582 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
583 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
585 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
587 if (NULL != mangled_symbol_name_alloc) {
588 g_free (mangled_symbol_name_alloc);
592 #else
594 static inline void
595 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
597 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
600 #endif
602 static inline void
603 emit_label (MonoAotCompile *acfg, const char *name)
605 mono_img_writer_emit_label (acfg->w, name);
608 static inline void
609 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
611 mono_img_writer_emit_bytes (acfg->w, buf, size);
614 static inline void
615 emit_string (MonoAotCompile *acfg, const char *value)
617 mono_img_writer_emit_string (acfg->w, value);
620 static inline void
621 emit_line (MonoAotCompile *acfg)
623 mono_img_writer_emit_line (acfg->w);
626 static inline void
627 emit_alignment (MonoAotCompile *acfg, int size)
629 mono_img_writer_emit_alignment (acfg->w, size);
632 static inline void
633 emit_alignment_code (MonoAotCompile *acfg, int size)
635 if (acfg->align_pad_value)
636 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
637 else
638 mono_img_writer_emit_alignment (acfg->w, size);
641 static inline void
642 emit_padding (MonoAotCompile *acfg, int size)
644 int i;
645 guint8 buf [16];
647 if (acfg->align_pad_value) {
648 for (i = 0; i < 16; ++i)
649 buf [i] = acfg->align_pad_value;
650 } else {
651 memset (buf, 0, sizeof (buf));
654 for (i = 0; i < size; i += 16) {
655 if (size - i < 16)
656 emit_bytes (acfg, buf, size - i);
657 else
658 emit_bytes (acfg, buf, 16);
662 static inline void
663 emit_pointer (MonoAotCompile *acfg, const char *target)
665 mono_img_writer_emit_pointer (acfg->w, target);
668 static inline void
669 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
671 if (prefix [0] != '\0') {
672 char *s = g_strdup_printf ("%s%s", prefix, target);
673 mono_img_writer_emit_pointer (acfg->w, s);
674 g_free (s);
675 } else {
676 mono_img_writer_emit_pointer (acfg->w, target);
680 static inline void
681 emit_int16 (MonoAotCompile *acfg, int value)
683 mono_img_writer_emit_int16 (acfg->w, value);
686 static inline void
687 emit_int32 (MonoAotCompile *acfg, int value)
689 mono_img_writer_emit_int32 (acfg->w, value);
692 static inline void
693 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
695 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
698 static inline void
699 emit_zero_bytes (MonoAotCompile *acfg, int num)
701 mono_img_writer_emit_zero_bytes (acfg->w, num);
704 static inline void
705 emit_byte (MonoAotCompile *acfg, guint8 val)
707 mono_img_writer_emit_byte (acfg->w, val);
710 #if defined(TARGET_WIN32) && defined(TARGET_X86)
712 static G_GNUC_UNUSED void
713 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
715 const char * mangled_symbol_name = name;
716 char * mangled_symbol_name_alloc = NULL;
718 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
719 mangled_symbol_name = mangled_symbol_name_alloc;
721 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
722 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
724 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
726 if (NULL != mangled_symbol_name_alloc) {
727 g_free (mangled_symbol_name_alloc);
731 #else
733 static G_GNUC_UNUSED void
734 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
736 mono_img_writer_emit_global (acfg->w, name, func);
739 #endif
741 static inline gboolean
742 link_shared_library (MonoAotCompile *acfg)
744 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
747 static inline gboolean
748 add_to_global_symbol_table (MonoAotCompile *acfg)
750 #ifdef TARGET_WIN32_MSVC
751 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
752 #else
753 return acfg->aot_opts.no_dlsym;
754 #endif
757 static void
758 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
760 if (add_to_global_symbol_table (acfg))
761 g_ptr_array_add (acfg->globals, g_strdup (name));
763 if (acfg->aot_opts.no_dlsym) {
764 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
765 } else {
766 emit_global_inner (acfg, name, func);
770 static void
771 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
773 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
776 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
777 static void
778 emit_info_symbol (MonoAotCompile *acfg, const char *name, gboolean func)
780 char symbol [MAX_SYMBOL_SIZE];
782 if (acfg->llvm) {
783 emit_label (acfg, name);
784 /* LLVM generated code references this */
785 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
786 emit_label (acfg, symbol);
788 #ifndef TARGET_WIN32_MSVC
789 emit_global_inner (acfg, symbol, FALSE);
790 #else
791 emit_global_inner (acfg, symbol, func);
792 #endif
793 } else {
794 emit_label (acfg, name);
798 static void
799 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
801 if (acfg->llvm) {
802 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
803 return;
806 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
807 #ifdef TARGET_MACH
808 /* On apple, all symbols need to be aligned to avoid warnings from ld */
809 emit_alignment (acfg, 4);
810 #endif
811 mono_img_writer_emit_label (acfg->w, name);
812 mono_img_writer_emit_string (acfg->w, value);
815 static G_GNUC_UNUSED void
816 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
818 do {
819 guint8 b = value & 0x7f;
820 value >>= 7;
821 if (value != 0) /* more bytes to come */
822 b |= 0x80;
823 emit_byte (acfg, b);
824 } while (value);
827 static G_GNUC_UNUSED void
828 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
830 gboolean more = 1;
831 gboolean negative = (value < 0);
832 guint32 size = 64;
833 guint8 byte;
835 while (more) {
836 byte = value & 0x7f;
837 value >>= 7;
838 /* the following is unnecessary if the
839 * implementation of >>= uses an arithmetic rather
840 * than logical shift for a signed left operand
842 if (negative)
843 /* sign extend */
844 value |= - ((gint64)1 <<(size - 7));
845 /* sign bit of byte is second high order bit (0x40) */
846 if ((value == 0 && !(byte & 0x40)) ||
847 (value == -1 && (byte & 0x40)))
848 more = 0;
849 else
850 byte |= 0x80;
851 emit_byte (acfg, byte);
855 static G_GNUC_UNUSED void
856 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
858 guint8 *p = buf;
860 do {
861 guint8 b = value & 0x7f;
862 value >>= 7;
863 if (value != 0) /* more bytes to come */
864 b |= 0x80;
865 *p ++ = b;
866 } while (value);
868 *endbuf = p;
871 static G_GNUC_UNUSED void
872 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
874 gboolean more = 1;
875 gboolean negative = (value < 0);
876 guint32 size = 32;
877 guint8 byte;
878 guint8 *p = buf;
880 while (more) {
881 byte = value & 0x7f;
882 value >>= 7;
883 /* the following is unnecessary if the
884 * implementation of >>= uses an arithmetic rather
885 * than logical shift for a signed left operand
887 if (negative)
888 /* sign extend */
889 value |= - (1 <<(size - 7));
890 /* sign bit of byte is second high order bit (0x40) */
891 if ((value == 0 && !(byte & 0x40)) ||
892 (value == -1 && (byte & 0x40)))
893 more = 0;
894 else
895 byte |= 0x80;
896 *p ++= byte;
899 *endbuf = p;
902 static void
903 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
905 // FIXME: Big-endian
906 buf [0] = (val >> 0) & 0xff;
907 buf [1] = (val >> 8) & 0xff;
908 buf [2] = (val >> 16) & 0xff;
909 buf [3] = (val >> 24) & 0xff;
911 *endbuf = buf + 4;
914 static void
915 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
917 buf [0] = (val >> 0) & 0xff;
918 buf [1] = (val >> 8) & 0xff;
920 *endbuf = buf + 2;
923 static void
924 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
926 int len = strlen (s);
928 memcpy (buf, s, len + 1);
929 *endbuf = buf + len + 1;
932 static void
933 emit_unset_mode (MonoAotCompile *acfg)
935 mono_img_writer_emit_unset_mode (acfg->w);
938 static G_GNUC_UNUSED void
939 emit_set_thumb_mode (MonoAotCompile *acfg)
941 emit_unset_mode (acfg);
942 fprintf (acfg->fp, ".code 16\n");
945 static G_GNUC_UNUSED void
946 emit_set_arm_mode (MonoAotCompile *acfg)
948 emit_unset_mode (acfg);
949 fprintf (acfg->fp, ".code 32\n");
952 static inline void
953 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
955 #ifdef TARGET_ARM64
956 int i;
958 g_assert (size % 4 == 0);
959 emit_unset_mode (acfg);
960 for (i = 0; i < size; i += 4)
961 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
962 #else
963 emit_bytes (acfg, buf, size);
964 #endif
967 /* ARCHITECTURE SPECIFIC CODE */
969 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64) || defined (TARGET_RISCV)
970 #define EMIT_DWARF_INFO 1
971 #endif
973 #ifdef TARGET_WIN32_MSVC
974 #undef EMIT_DWARF_INFO
975 #define EMIT_WIN32_CODEVIEW_INFO
976 #endif
978 #ifdef EMIT_WIN32_UNWIND_INFO
979 static UnwindInfoSectionCacheItem *
980 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
982 static void
983 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg);
985 static void
986 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info);
988 static void
989 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
990 #endif
992 static void
993 arch_free_unwind_info_section_cache (MonoAotCompile *acfg)
995 #ifdef EMIT_WIN32_UNWIND_INFO
996 free_unwind_info_section_cache_win32 (acfg);
997 #endif
1000 static void
1001 arch_emit_unwind_info_sections (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
1003 #ifdef EMIT_WIN32_UNWIND_INFO
1004 gboolean own_unwind_ops = FALSE;
1005 if (!unwind_ops) {
1006 unwind_ops = mono_unwind_get_cie_program ();
1007 own_unwind_ops = TRUE;
1010 emit_unwind_info_sections_win32 (acfg, function_start, function_end, unwind_ops);
1012 if (own_unwind_ops)
1013 mono_free_unwind_info (unwind_ops);
1014 #endif
1017 #if defined(TARGET_ARM)
1018 #define AOT_FUNC_ALIGNMENT 4
1019 #else
1020 #define AOT_FUNC_ALIGNMENT 16
1021 #endif
1023 #if defined(TARGET_POWERPC64) && !defined(MONO_ARCH_ILP32)
1024 #define PPC_LD_OP "ld"
1025 #define PPC_LDX_OP "ldx"
1026 #else
1027 #define PPC_LD_OP "lwz"
1028 #define PPC_LDX_OP "lwzx"
1029 #endif
1031 #ifdef TARGET_X86_64_WIN32_MSVC
1032 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
1033 #elif TARGET_AMD64
1034 #define AOT_TARGET_STR "AMD64"
1035 #endif
1037 #ifdef TARGET_ARM
1038 #ifdef TARGET_MACH
1039 #define AOT_TARGET_STR "ARM (MACH)"
1040 #else
1041 #define AOT_TARGET_STR "ARM (!MACH)"
1042 #endif
1043 #endif
1045 #ifdef TARGET_ARM64
1046 #ifdef TARGET_MACH
1047 #define AOT_TARGET_STR "ARM64 (MACH)"
1048 #else
1049 #define AOT_TARGET_STR "ARM64 (!MACH)"
1050 #endif
1051 #endif
1053 #ifdef TARGET_POWERPC64
1054 #ifdef MONO_ARCH_ILP32
1055 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
1056 #else
1057 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
1058 #endif
1059 #else
1060 #ifdef TARGET_POWERPC
1061 #ifdef MONO_ARCH_ILP32
1062 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
1063 #else
1064 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
1065 #endif
1066 #endif
1067 #endif
1069 #ifdef TARGET_RISCV32
1070 #define AOT_TARGET_STR "RISCV32"
1071 #endif
1073 #ifdef TARGET_RISCV64
1074 #define AOT_TARGET_STR "RISCV64"
1075 #endif
1077 #ifdef TARGET_X86
1078 #ifdef TARGET_WIN32
1079 #define AOT_TARGET_STR "X86 (WIN32)"
1080 #else
1081 #define AOT_TARGET_STR "X86"
1082 #endif
1083 #endif
1085 #ifndef AOT_TARGET_STR
1086 #define AOT_TARGET_STR ""
1087 #endif
1089 static void
1090 arch_init (MonoAotCompile *acfg)
1092 acfg->llc_args = g_string_new ("");
1093 acfg->as_args = g_string_new ("");
1094 acfg->llvm_owriter_supported = TRUE;
1097 * The prefix LLVM likes to put in front of symbol names on darwin.
1098 * The mach-os specs require this for globals, but LLVM puts them in front of all
1099 * symbols. We need to handle this, since we need to refer to LLVM generated
1100 * symbols.
1102 acfg->llvm_label_prefix = "";
1103 acfg->user_symbol_prefix = "";
1105 #if TARGET_X86 || TARGET_AMD64
1106 const gboolean has_custom_args = !!acfg->aot_opts.llvm_llc;
1107 #endif
1109 #if defined(TARGET_X86)
1110 g_string_append_printf (acfg->llc_args, " -march=x86 %s", has_custom_args ? "" : "-mcpu=generic");
1111 #endif
1113 #if defined(TARGET_AMD64)
1114 g_string_append_printf (acfg->llc_args, " -march=x86-64 %s", has_custom_args ? "" : "-mcpu=generic");
1115 /* NOP */
1116 acfg->align_pad_value = 0x90;
1117 #endif
1119 #ifdef TARGET_ARM
1120 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
1121 g_string_append (acfg->llc_args, "-mattr=+v6");
1122 } else {
1123 if (!(acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb")))
1124 g_string_append (acfg->llc_args, " -march=arm");
1126 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "ios")) {
1127 g_string_append (acfg->llc_args, " -mattr=+v7");
1128 g_string_append (acfg->llc_args, " -exception-model=dwarf -disable-fp-elim");
1131 #if defined(ARM_FPU_VFP_HARD)
1132 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
1133 g_string_append (acfg->as_args, " -mfpu=vfp3");
1134 #elif defined(ARM_FPU_VFP)
1135 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1136 g_string_append (acfg->as_args, " -mfpu=vfp3");
1137 #else
1138 g_string_append (acfg->llc_args, " -mattr=+soft-float");
1139 #endif
1141 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1142 acfg->thumb_mixed = TRUE;
1144 if (acfg->aot_opts.mtriple)
1145 mono_arch_set_target (acfg->aot_opts.mtriple);
1146 #endif
1148 #ifdef TARGET_ARM64
1149 g_string_append (acfg->llc_args, " -march=aarch64");
1150 acfg->inst_directive = ".inst";
1151 if (acfg->aot_opts.mtriple)
1152 mono_arch_set_target (acfg->aot_opts.mtriple);
1153 #endif
1155 #ifdef TARGET_MACH
1156 acfg->user_symbol_prefix = "_";
1157 acfg->llvm_label_prefix = "_";
1158 acfg->inst_directive = ".word";
1159 acfg->need_no_dead_strip = TRUE;
1160 acfg->aot_opts.gnu_asm = TRUE;
1161 #endif
1163 #if defined(__linux__) && !defined(TARGET_ARM)
1164 acfg->need_pt_gnu_stack = TRUE;
1165 #endif
1167 #ifdef TARGET_RISCV
1168 if (acfg->aot_opts.mtriple)
1169 mono_arch_set_target (acfg->aot_opts.mtriple);
1171 #ifdef TARGET_RISCV64
1173 g_string_append (acfg->as_args, " -march=rv64i ");
1174 #ifdef RISCV_FPABI_DOUBLE
1175 g_string_append (acfg->as_args, " -mabi=lp64d");
1176 #else
1177 g_string_append (acfg->as_args, " -mabi=lp64");
1178 #endif
1180 #else
1182 g_string_append (acfg->as_args, " -march=rv32i ");
1183 #ifdef RISCV_FPABI_DOUBLE
1184 g_string_append (acfg->as_args, " -mabi=ilp32d ");
1185 #else
1186 g_string_append (acfg->as_args, " -mabi=ilp32 ");
1187 #endif
1189 #endif
1191 #endif
1193 #ifdef MONOTOUCH
1194 acfg->global_symbols = TRUE;
1195 #endif
1197 #ifdef TARGET_ANDROID
1198 acfg->llvm_owriter_supported = FALSE;
1199 #endif
1202 #ifdef TARGET_ARM64
1205 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1206 static void
1207 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1209 int offset;
1211 g_assert (acfg->fp);
1212 emit_unset_mode (acfg);
1213 /* r16==ip0 */
1214 offset = (int)(got_slot * sizeof (target_mgreg_t));
1215 #ifdef TARGET_MACH
1216 /* clang's integrated assembler */
1217 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1218 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1219 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1220 #else
1221 /* Linux GAS */
1222 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1223 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1224 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1225 #endif
1228 static void
1229 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1231 int reg;
1233 g_assert (acfg->fp);
1234 emit_unset_mode (acfg);
1236 /* ldr rt, target */
1237 reg = arm_get_ldr_lit_reg (code);
1239 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1240 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1241 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1243 *code_size = 12;
1246 static void
1247 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1249 g_assert (acfg->fp);
1250 emit_unset_mode (acfg);
1251 if (ji && ji->relocation == MONO_R_ARM64_B) {
1252 fprintf (acfg->fp, "b %s\n", target);
1253 } else {
1254 if (ji)
1255 g_assert (ji->relocation == MONO_R_ARM64_BL);
1256 fprintf (acfg->fp, "bl %s\n", target);
1258 *call_size = 4;
1261 static void
1262 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1264 int reg;
1266 /* ldr rt, target */
1267 reg = arm_get_ldr_lit_reg (code);
1268 arm64_emit_load_got_slot (acfg, reg, got_slot);
1269 *code_size = 12;
1272 static void
1273 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1275 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (target_mgreg_t));
1276 fprintf (acfg->fp, "br x16\n");
1277 /* Used by mono_aot_get_plt_info_offset () */
1278 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1281 static void
1282 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1284 guint8 buf [256];
1285 guint8 *code;
1286 int imm;
1288 /* The common code */
1289 code = buf;
1290 imm = pagesize;
1291 /* The trampoline address is in IP0 */
1292 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1293 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1294 /* Compute the data slot address */
1295 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1296 /* Trampoline argument */
1297 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1298 /* Address */
1299 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1300 arm_brx (code, ARMREG_IP0);
1302 /* Emit it */
1303 emit_code_bytes (acfg, buf, code - buf);
1305 *size = code - buf;
1308 static void
1309 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1311 guint8 buf [256];
1312 guint8 *code;
1313 int i, count;
1315 count = (pagesize - common_tramp_size) / specific_tramp_size;
1316 for (i = 0; i < count; ++i) {
1317 code = buf;
1318 arm_adrx (code, ARMREG_IP0, code);
1319 /* Branch to the generic code */
1320 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1321 /* This has to be 2 pointers long */
1322 arm_nop (code);
1323 arm_nop (code);
1324 g_assert (code - buf == specific_tramp_size);
1325 emit_code_bytes (acfg, buf, code - buf);
1329 static void
1330 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1332 guint8 buf [128];
1333 guint8 *code;
1334 guint8 *labels [16];
1335 int common_tramp_size;
1336 int specific_tramp_size = 2 * 8;
1337 int imm, pagesize;
1338 char symbol [128];
1340 if (!acfg->aot_opts.use_trampolines_page)
1341 return;
1343 #ifdef TARGET_MACH
1344 /* Have to match the target pagesize */
1345 pagesize = 16384;
1346 #else
1347 pagesize = mono_pagesize ();
1348 #endif
1349 acfg->tramp_page_size = pagesize;
1351 /* The specific trampolines */
1352 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1353 emit_alignment (acfg, pagesize);
1354 emit_global (acfg, symbol, TRUE);
1355 emit_label (acfg, symbol);
1357 /* The common code */
1358 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1359 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1361 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1363 /* The rgctx trampolines */
1364 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1365 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1366 emit_alignment (acfg, pagesize);
1367 emit_global (acfg, symbol, TRUE);
1368 emit_label (acfg, symbol);
1370 /* The common code */
1371 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1372 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1374 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1376 /* The gsharedvt arg trampolines */
1377 /* These are the same as the specific trampolines */
1378 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1379 emit_alignment (acfg, pagesize);
1380 emit_global (acfg, symbol, TRUE);
1381 emit_label (acfg, symbol);
1383 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1384 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1386 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1388 /* Unbox arbitrary trampolines */
1389 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
1390 emit_alignment (acfg, pagesize);
1391 emit_global (acfg, symbol, TRUE);
1392 emit_label (acfg, symbol);
1394 code = buf;
1395 imm = pagesize;
1397 /* Unbox this arg */
1398 arm_addx_imm (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
1400 /* The trampoline address is in IP0 */
1401 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1402 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1403 /* Compute the data slot address */
1404 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1405 /* Address */
1406 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1407 arm_brx (code, ARMREG_IP0);
1409 /* Emit it */
1410 emit_code_bytes (acfg, buf, code - buf);
1412 common_tramp_size = code - buf;
1413 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = common_tramp_size;
1415 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1417 /* The IMT trampolines */
1418 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1419 emit_alignment (acfg, pagesize);
1420 emit_global (acfg, symbol, TRUE);
1421 emit_label (acfg, symbol);
1423 code = buf;
1424 imm = pagesize;
1425 /* The trampoline address is in IP0 */
1426 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1427 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1428 /* Compute the data slot address */
1429 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1430 /* Trampoline argument */
1431 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1433 /* Same as arch_emit_imt_trampoline () */
1434 labels [0] = code;
1435 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1436 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1437 labels [1] = code;
1438 arm_bcc (code, ARMCOND_EQ, 0);
1440 /* End-of-loop check */
1441 labels [2] = code;
1442 arm_cbzx (code, ARMREG_IP0, 0);
1444 /* Loop footer */
1445 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1446 arm_b (code, labels [0]);
1448 /* Match */
1449 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1450 /* Load vtable slot addr */
1451 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1452 /* Load vtable slot */
1453 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1454 arm_brx (code, ARMREG_IP0);
1456 /* No match */
1457 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1458 /* Load fail addr */
1459 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1460 arm_brx (code, ARMREG_IP0);
1462 emit_code_bytes (acfg, buf, code - buf);
1464 common_tramp_size = code - buf;
1465 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1467 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1470 static void
1471 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1473 /* Load argument from second GOT slot */
1474 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1475 /* Load generic trampoline address from first GOT slot */
1476 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1477 fprintf (acfg->fp, "br x16\n");
1478 *tramp_size = 7 * 4;
1481 static void
1482 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1484 emit_unset_mode (acfg);
1485 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
1486 fprintf (acfg->fp, "b %s\n", call_target);
1489 static void
1490 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1492 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1494 /* Load argument from first GOT slot */
1495 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1496 /* Load generic trampoline address from second GOT slot */
1497 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1498 fprintf (acfg->fp, "br x16\n");
1499 *tramp_size = 7 * 4;
1502 static void
1503 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1505 guint8 buf [128];
1506 guint8 *code, *labels [16];
1508 /* Load parameter from GOT slot into ip1 */
1509 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1511 code = buf;
1512 labels [0] = code;
1513 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1514 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1515 labels [1] = code;
1516 arm_bcc (code, ARMCOND_EQ, 0);
1518 /* End-of-loop check */
1519 labels [2] = code;
1520 arm_cbzx (code, ARMREG_IP0, 0);
1522 /* Loop footer */
1523 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1524 arm_b (code, labels [0]);
1526 /* Match */
1527 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1528 /* Load vtable slot addr */
1529 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1530 /* Load vtable slot */
1531 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1532 arm_brx (code, ARMREG_IP0);
1534 /* No match */
1535 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1536 /* Load fail addr */
1537 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1538 arm_brx (code, ARMREG_IP0);
1540 emit_code_bytes (acfg, buf, code - buf);
1542 *tramp_size = code - buf + (3 * 4);
1545 static void
1546 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1548 /* Similar to the specific trampolines, but the address is in the second slot */
1549 /* Load argument from first GOT slot */
1550 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1551 /* Load generic trampoline address from second GOT slot */
1552 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1553 fprintf (acfg->fp, "br x16\n");
1554 *tramp_size = 7 * 4;
1558 #endif
1560 #ifdef MONO_ARCH_AOT_SUPPORTED
1562 * arch_emit_direct_call:
1564 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1565 * calling code.
1567 static void
1568 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1570 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1571 /* Need to make sure this is exactly 5 bytes long */
1572 emit_unset_mode (acfg);
1573 fprintf (acfg->fp, "call %s\n", target);
1574 *call_size = 5;
1575 #elif defined(TARGET_ARM)
1576 emit_unset_mode (acfg);
1577 if (thumb)
1578 fprintf (acfg->fp, "blx %s\n", target);
1579 else
1580 fprintf (acfg->fp, "bl %s\n", target);
1581 *call_size = 4;
1582 #elif defined(TARGET_ARM64)
1583 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1584 #elif defined(TARGET_POWERPC)
1585 emit_unset_mode (acfg);
1586 fprintf (acfg->fp, "bl %s\n", target);
1587 *call_size = 4;
1588 #else
1589 g_assert_not_reached ();
1590 #endif
1593 static void
1594 arch_emit_label_address (MonoAotCompile *acfg, const char *target, gboolean external_call, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1596 #if defined(TARGET_ARM) && defined(TARGET_ANDROID)
1597 /* binutils ld does not support branch islands on arm32 */
1598 if (!thumb) {
1599 emit_unset_mode (acfg);
1600 fprintf (acfg->fp, "ldr pc,=%s\n", target);
1601 fprintf (acfg->fp, ".ltorg\n");
1602 *call_size = 8;
1603 } else
1604 #endif
1605 arch_emit_direct_call (acfg, target, external_call, thumb, ji, call_size);
1607 #endif
1610 * PPC32 design:
1611 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1612 * the GOT pointer.
1613 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1614 * in in the 2. slot of every GOT, and require every method to place the GOT
1615 * address in r30, even when it doesn't access the GOT otherwise. This way,
1616 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1620 * PPC64 design:
1621 * PPC64 uses function descriptors which greatly complicate all code, since
1622 * these are used very inconsistently in the runtime. Some functions like
1623 * mono_compile_method () return ftn descriptors, while others like the
1624 * trampoline creation functions do not.
1625 * We assume that all GOT slots contain function descriptors, and create
1626 * descriptors in aot-runtime.c when needed.
1627 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1628 * from function descriptors, we could do the same, but it would require
1629 * rewriting all the ppc/aot code to handle function descriptors properly.
1630 * So instead, we use the same approach as on PPC32.
1631 * This is a horrible mess, but fixing it would probably lead to an even bigger
1632 * one.
1636 * X86 design:
1637 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1640 #ifdef MONO_ARCH_AOT_SUPPORTED
1642 * arch_emit_got_offset:
1644 * The memory pointed to by CODE should hold native code for computing the GOT
1645 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1646 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1648 static void
1649 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1651 #if defined(TARGET_POWERPC64)
1652 emit_unset_mode (acfg);
1654 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1655 * unsupported relocations. So we store the got address into the .Lgot_addr
1656 * symbol which is in the text segment, compute its address, and load it.
1658 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1659 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1660 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1661 fprintf (acfg->fp, "add 30, 30, 0\n");
1662 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1663 acfg->label_generator ++;
1664 *code_size = 16;
1665 #elif defined(TARGET_POWERPC)
1666 emit_unset_mode (acfg);
1667 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1668 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1669 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1670 acfg->label_generator ++;
1671 *code_size = 8;
1672 #else
1673 guint32 offset = mono_arch_get_patch_offset (code);
1674 emit_bytes (acfg, code, offset);
1675 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1677 *code_size = offset + 4;
1678 #endif
1682 * arch_emit_got_access:
1684 * The memory pointed to by CODE should hold native code for loading a GOT
1685 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1686 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1688 static void
1689 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1691 #ifdef TARGET_AMD64
1692 /* mov reg, got+offset(%rip) */
1693 if (acfg->llvm) {
1694 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1695 int dreg;
1696 int rex_r;
1698 /* Decode reg, see amd64_mov_reg_membase () */
1699 rex_r = code [0] & AMD64_REX_R;
1700 g_assert (code [0] == 0x49 + rex_r);
1701 g_assert (code [1] == 0x8b);
1702 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1704 emit_unset_mode (acfg);
1705 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
1706 *code_size = 7;
1707 } else {
1708 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1709 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t)) - 4));
1710 *code_size = mono_arch_get_patch_offset (code) + 4;
1712 #elif defined(TARGET_X86)
1713 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1714 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (target_mgreg_t))));
1715 *code_size = mono_arch_get_patch_offset (code) + 4;
1716 #elif defined(TARGET_ARM)
1717 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1718 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t))) - 12);
1719 *code_size = mono_arch_get_patch_offset (code) + 4;
1720 #elif defined(TARGET_ARM64)
1721 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1722 arm64_emit_got_access (acfg, code, got_slot, code_size);
1723 #elif defined(TARGET_POWERPC)
1725 guint8 buf [32];
1727 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1728 code = buf;
1729 ppc_load32 (code, ppc_r0, got_slot * sizeof (target_mgreg_t));
1730 g_assert (code - buf == 8);
1731 emit_bytes (acfg, buf, code - buf);
1732 *code_size = code - buf;
1734 #else
1735 g_assert_not_reached ();
1736 #endif
1739 #endif
1741 #ifdef MONO_ARCH_AOT_SUPPORTED
1743 * arch_emit_objc_selector_ref:
1745 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1747 static void
1748 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1750 #if defined(TARGET_ARM)
1751 char symbol1 [MAX_SYMBOL_SIZE];
1752 char symbol2 [MAX_SYMBOL_SIZE];
1753 int lindex = acfg->objc_selector_index_2 ++;
1755 /* Emit ldr.imm/b */
1756 emit_bytes (acfg, code, 8);
1758 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1759 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1761 emit_label (acfg, symbol1);
1762 mono_img_writer_emit_unset_mode (acfg->w);
1763 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1765 *code_size = 12;
1766 #elif defined(TARGET_ARM64)
1767 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1768 #else
1769 g_assert_not_reached ();
1770 #endif
1772 #endif
1775 * arch_emit_plt_entry:
1777 * Emit code for the PLT entry.
1778 * The plt entry should look like this:
1779 * <indirect jump to GOT_SYMBOL + OFFSET>
1780 * <INFO_OFFSET embedded into the instruction stream>
1782 static void
1783 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1785 #if defined(TARGET_X86)
1786 /* jmp *<offset>(%ebx) */
1787 emit_byte (acfg, 0xff);
1788 emit_byte (acfg, 0xa3);
1789 emit_int32 (acfg, offset);
1790 /* Used by mono_aot_get_plt_info_offset */
1791 emit_int32 (acfg, info_offset);
1792 #elif defined(TARGET_AMD64)
1793 emit_unset_mode (acfg);
1794 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1795 /* Used by mono_aot_get_plt_info_offset */
1796 emit_int32 (acfg, info_offset);
1797 acfg->stats.plt_size += 10;
1798 #elif defined(TARGET_ARM)
1799 guint8 buf [256];
1800 guint8 *code;
1802 code = buf;
1803 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1804 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1805 emit_bytes (acfg, buf, code - buf);
1806 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1807 /* Used by mono_aot_get_plt_info_offset */
1808 emit_int32 (acfg, info_offset);
1809 #elif defined(TARGET_ARM64)
1810 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1811 #elif defined(TARGET_POWERPC)
1812 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1813 emit_unset_mode (acfg);
1814 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1815 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1816 fprintf (acfg->fp, "add 11, 11, 30\n");
1817 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1818 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1819 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
1820 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1821 #endif
1822 fprintf (acfg->fp, "mtctr 11\n");
1823 fprintf (acfg->fp, "bctr\n");
1824 emit_int32 (acfg, info_offset);
1825 #else
1826 g_assert_not_reached ();
1827 #endif
1831 * arch_emit_llvm_plt_entry:
1833 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1834 * This is only needed on arm to handle thumb interop.
1836 static void
1837 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1839 #if defined(TARGET_ARM)
1840 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1841 /* The caller already transitioned to thumb */
1842 /* The code below should be 12 bytes long */
1843 /* clang has trouble encoding these instructions, so emit the binary */
1844 #if 0
1845 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1846 /* thumb can't encode ld pc, [pc, ip] */
1847 fprintf (acfg->fp, "add ip, pc, ip\n");
1848 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1849 fprintf (acfg->fp, "bx ip\n");
1850 #endif
1851 emit_set_thumb_mode (acfg);
1852 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1853 fprintf (acfg->fp, ".2byte 0x44fc\n");
1854 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1855 fprintf (acfg->fp, ".2byte 0x4760\n");
1856 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1857 emit_int32 (acfg, info_offset);
1858 emit_unset_mode (acfg);
1859 emit_set_arm_mode (acfg);
1860 #else
1861 g_assert_not_reached ();
1862 #endif
1865 /* Save unwind_info in the module and emit the offset to the information at symbol */
1866 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1868 guint32 uw_offset, encoded_len;
1869 guint8 *encoded;
1871 emit_section_change (acfg, RODATA_SECT, 0);
1872 emit_global (acfg, symbol, FALSE);
1873 emit_label (acfg, symbol);
1875 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1876 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1877 g_free (encoded);
1878 emit_int32 (acfg, uw_offset);
1882 * arch_emit_specific_trampoline_pages:
1884 * Emits a page full of trampolines: each trampoline uses its own address to
1885 * lookup both the generic trampoline code and the data argument.
1886 * This page can be remapped in process multiple times so we can get an
1887 * unlimited number of trampolines.
1888 * Specifically this implementation uses the following trick: two memory pages
1889 * are allocated, with the first containing the data and the second containing the trampolines.
1890 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1891 * implementation does all the lifting.
1892 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1893 * on the arm 32 bit system.
1895 static void
1896 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1898 #if defined(TARGET_ARM)
1899 guint8 buf [128];
1900 guint8 *code;
1901 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1902 int i;
1903 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1904 GSList *unwind_ops = NULL;
1905 #define COMMON_TRAMP_SIZE 16
1906 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1907 int imm8, rot_amount;
1908 char symbol [128];
1910 if (!acfg->aot_opts.use_trampolines_page)
1911 return;
1913 acfg->tramp_page_size = pagesize;
1915 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1916 emit_alignment (acfg, pagesize);
1917 emit_global (acfg, symbol, TRUE);
1918 emit_label (acfg, symbol);
1920 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1921 code = buf;
1922 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1923 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1924 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1925 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1926 ARM_NOP (code);
1927 g_assert (code - buf == COMMON_TRAMP_SIZE);
1929 /* Emit it */
1930 emit_bytes (acfg, buf, code - buf);
1932 for (i = 0; i < count; ++i) {
1933 code = buf;
1934 ARM_PUSH (code, 0x5fff);
1935 ARM_BL (code, 0);
1936 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1937 g_assert (code - buf == 8);
1938 emit_bytes (acfg, buf, code - buf);
1941 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1942 * the instruction pointer address, so the generic trampoline at the start of the page
1943 * subtracts 4096 to get to the data page and loads the values
1944 * We again fit the generic trampiline in 16 bytes.
1946 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1947 emit_global (acfg, symbol, TRUE);
1948 emit_label (acfg, symbol);
1949 code = buf;
1950 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1951 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1952 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1953 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1954 ARM_NOP (code);
1955 g_assert (code - buf == COMMON_TRAMP_SIZE);
1957 /* Emit it */
1958 emit_bytes (acfg, buf, code - buf);
1960 for (i = 0; i < count; ++i) {
1961 code = buf;
1962 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1963 ARM_B (code, 0);
1964 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1965 g_assert (code - buf == 8);
1966 emit_bytes (acfg, buf, code - buf);
1970 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1972 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1973 emit_global (acfg, symbol, TRUE);
1974 emit_label (acfg, symbol);
1975 code = buf;
1976 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1977 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1978 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1979 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1980 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1981 g_assert (code - buf == COMMON_TRAMP_SIZE);
1982 /* Emit it */
1983 emit_bytes (acfg, buf, code - buf);
1985 for (i = 0; i < count; ++i) {
1986 code = buf;
1987 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1988 ARM_B (code, 0);
1989 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1990 g_assert (code - buf == 8);
1991 emit_bytes (acfg, buf, code - buf);
1994 /* now the unbox arbitrary trampolines: each specific trampolines puts in the ip register
1995 * the instruction pointer address, so the generic trampoline at the start of the page
1996 * subtracts 4096 to get to the data page and loads the target addr.
1997 * We again fit the generic trampoline in 16 bytes.
1999 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
2000 emit_global (acfg, symbol, TRUE);
2001 emit_label (acfg, symbol);
2002 code = buf;
2004 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2005 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
2006 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
2007 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
2008 ARM_NOP (code);
2009 g_assert (code - buf == COMMON_TRAMP_SIZE);
2011 /* Emit it */
2012 emit_bytes (acfg, buf, code - buf);
2014 for (i = 0; i < count; ++i) {
2015 code = buf;
2016 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
2017 ARM_B (code, 0);
2018 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
2019 g_assert (code - buf == 8);
2020 emit_bytes (acfg, buf, code - buf);
2023 /* now the imt trampolines: each specific trampolines puts in the ip register
2024 * the instruction pointer address, so the generic trampoline at the start of the page
2025 * subtracts 4096 to get to the data page and loads the values
2027 #define IMT_TRAMP_SIZE 72
2028 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
2029 emit_global (acfg, symbol, TRUE);
2030 emit_label (acfg, symbol);
2031 code = buf;
2032 /* Need at least two free registers, plus a slot for storing the pc */
2033 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2035 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
2036 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
2037 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
2039 /* The IMT method is in v5, r0 has the imt array address */
2041 loop_start = code;
2042 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2043 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2044 imt_found_check = code;
2045 ARM_B_COND (code, ARMCOND_EQ, 0);
2047 /* End-of-loop check */
2048 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2049 loop_end_check = code;
2050 ARM_B_COND (code, ARMCOND_EQ, 0);
2052 /* Loop footer */
2053 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2054 loop_branch_back = code;
2055 ARM_B (code, 0);
2056 arm_patch (loop_branch_back, loop_start);
2058 /* Match */
2059 arm_patch (imt_found_check, code);
2060 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2061 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2062 /* Save it to the third stack slot */
2063 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2064 /* Restore the registers and branch */
2065 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2067 /* No match */
2068 arm_patch (loop_end_check, code);
2069 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2070 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2071 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2072 ARM_NOP (code);
2074 /* Emit it */
2075 g_assert (code - buf == IMT_TRAMP_SIZE);
2076 emit_bytes (acfg, buf, code - buf);
2078 for (i = 0; i < count; ++i) {
2079 code = buf;
2080 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
2081 ARM_B (code, 0);
2082 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
2083 g_assert (code - buf == 8);
2084 emit_bytes (acfg, buf, code - buf);
2087 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
2088 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
2089 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
2090 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
2091 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = 16;
2093 /* Unwind info for specifc trampolines */
2094 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
2095 /* We unwind to the original caller, from the stack, since lr is clobbered */
2096 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (target_mgreg_t));
2097 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
2098 save_unwind_info (acfg, symbol, unwind_ops);
2099 mono_free_unwind_info (unwind_ops);
2101 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
2102 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2103 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (target_mgreg_t));
2104 save_unwind_info (acfg, symbol, unwind_ops);
2105 mono_free_unwind_info (unwind_ops);
2107 /* Unwind info for rgctx trampolines */
2108 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
2109 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2110 save_unwind_info (acfg, symbol, unwind_ops);
2112 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
2113 save_unwind_info (acfg, symbol, unwind_ops);
2114 mono_free_unwind_info (unwind_ops);
2116 /* Unwind info for gsharedvt trampolines */
2117 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2118 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2119 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (target_mgreg_t));
2120 save_unwind_info (acfg, symbol, unwind_ops);
2121 mono_free_unwind_info (unwind_ops);
2123 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2124 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2125 save_unwind_info (acfg, symbol, unwind_ops);
2126 mono_free_unwind_info (unwind_ops);
2128 /* Unwind info for unbox arbitrary trampolines */
2129 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_gen_p", acfg->user_symbol_prefix);
2130 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2131 save_unwind_info (acfg, symbol, unwind_ops);
2133 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_sp_p", acfg->user_symbol_prefix);
2134 save_unwind_info (acfg, symbol, unwind_ops);
2135 mono_free_unwind_info (unwind_ops);
2137 /* Unwind info for imt trampolines */
2138 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2139 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2140 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (target_mgreg_t));
2141 save_unwind_info (acfg, symbol, unwind_ops);
2142 mono_free_unwind_info (unwind_ops);
2144 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2145 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2146 save_unwind_info (acfg, symbol, unwind_ops);
2147 mono_free_unwind_info (unwind_ops);
2148 #elif defined(TARGET_ARM64)
2149 arm64_emit_specific_trampoline_pages (acfg);
2150 #endif
2154 * arch_emit_specific_trampoline:
2156 * Emit code for a specific trampoline. OFFSET is the offset of the first of
2157 * two GOT slots which contain the generic trampoline address and the trampoline
2158 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
2160 static void
2161 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2164 * The trampolines created here are variations of the specific
2165 * trampolines created in mono_arch_create_specific_trampoline (). The
2166 * differences are:
2167 * - the generic trampoline address is taken from a got slot.
2168 * - the offset of the got slot where the trampoline argument is stored
2169 * is embedded in the instruction stream, and the generic trampoline
2170 * can load the argument by loading the offset, adding it to the
2171 * address of the trampoline to get the address of the got slot, and
2172 * loading the argument from there.
2173 * - all the trampolines should be of the same length.
2175 #if defined(TARGET_AMD64)
2176 /* This should be exactly 8 bytes long */
2177 *tramp_size = 8;
2178 /* call *<offset>(%rip) */
2179 if (acfg->llvm) {
2180 emit_unset_mode (acfg);
2181 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2182 emit_zero_bytes (acfg, 2);
2183 } else {
2184 emit_byte (acfg, '\x41');
2185 emit_byte (acfg, '\xff');
2186 emit_byte (acfg, '\x15');
2187 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2188 emit_zero_bytes (acfg, 1);
2190 #elif defined(TARGET_ARM)
2191 guint8 buf [128];
2192 guint8 *code;
2194 /* This should be exactly 20 bytes long */
2195 *tramp_size = 20;
2196 code = buf;
2197 ARM_PUSH (code, 0x5fff);
2198 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
2199 /* Load the value from the GOT */
2200 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2201 /* Branch to it */
2202 ARM_BLX_REG (code, ARMREG_R1);
2204 g_assert (code - buf == 16);
2206 /* Emit it */
2207 emit_bytes (acfg, buf, code - buf);
2209 * Only one offset is needed, since the second one would be equal to the
2210 * first one.
2212 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 4);
2213 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 8);
2214 #elif defined(TARGET_ARM64)
2215 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
2216 #elif defined(TARGET_POWERPC)
2217 guint8 buf [128];
2218 guint8 *code;
2220 *tramp_size = 4;
2221 code = buf;
2224 * PPC has no ip relative addressing, so we need to compute the address
2225 * of the mscorlib got. That is slow and complex, so instead, we store it
2226 * in the second got slot of every aot image. The caller already computed
2227 * the address of its got and placed it into r30.
2229 emit_unset_mode (acfg);
2230 /* Load mscorlib got address */
2231 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2232 /* Load generic trampoline address */
2233 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2234 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2235 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2236 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2237 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2238 #endif
2239 fprintf (acfg->fp, "mtctr 11\n");
2240 /* Load trampoline argument */
2241 /* On ppc, we pass it normally to the generic trampoline */
2242 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2243 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2244 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2245 /* Branch to generic trampoline */
2246 fprintf (acfg->fp, "bctr\n");
2248 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2249 *tramp_size = 10 * 4;
2250 #else
2251 *tramp_size = 9 * 4;
2252 #endif
2253 #elif defined(TARGET_X86)
2254 guint8 buf [128];
2255 guint8 *code;
2257 /* Similar to the PPC code above */
2259 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2261 code = buf;
2262 /* Load mscorlib got address */
2263 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2264 /* Push trampoline argument */
2265 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2266 /* Load generic trampoline address */
2267 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2268 /* Branch to generic trampoline */
2269 x86_jump_reg (code, X86_ECX);
2271 emit_bytes (acfg, buf, code - buf);
2273 *tramp_size = 17;
2274 g_assert (code - buf == *tramp_size);
2275 #else
2276 g_assert_not_reached ();
2277 #endif
2281 * arch_emit_unbox_trampoline:
2283 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2284 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2286 * See mono_aot_get_unbox_trampoline.
2288 static void
2289 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2291 #if defined(TARGET_AMD64)
2292 guint8 buf [32];
2293 guint8 *code;
2294 int this_reg;
2296 this_reg = mono_arch_get_this_arg_reg (NULL);
2297 code = buf;
2298 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2300 emit_bytes (acfg, buf, code - buf);
2301 /* jump <method> */
2302 if (acfg->llvm) {
2303 emit_unset_mode (acfg);
2304 fprintf (acfg->fp, "jmp %s\n", call_target);
2305 } else {
2306 emit_byte (acfg, '\xe9');
2307 emit_symbol_diff (acfg, call_target, ".", -4);
2309 #elif defined(TARGET_X86)
2310 guint8 buf [32];
2311 guint8 *code;
2312 int this_pos = 4;
2314 code = buf;
2316 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, MONO_ABI_SIZEOF (MonoObject));
2318 emit_bytes (acfg, buf, code - buf);
2320 /* jump <method> */
2321 emit_byte (acfg, '\xe9');
2322 emit_symbol_diff (acfg, call_target, ".", -4);
2323 #elif defined(TARGET_ARM)
2324 guint8 buf [128];
2325 guint8 *code;
2327 if (acfg->thumb_mixed && cfg->compile_llvm) {
2328 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)MONO_ABI_SIZEOF (MonoObject));
2329 fprintf (acfg->fp, "b %s\n", call_target);
2330 fprintf (acfg->fp, ".arm\n");
2331 fprintf (acfg->fp, ".align 2\n");
2332 return;
2335 code = buf;
2337 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2339 emit_bytes (acfg, buf, code - buf);
2340 /* jump to method */
2341 if (acfg->thumb_mixed && cfg->compile_llvm)
2342 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2343 else
2344 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2345 #elif defined(TARGET_ARM64)
2346 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2347 #elif defined(TARGET_POWERPC)
2348 int this_pos = 3;
2350 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)MONO_ABI_SIZEOF (MonoObject));
2351 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2352 #else
2353 g_assert_not_reached ();
2354 #endif
2358 * arch_emit_static_rgctx_trampoline:
2360 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2361 * two GOT slots which contain the rgctx argument, and the method to jump to.
2362 * TRAMP_SIZE is set to the size of the emitted trampoline.
2363 * These kinds of trampolines cannot be enumerated statically, since there could
2364 * be one trampoline per method instantiation, so we emit the same code for all
2365 * trampolines, and parameterize them using two GOT slots.
2367 static void
2368 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2370 #if defined(TARGET_AMD64)
2371 /* This should be exactly 13 bytes long */
2372 *tramp_size = 13;
2374 if (acfg->llvm) {
2375 emit_unset_mode (acfg);
2376 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2377 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (target_mgreg_t)));
2378 } else {
2379 /* mov <OFFSET>(%rip), %r10 */
2380 emit_byte (acfg, '\x4d');
2381 emit_byte (acfg, '\x8b');
2382 emit_byte (acfg, '\x15');
2383 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2385 /* jmp *<offset>(%rip) */
2386 emit_byte (acfg, '\xff');
2387 emit_byte (acfg, '\x25');
2388 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4);
2390 #elif defined(TARGET_ARM)
2391 guint8 buf [128];
2392 guint8 *code;
2394 /* This should be exactly 24 bytes long */
2395 *tramp_size = 24;
2396 code = buf;
2397 /* Load rgctx value */
2398 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2399 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2400 /* Load branch addr + branch */
2401 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2402 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2404 g_assert (code - buf == 16);
2406 /* Emit it */
2407 emit_bytes (acfg, buf, code - buf);
2408 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 8);
2409 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 4);
2410 #elif defined(TARGET_ARM64)
2411 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2412 #elif defined(TARGET_POWERPC)
2413 guint8 buf [128];
2414 guint8 *code;
2416 *tramp_size = 4;
2417 code = buf;
2420 * PPC has no ip relative addressing, so we need to compute the address
2421 * of the mscorlib got. That is slow and complex, so instead, we store it
2422 * in the second got slot of every aot image. The caller already computed
2423 * the address of its got and placed it into r30.
2425 emit_unset_mode (acfg);
2426 /* Load mscorlib got address */
2427 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2428 /* Load rgctx */
2429 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2430 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2431 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2432 /* Load target address */
2433 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2434 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2435 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2436 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2437 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2438 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2439 #endif
2440 fprintf (acfg->fp, "mtctr 11\n");
2441 /* Branch to the target address */
2442 fprintf (acfg->fp, "bctr\n");
2444 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2445 *tramp_size = 11 * 4;
2446 #else
2447 *tramp_size = 9 * 4;
2448 #endif
2450 #elif defined(TARGET_X86)
2451 guint8 buf [128];
2452 guint8 *code;
2454 /* Similar to the PPC code above */
2456 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2458 code = buf;
2459 /* Load mscorlib got address */
2460 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2461 /* Load arg */
2462 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2463 /* Branch to the target address */
2464 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2466 emit_bytes (acfg, buf, code - buf);
2468 *tramp_size = 15;
2469 g_assert (code - buf == *tramp_size);
2470 #else
2471 g_assert_not_reached ();
2472 #endif
2476 * arch_emit_imt_trampoline:
2478 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2479 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2480 * key is the IMT key, and ptr holds the address of a memory location holding
2481 * the address to branch to if the IMT arg matches the key. The array is
2482 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2483 * fail_tramp.
2484 * TRAMP_SIZE is set to the size of the emitted trampoline.
2486 static void
2487 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2489 #if defined(TARGET_AMD64)
2490 guint8 *buf, *code;
2491 guint8 *labels [16];
2492 guint8 mov_buf[3];
2493 guint8 *mov_buf_ptr = mov_buf;
2495 const int kSizeOfMove = 7;
2497 code = buf = (guint8 *)g_malloc (256);
2499 /* FIXME: Optimize this, i.e. use binary search etc. */
2500 /* Maybe move the body into a separate function (slower, but much smaller) */
2502 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2504 if (acfg->llvm) {
2505 emit_unset_mode (acfg);
2506 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2509 labels [0] = code;
2510 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2511 labels [1] = code;
2512 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2514 /* Check key */
2515 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (target_mgreg_t));
2516 labels [2] = code;
2517 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2519 /* Loop footer */
2520 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (target_mgreg_t));
2521 amd64_jump_code (code, labels [0]);
2523 /* Match */
2524 mono_amd64_patch (labels [2], code);
2525 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t), sizeof (target_mgreg_t));
2526 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2528 /* No match */
2529 mono_amd64_patch (labels [1], code);
2530 /* Load fail tramp */
2531 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t));
2532 /* Check if there is a fail tramp */
2533 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2534 labels [3] = code;
2535 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2536 /* Jump to fail tramp */
2537 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2539 /* Fail */
2540 mono_amd64_patch (labels [3], code);
2541 x86_breakpoint (code);
2543 if (!acfg->llvm) {
2544 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2545 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2546 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2547 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2548 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2549 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2551 emit_bytes (acfg, buf, code - buf);
2553 *tramp_size = code - buf + kSizeOfMove;
2555 g_free (buf);
2557 #elif defined(TARGET_X86)
2558 guint8 *buf, *code;
2559 guint8 *labels [16];
2561 code = buf = g_malloc (256);
2563 /* Allocate a temporary stack slot */
2564 x86_push_reg (code, X86_EAX);
2565 /* Save EAX */
2566 x86_push_reg (code, X86_EAX);
2568 /* Load mscorlib got address */
2569 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2570 /* Load arg */
2571 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (target_mgreg_t), 4);
2573 labels [0] = code;
2574 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2575 labels [1] = code;
2576 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2578 /* Check key */
2579 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2580 labels [2] = code;
2581 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2583 /* Loop footer */
2584 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (target_mgreg_t));
2585 x86_jump_code (code, labels [0]);
2587 /* Match */
2588 mono_x86_patch (labels [2], code);
2589 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2590 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2591 /* Save the target address to the temporary stack location */
2592 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2593 /* Restore EAX */
2594 x86_pop_reg (code, X86_EAX);
2595 /* Jump to the target address */
2596 x86_ret (code);
2598 /* No match */
2599 mono_x86_patch (labels [1], code);
2600 /* Load fail tramp */
2601 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2602 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2603 labels [3] = code;
2604 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2605 /* Jump to fail tramp */
2606 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2607 x86_pop_reg (code, X86_EAX);
2608 x86_ret (code);
2610 /* Fail */
2611 mono_x86_patch (labels [3], code);
2612 x86_breakpoint (code);
2614 emit_bytes (acfg, buf, code - buf);
2616 *tramp_size = code - buf;
2618 g_free (buf);
2620 #elif defined(TARGET_ARM)
2621 guint8 buf [128];
2622 guint8 *code, *code2, *labels [16];
2624 code = buf;
2626 /* The IMT method is in v5 */
2628 /* Need at least two free registers, plus a slot for storing the pc */
2629 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2630 labels [0] = code;
2631 /* Load the parameter from the GOT */
2632 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2633 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2635 labels [1] = code;
2636 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2637 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2638 labels [2] = code;
2639 ARM_B_COND (code, ARMCOND_EQ, 0);
2641 /* End-of-loop check */
2642 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2643 labels [3] = code;
2644 ARM_B_COND (code, ARMCOND_EQ, 0);
2646 /* Loop footer */
2647 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2648 labels [4] = code;
2649 ARM_B (code, 0);
2650 arm_patch (labels [4], labels [1]);
2652 /* Match */
2653 arm_patch (labels [2], code);
2654 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2655 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2656 /* Save it to the third stack slot */
2657 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2658 /* Restore the registers and branch */
2659 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2661 /* No match */
2662 arm_patch (labels [3], code);
2663 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2664 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2665 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2667 /* Fixup offset */
2668 code2 = labels [0];
2669 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2671 emit_bytes (acfg, buf, code - buf);
2672 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (labels [0] + 8)) - 4);
2674 *tramp_size = code - buf + 4;
2675 #elif defined(TARGET_ARM64)
2676 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2677 #elif defined(TARGET_POWERPC)
2678 guint8 buf [128];
2679 guint8 *code, *labels [16];
2681 code = buf;
2683 /* Load the mscorlib got address */
2684 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r30);
2685 /* Load the parameter from the GOT */
2686 ppc_load (code, ppc_r0, offset * sizeof (target_mgreg_t));
2687 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2689 /* Load and check key */
2690 labels [1] = code;
2691 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2692 ppc_cmp (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2693 labels [2] = code;
2694 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2696 /* End-of-loop check */
2697 ppc_cmpi (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, 0);
2698 labels [3] = code;
2699 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2701 /* Loop footer */
2702 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (target_mgreg_t));
2703 labels [4] = code;
2704 ppc_b (code, 0);
2705 mono_ppc_patch (labels [4], labels [1]);
2707 /* Match */
2708 mono_ppc_patch (labels [2], code);
2709 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r12);
2710 /* r12 now contains the value of the vtable slot */
2711 /* this is not a function descriptor on ppc64 */
2712 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2713 ppc_mtctr (code, ppc_r12);
2714 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2716 /* Fail */
2717 mono_ppc_patch (labels [3], code);
2718 /* FIXME: */
2719 ppc_break (code);
2721 *tramp_size = code - buf;
2723 emit_bytes (acfg, buf, code - buf);
2724 #else
2725 g_assert_not_reached ();
2726 #endif
2730 #if defined (TARGET_AMD64)
2732 static void
2733 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2736 g_assert (acfg->fp);
2737 emit_unset_mode (acfg);
2739 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
2742 #endif
2746 * arch_emit_gsharedvt_arg_trampoline:
2748 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2749 * two GOT slots which contain the argument, and the code to jump to.
2750 * TRAMP_SIZE is set to the size of the emitted trampoline.
2751 * These kinds of trampolines cannot be enumerated statically, since there could
2752 * be one trampoline per method instantiation, so we emit the same code for all
2753 * trampolines, and parameterize them using two GOT slots.
2755 static void
2756 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2758 #if defined(TARGET_X86)
2759 guint8 buf [128];
2760 guint8 *code;
2762 /* Similar to the PPC code above */
2764 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2766 code = buf;
2767 /* Load mscorlib got address */
2768 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2769 /* Load arg */
2770 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2771 /* Branch to the target address */
2772 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2774 emit_bytes (acfg, buf, code - buf);
2776 *tramp_size = 15;
2777 g_assert (code - buf == *tramp_size);
2778 #elif defined(TARGET_ARM)
2779 guint8 buf [128];
2780 guint8 *code;
2782 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2783 /* Similar to arch_emit_specific_trampoline () */
2784 *tramp_size = 24;
2785 code = buf;
2786 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2787 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2788 /* Load the arg value from the GOT */
2789 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2790 /* Load the addr from the GOT */
2791 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2792 /* Branch to it */
2793 ARM_BX (code, ARMREG_R1);
2795 g_assert (code - buf == 20);
2797 /* Emit it */
2798 emit_bytes (acfg, buf, code - buf);
2799 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4);
2800 #elif defined(TARGET_ARM64)
2801 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2802 #elif defined (TARGET_AMD64)
2804 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2805 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2806 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2807 fprintf (acfg->fp, "jmp *%%r11\n");
2809 *tramp_size = 0x11;
2810 #else
2811 g_assert_not_reached ();
2812 #endif
2815 static void
2816 arch_emit_ftnptr_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2818 #if defined(TARGET_ARM)
2819 guint8 buf [128];
2820 guint8 *code;
2822 *tramp_size = 32;
2823 code = buf;
2825 /* Load target address and push it on stack */
2826 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 16);
2827 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2828 ARM_PUSH (code, 1 << ARMREG_IP);
2829 /* Load argument in ARMREG_IP */
2830 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2831 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2832 /* Branch */
2833 ARM_POP (code, 1 << ARMREG_PC);
2835 g_assert (code - buf == 24);
2837 /* Emit it */
2838 emit_bytes (acfg, buf, code - buf);
2839 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) + 12); // offset from ldr pc to addr
2840 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4); // offset from ldr pc to arg
2841 #else
2842 g_assert_not_reached ();
2843 #endif
2846 static void
2847 arch_emit_unbox_arbitrary_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2849 #if defined(TARGET_ARM64)
2850 emit_unset_mode (acfg);
2851 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
2852 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
2853 fprintf (acfg->fp, "br x17\n");
2854 *tramp_size = 5 * 4;
2855 #elif defined (TARGET_AMD64)
2856 guint8 buf [32];
2857 guint8 *code;
2858 int this_reg;
2860 this_reg = mono_arch_get_this_arg_reg (NULL);
2861 code = buf;
2862 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2863 emit_bytes (acfg, buf, code - buf);
2865 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2866 fprintf (acfg->fp, "jmp *%%rax\n");
2868 *tramp_size = 13;
2869 #elif defined (TARGET_ARM)
2870 guint8 buf [32];
2871 guint8 *code, *label;
2873 code = buf;
2874 /* Unbox */
2875 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2877 label = code;
2878 /* Calculate GOT slot */
2879 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
2880 /* Load target addr into PC*/
2881 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2883 g_assert (code - buf == 12);
2885 /* Emit it */
2886 emit_bytes (acfg, buf, code - buf);
2887 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (label + 8)) - 4);
2888 *tramp_size = 4 * 4;
2889 #else
2890 g_error ("NOT IMPLEMENTED: needed for AOT<>interp mixed mode transition");
2891 #endif
2894 /* END OF ARCH SPECIFIC CODE */
2896 static guint32
2897 mono_get_field_token (MonoClassField *field)
2899 MonoClass *klass = field->parent;
2900 int i;
2902 int fcount = mono_class_get_field_count (klass);
2903 MonoClassField *klass_fields = m_class_get_fields (klass);
2904 for (i = 0; i < fcount; ++i) {
2905 if (field == &klass_fields [i])
2906 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2909 g_assert_not_reached ();
2910 return 0;
2913 static inline void
2914 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2916 guint8 *p = buf;
2918 //printf ("ENCODE: %d 0x%x.\n", value, value);
2921 * Same encoding as the one used in the metadata, extended to handle values
2922 * greater than 0x1fffffff.
2924 if ((value >= 0) && (value <= 127))
2925 *p++ = value;
2926 else if ((value >= 0) && (value <= 16383)) {
2927 p [0] = 0x80 | (value >> 8);
2928 p [1] = value & 0xff;
2929 p += 2;
2930 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2931 p [0] = (value >> 24) | 0xc0;
2932 p [1] = (value >> 16) & 0xff;
2933 p [2] = (value >> 8) & 0xff;
2934 p [3] = value & 0xff;
2935 p += 4;
2937 else {
2938 p [0] = 0xff;
2939 p [1] = (value >> 24) & 0xff;
2940 p [2] = (value >> 16) & 0xff;
2941 p [3] = (value >> 8) & 0xff;
2942 p [4] = value & 0xff;
2943 p += 5;
2945 if (endbuf)
2946 *endbuf = p;
2949 static void
2950 stream_init (MonoDynamicStream *sh)
2952 sh->index = 0;
2953 sh->alloc_size = 4096;
2954 sh->data = (char *)g_malloc (4096);
2956 /* So offsets are > 0 */
2957 sh->data [0] = 0;
2958 sh->index ++;
2961 static void
2962 make_room_in_stream (MonoDynamicStream *stream, int size)
2964 if (size <= stream->alloc_size)
2965 return;
2967 while (stream->alloc_size <= size) {
2968 if (stream->alloc_size < 4096)
2969 stream->alloc_size = 4096;
2970 else
2971 stream->alloc_size *= 2;
2974 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2977 static guint32
2978 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2980 guint32 idx;
2982 make_room_in_stream (stream, stream->index + len);
2983 memcpy (stream->data + stream->index, data, len);
2984 idx = stream->index;
2985 stream->index += len;
2986 return idx;
2990 * add_to_blob:
2992 * Add data to the binary blob inside the aot image. Returns the offset inside the
2993 * blob where the data was stored.
2995 static guint32
2996 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2998 g_assert (!acfg->blob_closed);
3000 if (acfg->blob.alloc_size == 0)
3001 stream_init (&acfg->blob);
3003 acfg->stats.blob_size += data_len;
3005 return add_stream_data (&acfg->blob, (char*)data, data_len);
3008 static guint32
3009 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
3011 char buf [4] = {0};
3012 guint32 count;
3014 if (acfg->blob.alloc_size == 0)
3015 stream_init (&acfg->blob);
3017 count = acfg->blob.index % align;
3019 /* we assume the stream data will be aligned */
3020 if (count)
3021 add_stream_data (&acfg->blob, buf, 4 - count);
3023 return add_stream_data (&acfg->blob, (char*)data, data_len);
3026 /* Emit a table of data into the aot image */
3027 static void
3028 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
3030 if (acfg->data_outfile) {
3031 acfg->table_offsets [(int)table] = acfg->datafile_offset;
3032 fwrite (data,1, size, acfg->data_outfile);
3033 acfg->datafile_offset += size;
3034 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
3035 int align = 8 - size % 8;
3036 acfg->datafile_offset += align;
3037 guint8 align_buf [16];
3038 memset (&align_buf, 0, sizeof (align_buf));
3039 fwrite (align_buf, align, 1, acfg->data_outfile);
3040 } else if (acfg->llvm) {
3041 mono_llvm_emit_aot_data (symbol, data, size);
3042 } else {
3043 emit_section_change (acfg, RODATA_SECT, 0);
3044 emit_alignment (acfg, 8);
3045 emit_label (acfg, symbol);
3046 emit_bytes (acfg, data, size);
3051 * emit_offset_table:
3053 * Emit a table of increasing offsets in a compact form using differential encoding.
3054 * There is an index entry for each GROUP_SIZE number of entries. The greater the
3055 * group size, the more compact the table becomes, but the slower it becomes to compute
3056 * a given entry. Returns the size of the table.
3058 static guint32
3059 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
3061 gint32 current_offset;
3062 int i, buf_size, ngroups, index_entry_size;
3063 guint8 *p, *buf;
3064 guint8 *data_p, *data_buf;
3065 guint32 *index_offsets;
3067 ngroups = (noffsets + (group_size - 1)) / group_size;
3069 index_offsets = g_new0 (guint32, ngroups);
3071 buf_size = noffsets * 4;
3072 p = buf = (guint8 *)g_malloc0 (buf_size);
3074 current_offset = 0;
3075 for (i = 0; i < noffsets; ++i) {
3076 //printf ("D: %d -> %d\n", i, offsets [i]);
3077 if ((i % group_size) == 0) {
3078 index_offsets [i / group_size] = p - buf;
3079 /* Emit the full value for these entries */
3080 encode_value (offsets [i], p, &p);
3081 } else {
3082 /* The offsets are allowed to be non-increasing */
3083 //g_assert (offsets [i] >= current_offset);
3084 encode_value (offsets [i] - current_offset, p, &p);
3086 current_offset = offsets [i];
3088 data_buf = buf;
3089 data_p = p;
3091 if (ngroups && index_offsets [ngroups - 1] < 65000)
3092 index_entry_size = 2;
3093 else
3094 index_entry_size = 4;
3096 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
3097 p = buf = (guint8 *)g_malloc0 (buf_size);
3099 /* Emit the header */
3100 encode_int (noffsets, p, &p);
3101 encode_int (group_size, p, &p);
3102 encode_int (ngroups, p, &p);
3103 encode_int (index_entry_size, p, &p);
3105 /* Emit the index */
3106 for (i = 0; i < ngroups; ++i) {
3107 if (index_entry_size == 2)
3108 encode_int16 (index_offsets [i], p, &p);
3109 else
3110 encode_int (index_offsets [i], p, &p);
3112 /* Emit the data */
3113 memcpy (p, data_buf, data_p - data_buf);
3114 p += data_p - data_buf;
3116 g_assert (p - buf <= buf_size);
3118 emit_aot_data (acfg, table, symbol, buf, p - buf);
3120 g_free (buf);
3121 g_free (data_buf);
3123 return (int)(p - buf);
3126 static guint32
3127 get_image_index (MonoAotCompile *cfg, MonoImage *image)
3129 guint32 index;
3131 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
3132 if (index)
3133 return index - 1;
3134 else {
3135 index = g_hash_table_size (cfg->image_hash);
3136 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
3137 g_ptr_array_add (cfg->image_table, image);
3138 return index;
3142 static guint32
3143 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
3145 int i;
3146 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
3148 /* FIXME: Search referenced images as well */
3149 if (!acfg->typespec_classes) {
3150 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
3151 for (i = 0; i < len; i++) {
3152 ERROR_DECL (error);
3153 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
3154 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
3155 if (!is_ok (error)) {
3156 mono_error_cleanup (error);
3157 continue;
3159 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
3162 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
3165 static void
3166 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
3168 static void
3169 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
3171 static void
3172 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
3174 static void
3175 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
3177 static guint32
3178 get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst);
3180 static void
3181 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3183 guint8 *p = buf;
3186 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
3187 * information.
3190 if (mono_class_is_ginst (klass)) {
3191 guint32 token;
3192 g_assert (m_class_get_type_token (klass));
3194 /* Find a typespec for a class if possible */
3195 token = find_typespec_for_class (acfg, klass);
3196 if (token) {
3197 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
3198 encode_value (token, p, &p);
3199 } else {
3200 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
3201 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
3202 static int count = 0;
3203 guint8 *p1 = p;
3205 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
3206 encode_klass_ref (acfg, gclass, p, &p);
3207 guint32 offset = get_shared_ginst_ref (acfg, inst);
3208 encode_value (offset, p, &p);
3210 count += p - p1;
3212 } else if (m_class_get_type_token (klass)) {
3213 int iindex = get_image_index (acfg, m_class_get_image (klass));
3215 g_assert (mono_metadata_token_code (m_class_get_type_token (klass)) == MONO_TOKEN_TYPE_DEF);
3216 if (iindex == 0) {
3217 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
3218 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3219 } else {
3220 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
3221 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3222 encode_value (get_image_index (acfg, m_class_get_image (klass)), p, &p);
3224 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3225 MonoGenericContainer *container = mono_type_get_generic_param_owner (m_class_get_byval_arg (klass));
3226 MonoGenericParam *par = m_class_get_byval_arg (klass)->data.generic_param;
3228 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
3230 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
3231 if (par->gshared_constraint) {
3232 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
3233 encode_type (acfg, par->gshared_constraint, p, &p);
3234 encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
3235 } else {
3236 encode_value (m_class_get_byval_arg (klass)->type, p, &p);
3237 encode_value (mono_type_get_generic_param_num (m_class_get_byval_arg (klass)), p, &p);
3239 encode_value (container->is_anonymous ? 0 : 1, p, &p);
3241 if (!container->is_anonymous) {
3242 encode_value (container->is_method, p, &p);
3243 if (container->is_method)
3244 encode_method_ref (acfg, container->owner.method, p, &p);
3245 else
3246 encode_klass_ref (acfg, container->owner.klass, p, &p);
3249 } else if (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR) {
3250 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
3251 encode_type (acfg, m_class_get_byval_arg (klass), p, &p);
3252 } else {
3253 /* Array class */
3254 g_assert (m_class_get_rank (klass) > 0);
3255 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
3256 encode_value (m_class_get_rank (klass), p, &p);
3257 encode_klass_ref (acfg, m_class_get_element_class (klass), p, &p);
3260 acfg->stats.class_ref_count++;
3261 acfg->stats.class_ref_size += p - buf;
3263 *endbuf = p;
3266 static guint32
3267 get_shared_klass_ref (MonoAotCompile *acfg, MonoClass *klass)
3269 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
3270 guint8 *buf2, *p;
3272 if (!offset) {
3273 buf2 = (guint8 *)g_malloc (1024);
3274 p = buf2;
3276 encode_klass_ref_inner (acfg, klass, p, &p);
3277 g_assert (p - buf2 < 1024);
3279 offset = add_to_blob (acfg, buf2, p - buf2);
3280 g_free (buf2);
3282 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
3283 } else {
3284 offset --;
3287 return offset;
3291 * encode_klass_ref:
3293 * Encode a reference to KLASS. We use our home-grown encoding instead of the
3294 * standard metadata encoding.
3296 static void
3297 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3299 gboolean shared = FALSE;
3302 * The encoding of generic instances is large so emit them only once.
3304 if (mono_class_is_ginst (klass)) {
3305 guint32 token;
3306 g_assert (m_class_get_type_token (klass));
3308 /* Find a typespec for a class if possible */
3309 token = find_typespec_for_class (acfg, klass);
3310 if (!token)
3311 shared = TRUE;
3312 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3313 shared = TRUE;
3316 if (shared) {
3317 guint8 *p;
3318 guint32 offset = get_shared_klass_ref (acfg, klass);
3320 p = buf;
3321 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
3322 encode_value (offset, p, &p);
3323 *endbuf = p;
3324 return;
3327 encode_klass_ref_inner (acfg, klass, buf, endbuf);
3330 static void
3331 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
3333 guint32 token = mono_get_field_token (field);
3334 guint8 *p = buf;
3336 encode_klass_ref (cfg, field->parent, p, &p);
3337 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
3338 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
3339 *endbuf = p;
3342 static void
3343 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3345 guint8 *p = buf;
3346 int i;
3348 encode_value (inst->type_argc, p, &p);
3349 for (i = 0; i < inst->type_argc; ++i)
3350 encode_klass_ref (acfg, mono_class_from_mono_type_internal (inst->type_argv [i]), p, &p);
3352 acfg->stats.ginst_count++;
3353 acfg->stats.ginst_size += p - buf;
3355 *endbuf = p;
3358 static guint32
3359 get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst)
3361 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->ginst_blob_hash, ginst));
3362 if (!offset) {
3363 guint8 *buf2, *p2;
3365 buf2 = (guint8 *)g_malloc (1024);
3366 p2 = buf2;
3368 encode_ginst (acfg, ginst, p2, &p2);
3369 g_assert (p2 - buf2 < 1024);
3371 offset = add_to_blob (acfg, buf2, p2 - buf2);
3372 g_free (buf2);
3374 g_hash_table_insert (acfg->ginst_blob_hash, ginst, GUINT_TO_POINTER (offset + 1));
3375 } else {
3376 offset --;
3378 return offset;
3381 static void
3382 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3384 guint8 *p = buf;
3385 MonoGenericInst *inst;
3386 guint32 flags = (context->class_inst ? 1 : 0) | (context->method_inst ? 2 : 0);
3388 g_assert (flags);
3390 encode_value (flags, p, &p);
3391 inst = context->class_inst;
3392 if (inst) {
3393 guint32 offset = get_shared_ginst_ref (acfg, inst);
3394 encode_value (offset, p, &p);
3396 inst = context->method_inst;
3397 if (inst) {
3398 guint32 offset = get_shared_ginst_ref (acfg, inst);
3399 encode_value (offset, p, &p);
3401 *endbuf = p;
3404 static void
3405 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3407 guint8 *p = buf;
3409 if (t->has_cmods) {
3410 int count = mono_type_custom_modifier_count (t);
3412 *p = MONO_TYPE_CMOD_REQD;
3413 ++p;
3415 encode_value (count, p, &p);
3416 for (int i = 0; i < count; ++i) {
3417 ERROR_DECL (error);
3418 gboolean required;
3419 MonoType *cmod_type = mono_type_get_custom_modifier (t, i, &required, error);
3420 mono_error_assert_ok (error);
3421 encode_value (required, p, &p);
3422 encode_type (acfg, cmod_type, p, &p);
3426 /* t->attrs can be ignored */
3427 //g_assert (t->attrs == 0);
3429 if (t->pinned) {
3430 *p = MONO_TYPE_PINNED;
3431 ++p;
3433 if (t->byref) {
3434 *p = MONO_TYPE_BYREF;
3435 ++p;
3438 *p = t->type;
3439 p ++;
3441 switch (t->type) {
3442 case MONO_TYPE_VOID:
3443 case MONO_TYPE_BOOLEAN:
3444 case MONO_TYPE_CHAR:
3445 case MONO_TYPE_I1:
3446 case MONO_TYPE_U1:
3447 case MONO_TYPE_I2:
3448 case MONO_TYPE_U2:
3449 case MONO_TYPE_I4:
3450 case MONO_TYPE_U4:
3451 case MONO_TYPE_I8:
3452 case MONO_TYPE_U8:
3453 case MONO_TYPE_R4:
3454 case MONO_TYPE_R8:
3455 case MONO_TYPE_I:
3456 case MONO_TYPE_U:
3457 case MONO_TYPE_STRING:
3458 case MONO_TYPE_OBJECT:
3459 case MONO_TYPE_TYPEDBYREF:
3460 break;
3461 case MONO_TYPE_VALUETYPE:
3462 case MONO_TYPE_CLASS:
3463 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3464 break;
3465 case MONO_TYPE_SZARRAY:
3466 encode_klass_ref (acfg, t->data.klass, p, &p);
3467 break;
3468 case MONO_TYPE_PTR:
3469 encode_type (acfg, t->data.type, p, &p);
3470 break;
3471 case MONO_TYPE_GENERICINST: {
3472 MonoClass *gclass = t->data.generic_class->container_class;
3473 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3475 encode_klass_ref (acfg, gclass, p, &p);
3476 encode_ginst (acfg, inst, p, &p);
3477 break;
3479 case MONO_TYPE_ARRAY: {
3480 MonoArrayType *array = t->data.array;
3481 int i;
3483 encode_klass_ref (acfg, array->eklass, p, &p);
3484 encode_value (array->rank, p, &p);
3485 encode_value (array->numsizes, p, &p);
3486 for (i = 0; i < array->numsizes; ++i)
3487 encode_value (array->sizes [i], p, &p);
3488 encode_value (array->numlobounds, p, &p);
3489 for (i = 0; i < array->numlobounds; ++i)
3490 encode_value (array->lobounds [i], p, &p);
3491 break;
3493 case MONO_TYPE_VAR:
3494 case MONO_TYPE_MVAR:
3495 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3496 break;
3497 default:
3498 g_assert_not_reached ();
3501 *endbuf = p;
3504 static void
3505 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3507 guint8 *p = buf;
3508 guint32 flags = 0;
3509 int i;
3511 /* Similar to the metadata encoding */
3512 if (sig->generic_param_count)
3513 flags |= 0x10;
3514 if (sig->hasthis)
3515 flags |= 0x20;
3516 if (sig->explicit_this)
3517 flags |= 0x40;
3518 flags |= (sig->call_convention & 0x0F);
3520 *p = flags;
3521 ++p;
3522 if (sig->generic_param_count)
3523 encode_value (sig->generic_param_count, p, &p);
3524 encode_value (sig->param_count, p, &p);
3526 encode_type (acfg, sig->ret, p, &p);
3527 for (i = 0; i < sig->param_count; ++i) {
3528 if (sig->sentinelpos == i) {
3529 *p = MONO_TYPE_SENTINEL;
3530 ++p;
3532 encode_type (acfg, sig->params [i], p, &p);
3535 *endbuf = p;
3538 #define MAX_IMAGE_INDEX 250
3540 static void
3541 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3543 guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3544 guint32 token = method->token;
3545 MonoJumpInfoToken *ji;
3546 guint8 *p = buf;
3549 * The encoding for most methods is as follows:
3550 * - image index encoded as a leb128
3551 * - token index encoded as a leb128
3552 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3553 * types of method encodings.
3556 /* Mark methods which can't use aot trampolines because they need the further
3557 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3559 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3560 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3561 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3563 if (method->wrapper_type) {
3564 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3566 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3568 encode_value (method->wrapper_type, p, &p);
3570 switch (method->wrapper_type) {
3571 case MONO_WRAPPER_REMOTING_INVOKE:
3572 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3573 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3574 MonoMethod *m;
3576 m = mono_marshal_method_from_wrapper (method);
3577 g_assert (m);
3578 encode_method_ref (acfg, m, p, &p);
3579 break;
3581 case MONO_WRAPPER_PROXY_ISINST:
3582 case MONO_WRAPPER_LDFLD:
3583 case MONO_WRAPPER_LDFLDA:
3584 case MONO_WRAPPER_STFLD: {
3585 g_assert (info);
3586 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3587 break;
3589 case MONO_WRAPPER_ALLOC: {
3590 /* The GC name is saved once in MonoAotFileInfo */
3591 g_assert (info->d.alloc.alloc_type != -1);
3592 encode_value (info->d.alloc.alloc_type, p, &p);
3593 break;
3595 case MONO_WRAPPER_WRITE_BARRIER: {
3596 g_assert (info);
3597 break;
3599 case MONO_WRAPPER_STELEMREF: {
3600 g_assert (info);
3601 encode_value (info->subtype, p, &p);
3602 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3603 encode_value (info->d.virtual_stelemref.kind, p, &p);
3604 break;
3606 case MONO_WRAPPER_OTHER: {
3607 g_assert (info);
3608 encode_value (info->subtype, p, &p);
3609 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3610 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3611 encode_klass_ref (acfg, method->klass, p, &p);
3612 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3613 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3614 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3615 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3616 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
3617 encode_signature (acfg, info->d.interp_in.sig, p, &p);
3618 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3619 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3620 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3621 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3622 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
3623 encode_value (info->d.icall.jit_icall_id, p, &p);
3624 else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT)
3625 encode_value (info->d.aot_init.subtype, p, &p);
3626 break;
3628 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3629 g_assert (info);
3630 encode_value (info->subtype, p, &p);
3631 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3632 encode_value (info->d.icall.jit_icall_id, p, &p);
3633 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3634 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3635 } else {
3636 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3637 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3639 break;
3641 case MONO_WRAPPER_SYNCHRONIZED: {
3642 MonoMethod *m;
3644 m = mono_marshal_method_from_wrapper (method);
3645 g_assert (m);
3646 g_assert (m != method);
3647 encode_method_ref (acfg, m, p, &p);
3648 break;
3650 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3651 g_assert (info);
3652 encode_value (info->subtype, p, &p);
3654 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3655 encode_value (info->d.element_addr.rank, p, &p);
3656 encode_value (info->d.element_addr.elem_size, p, &p);
3657 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3658 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3659 } else {
3660 g_assert_not_reached ();
3662 break;
3664 case MONO_WRAPPER_CASTCLASS: {
3665 g_assert (info);
3666 encode_value (info->subtype, p, &p);
3667 break;
3669 case MONO_WRAPPER_RUNTIME_INVOKE: {
3670 g_assert (info);
3671 encode_value (info->subtype, p, &p);
3672 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3673 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3674 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3675 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3676 break;
3678 case MONO_WRAPPER_DELEGATE_INVOKE:
3679 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3680 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3681 if (method->is_inflated) {
3682 /* These wrappers are identified by their class */
3683 encode_value (1, p, &p);
3684 encode_klass_ref (acfg, method->klass, p, &p);
3685 } else {
3686 MonoMethodSignature *sig = mono_method_signature_internal (method);
3687 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3689 encode_value (0, p, &p);
3690 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3691 encode_value (info ? info->subtype : 0, p, &p);
3692 encode_signature (acfg, sig, p, &p);
3694 break;
3696 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3697 g_assert (info);
3698 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3699 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3700 break;
3702 default:
3703 g_assert_not_reached ();
3705 } else if (mono_method_signature_internal (method)->is_inflated) {
3707 * This is a generic method, find the original token which referenced it and
3708 * encode that.
3709 * Obtain the token from information recorded by the JIT.
3711 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3712 if (ji) {
3713 image_index = get_image_index (acfg, ji->image);
3714 g_assert (image_index < MAX_IMAGE_INDEX);
3715 token = ji->token;
3717 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3718 encode_value (image_index, p, &p);
3719 encode_value (token, p, &p);
3720 } else if (g_hash_table_lookup (acfg->method_blob_hash, method)) {
3721 /* Already emitted as part of an rgctx fetch */
3722 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
3723 offset --;
3725 encode_value ((MONO_AOT_METHODREF_BLOB_INDEX << 24), p, &p);
3726 encode_value (offset, p, &p);
3727 } else {
3728 MonoMethod *declaring;
3729 MonoGenericContext *context = mono_method_get_context (method);
3731 g_assert (method->is_inflated);
3732 declaring = ((MonoMethodInflated*)method)->declaring;
3735 * This might be a non-generic method of a generic instance, which
3736 * doesn't have a token since the reference is generated by the JIT
3737 * like Nullable:Box/Unbox, or by generic sharing.
3739 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3740 /* Encode the klass */
3741 encode_klass_ref (acfg, method->klass, p, &p);
3742 /* Encode the method */
3743 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3744 g_assert (image_index < MAX_IMAGE_INDEX);
3745 g_assert (declaring->token);
3746 token = declaring->token;
3747 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3748 encode_value (image_index, p, &p);
3749 encode_value (mono_metadata_token_index (token), p, &p);
3750 encode_generic_context (acfg, context, p, &p);
3752 } else if (token == 0) {
3753 /* This might be a method of a constructed type like int[,].Set */
3754 /* Obtain the token from information recorded by the JIT */
3755 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3756 if (ji) {
3757 image_index = get_image_index (acfg, ji->image);
3758 g_assert (image_index < MAX_IMAGE_INDEX);
3759 token = ji->token;
3761 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3762 encode_value (image_index, p, &p);
3763 encode_value (token, p, &p);
3764 } else {
3765 /* Array methods */
3766 g_assert (m_class_get_rank (method->klass));
3768 /* Encode directly */
3769 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3770 encode_klass_ref (acfg, method->klass, p, &p);
3771 if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass))
3772 encode_value (0, p, &p);
3773 else if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass) * 2)
3774 encode_value (1, p, &p);
3775 else if (!strcmp (method->name, "Get"))
3776 encode_value (2, p, &p);
3777 else if (!strcmp (method->name, "Address"))
3778 encode_value (3, p, &p);
3779 else if (!strcmp (method->name, "Set"))
3780 encode_value (4, p, &p);
3781 else
3782 g_assert_not_reached ();
3784 } else {
3785 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3787 if (image_index >= MONO_AOT_METHODREF_MIN) {
3788 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3789 encode_value (image_index, p, &p);
3790 encode_value (mono_metadata_token_index (token), p, &p);
3791 } else {
3792 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3796 acfg->stats.method_ref_count++;
3797 acfg->stats.method_ref_size += p - buf;
3799 *endbuf = p;
3802 static guint32
3803 get_shared_method_ref (MonoAotCompile *acfg, MonoMethod *method)
3805 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
3806 if (!offset) {
3807 guint8 *buf2, *p2;
3809 buf2 = (guint8 *)g_malloc (1024);
3810 p2 = buf2;
3812 encode_method_ref (acfg, method, p2, &p2);
3813 g_assert (p2 - buf2 < 1024);
3815 offset = add_to_blob (acfg, buf2, p2 - buf2);
3816 g_free (buf2);
3818 g_hash_table_insert (acfg->method_blob_hash, method, GUINT_TO_POINTER (offset + 1));
3819 } else {
3820 offset --;
3822 return offset;
3825 static gint
3826 compare_patches (gconstpointer a, gconstpointer b)
3828 int i, j;
3830 i = (*(MonoJumpInfo**)a)->ip.i;
3831 j = (*(MonoJumpInfo**)b)->ip.i;
3833 if (i < j)
3834 return -1;
3835 else
3836 if (i > j)
3837 return 1;
3838 else
3839 return 0;
3842 static G_GNUC_UNUSED char*
3843 patch_to_string (MonoJumpInfo *patch_info)
3845 GString *str;
3847 str = g_string_new ("");
3849 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3851 switch (patch_info->type) {
3852 case MONO_PATCH_INFO_VTABLE:
3853 mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
3854 break;
3855 default:
3856 break;
3858 g_string_append_printf (str, ")");
3859 return g_string_free (str, FALSE);
3863 * is_plt_patch:
3865 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3866 * PLT entry.
3868 static inline gboolean
3869 is_plt_patch (MonoJumpInfo *patch_info)
3871 switch (patch_info->type) {
3872 case MONO_PATCH_INFO_METHOD:
3873 case MONO_PATCH_INFO_JIT_ICALL_ID:
3874 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3875 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3876 case MONO_PATCH_INFO_RGCTX_FETCH:
3877 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
3878 return TRUE;
3879 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
3880 default:
3881 return FALSE;
3886 * get_plt_symbol:
3888 * Return the symbol identifying the plt entry PLT_OFFSET.
3890 static char*
3891 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3893 #ifdef TARGET_MACH
3895 * The Apple linker reorganizes object files, so it doesn't like branches to local
3896 * labels, since those have no relocations.
3898 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3899 #else
3900 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3901 #endif
3905 * get_plt_entry:
3907 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3909 static MonoPltEntry*
3910 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3912 MonoPltEntry *res;
3913 gboolean synchronized = FALSE;
3914 static int synchronized_symbol_idx;
3916 if (!is_plt_patch (patch_info))
3917 return NULL;
3919 if (!acfg->patch_to_plt_entry [patch_info->type])
3920 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3921 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3923 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3925 * Allocate a separate PLT slot for each such patch, since some plt
3926 * entries will refer to the method itself, and some will refer to the
3927 * wrapper.
3929 res = NULL;
3930 synchronized = TRUE;
3933 if (!res) {
3934 MonoJumpInfo *new_ji;
3936 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3938 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3939 res->plt_offset = acfg->plt_offset;
3940 res->ji = new_ji;
3941 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3942 if (acfg->aot_opts.write_symbols)
3943 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3944 if (synchronized) {
3945 /* Avoid duplicate symbols because we don't cache */
3946 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3947 if (res->debug_sym)
3948 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3949 synchronized_symbol_idx ++;
3952 if (res->debug_sym)
3953 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3954 else
3955 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3956 if (strstr (res->llvm_symbol, acfg->temp_prefix) == res->llvm_symbol) {
3957 /* The llvm symbol shouldn't be temporary, since the llvm generated object file references it */
3958 char *tmp = res->llvm_symbol;
3959 res->llvm_symbol = g_strdup (res->llvm_symbol + strlen (acfg->temp_prefix));
3960 g_free (tmp);
3963 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3965 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3967 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3968 //mono_print_ji (patch_info); printf ("\n");
3969 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3971 acfg->plt_offset ++;
3974 return res;
3977 static guint32
3978 lookup_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3980 guint32 got_offset;
3981 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3983 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3984 if (got_offset)
3985 return got_offset - 1;
3986 g_assert_not_reached ();
3990 * get_got_offset:
3992 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3993 * JI could be found if it exists, otherwise allocates a new one.
3995 static guint32
3996 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3998 guint32 got_offset;
3999 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
4001 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
4002 if (got_offset)
4003 return got_offset - 1;
4005 if (llvm) {
4006 got_offset = acfg->llvm_got_offset;
4007 acfg->llvm_got_offset ++;
4008 } else {
4009 got_offset = acfg->got_offset;
4010 acfg->got_offset ++;
4013 acfg->stats.got_slots ++;
4014 acfg->stats.got_slot_types [ji->type] ++;
4016 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
4017 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
4018 g_ptr_array_add (info->got_patches, ji);
4020 return got_offset;
4023 /* Add a method to the list of methods which need to be emitted */
4024 static void
4025 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
4027 g_assert (method);
4028 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
4029 g_ptr_array_add (acfg->methods, method);
4030 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
4031 acfg->nmethods = acfg->methods->len + 1;
4034 if (method->wrapper_type || extra) {
4035 int token = mono_metadata_token_index (method->token) - 1;
4036 if (token < 0)
4037 acfg->nextra_methods++;
4038 g_ptr_array_add (acfg->extra_methods, method);
4042 static gboolean
4043 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
4045 /* One instantiation with valuetypes is generated for each async method */
4046 if (m_class_get_image (method->klass) == mono_defaults.corlib && (!strcmp (m_class_get_name (method->klass), "AsyncMethodBuilderCore") || !strcmp (m_class_get_name (method->klass), "AsyncVoidMethodBuilder")))
4047 return TRUE;
4048 else
4049 return FALSE;
4052 static guint32
4053 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
4055 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
4057 g_assert (index);
4059 return index - 1;
4062 static int
4063 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
4065 int index;
4067 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
4068 if (index)
4069 return index - 1;
4071 index = acfg->method_index;
4072 add_method_with_index (acfg, method, index, extra);
4074 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
4076 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
4078 acfg->method_index ++;
4080 return index;
4083 static int
4084 add_method (MonoAotCompile *acfg, MonoMethod *method)
4086 return add_method_full (acfg, method, FALSE, 0);
4089 static void
4090 mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
4092 g_assert (acfg->dedup_stats);
4094 char *name = mono_aot_get_mangled_method_name (method);
4095 g_assert (name);
4097 // For stats
4098 char *stats_name = g_strdup (name);
4100 g_assert (acfg->dedup_cache);
4102 if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
4103 // This AOTCompile owns this method
4104 // We do this to decide whether to write it to disk
4105 // during a dedup run (first phase, where we skip).
4107 // If never changed, then maybe can avoid a recompile
4108 // of the cache.
4110 // Files not read in during last phase.
4111 acfg->dedup_cache_changed = TRUE;
4113 // owns name
4114 g_hash_table_insert (acfg->dedup_cache, name, method);
4115 } else {
4116 // owns name
4117 g_free (name);
4120 guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
4121 count++;
4122 g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
4125 static void
4126 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
4128 ERROR_DECL (error);
4130 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
4131 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
4132 if (!is_ok (error)) {
4133 /* vtype constraint */
4134 mono_error_cleanup (error);
4135 return;
4137 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4138 /* Use the gsharedvt version */
4139 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4140 mono_error_assert_ok (error);
4143 if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
4144 mono_dedup_cache_method (acfg, method);
4146 if (!acfg->dedup_emit_mode)
4147 return;
4150 if (acfg->aot_opts.log_generics)
4151 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4153 add_method_full (acfg, method, TRUE, depth);
4156 static void
4157 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
4159 add_extra_method_with_depth (acfg, method, 0);
4162 static void
4163 add_jit_icall_wrapper (MonoAotCompile *acfg, MonoJitICallInfo *callinfo)
4165 if (!callinfo->sig)
4166 return;
4168 g_assert (callinfo->name && callinfo->func);
4170 add_method (acfg, mono_marshal_get_icall_wrapper (callinfo, TRUE));
4173 #if ENABLE_LLVM
4175 static void
4176 add_lazy_init_wrappers (MonoAotCompile *acfg)
4178 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD));
4179 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_MRGCTX));
4180 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_VTABLE));
4181 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_THIS));
4184 #endif
4186 static MonoMethod*
4187 get_runtime_invoke_sig (MonoMethodSignature *sig)
4189 MonoMethodBuilder *mb;
4190 MonoMethod *m;
4192 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
4193 m = mono_mb_create_method (mb, sig, 16);
4194 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
4195 mono_mb_free (mb);
4196 return invoke;
4199 static MonoMethod*
4200 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
4202 return mono_marshal_get_runtime_invoke (method, virtual_);
4205 static gboolean
4206 can_marshal_struct (MonoClass *klass)
4208 MonoClassField *field;
4209 gboolean can_marshal = TRUE;
4210 gpointer iter = NULL;
4211 MonoMarshalType *info;
4212 int i;
4214 if (mono_class_is_auto_layout (klass))
4215 return FALSE;
4217 info = mono_marshal_load_type_info (klass);
4219 /* Only allow a few field types to avoid asserts in the marshalling code */
4220 while ((field = mono_class_get_fields_internal (klass, &iter))) {
4221 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
4222 continue;
4224 switch (field->type->type) {
4225 case MONO_TYPE_I4:
4226 case MONO_TYPE_U4:
4227 case MONO_TYPE_I1:
4228 case MONO_TYPE_U1:
4229 case MONO_TYPE_BOOLEAN:
4230 case MONO_TYPE_I2:
4231 case MONO_TYPE_U2:
4232 case MONO_TYPE_CHAR:
4233 case MONO_TYPE_I8:
4234 case MONO_TYPE_U8:
4235 case MONO_TYPE_I:
4236 case MONO_TYPE_U:
4237 case MONO_TYPE_PTR:
4238 case MONO_TYPE_R4:
4239 case MONO_TYPE_R8:
4240 case MONO_TYPE_STRING:
4241 break;
4242 case MONO_TYPE_VALUETYPE:
4243 if (!m_class_is_enumtype (mono_class_from_mono_type_internal (field->type)) && !can_marshal_struct (mono_class_from_mono_type_internal (field->type)))
4244 can_marshal = FALSE;
4245 break;
4246 case MONO_TYPE_SZARRAY: {
4247 gboolean has_mspec = FALSE;
4249 if (info) {
4250 for (i = 0; i < info->num_fields; ++i) {
4251 if (info->fields [i].field == field && info->fields [i].mspec)
4252 has_mspec = TRUE;
4255 if (!has_mspec)
4256 can_marshal = FALSE;
4257 break;
4259 default:
4260 can_marshal = FALSE;
4261 break;
4265 /* Special cases */
4266 /* Its hard to compute whenever these can be marshalled or not */
4267 if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
4268 return TRUE;
4270 return can_marshal;
4273 static void
4274 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
4276 /* Create a vtype instantiation */
4277 MonoGenericContext shared_context;
4278 MonoType **args;
4279 MonoGenericInst *inst;
4280 MonoGenericContainer *container;
4281 MonoClass **constraints;
4282 int i;
4284 memset (ctx, 0, sizeof (MonoGenericContext));
4286 if (mono_class_is_gtd (method->klass)) {
4287 shared_context = mono_class_get_generic_container (method->klass)->context;
4288 inst = shared_context.class_inst;
4290 args = g_new0 (MonoType*, inst->type_argc);
4291 for (i = 0; i < inst->type_argc; ++i) {
4292 args [i] = mono_get_int_type ();
4294 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4296 if (method->is_generic) {
4297 container = mono_method_get_generic_container (method);
4298 g_assert (!container->is_anonymous && container->is_method);
4299 shared_context = container->context;
4300 inst = shared_context.method_inst;
4302 args = g_new0 (MonoType*, inst->type_argc);
4303 for (i = 0; i < container->type_argc; ++i) {
4304 MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
4305 gboolean ref_only = FALSE;
4307 if (info && info->constraints) {
4308 constraints = info->constraints;
4310 while (*constraints) {
4311 MonoClass *cklass = *constraints;
4312 if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
4313 /* Inflaring the method with our vtype would not be valid */
4314 ref_only = TRUE;
4315 constraints ++;
4319 if (ref_only)
4320 args [i] = mono_get_object_type ();
4321 else
4322 args [i] = mono_get_int_type ();
4324 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4328 static void
4329 add_gc_wrappers (MonoAotCompile *acfg)
4331 MonoMethod *m;
4332 /* Managed Allocators */
4333 int nallocators = mono_gc_get_managed_allocator_types ();
4334 for (int i = 0; i < nallocators; ++i) {
4335 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
4336 add_method (acfg, m);
4337 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
4338 add_method (acfg, m);
4339 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
4340 add_method (acfg, m);
4343 /* write barriers */
4344 if (mono_gc_is_moving ()) {
4345 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4346 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4350 static gboolean
4351 contains_disable_reflection_attribute (MonoCustomAttrInfo *cattr)
4353 for (int i = 0; i < cattr->num_attrs; ++i) {
4354 MonoCustomAttrEntry *attr = &cattr->attrs [i];
4356 if (!attr->ctor)
4357 return FALSE;
4359 if (strcmp (m_class_get_name_space (attr->ctor->klass), "System.Runtime.CompilerServices"))
4360 return FALSE;
4362 if (strcmp (m_class_get_name (attr->ctor->klass), "DisablePrivateReflectionAttribute"))
4363 return FALSE;
4366 return TRUE;
4369 gboolean
4370 mono_aot_can_specialize (MonoMethod *method)
4372 if (!method)
4373 return FALSE;
4375 if (method->wrapper_type != MONO_WRAPPER_NONE)
4376 return FALSE;
4378 // If it's not private, we can't specialize
4379 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE)
4380 return FALSE;
4382 // If it has the attribute disabling the specialization, we can't specialize
4384 // Set by linker, indicates that the method can be found through reflection
4385 // and that call-site specialization shouldn't be done.
4387 // Important that this attribute is used for *nothing else*
4389 // If future authors make use of it (to disable more optimizations),
4390 // change this place to use a new attribute.
4391 ERROR_DECL (cattr_error);
4392 MonoCustomAttrInfo *cattr = mono_custom_attrs_from_class_checked (method->klass, cattr_error);
4394 if (!is_ok (cattr_error)) {
4395 mono_error_cleanup (cattr_error);
4396 goto cleanup_false;
4397 } else if (cattr && contains_disable_reflection_attribute (cattr)) {
4398 goto cleanup_true;
4401 cattr = mono_custom_attrs_from_method_checked (method, cattr_error);
4403 if (!is_ok (cattr_error)) {
4404 mono_error_cleanup (cattr_error);
4405 goto cleanup_false;
4406 } else if (cattr && contains_disable_reflection_attribute (cattr)) {
4407 goto cleanup_true;
4408 } else {
4409 goto cleanup_false;
4412 cleanup_false:
4413 if (cattr)
4414 mono_custom_attrs_free (cattr);
4415 return FALSE;
4417 cleanup_true:
4418 if (cattr)
4419 mono_custom_attrs_free (cattr);
4420 return TRUE;
4423 static void
4424 add_wrappers (MonoAotCompile *acfg)
4426 MonoMethod *method, *m;
4427 int i, j;
4428 MonoMethodSignature *sig, *csig;
4429 guint32 token;
4432 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
4433 * so there is only one wrapper of a given type, or inlining their contents into their
4434 * callers.
4436 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4437 ERROR_DECL (error);
4438 MonoMethod *method;
4439 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4440 gboolean skip = FALSE;
4442 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4443 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4445 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4446 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4447 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
4448 skip = TRUE;
4450 /* Skip methods which can not be handled by get_runtime_invoke () */
4451 sig = mono_method_signature_internal (method);
4452 if (!sig)
4453 continue;
4454 if ((sig->ret->type == MONO_TYPE_PTR) ||
4455 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
4456 skip = TRUE;
4457 if (mono_class_is_open_constructed_type (sig->ret))
4458 skip = TRUE;
4460 for (j = 0; j < sig->param_count; j++) {
4461 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
4462 skip = TRUE;
4463 if (mono_class_is_open_constructed_type (sig->params [j]))
4464 skip = TRUE;
4467 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4468 if (!mono_class_is_contextbound (method->klass)) {
4469 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
4470 gboolean has_nullable = FALSE;
4472 for (j = 0; j < sig->param_count; j++) {
4473 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (sig->params [j])))
4474 has_nullable = TRUE;
4477 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
4478 /* Supported by the dynamic runtime-invoke wrapper */
4479 skip = TRUE;
4481 if (info)
4482 mono_arch_dyn_call_free (info);
4484 #endif
4486 if (acfg->aot_opts.llvm_only)
4487 /* Supported by the gsharedvt based runtime-invoke wrapper */
4488 skip = TRUE;
4490 if (!skip) {
4491 //printf ("%s\n", mono_method_full_name (method, TRUE));
4492 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4496 if (mono_is_corlib_image (acfg->image->assembly->image)) {
4497 /* Runtime invoke wrappers */
4499 MonoType *void_type = mono_get_void_type ();
4500 MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
4502 /* void runtime-invoke () [.cctor] */
4503 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4504 csig->ret = void_type;
4505 add_method (acfg, get_runtime_invoke_sig (csig));
4507 /* void runtime-invoke () [Finalize] */
4508 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4509 csig->hasthis = 1;
4510 csig->ret = void_type;
4511 add_method (acfg, get_runtime_invoke_sig (csig));
4513 /* void runtime-invoke (string) [exception ctor] */
4514 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4515 csig->hasthis = 1;
4516 csig->ret = void_type;
4517 csig->params [0] = string_type;
4518 add_method (acfg, get_runtime_invoke_sig (csig));
4520 /* void runtime-invoke (string, string) [exception ctor] */
4521 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4522 csig->hasthis = 1;
4523 csig->ret = void_type;
4524 csig->params [0] = string_type;
4525 csig->params [1] = string_type;
4526 add_method (acfg, get_runtime_invoke_sig (csig));
4528 /* string runtime-invoke () [Exception.ToString ()] */
4529 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4530 csig->hasthis = 1;
4531 csig->ret = string_type;
4532 add_method (acfg, get_runtime_invoke_sig (csig));
4534 /* void runtime-invoke (string, Exception) [exception ctor] */
4535 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4536 csig->hasthis = 1;
4537 csig->ret = void_type;
4538 csig->params [0] = string_type;
4539 csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
4540 add_method (acfg, get_runtime_invoke_sig (csig));
4542 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
4543 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4544 csig->hasthis = 1;
4545 csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4546 csig->params [0] = string_type;
4547 csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4548 csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
4549 add_method (acfg, get_runtime_invoke_sig (csig));
4551 /* runtime-invoke used by finalizers */
4552 add_method (acfg, get_runtime_invoke (acfg, get_method_nofail (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4554 /* This is used by mono_runtime_capture_context () */
4555 method = mono_get_context_capture_method ();
4556 if (method)
4557 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4559 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4560 if (!acfg->aot_opts.llvm_only)
4561 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4562 #endif
4564 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4565 if (acfg->aot_opts.llvm_only) {
4566 int variants;
4568 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4569 for (variants = 0; variants < 4; ++variants) {
4570 for (i = 0; i < 40; ++i) {
4571 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4572 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4574 g_free (sig);
4579 /* stelemref */
4580 add_method (acfg, mono_marshal_get_stelemref ());
4582 add_gc_wrappers (acfg);
4584 /* Stelemref wrappers */
4586 MonoMethod **wrappers;
4587 int nwrappers;
4589 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4590 for (i = 0; i < nwrappers; ++i)
4591 add_method (acfg, wrappers [i]);
4592 g_free (wrappers);
4595 /* castclass_with_check wrapper */
4596 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4597 /* isinst_with_check wrapper */
4598 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4600 /* JIT icall wrappers */
4601 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall data */
4602 for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
4603 add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
4607 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4608 * we use the original method instead at runtime.
4609 * Since full-aot doesn't support remoting, this is not a problem.
4611 #if 0
4612 /* remoting-invoke wrappers */
4613 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4614 ERROR_DECL (error);
4615 MonoMethodSignature *sig;
4617 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4618 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4619 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4621 sig = mono_method_signature_internal (method);
4623 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4624 m = mono_marshal_get_remoting_invoke_with_check (method);
4626 add_method (acfg, m);
4629 #endif
4631 /* delegate-invoke wrappers */
4632 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4633 ERROR_DECL (error);
4634 MonoClass *klass;
4636 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4637 klass = mono_class_get_checked (acfg->image, token, error);
4639 if (!klass) {
4640 mono_error_cleanup (error);
4641 continue;
4644 if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4645 continue;
4647 if (!mono_class_is_gtd (klass)) {
4648 method = mono_get_delegate_invoke_internal (klass);
4650 m = mono_marshal_get_delegate_invoke (method, NULL);
4652 add_method (acfg, m);
4654 method = try_get_method_nofail (klass, "BeginInvoke", -1, 0);
4655 if (method)
4656 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4658 method = try_get_method_nofail (klass, "EndInvoke", -1, 0);
4659 if (method)
4660 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4662 MonoCustomAttrInfo *cattr;
4663 cattr = mono_custom_attrs_from_class_checked (klass, error);
4664 if (!is_ok (error)) {
4665 mono_error_cleanup (error);
4666 g_assert (!cattr);
4667 continue;
4670 if (cattr) {
4671 int j;
4673 for (j = 0; j < cattr->num_attrs; ++j)
4674 if (cattr->attrs [j].ctor && (!strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoNativeFunctionWrapperAttribute") || !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "UnmanagedFunctionPointerAttribute")))
4675 break;
4676 if (j < cattr->num_attrs) {
4677 MonoMethod *invoke;
4678 MonoMethod *wrapper;
4679 MonoMethod *del_invoke;
4681 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4682 invoke = mono_get_delegate_invoke_internal (klass);
4683 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4684 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4685 add_method (acfg, wrapper);
4686 add_method (acfg, del_invoke);
4688 mono_custom_attrs_free (cattr);
4690 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4691 ERROR_DECL (error);
4692 MonoGenericContext ctx;
4693 MonoMethod *inst, *gshared;
4696 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4698 /* Invoke */
4699 method = mono_get_delegate_invoke_internal (klass);
4700 create_gsharedvt_inst (acfg, method, &ctx);
4702 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4703 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4705 m = mono_marshal_get_delegate_invoke (inst, NULL);
4706 g_assert (m->is_inflated);
4708 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4709 mono_error_assert_ok (error);
4711 add_extra_method (acfg, gshared);
4713 /* begin-invoke */
4714 method = mono_get_delegate_begin_invoke_internal (klass);
4715 if (method) {
4716 create_gsharedvt_inst (acfg, method, &ctx);
4718 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4719 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4721 m = mono_marshal_get_delegate_begin_invoke (inst);
4722 g_assert (m->is_inflated);
4724 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4725 mono_error_assert_ok (error);
4727 add_extra_method (acfg, gshared);
4730 /* end-invoke */
4731 method = mono_get_delegate_end_invoke_internal (klass);
4732 if (method) {
4733 create_gsharedvt_inst (acfg, method, &ctx);
4735 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4736 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4738 m = mono_marshal_get_delegate_end_invoke (inst);
4739 g_assert (m->is_inflated);
4741 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4742 mono_error_assert_ok (error);
4744 add_extra_method (acfg, gshared);
4749 /* array access wrappers */
4750 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4751 ERROR_DECL (error);
4752 MonoClass *klass;
4754 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4755 klass = mono_class_get_checked (acfg->image, token, error);
4757 if (!klass) {
4758 mono_error_cleanup (error);
4759 continue;
4762 if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
4763 MonoMethod *m, *wrapper;
4765 /* Add runtime-invoke wrappers too */
4767 m = get_method_nofail (klass, "Get", -1, 0);
4768 g_assert (m);
4769 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4770 add_extra_method (acfg, wrapper);
4771 if (!acfg->aot_opts.llvm_only)
4772 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4774 m = get_method_nofail (klass, "Set", -1, 0);
4775 g_assert (m);
4776 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4777 add_extra_method (acfg, wrapper);
4778 if (!acfg->aot_opts.llvm_only)
4779 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4783 /* Synchronized wrappers */
4784 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4785 ERROR_DECL (error);
4786 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4787 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4788 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4790 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4791 if (method->is_generic) {
4792 // FIXME:
4793 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4794 ERROR_DECL (error);
4795 MonoGenericContext ctx;
4796 MonoMethod *inst, *gshared, *m;
4799 * Create a generic wrapper for a generic instance, and AOT that.
4801 create_gsharedvt_inst (acfg, method, &ctx);
4802 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4803 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4804 m = mono_marshal_get_synchronized_wrapper (inst);
4805 g_assert (m->is_inflated);
4806 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4807 mono_error_assert_ok (error);
4809 add_method (acfg, gshared);
4810 } else {
4811 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4816 /* pinvoke wrappers */
4817 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4818 ERROR_DECL (error);
4819 MonoMethod *method;
4820 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4822 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4823 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4825 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4826 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4827 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4830 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4831 if (acfg->aot_opts.llvm_only) {
4832 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4833 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (method), FALSE, TRUE, FALSE);
4838 /* native-to-managed wrappers */
4839 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4840 ERROR_DECL (error);
4841 MonoMethod *method;
4842 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4843 MonoCustomAttrInfo *cattr;
4844 int j;
4846 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4847 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4850 * Only generate native-to-managed wrappers for methods which have an
4851 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4852 * name to avoid defining a new assembly to contain it.
4854 cattr = mono_custom_attrs_from_method_checked (method, error);
4855 if (!is_ok (error)) {
4856 char *name = mono_method_get_full_name (method);
4857 report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
4858 g_free (name);
4861 if (cattr) {
4862 for (j = 0; j < cattr->num_attrs; ++j)
4863 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
4864 break;
4865 if (j < cattr->num_attrs) {
4866 MonoCustomAttrEntry *e = &cattr->attrs [j];
4867 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
4868 const char *p = (const char*)e->data;
4869 const char *named;
4870 int slen, num_named, named_type;
4871 char *n;
4872 MonoType *t;
4873 MonoClass *klass;
4874 char *export_name = NULL;
4875 MonoMethod *wrapper;
4877 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4878 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4879 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See https://docs.microsoft.com/xamarin/ios/internals/limitations#reverse-callbacks",
4880 mono_method_full_name (method, TRUE));
4881 exit (1);
4884 g_assert (sig->param_count == 1);
4885 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type_internal (sig->params [0])), "Type"));
4888 * Decode the cattr manually since we can't create objects
4889 * during aot compilation.
4892 /* Skip prolog */
4893 p += 2;
4895 /* From load_cattr_value () in reflection.c */
4896 slen = mono_metadata_decode_value (p, &p);
4897 n = (char *)g_memdup (p, slen + 1);
4898 n [slen] = 0;
4899 t = mono_reflection_type_from_name_checked (n, acfg->image, error);
4900 g_assert (t);
4901 mono_error_assert_ok (error);
4902 g_free (n);
4904 klass = mono_class_from_mono_type_internal (t);
4905 g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
4907 p += slen;
4909 num_named = read16 (p);
4910 p += 2;
4912 g_assert (num_named < 2);
4913 if (num_named == 1) {
4914 int name_len;
4915 char *name;
4917 /* parse ExportSymbol attribute */
4918 named = p;
4919 named_type = *named;
4920 named += 1;
4921 /* data_type = *named; */
4922 named += 1;
4924 name_len = mono_metadata_decode_blob_size (named, &named);
4925 name = (char *)g_malloc (name_len + 1);
4926 memcpy (name, named, name_len);
4927 name [name_len] = 0;
4928 named += name_len;
4930 g_assert (named_type == 0x54);
4931 g_assert (!strcmp (name, "ExportSymbol"));
4933 /* load_cattr_value (), string case */
4934 MONO_DISABLE_WARNING (4310) // cast truncates constant value
4935 g_assert (*named != (char)0xFF);
4936 MONO_RESTORE_WARNING
4937 slen = mono_metadata_decode_value (named, &named);
4938 export_name = (char *)g_malloc (slen + 1);
4939 memcpy (export_name, named, slen);
4940 export_name [slen] = 0;
4941 named += slen;
4944 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
4945 mono_error_assert_ok (error);
4947 add_method (acfg, wrapper);
4948 if (export_name)
4949 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4951 g_free (cattr);
4954 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4955 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4956 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4960 /* StructureToPtr/PtrToStructure wrappers */
4961 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4962 ERROR_DECL (error);
4963 MonoClass *klass;
4965 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4966 klass = mono_class_get_checked (acfg->image, token, error);
4968 if (!klass) {
4969 mono_error_cleanup (error);
4970 continue;
4973 if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4974 !(m_class_get_nested_in (klass) && strstr (m_class_get_name (m_class_get_nested_in (klass)), "<PrivateImplementationDetails>") == m_class_get_name (m_class_get_nested_in (klass)))) {
4975 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4976 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4981 static gboolean
4982 has_type_vars (MonoClass *klass)
4984 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
4985 return TRUE;
4986 if (m_class_get_rank (klass))
4987 return has_type_vars (m_class_get_element_class (klass));
4988 if (mono_class_is_ginst (klass)) {
4989 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4990 if (context->class_inst) {
4991 int i;
4993 for (i = 0; i < context->class_inst->type_argc; ++i)
4994 if (has_type_vars (mono_class_from_mono_type_internal (context->class_inst->type_argv [i])))
4995 return TRUE;
4998 if (mono_class_is_gtd (klass))
4999 return TRUE;
5000 return FALSE;
5003 static gboolean
5004 is_vt_inst (MonoGenericInst *inst)
5006 int i;
5008 for (i = 0; i < inst->type_argc; ++i) {
5009 MonoType *t = inst->type_argv [i];
5010 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
5011 return TRUE;
5013 return FALSE;
5016 static gboolean
5017 method_has_type_vars (MonoMethod *method)
5019 if (has_type_vars (method->klass))
5020 return TRUE;
5022 if (method->is_inflated) {
5023 MonoGenericContext *context = mono_method_get_context (method);
5024 if (context->method_inst) {
5025 int i;
5027 for (i = 0; i < context->method_inst->type_argc; ++i)
5028 if (has_type_vars (mono_class_from_mono_type_internal (context->method_inst->type_argv [i])))
5029 return TRUE;
5032 return FALSE;
5035 static
5036 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
5038 return opts->mode == MONO_AOT_MODE_FULL;
5041 static
5042 gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
5044 return opts->interp;
5047 static
5048 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
5050 return opts->mode == MONO_AOT_MODE_HYBRID;
5053 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
5055 static void
5056 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
5058 /* This might lead to a huge code blowup so only do it if neccesary */
5059 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
5060 return;
5062 add_generic_class_with_depth (acfg, klass, 0, ref);
5065 static gboolean
5066 check_type_depth (MonoType *t, int depth)
5068 int i;
5070 if (depth > 8)
5071 return TRUE;
5073 switch (t->type) {
5074 case MONO_TYPE_GENERICINST: {
5075 MonoGenericClass *gklass = t->data.generic_class;
5076 MonoGenericInst *ginst = gklass->context.class_inst;
5078 if (ginst) {
5079 for (i = 0; i < ginst->type_argc; ++i) {
5080 if (check_type_depth (ginst->type_argv [i], depth + 1))
5081 return TRUE;
5084 break;
5086 default:
5087 break;
5090 return FALSE;
5093 static void
5094 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
5097 * add_generic_class:
5099 * Add all methods of a generic class.
5101 static void
5102 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
5104 MonoMethod *method;
5105 MonoClassField *field;
5106 gpointer iter;
5107 gboolean use_gsharedvt = FALSE;
5109 if (!acfg->ginst_hash)
5110 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
5112 mono_class_init_internal (klass);
5114 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
5115 return;
5117 if (has_type_vars (klass))
5118 return;
5120 if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
5121 return;
5123 if (mono_class_has_failure (klass))
5124 return;
5126 if (!acfg->ginst_hash)
5127 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
5129 if (g_hash_table_lookup (acfg->ginst_hash, klass))
5130 return;
5132 if (check_type_depth (m_class_get_byval_arg (klass), 0))
5133 return;
5135 if (acfg->aot_opts.log_generics) {
5136 char *s = mono_type_full_name (m_class_get_byval_arg (klass));
5137 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
5138 g_free (s);
5141 g_hash_table_insert (acfg->ginst_hash, klass, klass);
5144 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
5145 * Enable this only for some classes since gsharedvt might not support all methods.
5147 if ((acfg->opts & MONO_OPT_GSHAREDVT) && m_class_get_image (klass) == 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) &&
5148 (!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
5149 use_gsharedvt = TRUE;
5151 iter = NULL;
5152 while ((method = mono_class_get_methods (klass, &iter))) {
5153 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
5155 * This is partial sharing, and we can't handle it yet
5157 continue;
5160 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
5161 /* Already added */
5162 add_types_from_method_header (acfg, method);
5163 continue;
5166 if (method->is_generic)
5167 /* FIXME: */
5168 continue;
5171 * FIXME: Instances which are referenced by these methods are not added,
5172 * for example Array.Resize<int> for List<int>.Add ().
5174 add_extra_method_with_depth (acfg, method, depth + 1);
5177 iter = NULL;
5178 while ((field = mono_class_get_fields_internal (klass, &iter))) {
5179 if (field->type->type == MONO_TYPE_GENERICINST)
5180 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (field->type), depth + 1, "field");
5183 if (m_class_is_delegate (klass)) {
5184 method = mono_get_delegate_invoke_internal (klass);
5186 method = mono_marshal_get_delegate_invoke (method, NULL);
5188 if (acfg->aot_opts.log_generics)
5189 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
5191 add_method (acfg, method);
5194 /* Add superclasses */
5195 if (m_class_get_parent (klass))
5196 add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
5198 const char *klass_name = m_class_get_name (klass);
5199 const char *klass_name_space = m_class_get_name_space (klass);
5200 const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
5202 * For ICollection<T>, add instances of the helper methods
5203 * in Array, since a T[] could be cast to ICollection<T>.
5205 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
5206 (!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"))) {
5207 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5208 MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
5209 gpointer iter;
5210 char *name_prefix;
5212 if (!strcmp (klass_name, "IEnumerator`1"))
5213 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
5214 else
5215 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
5217 /* Add the T[]/InternalEnumerator class */
5218 if (!strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IEnumerator`1")) {
5219 ERROR_DECL (error);
5220 MonoClass *nclass;
5222 iter = NULL;
5223 while ((nclass = mono_class_get_nested_types (m_class_get_parent (array_class), &iter))) {
5224 if (!strcmp (m_class_get_name (nclass), "InternalEnumerator`1"))
5225 break;
5227 g_assert (nclass);
5228 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
5229 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5230 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
5233 iter = NULL;
5234 while ((method = mono_class_get_methods (array_class, &iter))) {
5235 if (!strncmp (method->name, name_prefix, strlen (name_prefix))) {
5236 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
5238 if (m->is_inflated && !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE))
5239 add_extra_method_with_depth (acfg, m, depth);
5243 g_free (name_prefix);
5246 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
5247 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5248 ERROR_DECL (error);
5249 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5250 MonoClass *icomparable, *gcomparer, *icomparable_inst;
5251 MonoGenericContext ctx;
5252 MonoType *args [16];
5254 memset (&ctx, 0, sizeof (ctx));
5256 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
5258 args [0] = m_class_get_byval_arg (tclass);
5259 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5261 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
5262 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5264 if (mono_class_is_assignable_from_internal (icomparable_inst, tclass)) {
5265 MonoClass *gcomparer_inst;
5266 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
5267 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5268 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5270 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
5274 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
5275 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5276 ERROR_DECL (error);
5277 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5278 MonoClass *iface, *gcomparer, *iface_inst;
5279 MonoGenericContext ctx;
5280 MonoType *args [16];
5282 memset (&ctx, 0, sizeof (ctx));
5284 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
5285 g_assert (iface);
5286 args [0] = m_class_get_byval_arg (tclass);
5287 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5289 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
5290 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5292 if (mono_class_is_assignable_from_internal (iface_inst, tclass)) {
5293 MonoClass *gcomparer_inst;
5294 ERROR_DECL (error);
5296 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
5297 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5298 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5299 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
5303 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
5304 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5305 MonoClass *enum_comparer;
5306 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5307 MonoGenericContext ctx;
5308 MonoType *args [16];
5310 if (m_class_is_enumtype (tclass)) {
5311 MonoClass *enum_comparer_inst;
5312 ERROR_DECL (error);
5314 memset (&ctx, 0, sizeof (ctx));
5315 args [0] = m_class_get_byval_arg (tclass);
5316 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5318 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5319 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
5320 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5321 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
5325 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
5326 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5327 MonoClass *comparer;
5328 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5329 MonoGenericContext ctx;
5330 MonoType *args [16];
5332 if (m_class_is_enumtype (tclass)) {
5333 MonoClass *comparer_inst;
5334 ERROR_DECL (error);
5336 memset (&ctx, 0, sizeof (ctx));
5337 args [0] = m_class_get_byval_arg (tclass);
5338 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5340 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
5341 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
5342 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5343 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
5348 static void
5349 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
5351 int i;
5352 MonoGenericContext ctx;
5353 MonoType *args [16];
5355 if (acfg->aot_opts.no_instances)
5356 return;
5358 memset (&ctx, 0, sizeof (ctx));
5360 for (i = 0; i < ninsts; ++i) {
5361 ERROR_DECL (error);
5362 MonoClass *generic_inst;
5363 args [0] = insts [i];
5364 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5365 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
5366 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5367 add_generic_class (acfg, generic_inst, force, "");
5371 static void
5372 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
5374 ERROR_DECL (error);
5375 MonoMethodHeader *header;
5376 MonoMethodSignature *sig;
5377 int j, depth;
5379 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5381 sig = mono_method_signature_internal (method);
5383 if (sig) {
5384 for (j = 0; j < sig->param_count; ++j)
5385 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
5386 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (sig->params [j]), depth + 1, "arg");
5389 header = mono_method_get_header_checked (method, error);
5391 if (header) {
5392 for (j = 0; j < header->num_locals; ++j)
5393 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
5394 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (header->locals [j]), depth + 1, "local");
5395 mono_metadata_free_mh (header);
5396 } else {
5397 mono_error_cleanup (error); /* FIXME report the error */
5403 * add_generic_instances:
5405 * Add instances referenced by the METHODSPEC/TYPESPEC table.
5407 static void
5408 add_generic_instances (MonoAotCompile *acfg)
5410 int i;
5411 guint32 token;
5412 MonoMethod *method;
5413 MonoGenericContext *context;
5415 if (acfg->aot_opts.no_instances)
5416 return;
5418 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
5419 ERROR_DECL (error);
5420 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
5421 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
5423 if (!method) {
5424 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
5425 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
5426 mono_error_cleanup (error);
5427 continue;
5430 if (m_class_get_image (method->klass) != acfg->image)
5431 continue;
5433 context = mono_method_get_context (method);
5435 if (context && ((context->class_inst && context->class_inst->is_open)))
5436 continue;
5439 * For open methods, create an instantiation which can be passed to the JIT.
5440 * FIXME: Handle class_inst as well.
5442 if (context && context->method_inst && context->method_inst->is_open) {
5443 ERROR_DECL (error);
5444 MonoGenericContext shared_context;
5445 MonoGenericInst *inst;
5446 MonoType **type_argv;
5447 int i;
5448 MonoMethod *declaring_method;
5449 gboolean supported = TRUE;
5451 /* Check that the context doesn't contain open constructed types */
5452 if (context->class_inst) {
5453 inst = context->class_inst;
5454 for (i = 0; i < inst->type_argc; ++i) {
5455 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)
5456 continue;
5457 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5458 supported = FALSE;
5461 if (context->method_inst) {
5462 inst = context->method_inst;
5463 for (i = 0; i < inst->type_argc; ++i) {
5464 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)
5465 continue;
5466 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5467 supported = FALSE;
5471 if (!supported)
5472 continue;
5474 memset (&shared_context, 0, sizeof (MonoGenericContext));
5476 inst = context->class_inst;
5477 if (inst) {
5478 type_argv = g_new0 (MonoType*, inst->type_argc);
5479 for (i = 0; i < inst->type_argc; ++i) {
5480 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)
5481 type_argv [i] = mono_get_object_type ();
5482 else
5483 type_argv [i] = inst->type_argv [i];
5486 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5487 g_free (type_argv);
5490 inst = context->method_inst;
5491 if (inst) {
5492 type_argv = g_new0 (MonoType*, inst->type_argc);
5493 for (i = 0; i < inst->type_argc; ++i) {
5494 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)
5495 type_argv [i] = mono_get_object_type ();
5496 else
5497 type_argv [i] = inst->type_argv [i];
5500 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5501 g_free (type_argv);
5504 if (method->is_generic || mono_class_is_gtd (method->klass))
5505 declaring_method = method;
5506 else
5507 declaring_method = mono_method_get_declaring_generic_method (method);
5509 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
5510 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5514 * If the method is fully sharable, it was already added in place of its
5515 * generic definition.
5517 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
5518 continue;
5521 * FIXME: Partially shared methods are not shared here, so we end up with
5522 * many identical methods.
5524 add_extra_method (acfg, method);
5527 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
5528 ERROR_DECL (error);
5529 MonoClass *klass;
5531 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
5533 klass = mono_class_get_checked (acfg->image, token, error);
5534 if (!klass || m_class_get_rank (klass)) {
5535 mono_error_cleanup (error);
5536 continue;
5539 add_generic_class (acfg, klass, FALSE, "typespec");
5542 /* Add types of args/locals */
5543 for (i = 0; i < acfg->methods->len; ++i) {
5544 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5545 add_types_from_method_header (acfg, method);
5548 if (acfg->image == mono_defaults.corlib) {
5549 MonoClass *klass;
5550 MonoType *insts [256];
5551 int ninsts = 0;
5553 MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
5554 MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
5555 MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
5556 MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
5557 MonoType *int32_type = mono_get_int32_type ();
5558 MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
5559 MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
5560 MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
5561 MonoType *object_type = mono_get_object_type ();
5563 insts [ninsts ++] = byte_type;
5564 insts [ninsts ++] = sbyte_type;
5565 insts [ninsts ++] = int16_type;
5566 insts [ninsts ++] = uint16_type;
5567 insts [ninsts ++] = int32_type;
5568 insts [ninsts ++] = uint32_type;
5569 insts [ninsts ++] = int64_type;
5570 insts [ninsts ++] = uint64_type;
5571 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
5572 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
5573 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
5574 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
5576 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5577 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5578 if (klass)
5579 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5580 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5581 if (klass)
5582 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5584 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5586 MonoClass *enum_comparer;
5587 MonoType *insts [16];
5588 int ninsts;
5590 ninsts = 0;
5591 insts [ninsts ++] = int32_type;
5592 insts [ninsts ++] = uint32_type;
5593 insts [ninsts ++] = uint16_type;
5594 insts [ninsts ++] = byte_type;
5595 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5596 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5598 ninsts = 0;
5599 insts [ninsts ++] = int16_type;
5600 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5601 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5603 ninsts = 0;
5604 insts [ninsts ++] = sbyte_type;
5605 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5606 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5608 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5609 ninsts = 0;
5610 insts [ninsts ++] = int64_type;
5611 insts [ninsts ++] = uint64_type;
5612 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5615 /* Add instances of the array generic interfaces for primitive types */
5616 /* This will add instances of the InternalArray_ helper methods in Array too */
5617 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5618 if (klass)
5619 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5621 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5622 if (klass)
5623 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5625 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5626 if (klass)
5627 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5630 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5631 * used for all instances of GetGenericValueImpl by the AOT runtime.
5634 ERROR_DECL (error);
5635 MonoGenericContext ctx;
5636 MonoType *args [16];
5637 MonoMethod *get_method;
5638 MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
5640 get_method = mono_class_get_method_from_name_checked (array_klass, "GetGenericValueImpl", 2, 0, error);
5641 mono_error_assert_ok (error);
5643 if (get_method) {
5644 memset (&ctx, 0, sizeof (ctx));
5645 args [0] = object_type;
5646 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5647 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
5648 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5652 /* Same for CompareExchange<T>/Exchange<T> */
5654 MonoGenericContext ctx;
5655 MonoType *args [16];
5656 MonoMethod *m;
5657 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5658 gpointer iter = NULL;
5660 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5661 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5662 ERROR_DECL (error);
5663 memset (&ctx, 0, sizeof (ctx));
5664 args [0] = object_type;
5665 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5666 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5667 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5672 /* object[] accessor wrappers. */
5673 for (i = 1; i < 4; ++i) {
5674 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
5675 MonoMethod *m;
5677 m = get_method_nofail (obj_array_class, "Get", i, 0);
5678 g_assert (m);
5680 m = mono_marshal_get_array_accessor_wrapper (m);
5681 add_extra_method (acfg, m);
5683 m = get_method_nofail (obj_array_class, "Address", i, 0);
5684 g_assert (m);
5686 m = mono_marshal_get_array_accessor_wrapper (m);
5687 add_extra_method (acfg, m);
5689 m = get_method_nofail (obj_array_class, "Set", i + 1, 0);
5690 g_assert (m);
5692 m = mono_marshal_get_array_accessor_wrapper (m);
5693 add_extra_method (acfg, m);
5698 static char *
5699 decode_direct_icall_symbol_name_attribute (MonoMethod *method)
5701 ERROR_DECL (error);
5703 int j = 0;
5704 char *symbol_name = NULL;
5706 MonoCustomAttrInfo *cattr = mono_custom_attrs_from_method_checked (method, error);
5707 if (mono_error_ok(error) && cattr) {
5708 for (j = 0; j < cattr->num_attrs; j++)
5709 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoDirectICallSymbolNameAttribute"))
5710 break;
5712 if (j < cattr->num_attrs) {
5713 MonoCustomAttrEntry *e = &cattr->attrs [j];
5714 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
5715 if (e->data && sig && sig->param_count == 1 && sig->params [0]->type == MONO_TYPE_STRING) {
5717 * Decode the cattr manually since we can't create objects
5718 * during aot compilation.
5721 /* Skip prolog */
5722 const char *p = ((const char*)e->data) + 2;
5723 int slen = mono_metadata_decode_value (p, &p);
5725 symbol_name = (char *)g_memdup (p, slen + 1);
5726 if (symbol_name)
5727 symbol_name [slen] = 0;
5732 return symbol_name;
5734 static const char*
5735 lookup_external_icall_symbol_name_aot (MonoMethod *method)
5737 g_assert (method_to_external_icall_symbol_name);
5739 gpointer key, value;
5740 if (g_hash_table_lookup_extended (method_to_external_icall_symbol_name, method, &key, &value))
5741 return (const char*)value;
5743 char *symbol_name = decode_direct_icall_symbol_name_attribute (method);
5744 g_hash_table_insert (method_to_external_icall_symbol_name, method, symbol_name);
5746 return symbol_name;
5749 static const char*
5750 lookup_icall_symbol_name_aot (MonoMethod *method)
5752 const char * symbol_name = mono_lookup_icall_symbol (method);
5753 if (!symbol_name)
5754 symbol_name = lookup_external_icall_symbol_name_aot (method);
5756 return symbol_name;
5759 gboolean
5760 mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
5762 gboolean enable_icall = FALSE;
5763 if (cfg->compile_aot)
5764 enable_icall = lookup_external_icall_symbol_name_aot (method) ? TRUE : FALSE;
5765 else
5766 enable_icall = FALSE;
5768 return enable_icall;
5772 * is_direct_callable:
5774 * Return whenever the method identified by JI is directly callable without
5775 * going through the PLT.
5777 static gboolean
5778 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5780 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5781 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5782 if (callee_cfg) {
5783 gboolean direct_callable = TRUE;
5785 if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
5786 direct_callable = FALSE;
5788 if (direct_callable && (!acfg->llvm || acfg->aot_opts.llvm_disable_self_init) && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5789 direct_callable = FALSE;
5791 if (direct_callable && !strcmp (callee_cfg->method->name, ".cctor"))
5792 direct_callable = FALSE;
5795 // FIXME: Support inflated methods, it asserts in mini_llvm_init_gshared_method_this () because the method is not in
5796 // amodule->extra_methods.
5798 if (direct_callable && callee_cfg->method->is_inflated)
5799 direct_callable = FALSE;
5801 if (direct_callable && (callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5802 // FIXME: Maybe call the wrapper directly ?
5803 direct_callable = FALSE;
5805 if (direct_callable && (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls)) {
5806 /* Disable this so all calls go through load_method (), see the
5807 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5808 * mono_debugger_agent_init ().
5810 direct_callable = FALSE;
5813 if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC))
5814 /* sgen does some initialization when the allocator method is created */
5815 direct_callable = FALSE;
5816 if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER))
5817 /* we don't know at compile time whether sgen is concurrent or not */
5818 direct_callable = FALSE;
5820 if (direct_callable)
5821 return TRUE;
5823 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5824 if (acfg->aot_opts.direct_pinvoke)
5825 return TRUE;
5826 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5827 if (acfg->aot_opts.direct_icalls)
5828 return TRUE;
5829 return FALSE;
5832 return FALSE;
5835 #ifdef MONO_ARCH_AOT_SUPPORTED
5836 static const char *
5837 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5839 MonoImage *image = m_class_get_image (method->klass);
5840 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5841 MonoTableInfo *tables = image->tables;
5842 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5843 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5844 guint32 im_cols [MONO_IMPLMAP_SIZE];
5845 char *import;
5847 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5848 if (import != NULL)
5849 return import;
5851 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5852 return NULL;
5854 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5856 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5857 return NULL;
5859 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5861 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5863 return import;
5865 #else
5866 static const char *
5867 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5869 return NULL;
5871 #endif
5873 static gint
5874 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5876 if (a->native_offset == b->native_offset)
5877 return a->il_offset - b->il_offset;
5878 else
5879 return a->native_offset - b->native_offset;
5883 * compute_line_numbers:
5885 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5886 * entry.
5888 static MonoDebugSourceLocation**
5889 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5891 MonoDebugMethodInfo *minfo;
5892 MonoDebugLineNumberEntry *ln_array;
5893 MonoDebugSourceLocation *loc;
5894 int i, prev_line, prev_il_offset;
5895 int *native_to_il_offset = NULL;
5896 MonoDebugSourceLocation **res;
5897 gboolean first;
5899 minfo = mono_debug_lookup_method (method);
5900 if (!minfo)
5901 return NULL;
5902 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5903 if (debug_info->code_size != code_size)
5904 return NULL;
5906 g_assert (code_size);
5908 /* Compute the native->IL offset mapping */
5910 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5911 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5913 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5915 native_to_il_offset = g_new0 (int, code_size + 1);
5917 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5918 int j;
5919 MonoDebugLineNumberEntry *lne = &ln_array [i];
5921 if (i == 0) {
5922 for (j = 0; j < lne->native_offset; ++j)
5923 native_to_il_offset [j] = -1;
5926 if (i < debug_info->num_line_numbers - 1) {
5927 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5929 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5930 native_to_il_offset [j] = lne->il_offset;
5931 } else {
5932 for (j = lne->native_offset; j < code_size; ++j)
5933 native_to_il_offset [j] = lne->il_offset;
5936 g_free (ln_array);
5938 /* Compute the native->line number mapping */
5939 res = g_new0 (MonoDebugSourceLocation*, code_size);
5940 prev_il_offset = -1;
5941 prev_line = -1;
5942 first = TRUE;
5943 for (i = 0; i < code_size; ++i) {
5944 int il_offset = native_to_il_offset [i];
5946 if (il_offset == -1 || il_offset == prev_il_offset)
5947 continue;
5948 prev_il_offset = il_offset;
5949 loc = mono_debug_method_lookup_location (minfo, il_offset);
5950 if (!(loc && loc->source_file))
5951 continue;
5952 if (loc->row == prev_line) {
5953 mono_debug_free_source_location (loc);
5954 continue;
5956 prev_line = loc->row;
5957 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5958 if (first)
5959 /* This will cover the prolog too */
5960 res [0] = loc;
5961 else
5962 res [i] = loc;
5963 first = FALSE;
5965 return res;
5968 static int
5969 get_file_index (MonoAotCompile *acfg, const char *source_file)
5971 int findex;
5973 // FIXME: Free these
5974 if (!acfg->dwarf_ln_filenames)
5975 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5976 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5977 if (!findex) {
5978 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5979 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5980 emit_unset_mode (acfg);
5981 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5983 return findex;
5986 #ifdef TARGET_ARM64
5987 #define INST_LEN 4
5988 #else
5989 #define INST_LEN 1
5990 #endif
5993 * emit_and_reloc_code:
5995 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5996 * is true, calls are made through the GOT too. This is used for emitting trampolines
5997 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5998 * since trampolines are needed to make PLT work.
6000 static void
6001 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
6003 int i, pindex, start_index;
6004 GPtrArray *patches;
6005 MonoJumpInfo *patch_info;
6006 MonoDebugSourceLocation **locs = NULL;
6007 gboolean skip, prologue_end = FALSE;
6008 #ifdef MONO_ARCH_AOT_SUPPORTED
6009 gboolean direct_call, external_call;
6010 guint32 got_slot;
6011 const char *direct_call_target = 0;
6012 const char *direct_pinvoke;
6013 #endif
6015 if (acfg->gas_line_numbers && method && debug_info) {
6016 locs = compute_line_numbers (method, code_len, debug_info);
6017 if (!locs) {
6018 int findex = get_file_index (acfg, "<unknown>");
6019 emit_unset_mode (acfg);
6020 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
6024 /* Collect and sort relocations */
6025 patches = g_ptr_array_new ();
6026 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
6027 g_ptr_array_add (patches, patch_info);
6028 g_ptr_array_sort (patches, compare_patches);
6030 start_index = 0;
6031 for (i = 0; i < code_len; i += INST_LEN) {
6032 patch_info = NULL;
6033 for (pindex = start_index; pindex < patches->len; ++pindex) {
6034 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6035 if (patch_info->ip.i >= i)
6036 break;
6039 if (locs && locs [i]) {
6040 MonoDebugSourceLocation *loc = locs [i];
6041 int findex;
6042 const char *options;
6044 findex = get_file_index (acfg, loc->source_file);
6045 emit_unset_mode (acfg);
6046 if (!prologue_end)
6047 options = " prologue_end";
6048 else
6049 options = "";
6050 prologue_end = TRUE;
6051 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
6052 mono_debug_free_source_location (loc);
6055 skip = FALSE;
6056 #ifdef MONO_ARCH_AOT_SUPPORTED
6057 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
6058 start_index = pindex;
6060 switch (patch_info->type) {
6061 case MONO_PATCH_INFO_NONE:
6062 break;
6063 case MONO_PATCH_INFO_GOT_OFFSET: {
6064 int code_size;
6066 arch_emit_got_offset (acfg, code + i, &code_size);
6067 i += code_size - INST_LEN;
6068 skip = TRUE;
6069 patch_info->type = MONO_PATCH_INFO_NONE;
6070 break;
6072 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
6073 int code_size, index;
6074 char *selector = (char *)patch_info->data.target;
6076 if (!acfg->objc_selector_to_index)
6077 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
6078 if (!acfg->objc_selectors)
6079 acfg->objc_selectors = g_ptr_array_new ();
6080 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
6081 if (index)
6082 index --;
6083 else {
6084 index = acfg->objc_selector_index;
6085 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
6086 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
6087 acfg->objc_selector_index ++;
6090 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
6091 i += code_size - INST_LEN;
6092 skip = TRUE;
6093 patch_info->type = MONO_PATCH_INFO_NONE;
6094 break;
6096 default: {
6098 * If this patch is a call, try emitting a direct call instead of
6099 * through a PLT entry. This is possible if the called method is in
6100 * the same assembly and requires no initialization.
6102 direct_call = FALSE;
6103 external_call = FALSE;
6104 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
6105 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
6106 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
6108 // Don't compile inflated methods if we're doing dedup
6109 if (acfg->aot_opts.dedup && !mono_aot_can_dedup (patch_info->data.method)) {
6110 char *name = mono_aot_get_mangled_method_name (patch_info->data.method);
6111 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
6112 g_free (name);
6114 direct_call = TRUE;
6115 direct_call_target = callee_cfg->asm_symbol;
6116 patch_info->type = MONO_PATCH_INFO_NONE;
6117 acfg->stats.direct_calls ++;
6121 acfg->stats.all_calls ++;
6122 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
6123 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
6124 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
6125 direct_pinvoke = lookup_icall_symbol_name_aot (patch_info->data.method);
6126 else
6127 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
6128 if (direct_pinvoke) {
6129 direct_call = TRUE;
6130 g_assert (strlen (direct_pinvoke) < 1000);
6131 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
6134 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
6135 const char *sym = mono_find_jit_icall_info (patch_info->data.jit_icall_id)->c_symbol;
6136 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
6137 /* Call to a C function implementing a jit icall */
6138 direct_call = TRUE;
6139 external_call = TRUE;
6140 g_assert (strlen (sym) < 1000);
6141 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
6143 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ID) {
6144 MonoJitICallInfo * const info = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
6145 const char * const sym = info->c_symbol;
6146 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
6147 /* Call to a jit icall without a wrapper */
6148 direct_call = TRUE;
6149 external_call = TRUE;
6150 g_assert (strlen (sym) < 1000);
6151 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
6154 if (direct_call) {
6155 patch_info->type = MONO_PATCH_INFO_NONE;
6156 acfg->stats.direct_calls ++;
6159 if (!got_only && !direct_call) {
6160 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
6161 if (plt_entry) {
6162 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
6163 direct_call = TRUE;
6164 direct_call_target = plt_entry->symbol;
6166 /* Nullify the patch */
6167 patch_info->type = MONO_PATCH_INFO_NONE;
6168 plt_entry->jit_used = TRUE;
6172 if (direct_call) {
6173 int call_size;
6175 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
6176 i += call_size - INST_LEN;
6177 } else {
6178 int code_size;
6180 got_slot = get_got_offset (acfg, FALSE, patch_info);
6182 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
6183 i += code_size - INST_LEN;
6185 skip = TRUE;
6189 #endif /* MONO_ARCH_AOT_SUPPORTED */
6191 if (!skip) {
6192 /* Find next patch */
6193 patch_info = NULL;
6194 for (pindex = start_index; pindex < patches->len; ++pindex) {
6195 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6196 if (patch_info->ip.i >= i)
6197 break;
6200 /* Try to emit multiple bytes at once */
6201 if (pindex < patches->len && patch_info->ip.i > i) {
6202 int limit;
6204 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
6205 if (locs && locs [limit])
6206 break;
6209 emit_code_bytes (acfg, code + i, limit - i);
6210 i = limit - INST_LEN;
6211 } else {
6212 emit_code_bytes (acfg, code + i, INST_LEN);
6217 g_ptr_array_free (patches, TRUE);
6218 g_free (locs);
6222 * sanitize_symbol:
6224 * Return a modified version of S which only includes characters permissible in symbols.
6226 static char*
6227 sanitize_symbol (MonoAotCompile *acfg, char *s)
6229 gboolean process = FALSE;
6230 int i, len;
6231 GString *gs;
6232 char *res;
6234 if (!s)
6235 return s;
6237 len = strlen (s);
6238 for (i = 0; i < len; ++i)
6239 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
6240 process = TRUE;
6241 if (!process)
6242 return s;
6244 gs = g_string_sized_new (len);
6245 for (i = 0; i < len; ++i) {
6246 guint8 c = s [i];
6247 if (c <= 0x7f && (isalnum (c) || c == '_')) {
6248 g_string_append_c (gs, c);
6249 } else if (c > 0x7f) {
6250 /* multi-byte utf8 */
6251 g_string_append_printf (gs, "_0x%x", c);
6252 i ++;
6253 c = s [i];
6254 while (c >> 6 == 0x2) {
6255 g_string_append_printf (gs, "%x", c);
6256 i ++;
6257 c = s [i];
6259 g_string_append_printf (gs, "_");
6260 i --;
6261 } else {
6262 g_string_append_c (gs, '_');
6266 res = mono_mempool_strdup (acfg->mempool, gs->str);
6267 g_string_free (gs, TRUE);
6268 return res;
6271 static char*
6272 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
6274 char *name1, *name2, *cached;
6275 int i, j, len, count;
6276 MonoMethod *cached_method;
6278 name1 = mono_method_full_name (method, TRUE);
6280 #ifdef TARGET_MACH
6281 // This is so that we don't accidentally create a local symbol (which starts with 'L')
6282 if ((!prefix || !*prefix) && name1 [0] == 'L')
6283 prefix = "_";
6284 #endif
6286 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6287 char adjustedPrefix [MAX_SYMBOL_SIZE];
6288 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
6289 #endif
6291 len = strlen (name1);
6292 name2 = (char *) g_malloc (strlen (prefix) + len + 16);
6293 memcpy (name2, prefix, strlen (prefix));
6294 j = strlen (prefix);
6295 for (i = 0; i < len; ++i) {
6296 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
6297 name2 [j ++] = '_';
6298 } else if (isalnum (name1 [i])) {
6299 name2 [j ++] = name1 [i];
6300 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
6301 i += 2;
6302 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
6303 name2 [j ++] = '_';
6304 i++;
6305 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
6306 } else
6307 name2 [j ++] = '_';
6309 name2 [j] = '\0';
6311 g_free (name1);
6313 count = 0;
6314 while (TRUE) {
6315 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
6316 if (!(cached_method && cached_method != method))
6317 break;
6318 sprintf (name2 + j, "_%d", count);
6319 count ++;
6322 cached = g_strdup (name2);
6323 g_hash_table_insert (cache, cached, method);
6325 return name2;
6328 static void
6329 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
6331 MonoMethod *method;
6332 int method_index;
6333 guint8 *code;
6334 char *debug_sym = NULL;
6335 char *symbol = NULL;
6336 int func_alignment = AOT_FUNC_ALIGNMENT;
6337 char *export_name;
6339 g_assert (!ignore_cfg (cfg));
6341 method = cfg->orig_method;
6342 code = cfg->native_code;
6344 method_index = get_method_index (acfg, method);
6345 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
6347 /* Make the labels local */
6348 emit_section_change (acfg, ".text", 0);
6349 emit_alignment_code (acfg, func_alignment);
6351 if (acfg->global_symbols && acfg->need_no_dead_strip)
6352 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
6354 emit_label (acfg, cfg->asm_symbol);
6356 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
6358 * Write a C style symbol for every method, this has two uses:
6359 * - it works on platforms where the dwarf debugging info is not
6360 * yet supported.
6361 * - it allows the setting of breakpoints of aot-ed methods.
6364 // Comment out to force dedup to link these symbols and forbid compiling
6365 // in duplicated code. This is an "assert when linking if broken" trick.
6366 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6367 /*debug_sym = mono_aot_get_mangled_method_name (method);*/
6368 /*else*/
6369 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
6371 cfg->asm_debug_symbol = g_strdup (debug_sym);
6373 if (acfg->need_no_dead_strip)
6374 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6376 // Comment out to force dedup to link these symbols and forbid compiling
6377 // in duplicated code. This is an "assert when linking if broken" trick.
6378 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6379 /*emit_global_inner (acfg, debug_sym, TRUE);*/
6380 /*else*/
6381 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
6383 emit_label (acfg, debug_sym);
6386 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
6387 if (export_name) {
6388 /* Emit a global symbol for the method */
6389 emit_global_inner (acfg, export_name, TRUE);
6390 emit_label (acfg, export_name);
6393 if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
6394 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
6396 acfg->stats.code_size += cfg->code_len;
6398 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
6400 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 ()));
6402 emit_line (acfg);
6404 if (acfg->aot_opts.write_symbols) {
6405 if (debug_sym)
6406 emit_symbol_size (acfg, debug_sym, ".");
6407 else
6408 emit_symbol_size (acfg, cfg->asm_symbol, ".");
6409 g_free (debug_sym);
6412 emit_label (acfg, symbol);
6414 arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
6416 g_free (symbol);
6420 * encode_patch:
6422 * Encode PATCH_INFO into its disk representation.
6424 static void
6425 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
6427 guint8 *p = buf;
6429 switch (patch_info->type) {
6430 case MONO_PATCH_INFO_NONE:
6431 break;
6432 case MONO_PATCH_INFO_IMAGE:
6433 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
6434 break;
6435 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
6436 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6437 case MONO_PATCH_INFO_GC_NURSERY_START:
6438 case MONO_PATCH_INFO_GC_NURSERY_BITS:
6439 break;
6440 case MONO_PATCH_INFO_SWITCH: {
6441 gpointer *table = (gpointer *)patch_info->data.table->table;
6442 int k;
6444 encode_value (patch_info->data.table->table_size, p, &p);
6445 for (k = 0; k < patch_info->data.table->table_size; k++)
6446 encode_value ((int)(gssize)table [k], p, &p);
6447 break;
6449 case MONO_PATCH_INFO_METHODCONST:
6450 case MONO_PATCH_INFO_METHOD:
6451 case MONO_PATCH_INFO_METHOD_JUMP:
6452 case MONO_PATCH_INFO_METHOD_FTNDESC:
6453 case MONO_PATCH_INFO_ICALL_ADDR:
6454 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
6455 case MONO_PATCH_INFO_METHOD_RGCTX:
6456 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
6457 encode_method_ref (acfg, patch_info->data.method, p, &p);
6458 break;
6459 case MONO_PATCH_INFO_AOT_JIT_INFO:
6460 case MONO_PATCH_INFO_CASTCLASS_CACHE:
6461 encode_value (patch_info->data.index, p, &p);
6462 break;
6463 case MONO_PATCH_INFO_JIT_ICALL_ID:
6464 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6465 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
6466 encode_value (patch_info->data.jit_icall_id, p, &p);
6467 break;
6468 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
6469 encode_value (patch_info->data.uindex, p, &p);
6470 break;
6471 case MONO_PATCH_INFO_LDSTR_LIT: {
6472 guint32 len = strlen (patch_info->data.name);
6473 encode_value (len, p, &p);
6474 memcpy (p, patch_info->data.name, len + 1);
6475 p += len + 1;
6476 break;
6478 case MONO_PATCH_INFO_LDSTR: {
6479 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
6480 guint32 token = patch_info->data.token->token;
6481 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
6482 encode_value (image_index, p, &p);
6483 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
6484 break;
6486 case MONO_PATCH_INFO_RVA:
6487 case MONO_PATCH_INFO_DECLSEC:
6488 case MONO_PATCH_INFO_LDTOKEN:
6489 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
6490 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
6491 encode_value (patch_info->data.token->token, p, &p);
6492 encode_value (patch_info->data.token->has_context, p, &p);
6493 if (patch_info->data.token->has_context)
6494 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
6495 break;
6496 case MONO_PATCH_INFO_EXC_NAME: {
6497 MonoClass *ex_class;
6499 ex_class =
6500 mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
6501 "System", (const char *)patch_info->data.target);
6502 encode_klass_ref (acfg, ex_class, p, &p);
6503 break;
6505 case MONO_PATCH_INFO_R4:
6506 encode_value (*((guint32 *)patch_info->data.target), p, &p);
6507 break;
6508 case MONO_PATCH_INFO_R8:
6509 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
6510 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
6511 break;
6512 case MONO_PATCH_INFO_VTABLE:
6513 case MONO_PATCH_INFO_CLASS:
6514 case MONO_PATCH_INFO_IID:
6515 case MONO_PATCH_INFO_ADJUSTED_IID:
6516 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
6517 break;
6518 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6519 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
6520 if (patch_info->data.del_tramp->method) {
6521 encode_value (1, p, &p);
6522 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
6523 } else {
6524 encode_value (0, p, &p);
6526 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
6527 break;
6528 case MONO_PATCH_INFO_FIELD:
6529 case MONO_PATCH_INFO_SFLDA:
6530 encode_field_info (acfg, patch_info->data.field, p, &p);
6531 break;
6532 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
6533 break;
6534 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
6535 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
6536 break;
6537 case MONO_PATCH_INFO_RGCTX_FETCH:
6538 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6539 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6540 guint32 offset;
6543 * entry->d.klass/method has a lenghtly encoding and multiple rgctx_fetch entries
6544 * reference the same klass/method, so encode it only once.
6545 * For patches which refer to got entries, this sharing is done by get_got_offset, but
6546 * these are not got entries.
6548 if (entry->in_mrgctx) {
6549 offset = get_shared_method_ref (acfg, entry->d.method);
6550 } else {
6551 offset = get_shared_klass_ref (acfg, entry->d.klass);
6554 encode_value (offset, p, &p);
6555 g_assert ((int)entry->info_type < 256);
6556 g_assert (entry->data->type < 256);
6557 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
6558 encode_patch (acfg, entry->data, p, &p);
6559 break;
6561 case MONO_PATCH_INFO_SEQ_POINT_INFO:
6562 case MONO_PATCH_INFO_AOT_MODULE:
6563 break;
6564 case MONO_PATCH_INFO_SIGNATURE:
6565 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
6566 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
6567 break;
6568 case MONO_PATCH_INFO_GSHAREDVT_CALL:
6569 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
6570 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
6571 break;
6572 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
6573 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
6574 int i;
6576 encode_method_ref (acfg, info->method, p, &p);
6577 encode_value (info->num_entries, p, &p);
6578 for (i = 0; i < info->num_entries; ++i) {
6579 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
6581 encode_value (template_->info_type, p, &p);
6582 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
6583 case MONO_PATCH_INFO_CLASS:
6584 encode_klass_ref (acfg, mono_class_from_mono_type_internal ((MonoType *)template_->data), p, &p);
6585 break;
6586 case MONO_PATCH_INFO_FIELD:
6587 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
6588 break;
6589 default:
6590 g_assert_not_reached ();
6591 break;
6594 break;
6596 case MONO_PATCH_INFO_VIRT_METHOD:
6597 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
6598 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
6599 break;
6600 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
6601 break;
6602 default:
6603 g_error ("unable to handle jump info %d", patch_info->type);
6606 *endbuf = p;
6609 static void
6610 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, guint8 *buf, guint8 **endbuf)
6612 guint8 *p = buf;
6613 guint32 pindex, offset;
6614 MonoJumpInfo *patch_info;
6616 encode_value (n_patches, p, &p);
6618 for (pindex = 0; pindex < patches->len; ++pindex) {
6619 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6621 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
6622 /* Nothing to do */
6623 continue;
6624 /* This shouldn't allocate a new offset */
6625 offset = lookup_got_offset (acfg, llvm, patch_info);
6626 encode_value (offset, p, &p);
6629 *endbuf = p;
6632 static void
6633 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6635 MonoMethod *method;
6636 int pindex, buf_size, n_patches;
6637 GPtrArray *patches;
6638 MonoJumpInfo *patch_info;
6639 guint8 *p, *buf;
6640 guint32 offset;
6641 gboolean needs_ctx = FALSE;
6643 method = cfg->orig_method;
6645 (void)get_method_index (acfg, method);
6647 /* Sort relocations */
6648 patches = g_ptr_array_new ();
6649 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6650 g_ptr_array_add (patches, patch_info);
6651 if (!acfg->aot_opts.llvm_only)
6652 g_ptr_array_sort (patches, compare_patches);
6654 /**********************/
6655 /* Encode method info */
6656 /**********************/
6658 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6660 guint32 *got_offsets = g_new0 (guint32, patches->len);
6662 n_patches = 0;
6663 for (pindex = 0; pindex < patches->len; ++pindex) {
6664 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6666 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6667 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6668 patch_info->type = MONO_PATCH_INFO_NONE;
6669 /* Nothing to do */
6670 continue;
6673 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6674 /* Stored in a GOT slot initialized at module load time */
6675 patch_info->type = MONO_PATCH_INFO_NONE;
6676 continue;
6679 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6680 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6681 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6682 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6683 /* Stored in a GOT slot initialized at module load time */
6684 patch_info->type = MONO_PATCH_INFO_NONE;
6685 continue;
6688 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6689 /* Calls are made through the PLT */
6690 patch_info->type = MONO_PATCH_INFO_NONE;
6691 continue;
6694 if (acfg->aot_opts.llvm_only && patch_info->type == MONO_PATCH_INFO_METHOD)
6695 needs_ctx = TRUE;
6697 /* This shouldn't allocate a new offset */
6698 offset = lookup_got_offset (acfg, cfg->compile_llvm, patch_info);
6699 if (offset >= acfg->nshared_got_entries)
6700 got_offsets [n_patches ++] = offset;
6703 if (n_patches)
6704 g_assert (cfg->has_got_slots);
6706 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6707 p = buf = (guint8 *)g_malloc (buf_size);
6709 MonoGenericContext *ctx = mono_method_get_context (cfg->method);
6711 guint8 flags = 0;
6712 if (mono_class_get_cctor (method->klass))
6713 flags |= MONO_AOT_METHOD_FLAG_HAS_CCTOR;
6714 if (mini_jit_info_is_gsharedvt (cfg->jit_info) && mini_is_gsharedvt_variable_signature (mono_method_signature_internal (jinfo_get_method (cfg->jit_info))))
6715 flags |= MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE;
6716 if (n_patches)
6717 flags |= MONO_AOT_METHOD_FLAG_HAS_PATCHES;
6718 if (needs_ctx && ctx)
6719 flags |= MONO_AOT_METHOD_FLAG_HAS_CTX;
6720 encode_value (flags, p, &p);
6721 if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
6722 encode_klass_ref (acfg, method->klass, p, &p);
6723 if (needs_ctx && ctx)
6724 encode_generic_context (acfg, ctx, p, &p);
6726 if (n_patches) {
6727 encode_value (n_patches, p, &p);
6728 for (int i = 0; i < n_patches; ++i)
6729 encode_value (got_offsets [i], p, &p);
6732 g_ptr_array_free (patches, TRUE);
6733 g_free (got_offsets);
6735 acfg->stats.method_info_size += p - buf;
6737 g_assert (p - buf < buf_size);
6739 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6740 g_free (buf);
6743 static guint32
6744 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6746 guint32 cache_index;
6747 guint32 offset;
6749 /* Reuse the unwind module to canonize and store unwind info entries */
6750 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6752 /* Use +/- 1 to distinguish 0s from missing entries */
6753 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6754 if (offset)
6755 return offset - 1;
6756 else {
6757 guint8 buf [16];
6758 guint8 *p;
6761 * It would be easier to use assembler symbols, but the caller needs an
6762 * offset now.
6764 offset = acfg->unwind_info_offset;
6765 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6766 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6768 p = buf;
6769 encode_value (encoded_len, p, &p);
6771 acfg->unwind_info_offset += encoded_len + (p - buf);
6772 return offset;
6776 static void
6777 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6779 int i, k, buf_size;
6780 guint32 debug_info_size, seq_points_size;
6781 guint8 *code;
6782 MonoMethodHeader *header;
6783 guint8 *p, *buf, *debug_info;
6784 MonoJitInfo *jinfo = cfg->jit_info;
6785 guint32 flags;
6786 gboolean use_unwind_ops = FALSE;
6787 MonoSeqPointInfo *seq_points;
6789 code = cfg->native_code;
6790 header = cfg->header;
6792 if (!acfg->aot_opts.nodebug) {
6793 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6794 } else {
6795 debug_info = NULL;
6796 debug_info_size = 0;
6799 seq_points = cfg->seq_point_info;
6800 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6802 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6803 if (jinfo->has_try_block_holes) {
6804 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6805 buf_size += table->num_holes * 16;
6808 p = buf = (guint8 *)g_malloc (buf_size);
6810 use_unwind_ops = cfg->unwind_ops != NULL;
6812 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);
6814 encode_value (flags, p, &p);
6816 if (use_unwind_ops) {
6817 guint32 encoded_len;
6818 guint8 *encoded;
6819 guint32 unwind_desc;
6821 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6823 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6824 encode_value (unwind_desc, p, &p);
6826 g_free (encoded);
6827 } else {
6828 encode_value (jinfo->unwind_info, p, &p);
6831 /*Encode the number of holes before the number of clauses to make decoding easier*/
6832 if (jinfo->has_try_block_holes) {
6833 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6834 encode_value (table->num_holes, p, &p);
6837 if (jinfo->has_arch_eh_info) {
6839 * In AOT mode, the code length is calculated from the address of the previous method,
6840 * which could include alignment padding, so calculating the start of the epilog as
6841 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6843 encode_value (jinfo->code_size, p, &p);
6846 /* Exception table */
6847 if (cfg->compile_llvm) {
6849 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6850 * since the information is only available to llc. Instead, we let llc save the data
6851 * into the LSDA, and read it from there at runtime.
6853 /* The assembly might be CIL stripped so emit the data ourselves */
6854 if (header->num_clauses)
6855 encode_value (header->num_clauses, p, &p);
6857 for (k = 0; k < header->num_clauses; ++k) {
6858 MonoExceptionClause *clause;
6860 clause = &header->clauses [k];
6862 encode_value (clause->flags, p, &p);
6863 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6864 if (clause->data.catch_class) {
6865 guint8 *buf2, *p2;
6866 int len;
6868 buf2 = (guint8 *)g_malloc (4096);
6869 p2 = buf2;
6870 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6871 len = p2 - buf2;
6872 g_assert (len < 4096);
6873 encode_value (len, p, &p);
6874 memcpy (p, buf2, len);
6875 p += p2 - buf2;
6876 g_free (buf2);
6877 } else {
6878 encode_value (0, p, &p);
6882 /* Emit the IL ranges too, since they might not be available at runtime */
6883 encode_value (clause->try_offset, p, &p);
6884 encode_value (clause->try_len, p, &p);
6885 encode_value (clause->handler_offset, p, &p);
6886 encode_value (clause->handler_len, p, &p);
6888 /* Emit a list of nesting clauses */
6889 for (i = 0; i < header->num_clauses; ++i) {
6890 gint32 cindex1 = k;
6891 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6892 gint32 cindex2 = i;
6893 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6895 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6896 encode_value (i, p, &p);
6898 encode_value (-1, p, &p);
6900 } else {
6901 if (jinfo->num_clauses)
6902 encode_value (jinfo->num_clauses, p, &p);
6904 for (k = 0; k < jinfo->num_clauses; ++k) {
6905 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6907 encode_value (ei->flags, p, &p);
6908 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6909 /* Not used for catch clauses */
6910 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6911 encode_value (ei->exvar_offset, p, &p);
6912 #else
6913 encode_value (ei->exvar_offset, p, &p);
6914 #endif
6916 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6917 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6918 else {
6919 if (ei->data.catch_class) {
6920 guint8 *buf2, *p2;
6921 int len;
6923 buf2 = (guint8 *)g_malloc (4096);
6924 p2 = buf2;
6925 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6926 len = p2 - buf2;
6927 g_assert (len < 4096);
6928 encode_value (len, p, &p);
6929 memcpy (p, buf2, len);
6930 p += p2 - buf2;
6931 g_free (buf2);
6932 } else {
6933 encode_value (0, p, &p);
6937 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6938 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6939 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6943 if (jinfo->has_try_block_holes) {
6944 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6945 for (i = 0; i < table->num_holes; ++i) {
6946 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6947 encode_value (hole->clause, p, &p);
6948 encode_value (hole->length, p, &p);
6949 encode_value (hole->offset, p, &p);
6953 if (jinfo->has_arch_eh_info) {
6954 MonoArchEHJitInfo *eh_info;
6956 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6957 encode_value (eh_info->stack_size, p, &p);
6958 encode_value (eh_info->epilog_size, p, &p);
6961 if (jinfo->has_generic_jit_info) {
6962 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6963 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6964 guint8 *buf2, *p2;
6965 int len;
6967 encode_value (gi->nlocs, p, &p);
6968 if (gi->nlocs) {
6969 for (i = 0; i < gi->nlocs; ++i) {
6970 MonoDwarfLocListEntry *entry = &gi->locations [i];
6972 encode_value (entry->is_reg ? 1 : 0, p, &p);
6973 encode_value (entry->reg, p, &p);
6974 if (!entry->is_reg)
6975 encode_value (entry->offset, p, &p);
6976 if (i == 0)
6977 g_assert (entry->from == 0);
6978 else
6979 encode_value (entry->from, p, &p);
6980 encode_value (entry->to, p, &p);
6982 } else {
6983 if (!cfg->compile_llvm) {
6984 encode_value (gi->has_this ? 1 : 0, p, &p);
6985 encode_value (gi->this_reg, p, &p);
6986 encode_value (gi->this_offset, p, &p);
6991 * Need to encode jinfo->method too, since it is not equal to 'method'
6992 * when using generic sharing.
6994 buf2 = (guint8 *)g_malloc (4096);
6995 p2 = buf2;
6996 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6997 len = p2 - buf2;
6998 g_assert (len < 4096);
6999 encode_value (len, p, &p);
7000 memcpy (p, buf2, len);
7001 p += p2 - buf2;
7002 g_free (buf2);
7004 if (gsctx && gsctx->is_gsharedvt) {
7005 encode_value (1, p, &p);
7006 } else {
7007 encode_value (0, p, &p);
7011 if (seq_points_size)
7012 p += mono_seq_point_info_write (seq_points, p);
7014 g_assert (debug_info_size < buf_size);
7016 encode_value (debug_info_size, p, &p);
7017 if (debug_info_size) {
7018 memcpy (p, debug_info, debug_info_size);
7019 p += debug_info_size;
7020 g_free (debug_info);
7023 /* GC Map */
7024 if (cfg->gc_map) {
7025 encode_value (cfg->gc_map_size, p, &p);
7026 /* The GC map requires 4 bytes of alignment */
7027 while ((gsize)p % 4)
7028 p ++;
7029 memcpy (p, cfg->gc_map, cfg->gc_map_size);
7030 p += cfg->gc_map_size;
7033 acfg->stats.ex_info_size += p - buf;
7035 g_assert (p - buf < buf_size);
7037 /* Emit info */
7038 /* The GC Map requires 4 byte alignment */
7039 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
7040 g_free (buf);
7043 static guint32
7044 emit_klass_info (MonoAotCompile *acfg, guint32 token)
7046 ERROR_DECL (error);
7047 MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
7048 guint8 *p, *buf;
7049 int i, buf_size, res;
7050 gboolean no_special_static, cant_encode;
7051 gpointer iter = NULL;
7053 if (!klass) {
7054 mono_error_cleanup (error);
7056 buf_size = 16;
7058 p = buf = (guint8 *)g_malloc (buf_size);
7060 /* Mark as unusable */
7061 encode_value (-1, p, &p);
7063 res = add_to_blob (acfg, buf, p - buf);
7064 g_free (buf);
7066 return res;
7069 buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
7070 p = buf = (guint8 *)g_malloc (buf_size);
7072 g_assert (klass);
7074 mono_class_init_internal (klass);
7076 mono_class_get_nested_types (klass, &iter);
7077 g_assert (m_class_is_nested_classes_inited (klass));
7079 mono_class_setup_vtable (klass);
7082 * Emit all the information which is required for creating vtables so
7083 * the runtime does not need to create the MonoMethod structures which
7084 * take up a lot of space.
7087 no_special_static = !mono_class_has_special_static_fields (klass);
7089 /* Check whenever we have enough info to encode the vtable */
7090 cant_encode = FALSE;
7091 MonoMethod **klass_vtable = m_class_get_vtable (klass);
7092 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
7093 MonoMethod *cm = klass_vtable [i];
7095 if (cm && mono_method_signature_internal (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
7096 cant_encode = TRUE;
7099 mono_class_has_finalizer (klass);
7100 if (mono_class_has_failure (klass))
7101 cant_encode = TRUE;
7103 if (mono_class_is_gtd (klass) || cant_encode) {
7104 encode_value (-1, p, &p);
7105 } else {
7106 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
7107 encode_value (m_class_get_vtable_size (klass), p, &p);
7108 encode_value ((m_class_has_weak_fields (klass) << 9) | (mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (m_class_has_static_refs (klass) << 6) | (m_class_has_references (klass) << 5) | ((m_class_is_blittable (klass) << 4) | (has_nested ? 1 : 0) << 3) | (m_class_has_cctor (klass) << 2) | (m_class_has_finalize (klass) << 1) | m_class_is_ghcimpl (klass), p, &p);
7109 if (m_class_has_cctor (klass))
7110 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
7111 if (m_class_has_finalize (klass))
7112 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
7114 encode_value (m_class_get_instance_size (klass), p, &p);
7115 encode_value (mono_class_data_size (klass), p, &p);
7116 encode_value (m_class_get_packing_size (klass), p, &p);
7117 encode_value (m_class_get_min_align (klass), p, &p);
7119 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
7120 MonoMethod *cm = klass_vtable [i];
7122 if (cm)
7123 encode_method_ref (acfg, cm, p, &p);
7124 else
7125 encode_value (0, p, &p);
7129 acfg->stats.class_info_size += p - buf;
7131 g_assert (p - buf < buf_size);
7132 res = add_to_blob (acfg, buf, p - buf);
7133 g_free (buf);
7135 return res;
7138 static char*
7139 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
7141 char *debug_sym = NULL;
7142 char *prefix;
7144 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
7145 /* Need to add a prefix to create unique symbols */
7146 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
7147 } else {
7148 #if defined(TARGET_WIN32) && defined(TARGET_X86)
7149 prefix = mangle_symbol_alloc ("plt_");
7150 #else
7151 prefix = g_strdup ("plt_");
7152 #endif
7155 switch (ji->type) {
7156 case MONO_PATCH_INFO_METHOD:
7157 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
7158 break;
7159 case MONO_PATCH_INFO_JIT_ICALL_ID:
7160 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
7161 break;
7162 case MONO_PATCH_INFO_RGCTX_FETCH:
7163 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
7164 break;
7165 case MONO_PATCH_INFO_ICALL_ADDR:
7166 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
7167 char *s = get_debug_sym (ji->data.method, "", cache);
7169 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
7170 g_free (s);
7171 break;
7173 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
7174 debug_sym = g_strdup_printf ("%s_jit_icall_native_specific_trampoline_lazy_fetch_%lu", prefix, (gulong)ji->data.uindex);
7175 break;
7176 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
7177 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
7178 break;
7179 default:
7180 break;
7183 g_free (prefix);
7185 return sanitize_symbol (acfg, debug_sym);
7189 * Calls made from AOTed code are routed through a table of jumps similar to the
7190 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
7191 * control to the AOT runtime through a trampoline.
7193 static void
7194 emit_plt (MonoAotCompile *acfg)
7196 int i;
7198 if (acfg->aot_opts.llvm_only) {
7199 g_assert (acfg->plt_offset == 1);
7200 return;
7203 emit_line (acfg);
7205 emit_section_change (acfg, ".text", 0);
7206 emit_alignment_code (acfg, 16);
7207 emit_info_symbol (acfg, "plt", TRUE);
7208 emit_label (acfg, acfg->plt_symbol);
7210 for (i = 0; i < acfg->plt_offset; ++i) {
7211 char *debug_sym = NULL;
7212 MonoPltEntry *plt_entry = NULL;
7214 if (i == 0)
7216 * The first plt entry is unused.
7218 continue;
7220 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7222 debug_sym = plt_entry->debug_sym;
7224 if (acfg->thumb_mixed && !plt_entry->jit_used)
7225 /* Emit only a thumb version */
7226 continue;
7228 /* Skip plt entries not actually called */
7229 if (!plt_entry->jit_used && !plt_entry->llvm_used)
7230 continue;
7232 if (acfg->llvm && !acfg->thumb_mixed) {
7233 emit_label (acfg, plt_entry->llvm_symbol);
7234 if (acfg->llvm) {
7235 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7236 #if defined(TARGET_MACH)
7237 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
7238 #endif
7242 if (debug_sym) {
7243 if (acfg->need_no_dead_strip) {
7244 emit_unset_mode (acfg);
7245 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7247 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7248 emit_label (acfg, debug_sym);
7251 emit_label (acfg, plt_entry->symbol);
7253 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
7255 if (debug_sym)
7256 emit_symbol_size (acfg, debug_sym, ".");
7259 if (acfg->thumb_mixed) {
7260 /* Make sure the ARM symbols don't alias the thumb ones */
7261 emit_zero_bytes (acfg, 16);
7264 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
7265 * code.
7267 for (i = 0; i < acfg->plt_offset; ++i) {
7268 char *debug_sym = NULL;
7269 MonoPltEntry *plt_entry = NULL;
7271 if (i == 0)
7272 continue;
7274 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7276 /* Skip plt entries not actually called by LLVM code */
7277 if (!plt_entry->llvm_used)
7278 continue;
7280 if (acfg->aot_opts.write_symbols) {
7281 if (plt_entry->debug_sym)
7282 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
7285 if (debug_sym) {
7286 #if defined(TARGET_MACH)
7287 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
7288 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7289 #endif
7290 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7291 emit_label (acfg, debug_sym);
7293 fprintf (acfg->fp, "\n.thumb_func\n");
7295 emit_label (acfg, plt_entry->llvm_symbol);
7297 if (acfg->llvm)
7298 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7300 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
7302 if (debug_sym) {
7303 emit_symbol_size (acfg, debug_sym, ".");
7304 g_free (debug_sym);
7309 emit_symbol_size (acfg, acfg->plt_symbol, ".");
7311 emit_info_symbol (acfg, "plt_end", TRUE);
7313 arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
7317 * emit_trampoline_full:
7319 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
7320 * create_jit_info_for_trampoline ().
7322 static G_GNUC_UNUSED void
7323 emit_trampoline_full (MonoAotCompile *acfg, MonoTrampInfo *info, gboolean emit_tinfo)
7325 char start_symbol [MAX_SYMBOL_SIZE];
7326 char end_symbol [MAX_SYMBOL_SIZE];
7327 char symbol [MAX_SYMBOL_SIZE];
7328 guint32 buf_size, info_offset;
7329 MonoJumpInfo *patch_info;
7330 guint8 *buf, *p;
7331 GPtrArray *patches;
7332 char *name;
7333 guint8 *code;
7334 guint32 code_size;
7335 MonoJumpInfo *ji;
7336 GSList *unwind_ops;
7338 g_assert (info);
7340 name = info->name;
7341 code = info->code;
7342 code_size = info->code_size;
7343 ji = info->ji;
7344 unwind_ops = info->unwind_ops;
7346 /* Emit code */
7348 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
7350 emit_section_change (acfg, ".text", 0);
7351 emit_global (acfg, start_symbol, TRUE);
7352 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7353 emit_label (acfg, start_symbol);
7355 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
7356 emit_label (acfg, symbol);
7359 * The code should access everything through the GOT, so we pass
7360 * TRUE here.
7362 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
7364 emit_symbol_size (acfg, start_symbol, ".");
7366 if (emit_tinfo) {
7367 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
7368 emit_label (acfg, end_symbol);
7371 /* Emit info */
7373 /* Sort relocations */
7374 patches = g_ptr_array_new ();
7375 for (patch_info = ji; patch_info; patch_info = patch_info->next)
7376 if (patch_info->type != MONO_PATCH_INFO_NONE)
7377 g_ptr_array_add (patches, patch_info);
7378 g_ptr_array_sort (patches, compare_patches);
7380 buf_size = patches->len * 128 + 128;
7381 buf = (guint8 *)g_malloc (buf_size);
7382 p = buf;
7384 encode_patch_list (acfg, patches, patches->len, FALSE, p, &p);
7385 g_assert (p - buf < buf_size);
7386 g_ptr_array_free (patches, TRUE);
7388 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
7390 info_offset = add_to_blob (acfg, buf, p - buf);
7392 emit_section_change (acfg, RODATA_SECT, 0);
7393 emit_global (acfg, symbol, FALSE);
7394 emit_label (acfg, symbol);
7396 emit_int32 (acfg, info_offset);
7398 if (emit_tinfo) {
7399 guint8 *encoded;
7400 guint32 encoded_len;
7401 guint32 uw_offset;
7404 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
7406 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
7407 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
7408 g_free (encoded);
7410 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
7411 emit_int32 (acfg, uw_offset);
7414 /* Emit debug info */
7415 if (unwind_ops) {
7416 char symbol2 [MAX_SYMBOL_SIZE];
7418 sprintf (symbol, "%s", name);
7419 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
7421 arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
7423 if (acfg->dwarf)
7424 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
7427 g_free (buf);
7430 static G_GNUC_UNUSED void
7431 emit_trampoline (MonoAotCompile *acfg, MonoTrampInfo *info)
7433 emit_trampoline_full (acfg, info, TRUE);
7436 static void
7437 emit_trampolines (MonoAotCompile *acfg)
7439 char symbol [MAX_SYMBOL_SIZE];
7440 char end_symbol [MAX_SYMBOL_SIZE];
7441 int i, tramp_got_offset;
7442 int ntype;
7443 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7444 int tramp_type;
7445 #endif
7447 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_interp (&acfg->aot_opts))
7448 return;
7449 if (acfg->aot_opts.llvm_only)
7450 return;
7452 g_assert (acfg->image->assembly);
7454 /* Currently, we emit most trampolines into the mscorlib AOT image. */
7455 if (mono_is_corlib_image(acfg->image->assembly->image)) {
7456 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7457 MonoTrampInfo *info;
7460 * Emit the generic trampolines.
7462 * We could save some code by treating the generic trampolines as a wrapper
7463 * method, but that approach has its own complexities, so we choose the simpler
7464 * method.
7466 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
7467 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
7468 #ifdef DISABLE_REMOTING
7469 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
7470 continue;
7471 #endif
7472 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
7473 emit_trampoline (acfg, info);
7474 mono_tramp_info_free (info);
7477 /* Emit the exception related code pieces */
7478 mono_arch_get_restore_context (&info, TRUE);
7479 emit_trampoline (acfg, info);
7480 mono_tramp_info_free (info);
7482 mono_arch_get_call_filter (&info, TRUE);
7483 emit_trampoline (acfg, info);
7484 mono_tramp_info_free (info);
7486 mono_arch_get_throw_exception (&info, TRUE);
7487 emit_trampoline (acfg, info);
7488 mono_tramp_info_free (info);
7490 mono_arch_get_rethrow_exception (&info, TRUE);
7491 emit_trampoline (acfg, info);
7492 mono_tramp_info_free (info);
7494 mono_arch_get_rethrow_preserve_exception (&info, TRUE);
7495 emit_trampoline (acfg, info);
7496 mono_tramp_info_free (info);
7498 mono_arch_get_throw_corlib_exception (&info, TRUE);
7499 emit_trampoline (acfg, info);
7500 mono_tramp_info_free (info);
7502 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
7503 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
7504 emit_trampoline (acfg, info);
7505 mono_tramp_info_free (info);
7507 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
7508 emit_trampoline (acfg, info);
7509 mono_tramp_info_free (info);
7510 #endif
7512 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
7513 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
7514 if (info) {
7515 emit_trampoline_full (acfg, info, TRUE);
7517 /* Create a separate out trampoline for more information in stack traces */
7518 info->name = g_strdup ("gsharedvt_out_trampoline");
7519 emit_trampoline_full (acfg, info, TRUE);
7520 mono_tramp_info_free (info);
7522 #endif
7524 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
7526 GSList *l = mono_arch_get_trampolines (TRUE);
7528 while (l) {
7529 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7531 emit_trampoline (acfg, info);
7532 l = l->next;
7535 #endif
7537 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
7538 int offset;
7540 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
7541 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7542 emit_trampoline (acfg, info);
7543 mono_tramp_info_free (info);
7545 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
7546 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7547 emit_trampoline (acfg, info);
7548 mono_tramp_info_free (info);
7551 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
7552 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
7553 emit_trampoline (acfg, info);
7554 mono_tramp_info_free (info);
7555 #endif
7558 GSList *l;
7560 /* delegate_invoke_impl trampolines */
7561 l = mono_arch_get_delegate_invoke_impls ();
7562 while (l) {
7563 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7565 emit_trampoline (acfg, info);
7566 l = l->next;
7570 if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
7571 mono_arch_get_interp_to_native_trampoline (&info);
7572 emit_trampoline (acfg, info);
7574 #ifdef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
7575 mono_arch_get_native_to_interp_trampoline (&info);
7576 emit_trampoline (acfg, info);
7577 #endif
7580 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
7582 /* Emit trampolines which are numerous */
7585 * These include the following:
7586 * - specific trampolines
7587 * - static rgctx invoke trampolines
7588 * - imt trampolines
7589 * These trampolines have the same code, they are parameterized by GOT
7590 * slots.
7591 * They are defined in this file, in the arch_... routines instead of
7592 * in tramp-<ARCH>.c, since it is easier to do it this way.
7596 * When running in aot-only mode, we can't create specific trampolines at
7597 * runtime, so we create a few, and save them in the AOT file.
7598 * Normal trampolines embed their argument as a literal inside the
7599 * trampoline code, we can't do that here, so instead we embed an offset
7600 * which needs to be added to the trampoline address to get the address of
7601 * the GOT slot which contains the argument value.
7602 * The generated trampolines jump to the generic trampolines using another
7603 * GOT slot, which will be setup by the AOT loader to point to the
7604 * generic trampoline code of the given type.
7608 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
7609 * each class).
7612 emit_section_change (acfg, ".text", 0);
7614 tramp_got_offset = acfg->got_offset;
7616 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
7617 switch (ntype) {
7618 case MONO_AOT_TRAMP_SPECIFIC:
7619 sprintf (symbol, "specific_trampolines");
7620 break;
7621 case MONO_AOT_TRAMP_STATIC_RGCTX:
7622 sprintf (symbol, "static_rgctx_trampolines");
7623 break;
7624 case MONO_AOT_TRAMP_IMT:
7625 sprintf (symbol, "imt_trampolines");
7626 break;
7627 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7628 sprintf (symbol, "gsharedvt_arg_trampolines");
7629 break;
7630 case MONO_AOT_TRAMP_FTNPTR_ARG:
7631 sprintf (symbol, "ftnptr_arg_trampolines");
7632 break;
7633 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7634 sprintf (symbol, "unbox_arbitrary_trampolines");
7635 break;
7636 default:
7637 g_assert_not_reached ();
7640 sprintf (end_symbol, "%s_e", symbol);
7642 if (acfg->aot_opts.write_symbols)
7643 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
7645 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7646 emit_info_symbol (acfg, symbol, TRUE);
7648 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
7650 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
7651 int tramp_size = 0;
7653 switch (ntype) {
7654 case MONO_AOT_TRAMP_SPECIFIC:
7655 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
7656 tramp_got_offset += 2;
7657 break;
7658 case MONO_AOT_TRAMP_STATIC_RGCTX:
7659 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
7660 tramp_got_offset += 2;
7661 break;
7662 case MONO_AOT_TRAMP_IMT:
7663 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
7664 tramp_got_offset += 1;
7665 break;
7666 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7667 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7668 tramp_got_offset += 2;
7669 break;
7670 case MONO_AOT_TRAMP_FTNPTR_ARG:
7671 arch_emit_ftnptr_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7672 tramp_got_offset += 2;
7673 break;
7674 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7675 arch_emit_unbox_arbitrary_trampoline (acfg, tramp_got_offset, &tramp_size);
7676 tramp_got_offset += 1;
7677 break;
7678 default:
7679 g_assert_not_reached ();
7681 if (!acfg->trampoline_size [ntype]) {
7682 g_assert (tramp_size);
7683 acfg->trampoline_size [ntype] = tramp_size;
7687 emit_label (acfg, end_symbol);
7688 emit_int32 (acfg, 0);
7691 arch_emit_specific_trampoline_pages (acfg);
7693 /* Reserve some entries at the end of the GOT for our use */
7694 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
7697 acfg->got_offset += acfg->num_trampoline_got_entries;
7700 static gboolean
7701 str_begins_with (const char *str1, const char *str2)
7703 int len = strlen (str2);
7704 return strncmp (str1, str2, len) == 0;
7707 void*
7708 mono_aot_readonly_field_override (MonoClassField *field)
7710 ReadOnlyValue *rdv;
7711 for (rdv = readonly_values; rdv; rdv = rdv->next) {
7712 char *p = rdv->name;
7713 int len;
7714 len = strlen (m_class_get_name_space (field->parent));
7715 if (strncmp (p, m_class_get_name_space (field->parent), len))
7716 continue;
7717 p += len;
7718 if (*p++ != '.')
7719 continue;
7720 len = strlen (m_class_get_name (field->parent));
7721 if (strncmp (p, m_class_get_name (field->parent), len))
7722 continue;
7723 p += len;
7724 if (*p++ != '.')
7725 continue;
7726 if (strcmp (p, field->name))
7727 continue;
7728 switch (rdv->type) {
7729 case MONO_TYPE_I1:
7730 return &rdv->value.i1;
7731 case MONO_TYPE_I2:
7732 return &rdv->value.i2;
7733 case MONO_TYPE_I4:
7734 return &rdv->value.i4;
7735 default:
7736 break;
7739 return NULL;
7742 static void
7743 add_readonly_value (MonoAotOptions *opts, const char *val)
7745 ReadOnlyValue *rdv;
7746 const char *fval;
7747 const char *tval;
7748 /* the format of val is:
7749 * namespace.typename.fieldname=type/value
7750 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7752 fval = strrchr (val, '/');
7753 if (!fval) {
7754 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7755 exit (1);
7757 tval = strrchr (val, '=');
7758 if (!tval) {
7759 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7760 exit (1);
7762 rdv = g_new0 (ReadOnlyValue, 1);
7763 rdv->name = (char *)g_malloc0 (tval - val + 1);
7764 memcpy (rdv->name, val, tval - val);
7765 tval++;
7766 fval++;
7767 if (strncmp (tval, "i1", 2) == 0) {
7768 rdv->value.i1 = atoi (fval);
7769 rdv->type = MONO_TYPE_I1;
7770 } else if (strncmp (tval, "i2", 2) == 0) {
7771 rdv->value.i2 = atoi (fval);
7772 rdv->type = MONO_TYPE_I2;
7773 } else if (strncmp (tval, "i4", 2) == 0) {
7774 rdv->value.i4 = atoi (fval);
7775 rdv->type = MONO_TYPE_I4;
7776 } else {
7777 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7778 exit (1);
7780 rdv->next = readonly_values;
7781 readonly_values = rdv;
7784 static gchar *
7785 clean_path (gchar * path)
7787 if (!path)
7788 return NULL;
7790 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7791 return path;
7793 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7794 g_free (path);
7796 return clean;
7799 static const gchar *
7800 wrap_path (const gchar * path)
7802 int len;
7803 if (!path)
7804 return NULL;
7806 // If the string contains no spaces, just return the original string.
7807 if (strstr (path, " ") == NULL)
7808 return path;
7810 // If the string is already wrapped in quotes, return it.
7811 len = strlen (path);
7812 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7813 return path;
7815 // If the string contains spaces, then wrap it in quotes.
7816 gchar *clean = g_strdup_printf ("\"%s\"", path);
7818 return clean;
7821 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7822 static void
7823 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7825 ptrdiff_t len = end-start;
7826 if (len > 0)
7827 g_ptr_array_add (args, g_strndup (start, len));
7830 static GPtrArray *
7831 mono_aot_split_options (const char *aot_options)
7833 enum MonoAotOptionState {
7834 MONO_AOT_OPTION_STATE_DEFAULT,
7835 MONO_AOT_OPTION_STATE_STRING,
7836 MONO_AOT_OPTION_STATE_ESCAPE,
7839 GPtrArray *args = g_ptr_array_new ();
7840 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7841 gchar const *opt_start = aot_options;
7842 gboolean end_of_string = FALSE;
7843 gchar cur;
7845 g_return_val_if_fail (aot_options != NULL, NULL);
7847 while ((cur = *aot_options) != '\0') {
7848 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7849 goto next;
7851 switch (cur) {
7852 case '"':
7853 // If we find a quote, then if we're in the default case then
7854 // it means we've found the start of a string, if not then it
7855 // means we've found the end of the string and should switch
7856 // back to the default case.
7857 switch (state) {
7858 case MONO_AOT_OPTION_STATE_DEFAULT:
7859 state = MONO_AOT_OPTION_STATE_STRING;
7860 break;
7861 case MONO_AOT_OPTION_STATE_STRING:
7862 state = MONO_AOT_OPTION_STATE_DEFAULT;
7863 break;
7864 case MONO_AOT_OPTION_STATE_ESCAPE:
7865 g_assert_not_reached ();
7866 break;
7868 break;
7869 case '\\':
7870 // If we've found an escaping operator, then this means we
7871 // should not process the next character if inside a string.
7872 if (state == MONO_AOT_OPTION_STATE_STRING)
7873 state = MONO_AOT_OPTION_STATE_ESCAPE;
7874 break;
7875 case ',':
7876 // If we're in the default state then this means we've found
7877 // an option, store it for later processing.
7878 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7879 goto new_opt;
7880 break;
7883 next:
7884 aot_options++;
7885 restart:
7886 // If the next character is end of string, then process the last option.
7887 if (*(aot_options) == '\0') {
7888 end_of_string = TRUE;
7889 goto new_opt;
7891 continue;
7893 new_opt:
7894 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7895 opt_start = ++aot_options;
7896 if (end_of_string)
7897 break;
7898 goto restart; // Check for null and continue loop
7901 return args;
7904 static void
7905 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7907 GPtrArray* args;
7909 args = mono_aot_split_options (aot_options ? aot_options : "");
7910 for (int i = 0; i < args->len; ++i) {
7911 const char *arg = (const char *)g_ptr_array_index (args, i);
7913 if (str_begins_with (arg, "outfile=")) {
7914 opts->outfile = g_strdup (arg + strlen ("outfile="));
7915 } else if (str_begins_with (arg, "llvm-outfile=")) {
7916 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7917 } else if (str_begins_with (arg, "temp-path=")) {
7918 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7919 } else if (str_begins_with (arg, "save-temps")) {
7920 opts->save_temps = TRUE;
7921 } else if (str_begins_with (arg, "keep-temps")) {
7922 opts->save_temps = TRUE;
7923 } else if (str_begins_with (arg, "write-symbols")) {
7924 opts->write_symbols = TRUE;
7925 } else if (str_begins_with (arg, "no-write-symbols")) {
7926 opts->write_symbols = FALSE;
7927 // Intentionally undocumented -- one-off experiment
7928 } else if (str_begins_with (arg, "metadata-only")) {
7929 opts->metadata_only = TRUE;
7930 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7931 opts->bind_to_runtime_version = TRUE;
7932 } else if (str_begins_with (arg, "full")) {
7933 opts->mode = MONO_AOT_MODE_FULL;
7934 } else if (str_begins_with (arg, "hybrid")) {
7935 opts->mode = MONO_AOT_MODE_HYBRID;
7936 } else if (str_begins_with (arg, "interp")) {
7937 opts->interp = TRUE;
7938 } else if (str_begins_with (arg, "threads=")) {
7939 opts->nthreads = atoi (arg + strlen ("threads="));
7940 } else if (str_begins_with (arg, "static")) {
7941 opts->static_link = TRUE;
7942 opts->no_dlsym = TRUE;
7943 } else if (str_begins_with (arg, "asmonly")) {
7944 opts->asm_only = TRUE;
7945 } else if (str_begins_with (arg, "asmwriter")) {
7946 opts->asm_writer = TRUE;
7947 } else if (str_begins_with (arg, "nodebug")) {
7948 opts->nodebug = TRUE;
7949 } else if (str_begins_with (arg, "dwarfdebug")) {
7950 opts->dwarf_debug = TRUE;
7951 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7952 } else if (str_begins_with (arg, "nopagetrampolines")) {
7953 opts->use_trampolines_page = FALSE;
7954 } else if (str_begins_with (arg, "ntrampolines=")) {
7955 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7956 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7957 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7958 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7959 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7960 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7961 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7962 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7963 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7964 } else if (str_begins_with (arg, "nftnptr-arg-trampolines=")) {
7965 opts->nftnptr_arg_trampolines = atoi (arg + strlen ("nftnptr-arg-trampolines="));
7966 } else if (str_begins_with (arg, "nunbox-arbitrary-trampolines=")) {
7967 opts->nunbox_arbitrary_trampolines = atoi (arg + strlen ("unbox-arbitrary-trampolines="));
7968 } else if (str_begins_with (arg, "tool-prefix=")) {
7969 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7970 } else if (str_begins_with (arg, "ld-flags=")) {
7971 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7972 } else if (str_begins_with (arg, "soft-debug")) {
7973 opts->soft_debug = TRUE;
7974 // Intentionally undocumented x2-- deprecated
7975 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7976 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7977 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7978 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7979 } else if (str_begins_with (arg, "msym-dir=")) {
7980 mini_debug_options.no_seq_points_compact_data = FALSE;
7981 opts->gen_msym_dir = TRUE;
7982 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));
7983 } else if (str_begins_with (arg, "direct-pinvoke")) {
7984 opts->direct_pinvoke = TRUE;
7985 } else if (str_begins_with (arg, "direct-icalls")) {
7986 opts->direct_icalls = TRUE;
7987 } else if (str_begins_with (arg, "no-direct-calls")) {
7988 opts->no_direct_calls = TRUE;
7989 } else if (str_begins_with (arg, "print-skipped")) {
7990 opts->print_skipped_methods = TRUE;
7991 } else if (str_begins_with (arg, "stats")) {
7992 opts->stats = TRUE;
7993 // Intentionally undocumented-- has no known function other than to debug the compiler
7994 } else if (str_begins_with (arg, "no-instances")) {
7995 opts->no_instances = TRUE;
7996 // Intentionally undocumented x4-- Used for internal debugging of compiler
7997 } else if (str_begins_with (arg, "log-generics")) {
7998 opts->log_generics = TRUE;
7999 } else if (str_begins_with (arg, "log-instances=")) {
8000 opts->log_instances = TRUE;
8001 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
8002 } else if (str_begins_with (arg, "log-instances")) {
8003 opts->log_instances = TRUE;
8004 } else if (str_begins_with (arg, "internal-logfile=")) {
8005 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
8006 } else if (str_begins_with (arg, "dedup-skip")) {
8007 opts->dedup = TRUE;
8008 } else if (str_begins_with (arg, "dedup-include=")) {
8009 opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
8010 } else if (str_begins_with (arg, "mtriple=")) {
8011 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
8012 } else if (str_begins_with (arg, "llvm-path=")) {
8013 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
8014 } else if (!strcmp (arg, "try-llvm")) {
8015 // If we can load LLVM, use it
8016 // Note: if you call this function from anywhere but mono_compile_assembly,
8017 // this will only set the try_llvm attribute and not do the probing / set the
8018 // attribute.
8019 opts->try_llvm = TRUE;
8020 } else if (!strcmp (arg, "llvm")) {
8021 opts->llvm = TRUE;
8022 } else if (str_begins_with (arg, "readonly-value=")) {
8023 add_readonly_value (opts, arg + strlen ("readonly-value="));
8024 } else if (str_begins_with (arg, "info")) {
8025 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
8026 exit (0);
8027 // Intentionally undocumented: Used for precise stack maps, which are not available yet
8028 } else if (str_begins_with (arg, "gc-maps")) {
8029 mini_gc_enable_gc_maps_for_aot ();
8030 // Intentionally undocumented: Used for internal debugging
8031 } else if (str_begins_with (arg, "dump")) {
8032 opts->dump_json = TRUE;
8033 } else if (str_begins_with (arg, "llvmonly")) {
8034 opts->mode = MONO_AOT_MODE_FULL;
8035 opts->llvm = TRUE;
8036 opts->llvm_only = TRUE;
8037 } else if (str_begins_with (arg, "data-outfile=")) {
8038 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
8039 } else if (str_begins_with (arg, "profile=")) {
8040 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
8041 } else if (!strcmp (arg, "profile-only")) {
8042 opts->profile_only = TRUE;
8043 } else if (!strcmp (arg, "verbose")) {
8044 opts->verbose = TRUE;
8045 } else if (str_begins_with (arg, "llvmopts=")){
8046 if (opts->llvm_opts) {
8047 char *s = g_strdup_printf ("%s %s", opts->llvm_opts, arg + strlen ("llvmopts="));
8048 g_free (opts->llvm_opts);
8049 opts->llvm_opts = s;
8050 } else {
8051 opts->llvm_opts = g_strdup (arg + strlen ("llvmopts="));
8053 } else if (str_begins_with (arg, "llvmllc=")){
8054 opts->llvm_llc = g_strdup (arg + strlen ("llvmllc="));
8055 } else if (!strcmp (arg, "deterministic")) {
8056 opts->deterministic = TRUE;
8057 } else if (!strcmp (arg, "no-opt")) {
8058 opts->no_opt = TRUE;
8059 } else if (str_begins_with (arg, "clangxx=")) {
8060 opts->clangxx = g_strdup (arg + strlen ("clangxx="));
8061 } else if (str_begins_with (arg, "depfile=")) {
8062 opts->depfile = g_strdup (arg + strlen ("depfile="));
8063 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
8064 printf ("Supported options for --aot:\n");
8065 printf (" asmonly\n");
8066 printf (" bind-to-runtime-version\n");
8067 printf (" bitcode\n");
8068 printf (" data-outfile=\n");
8069 printf (" direct-icalls\n");
8070 printf (" direct-pinvoke\n");
8071 printf (" dwarfdebug\n");
8072 printf (" full\n");
8073 printf (" hybrid\n");
8074 printf (" info\n");
8075 printf (" keep-temps\n");
8076 printf (" llvm\n");
8077 printf (" llvmonly\n");
8078 printf (" llvm-outfile=\n");
8079 printf (" llvm-path=\n");
8080 printf (" msym-dir=\n");
8081 printf (" mtriple\n");
8082 printf (" nimt-trampolines=\n");
8083 printf (" nodebug\n");
8084 printf (" no-direct-calls\n");
8085 printf (" no-write-symbols\n");
8086 printf (" nrgctx-trampolines=\n");
8087 printf (" nrgctx-fetch-trampolines=\n");
8088 printf (" ngsharedvt-trampolines=\n");
8089 printf (" nftnptr-arg-trampolines=\n");
8090 printf (" nunbox-arbitrary-trampolines=\n");
8091 printf (" ntrampolines=\n");
8092 printf (" outfile=\n");
8093 printf (" profile=\n");
8094 printf (" profile-only\n");
8095 printf (" print-skipped-methods\n");
8096 printf (" readonly-value=\n");
8097 printf (" save-temps\n");
8098 printf (" soft-debug\n");
8099 printf (" static\n");
8100 printf (" stats\n");
8101 printf (" temp-path=\n");
8102 printf (" tool-prefix=\n");
8103 printf (" threads=\n");
8104 printf (" write-symbols\n");
8105 printf (" verbose\n");
8106 printf (" no-opt\n");
8107 printf (" llvmopts=\n");
8108 printf (" llvmllc=\n");
8109 printf (" clangxx=\n");
8110 printf (" depfile=\n");
8111 printf (" help/?\n");
8112 exit (0);
8113 } else {
8114 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
8115 exit (1);
8118 g_free ((gpointer) arg);
8121 if (opts->use_trampolines_page) {
8122 opts->ntrampolines = 0;
8123 opts->nrgctx_trampolines = 0;
8124 opts->nimt_trampolines = 0;
8125 opts->ngsharedvt_arg_trampolines = 0;
8126 opts->nftnptr_arg_trampolines = 0;
8127 opts->nunbox_arbitrary_trampolines = 0;
8130 g_ptr_array_free (args, /*free_seg=*/TRUE);
8133 static void
8134 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
8136 MonoMethod *method = (MonoMethod*)key;
8137 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
8138 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
8139 MonoJumpInfoToken *new_ji;
8141 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
8142 new_ji->image = ji->image;
8143 new_ji->token = ji->token;
8144 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
8147 static gboolean
8148 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
8150 if (m_class_get_type_token (klass))
8151 return TRUE;
8152 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR))
8153 return TRUE;
8154 if (m_class_get_rank (klass))
8155 return can_encode_class (acfg, m_class_get_element_class (klass));
8156 return FALSE;
8159 static gboolean
8160 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
8162 if (method->wrapper_type) {
8163 switch (method->wrapper_type) {
8164 case MONO_WRAPPER_NONE:
8165 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8166 case MONO_WRAPPER_XDOMAIN_INVOKE:
8167 case MONO_WRAPPER_STFLD:
8168 case MONO_WRAPPER_LDFLD:
8169 case MONO_WRAPPER_LDFLDA:
8170 case MONO_WRAPPER_STELEMREF:
8171 case MONO_WRAPPER_PROXY_ISINST:
8172 case MONO_WRAPPER_ALLOC:
8173 case MONO_WRAPPER_REMOTING_INVOKE:
8174 case MONO_WRAPPER_OTHER:
8175 case MONO_WRAPPER_WRITE_BARRIER:
8176 case MONO_WRAPPER_DELEGATE_INVOKE:
8177 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8178 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8179 case MONO_WRAPPER_SYNCHRONIZED:
8180 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8181 break;
8182 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8183 case MONO_WRAPPER_CASTCLASS: {
8184 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8186 if (info)
8187 return TRUE;
8188 else
8189 return FALSE;
8190 break;
8192 default:
8193 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
8194 return FALSE;
8196 } else {
8197 if (!method->token) {
8198 /* The method is part of a constructed type like Int[,].Set (). */
8199 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
8200 if (m_class_get_rank (method->klass))
8201 return TRUE;
8202 return FALSE;
8206 return TRUE;
8209 static gboolean
8210 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
8212 switch (patch_info->type) {
8213 case MONO_PATCH_INFO_METHOD:
8214 case MONO_PATCH_INFO_METHOD_FTNDESC:
8215 case MONO_PATCH_INFO_METHODCONST:
8216 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
8217 MonoMethod *method = patch_info->data.method;
8219 return can_encode_method (acfg, method);
8221 case MONO_PATCH_INFO_VTABLE:
8222 case MONO_PATCH_INFO_CLASS:
8223 case MONO_PATCH_INFO_IID:
8224 case MONO_PATCH_INFO_ADJUSTED_IID:
8225 if (!can_encode_class (acfg, patch_info->data.klass)) {
8226 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
8227 return FALSE;
8229 break;
8230 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
8231 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
8232 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
8233 return FALSE;
8235 break;
8237 case MONO_PATCH_INFO_RGCTX_FETCH:
8238 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
8239 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
8241 if (entry->in_mrgctx) {
8242 if (!can_encode_method (acfg, entry->d.method))
8243 return FALSE;
8244 } else {
8245 if (!can_encode_class (acfg, entry->d.klass))
8246 return FALSE;
8248 if (!can_encode_patch (acfg, entry->data))
8249 return FALSE;
8250 break;
8252 default:
8253 break;
8256 return TRUE;
8259 static gboolean
8260 is_concrete_type (MonoType *t)
8262 MonoClass *klass;
8263 int i;
8265 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
8266 return FALSE;
8267 if (t->type == MONO_TYPE_GENERICINST) {
8268 MonoGenericContext *orig_ctx;
8269 MonoGenericInst *inst;
8270 MonoType *arg;
8272 if (!MONO_TYPE_ISSTRUCT (t))
8273 return TRUE;
8274 klass = mono_class_from_mono_type_internal (t);
8275 orig_ctx = &mono_class_get_generic_class (klass)->context;
8277 inst = orig_ctx->class_inst;
8278 if (inst) {
8279 for (i = 0; i < inst->type_argc; ++i) {
8280 arg = mini_get_underlying_type (inst->type_argv [i]);
8281 if (!is_concrete_type (arg))
8282 return FALSE;
8285 inst = orig_ctx->method_inst;
8286 if (inst) {
8287 for (i = 0; i < inst->type_argc; ++i) {
8288 arg = mini_get_underlying_type (inst->type_argv [i]);
8289 if (!is_concrete_type (arg))
8290 return FALSE;
8294 return TRUE;
8297 static MonoMethodSignature*
8298 get_concrete_sig (MonoMethodSignature *sig)
8300 gboolean concrete = TRUE;
8302 if (!sig->has_type_parameters)
8303 return sig;
8305 /* For signatures created during generic sharing, convert them to a concrete signature if possible */
8306 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
8307 int i;
8309 //printf ("%s\n", mono_signature_full_name (sig));
8311 if (sig->ret->byref)
8312 copy->ret = m_class_get_this_arg (mono_defaults.int_class);
8313 else
8314 copy->ret = mini_get_underlying_type (sig->ret);
8315 if (!is_concrete_type (copy->ret))
8316 concrete = FALSE;
8317 for (i = 0; i < sig->param_count; ++i) {
8318 if (sig->params [i]->byref) {
8319 MonoType *t = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->params [i]));
8320 t = mini_get_underlying_type (t);
8321 copy->params [i] = m_class_get_this_arg (mono_class_from_mono_type_internal (t));
8322 } else {
8323 copy->params [i] = mini_get_underlying_type (sig->params [i]);
8325 if (!is_concrete_type (copy->params [i]))
8326 concrete = FALSE;
8328 copy->has_type_parameters = 0;
8329 if (!concrete)
8330 return NULL;
8331 return copy;
8334 /* LOCKING: Assumes the loader lock is held */
8335 static void
8336 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
8338 MonoMethod *wrapper;
8339 gboolean add_in = gsharedvt_in;
8340 gboolean add_out = gsharedvt_out;
8342 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
8343 add_in = FALSE;
8344 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
8345 add_out = FALSE;
8347 if (!add_in && !add_out)
8348 return;
8350 if (mini_is_gsharedvt_variable_signature (sig))
8351 return;
8353 if (add_in)
8354 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
8355 if (add_out)
8356 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
8358 sig = get_concrete_sig (sig);
8359 if (!sig)
8360 return;
8361 //printf ("%s\n", mono_signature_full_name (sig));
8363 if (gsharedvt_in) {
8364 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
8365 add_extra_method (acfg, wrapper);
8367 if (gsharedvt_out) {
8368 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
8369 add_extra_method (acfg, wrapper);
8372 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
8373 if (interp_in) {
8374 wrapper = mini_get_interp_in_wrapper (sig);
8375 add_extra_method (acfg, wrapper);
8376 //printf ("X: %s\n", mono_method_full_name (wrapper, 1));
8378 #endif
8382 * compile_method:
8384 * AOT compile a given method.
8385 * This function might be called by multiple threads, so it must be thread-safe.
8387 static void
8388 compile_method (MonoAotCompile *acfg, MonoMethod *method)
8390 MonoCompile *cfg;
8391 MonoJumpInfo *patch_info;
8392 gboolean skip;
8393 int index, depth;
8394 MonoMethod *wrapped;
8395 gint64 jit_time_start;
8396 JitFlags flags;
8398 if (acfg->aot_opts.metadata_only)
8399 return;
8401 mono_acfg_lock (acfg);
8402 index = get_method_index (acfg, method);
8403 mono_acfg_unlock (acfg);
8405 /* fixme: maybe we can also precompile wrapper methods */
8406 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8407 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8408 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
8409 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
8410 return;
8413 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8414 return;
8416 wrapped = mono_marshal_method_from_wrapper (method);
8417 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
8418 // FIXME: The wrapper should be generic too, but it is not
8419 return;
8421 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
8422 return;
8424 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
8425 return;
8427 mono_atomic_inc_i32 (&acfg->stats.mcount);
8429 #if 0
8430 if (method->is_generic || mono_class_is_gtd (method->klass)) {
8431 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8432 return;
8434 #endif
8436 //acfg->aot_opts.print_skipped_methods = TRUE;
8439 * Since these methods are the only ones which are compiled with
8440 * AOT support, and they are not used by runtime startup/shutdown code,
8441 * the runtime will not see AOT methods during AOT compilation,so it
8442 * does not need to support them by creating a fake GOT etc.
8444 flags = JIT_FLAG_AOT;
8445 if (mono_aot_mode_is_full (&acfg->aot_opts))
8446 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
8447 if (acfg->llvm)
8448 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
8449 if (acfg->aot_opts.llvm_only)
8450 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
8451 if (acfg->aot_opts.no_direct_calls)
8452 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
8453 if (acfg->aot_opts.direct_pinvoke)
8454 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
8455 if (acfg->aot_opts.interp)
8456 flags = (JitFlags)(flags | JIT_FLAG_INTERP);
8458 jit_time_start = mono_time_track_start ();
8459 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
8460 mono_time_track_end (&mono_jit_stats.jit_time, jit_time_start);
8462 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
8463 if (acfg->aot_opts.print_skipped_methods)
8464 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
8465 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8466 return;
8468 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
8469 /* Some instances cannot be JITted due to constraints etc. */
8470 if (!method->is_inflated)
8471 report_loader_error (acfg, &cfg->error, FALSE, "Unable to compile method '%s' due to: '%s'.\n", mono_method_get_full_name (method), mono_error_get_message (&cfg->error));
8472 /* Let the exception happen at runtime */
8473 return;
8476 if (cfg->disable_aot) {
8477 if (acfg->aot_opts.print_skipped_methods)
8478 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
8479 mono_atomic_inc_i32 (&acfg->stats.ocount);
8480 return;
8482 cfg->method_index = index;
8484 /* Nullify patches which need no aot processing */
8485 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8486 switch (patch_info->type) {
8487 case MONO_PATCH_INFO_LABEL:
8488 case MONO_PATCH_INFO_BB:
8489 patch_info->type = MONO_PATCH_INFO_NONE;
8490 break;
8491 default:
8492 break;
8496 /* Collect method->token associations from the cfg */
8497 mono_acfg_lock (acfg);
8498 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
8499 mono_acfg_unlock (acfg);
8500 g_hash_table_destroy (cfg->token_info_hash);
8501 cfg->token_info_hash = NULL;
8504 * Check for absolute addresses.
8506 skip = FALSE;
8507 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8508 switch (patch_info->type) {
8509 case MONO_PATCH_INFO_ABS:
8510 /* unable to handle this */
8511 skip = TRUE;
8512 break;
8513 default:
8514 break;
8518 if (skip) {
8519 if (acfg->aot_opts.print_skipped_methods)
8520 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
8521 mono_atomic_inc_i32 (&acfg->stats.abscount);
8522 return;
8525 /* Lock for the rest of the code */
8526 mono_acfg_lock (acfg);
8528 if (cfg->gsharedvt)
8529 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
8530 else if (cfg->gshared)
8531 acfg->stats.method_categories [METHOD_CAT_INST] ++;
8532 else if (cfg->method->wrapper_type)
8533 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
8534 else
8535 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
8538 * Check for methods/klasses we can't encode.
8540 skip = FALSE;
8541 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8542 if (!can_encode_patch (acfg, patch_info))
8543 skip = TRUE;
8546 if (skip) {
8547 if (acfg->aot_opts.print_skipped_methods)
8548 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
8549 acfg->stats.ocount++;
8550 mono_acfg_unlock (acfg);
8551 return;
8554 if (!cfg->compile_llvm)
8555 acfg->has_jitted_code = TRUE;
8557 if (method->is_inflated && acfg->aot_opts.log_instances) {
8558 if (acfg->instances_logfile)
8559 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8560 else
8561 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8564 /* Adds generic instances referenced by this method */
8566 * The depth is used to avoid infinite loops when generic virtual recursion is
8567 * encountered.
8569 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
8570 if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8571 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8572 switch (patch_info->type) {
8573 case MONO_PATCH_INFO_RGCTX_FETCH:
8574 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
8575 case MONO_PATCH_INFO_METHOD:
8576 case MONO_PATCH_INFO_METHOD_FTNDESC:
8577 case MONO_PATCH_INFO_METHOD_RGCTX: {
8578 MonoMethod *m = NULL;
8580 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
8581 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
8583 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE || e->info_type == MONO_RGCTX_INFO_METHOD_FTNDESC)
8584 m = e->data->data.method;
8585 } else {
8586 m = patch_info->data.method;
8589 if (!m)
8590 break;
8591 if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8592 if (!(mono_class_generic_sharing_enabled (m->klass) &&
8593 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
8594 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
8595 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8596 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
8597 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
8598 } else {
8599 add_extra_method_with_depth (acfg, m, depth + 1);
8600 add_types_from_method_header (acfg, m);
8603 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
8605 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
8606 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
8608 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
8609 add_extra_method_with_depth (acfg, m, depth + 1);
8611 break;
8613 case MONO_PATCH_INFO_VTABLE: {
8614 MonoClass *klass = patch_info->data.klass;
8616 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
8617 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
8618 break;
8620 case MONO_PATCH_INFO_SFLDA: {
8621 MonoClass *klass = patch_info->data.field->parent;
8623 /* The .cctor needs to run at runtime. */
8624 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))
8625 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
8626 break;
8628 default:
8629 break;
8634 /* Determine whenever the method has GOT slots */
8635 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8636 switch (patch_info->type) {
8637 case MONO_PATCH_INFO_GOT_OFFSET:
8638 case MONO_PATCH_INFO_NONE:
8639 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
8640 case MONO_PATCH_INFO_GC_NURSERY_START:
8641 case MONO_PATCH_INFO_GC_NURSERY_BITS:
8642 break;
8643 case MONO_PATCH_INFO_IMAGE:
8644 /* The assembly is stored in GOT slot 0 */
8645 if (patch_info->data.image != acfg->image)
8646 cfg->has_got_slots = TRUE;
8647 break;
8648 default:
8649 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
8650 cfg->has_got_slots = TRUE;
8651 break;
8655 if (!cfg->has_got_slots)
8656 mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
8658 /* Add gsharedvt wrappers for signatures used by the method */
8659 if (acfg->aot_opts.llvm_only) {
8660 GSList *l;
8662 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8663 /* These only need out wrappers */
8664 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, FALSE);
8666 for (l = cfg->signatures; l; l = l->next) {
8667 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8669 /* These only need in wrappers */
8670 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8673 for (l = cfg->interp_in_signatures; l; l = l->next) {
8674 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8676 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8678 } else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
8679 /* The interpreter uses these wrappers to call aot-ed code */
8680 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8681 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, TRUE);
8684 if (cfg->llvm_only)
8685 acfg->stats.llvm_count ++;
8688 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
8690 /* Make a copy of the patch info which is in the mempool */
8692 MonoJumpInfo *patches = NULL, *patches_end = NULL;
8694 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8695 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
8697 if (!patches)
8698 patches = new_patch_info;
8699 else
8700 patches_end->next = new_patch_info;
8701 patches_end = new_patch_info;
8703 cfg->patch_info = patches;
8705 /* Make a copy of the unwind info */
8707 GSList *l, *unwind_ops;
8708 MonoUnwindOp *op;
8710 unwind_ops = NULL;
8711 for (l = cfg->unwind_ops; l; l = l->next) {
8712 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
8713 memcpy (op, l->data, sizeof (MonoUnwindOp));
8714 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
8716 cfg->unwind_ops = g_slist_reverse (unwind_ops);
8718 /* Make a copy of the argument/local info */
8720 ERROR_DECL (error);
8721 MonoInst **args, **locals;
8722 MonoMethodSignature *sig;
8723 MonoMethodHeader *header;
8724 int i;
8726 sig = mono_method_signature_internal (method);
8727 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
8728 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
8729 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8730 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
8732 cfg->args = args;
8734 header = mono_method_get_header_checked (method, error);
8735 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8736 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
8737 for (i = 0; i < header->num_locals; ++i) {
8738 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8739 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
8741 mono_metadata_free_mh (header);
8742 cfg->locals = locals;
8745 /* Free some fields used by cfg to conserve memory */
8746 mono_empty_compile (cfg);
8748 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
8750 while (index >= acfg->cfgs_size) {
8751 MonoCompile **new_cfgs;
8752 int new_size;
8754 new_size = acfg->cfgs_size * 2;
8755 new_cfgs = g_new0 (MonoCompile*, new_size);
8756 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
8757 g_free (acfg->cfgs);
8758 acfg->cfgs = new_cfgs;
8759 acfg->cfgs_size = new_size;
8761 acfg->cfgs [index] = cfg;
8763 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
8765 /* Update global stats while holding a lock. */
8766 mono_update_jit_stats (cfg);
8769 if (cfg->orig_method->wrapper_type)
8770 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
8773 mono_acfg_unlock (acfg);
8775 mono_atomic_inc_i32 (&acfg->stats.ccount);
8778 static mono_thread_start_return_t WINAPI
8779 compile_thread_main (gpointer user_data)
8781 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
8782 GPtrArray *methods = ((GPtrArray **)user_data) [1];
8783 int i;
8785 ERROR_DECL (error);
8786 MonoInternalThread *internal = mono_thread_internal_current ();
8787 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", error);
8788 mono_error_assert_ok (error);
8789 mono_thread_set_name_internal (internal, str, MonoSetThreadNameFlag_Permanent, error);
8790 mono_error_assert_ok (error);
8792 for (i = 0; i < methods->len; ++i)
8793 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
8795 return 0;
8798 /* Used by the LLVM backend */
8799 guint32
8800 mono_aot_get_got_offset (MonoJumpInfo *ji)
8802 return get_got_offset (llvm_acfg, TRUE, ji);
8806 * mono_aot_is_shared_got_offset:
8808 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8809 * when the AOT image is loaded.
8811 gboolean
8812 mono_aot_is_shared_got_offset (int offset)
8814 return offset < llvm_acfg->nshared_got_entries;
8817 char*
8818 mono_aot_get_method_name (MonoCompile *cfg)
8820 MonoMethod *method = cfg->orig_method;
8822 /* Use the mangled name if possible */
8823 if (method->wrapper_type == MONO_WRAPPER_OTHER) {
8824 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8825 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8826 return mono_aot_get_mangled_method_name (method);
8829 if (llvm_acfg->aot_opts.static_link)
8830 /* Include the assembly name too to avoid duplicate symbol errors */
8831 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8832 else
8833 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8836 static gboolean
8837 append_mangled_type (GString *s, MonoType *t)
8839 if (t->byref)
8840 g_string_append_printf (s, "b");
8841 switch (t->type) {
8842 case MONO_TYPE_VOID:
8843 g_string_append_printf (s, "void");
8844 break;
8845 case MONO_TYPE_I1:
8846 g_string_append_printf (s, "i1");
8847 break;
8848 case MONO_TYPE_U1:
8849 g_string_append_printf (s, "u1");
8850 break;
8851 case MONO_TYPE_I2:
8852 g_string_append_printf (s, "i2");
8853 break;
8854 case MONO_TYPE_U2:
8855 g_string_append_printf (s, "u2");
8856 break;
8857 case MONO_TYPE_I4:
8858 g_string_append_printf (s, "i4");
8859 break;
8860 case MONO_TYPE_U4:
8861 g_string_append_printf (s, "u4");
8862 break;
8863 case MONO_TYPE_I8:
8864 g_string_append_printf (s, "i8");
8865 break;
8866 case MONO_TYPE_U8:
8867 g_string_append_printf (s, "u8");
8868 break;
8869 case MONO_TYPE_I:
8870 g_string_append_printf (s, "ii");
8871 break;
8872 case MONO_TYPE_U:
8873 g_string_append_printf (s, "ui");
8874 break;
8875 case MONO_TYPE_R4:
8876 g_string_append_printf (s, "fl");
8877 break;
8878 case MONO_TYPE_R8:
8879 g_string_append_printf (s, "do");
8880 break;
8881 case MONO_TYPE_OBJECT:
8882 g_string_append_printf (s, "obj");
8883 break;
8884 default: {
8885 char *fullname = mono_type_full_name (t);
8886 GString *temp;
8887 char *temps;
8888 int i, len;
8891 * Have to create a mangled name which is:
8892 * - a valid symbol
8893 * - unique
8895 temp = g_string_new ("");
8896 len = strlen (fullname);
8897 for (i = 0; i < len; ++i) {
8898 char c = fullname [i];
8899 if (isalnum (c)) {
8900 g_string_append_c (temp, c);
8901 } else if (c == '_') {
8902 g_string_append_c (temp, '_');
8903 g_string_append_c (temp, '_');
8904 } else {
8905 g_string_append_c (temp, '_');
8906 g_string_append_printf (temp, "%x", (int)c);
8909 temps = g_string_free (temp, FALSE);
8910 /* Include the length to avoid different length type names aliasing each other */
8911 g_string_append_printf (s, "cl%x_%s_", (int)strlen (temps), temps);
8912 g_free (temps);
8915 if (t->attrs)
8916 g_string_append_printf (s, "_attrs_%d", t->attrs);
8917 return TRUE;
8920 static gboolean
8921 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8923 int i;
8924 gboolean supported;
8926 if (sig->pinvoke)
8927 g_string_append_printf (s, "pinvoke_");
8928 supported = append_mangled_type (s, sig->ret);
8929 if (!supported)
8930 return FALSE;
8931 g_string_append_printf (s, "_");
8932 if (sig->hasthis)
8933 g_string_append_printf (s, "this_");
8934 for (i = 0; i < sig->param_count; ++i) {
8935 supported = append_mangled_type (s, sig->params [i]);
8936 if (!supported)
8937 return FALSE;
8940 return TRUE;
8943 static void
8944 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8946 const char *label;
8948 switch (wrapper_type) {
8949 case MONO_WRAPPER_REMOTING_INVOKE:
8950 label = "remoting_invoke";
8951 break;
8952 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8953 label = "remoting_invoke_check";
8954 break;
8955 case MONO_WRAPPER_XDOMAIN_INVOKE:
8956 label = "remoting_invoke_xdomain";
8957 break;
8958 case MONO_WRAPPER_PROXY_ISINST:
8959 label = "proxy_isinst";
8960 break;
8961 case MONO_WRAPPER_LDFLD:
8962 label = "ldfld";
8963 break;
8964 case MONO_WRAPPER_LDFLDA:
8965 label = "ldflda";
8966 break;
8967 case MONO_WRAPPER_STFLD:
8968 label = "stfld";
8969 break;
8970 case MONO_WRAPPER_ALLOC:
8971 label = "alloc";
8972 break;
8973 case MONO_WRAPPER_WRITE_BARRIER:
8974 label = "write_barrier";
8975 break;
8976 case MONO_WRAPPER_STELEMREF:
8977 label = "stelemref";
8978 break;
8979 case MONO_WRAPPER_OTHER:
8980 label = "unknown";
8981 break;
8982 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8983 label = "man2native";
8984 break;
8985 case MONO_WRAPPER_SYNCHRONIZED:
8986 label = "synch";
8987 break;
8988 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8989 label = "man2man";
8990 break;
8991 case MONO_WRAPPER_CASTCLASS:
8992 label = "castclass";
8993 break;
8994 case MONO_WRAPPER_RUNTIME_INVOKE:
8995 label = "run_invoke";
8996 break;
8997 case MONO_WRAPPER_DELEGATE_INVOKE:
8998 label = "del_inv";
8999 break;
9000 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
9001 label = "del_beg_inv";
9002 break;
9003 case MONO_WRAPPER_DELEGATE_END_INVOKE:
9004 label = "del_end_inv";
9005 break;
9006 case MONO_WRAPPER_NATIVE_TO_MANAGED:
9007 label = "native2man";
9008 break;
9009 default:
9010 g_assert_not_reached ();
9013 g_string_append_printf (s, "%s_", label);
9016 static void
9017 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
9019 const char *label;
9021 switch (subtype)
9023 case WRAPPER_SUBTYPE_NONE:
9024 return;
9025 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
9026 label = "elem_addr";
9027 break;
9028 case WRAPPER_SUBTYPE_STRING_CTOR:
9029 label = "str_ctor";
9030 break;
9031 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
9032 label = "virt_stelem";
9033 break;
9034 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
9035 label = "fast_mon_enter";
9036 break;
9037 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
9038 label = "fast_mon_enter_4";
9039 break;
9040 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
9041 label = "fast_monitor_exit";
9042 break;
9043 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
9044 label = "ptr2struct";
9045 break;
9046 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
9047 label = "struct2ptr";
9048 break;
9049 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
9050 label = "castclass_w_cache";
9051 break;
9052 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
9053 label = "isinst_w_cache";
9054 break;
9055 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
9056 label = "run_inv_norm";
9057 break;
9058 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
9059 label = "run_inv_dyn";
9060 break;
9061 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
9062 label = "run_inv_dir";
9063 break;
9064 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
9065 label = "run_inv_vir";
9066 break;
9067 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
9068 label = "icall";
9069 break;
9070 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
9071 label = "native_func_aot";
9072 break;
9073 case WRAPPER_SUBTYPE_PINVOKE:
9074 label = "pinvoke";
9075 break;
9076 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
9077 label = "synch_inner";
9078 break;
9079 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
9080 label = "gshared_in";
9081 break;
9082 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
9083 label = "gshared_out";
9084 break;
9085 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
9086 label = "array_acc";
9087 break;
9088 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
9089 label = "generic_arry_help";
9090 break;
9091 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
9092 label = "del_inv_virt";
9093 break;
9094 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
9095 label = "del_inv_bound";
9096 break;
9097 case WRAPPER_SUBTYPE_INTERP_IN:
9098 label = "interp_in";
9099 break;
9100 case WRAPPER_SUBTYPE_INTERP_LMF:
9101 label = "interp_lmf";
9102 break;
9103 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
9104 label = "gsharedvt_in_sig";
9105 break;
9106 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
9107 label = "gsharedvt_out_sig";
9108 break;
9109 case WRAPPER_SUBTYPE_AOT_INIT:
9110 label = "aot_init";
9111 break;
9112 default:
9113 g_assert_not_reached ();
9116 g_string_append_printf (s, "%s_", label);
9119 static char *
9120 sanitize_mangled_string (const char *input)
9122 GString *s = g_string_new ("");
9124 for (int i=0; input [i] != '\0'; i++) {
9125 char c = input [i];
9126 switch (c) {
9127 case '.':
9128 g_string_append (s, "_dot_");
9129 break;
9130 case ' ':
9131 g_string_append (s, "_");
9132 break;
9133 case '`':
9134 g_string_append (s, "_bt_");
9135 break;
9136 case '<':
9137 g_string_append (s, "_le_");
9138 break;
9139 case '>':
9140 g_string_append (s, "_gt_");
9141 break;
9142 case '/':
9143 g_string_append (s, "_sl_");
9144 break;
9145 case '[':
9146 g_string_append (s, "_lbrack_");
9147 break;
9148 case ']':
9149 g_string_append (s, "_rbrack_");
9150 break;
9151 case '(':
9152 g_string_append (s, "_lparen_");
9153 break;
9154 case '-':
9155 g_string_append (s, "_dash_");
9156 break;
9157 case ')':
9158 g_string_append (s, "_rparen_");
9159 break;
9160 case ',':
9161 g_string_append (s, "_comma_");
9162 break;
9163 case ':':
9164 g_string_append (s, "_colon_");
9165 break;
9166 default:
9167 g_string_append_c (s, c);
9171 return g_string_free (s, FALSE);
9174 static gboolean
9175 append_mangled_klass (GString *s, MonoClass *klass)
9177 char *klass_desc = mono_class_full_name (klass);
9178 g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
9179 g_free (klass_desc);
9181 // Success
9182 return TRUE;
9185 static gboolean
9186 append_mangled_method (GString *s, MonoMethod *method);
9188 static gboolean
9189 append_mangled_wrapper (GString *s, MonoMethod *method)
9191 gboolean success = TRUE;
9192 gboolean append_sig = TRUE;
9193 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9194 g_string_append_printf (s, "wrapper_");
9195 /* Most wrappers are in mscorlib */
9196 if (m_class_get_image (method->klass) != mono_get_corlib ())
9197 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9199 if (method->wrapper_type != MONO_WRAPPER_OTHER && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
9200 append_mangled_wrapper_type (s, method->wrapper_type);
9202 switch (method->wrapper_type) {
9203 case MONO_WRAPPER_REMOTING_INVOKE:
9204 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
9205 case MONO_WRAPPER_XDOMAIN_INVOKE: {
9206 MonoMethod *m = mono_marshal_method_from_wrapper (method);
9207 g_assert (m);
9208 success = success && append_mangled_method (s, m);
9209 break;
9211 case MONO_WRAPPER_PROXY_ISINST:
9212 case MONO_WRAPPER_LDFLD:
9213 case MONO_WRAPPER_LDFLDA:
9214 case MONO_WRAPPER_STFLD: {
9215 g_assert (info);
9216 success = success && append_mangled_klass (s, info->d.proxy.klass);
9217 break;
9219 case MONO_WRAPPER_ALLOC: {
9220 /* The GC name is saved once in MonoAotFileInfo */
9221 g_assert (info->d.alloc.alloc_type != -1);
9222 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
9223 // SlowAlloc, etc
9224 g_string_append_printf (s, "%s_", method->name);
9225 break;
9227 case MONO_WRAPPER_WRITE_BARRIER: {
9228 g_string_append_printf (s, "%s_", method->name);
9229 break;
9231 case MONO_WRAPPER_STELEMREF: {
9232 append_mangled_wrapper_subtype (s, info->subtype);
9233 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
9234 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
9235 break;
9237 case MONO_WRAPPER_OTHER: {
9238 append_mangled_wrapper_subtype (s, info->subtype);
9239 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
9240 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
9241 success = success && append_mangled_klass (s, method->klass);
9242 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
9243 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
9244 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
9245 success = success && append_mangled_method (s, info->d.array_accessor.method);
9246 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
9247 append_mangled_signature (s, info->d.interp_in.sig);
9248 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
9249 append_mangled_signature (s, info->d.gsharedvt.sig);
9250 append_sig = FALSE;
9251 } else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
9252 append_mangled_signature (s, info->d.gsharedvt.sig);
9253 append_sig = FALSE;
9254 } else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
9255 g_string_append_printf (s, "%s", method->name);
9256 else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT) {
9257 g_string_append_printf (s, "%s_%d_", m_class_get_image (method->klass)->assembly->aname.name, info->d.aot_init.subtype);
9258 append_sig = FALSE;
9260 break;
9262 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
9263 append_mangled_wrapper_subtype (s, info->subtype);
9264 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
9265 const char *name = method->name;
9266 const char *prefix = "__icall_wrapper_";
9267 if (strstr (name, prefix) == name)
9268 name += strlen (prefix);
9269 g_string_append_printf (s, "%s", name);
9270 append_sig = FALSE;
9271 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
9272 success = success && append_mangled_method (s, info->d.managed_to_native.method);
9273 } else {
9274 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
9275 success = success && append_mangled_method (s, info->d.managed_to_native.method);
9277 break;
9279 case MONO_WRAPPER_SYNCHRONIZED: {
9280 MonoMethod *m;
9282 m = mono_marshal_method_from_wrapper (method);
9283 g_assert (m);
9284 g_assert (m != method);
9285 success = success && append_mangled_method (s, m);
9286 break;
9288 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
9289 append_mangled_wrapper_subtype (s, info->subtype);
9291 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
9292 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
9293 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
9294 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
9295 success = success && append_mangled_method (s, info->d.string_ctor.method);
9296 } else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
9297 success = success && append_mangled_method (s, info->d.generic_array_helper.method);
9298 } else {
9299 success = FALSE;
9301 break;
9303 case MONO_WRAPPER_CASTCLASS: {
9304 append_mangled_wrapper_subtype (s, info->subtype);
9305 break;
9307 case MONO_WRAPPER_RUNTIME_INVOKE: {
9308 append_mangled_wrapper_subtype (s, info->subtype);
9309 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
9310 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
9311 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
9312 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
9313 break;
9315 case MONO_WRAPPER_DELEGATE_INVOKE:
9316 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
9317 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
9318 if (method->is_inflated) {
9319 /* These wrappers are identified by their class */
9320 g_string_append_printf (s, "i_");
9321 success = success && append_mangled_klass (s, method->klass);
9322 } else {
9323 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9325 g_string_append_printf (s, "u_");
9326 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
9327 append_mangled_wrapper_subtype (s, info->subtype);
9328 g_string_append_printf (s, "u_sigstart");
9330 break;
9332 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
9333 g_assert (info);
9334 success = success && append_mangled_method (s, info->d.native_to_managed.method);
9335 success = success && append_mangled_klass (s, method->klass);
9336 break;
9338 default:
9339 g_assert_not_reached ();
9341 if (success && append_sig)
9342 success = append_mangled_signature (s, mono_method_signature_internal (method));
9343 return success;
9346 static void
9347 append_mangled_ginst (GString *str, MonoGenericInst *ginst)
9349 int i;
9351 for (i = 0; i < ginst->type_argc; ++i) {
9352 if (i > 0)
9353 g_string_append (str, ", ");
9354 MonoType *type = ginst->type_argv [i];
9355 switch (type->type) {
9356 case MONO_TYPE_VAR:
9357 case MONO_TYPE_MVAR: {
9358 MonoType *constraint = NULL;
9359 if (type->data.generic_param)
9360 constraint = type->data.generic_param->gshared_constraint;
9361 if (constraint) {
9362 g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
9363 g_string_append (str, "gshared:");
9364 mono_type_get_desc (str, constraint, TRUE);
9365 break;
9367 // Else falls through to common case
9369 default:
9370 mono_type_get_desc (str, type, TRUE);
9375 static void
9376 append_mangled_context (GString *str, MonoGenericContext *context)
9378 GString *res = g_string_new ("");
9380 g_string_append_printf (res, "gens_");
9381 g_string_append (res, "00");
9383 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
9384 good = good || (context->method_inst && context->method_inst->type_argc > 0);
9385 g_assert (good);
9387 if (context->class_inst)
9388 append_mangled_ginst (res, context->class_inst);
9389 if (context->method_inst) {
9390 if (context->class_inst)
9391 g_string_append (res, "11");
9392 append_mangled_ginst (res, context->method_inst);
9394 g_string_append_printf (str, "gens_%s", res->str);
9395 g_free (res);
9398 static gboolean
9399 append_mangled_method (GString *s, MonoMethod *method)
9401 if (method->wrapper_type)
9402 return append_mangled_wrapper (s, method);
9404 if (method->is_inflated) {
9405 g_string_append_printf (s, "inflated_");
9406 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
9407 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
9409 append_mangled_context (s, &imethod->context);
9410 g_string_append_printf (s, "_declared_by_%s_", m_class_get_image (imethod->declaring->klass)->assembly->aname.name);
9411 append_mangled_method (s, imethod->declaring);
9412 } else if (method->is_generic) {
9413 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9415 g_string_append_printf (s, "generic_");
9416 append_mangled_klass (s, method->klass);
9417 g_string_append_printf (s, "_%s_", method->name);
9419 MonoGenericContainer *container = mono_method_get_generic_container (method);
9420 g_string_append_printf (s, "_");
9421 append_mangled_context (s, &container->context);
9423 return append_mangled_signature (s, mono_method_signature_internal (method));
9424 } else {
9425 g_string_append_printf (s, "%s", m_class_get_image (method->klass)->assembly->aname.name);
9426 append_mangled_klass (s, method->klass);
9427 g_string_append_printf (s, "_%s_", method->name);
9428 if (!append_mangled_signature (s, mono_method_signature_internal (method))) {
9429 g_string_free (s, TRUE);
9430 return FALSE;
9434 return TRUE;
9438 * mono_aot_get_mangled_method_name:
9440 * Return a unique mangled name for METHOD, or NULL.
9442 char*
9443 mono_aot_get_mangled_method_name (MonoMethod *method)
9445 // FIXME: use static cache (mempool?)
9446 // We call this a *lot*
9448 GString *s = g_string_new ("aot_");
9449 if (!append_mangled_method (s, method)) {
9450 g_string_free (s, TRUE);
9451 return NULL;
9452 } else {
9453 char *out = g_string_free (s, FALSE);
9454 // Scrub method and class names
9455 char *cleaned = sanitize_mangled_string (out);
9456 g_free (out);
9457 return cleaned;
9461 gboolean
9462 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
9464 return is_direct_callable (llvm_acfg, NULL, patch_info);
9467 void
9468 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
9470 MonoPltEntry *plt_entry;
9472 plt_entry = get_plt_entry (llvm_acfg, patch_info);
9473 plt_entry->llvm_used = FALSE;
9476 char*
9477 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
9479 const char *sym = NULL;
9481 if (llvm_acfg->aot_opts.direct_icalls) {
9482 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9483 /* Call to a C function implementing a jit icall */
9484 sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
9485 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9486 MonoMethod *method = (MonoMethod *)data;
9487 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9488 sym = lookup_icall_symbol_name_aot (method);
9489 else if (llvm_acfg->aot_opts.direct_pinvoke)
9490 sym = get_pinvoke_import (llvm_acfg, method);
9491 } else if (type == MONO_PATCH_INFO_JIT_ICALL_ID) {
9492 MonoJitICallInfo const * const info = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data);
9493 char const * const name = info->c_symbol;
9494 if (name && info->func == info->wrapper)
9495 sym = name;
9497 if (sym)
9498 return g_strdup (sym);
9500 return NULL;
9503 char*
9504 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
9506 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
9507 MonoPltEntry *plt_entry;
9508 const char *sym = NULL;
9510 ji->type = type;
9511 ji->data.target = data;
9513 if (!can_encode_patch (llvm_acfg, ji))
9514 return NULL;
9516 if (llvm_acfg->aot_opts.direct_icalls) {
9517 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9518 /* Call to a C function implementing a jit icall */
9519 sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
9520 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9521 MonoMethod *method = (MonoMethod *)data;
9522 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9523 sym = lookup_icall_symbol_name_aot (method);
9525 if (sym)
9526 return g_strdup (sym);
9529 plt_entry = get_plt_entry (llvm_acfg, ji);
9530 plt_entry->llvm_used = TRUE;
9532 #if defined(TARGET_MACH)
9533 return g_strdup (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
9534 #else
9535 return g_strdup (plt_entry->llvm_symbol);
9536 #endif
9540 mono_aot_get_method_index (MonoMethod *method)
9542 g_assert (llvm_acfg);
9543 return get_method_index (llvm_acfg, method);
9546 MonoJumpInfo*
9547 mono_aot_patch_info_dup (MonoJumpInfo* ji)
9549 MonoJumpInfo *res;
9551 mono_acfg_lock (llvm_acfg);
9552 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
9553 mono_acfg_unlock (llvm_acfg);
9555 return res;
9558 static int
9559 execute_system (const char * command)
9561 int status = 0;
9563 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
9564 // We need an extra set of quotes around the whole command to properly handle commands
9565 // with spaces since internally the command is called through "cmd /c.
9566 char * quoted_command = g_strdup_printf ("\"%s\"", command);
9568 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
9569 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
9570 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
9571 status = _wsystem (wstr);
9572 g_free (wstr);
9574 g_free (quoted_command);
9575 #elif defined (HAVE_SYSTEM)
9576 status = system (command);
9577 #else
9578 g_assert_not_reached ();
9579 #endif
9581 return status;
9584 #ifdef ENABLE_LLVM
9587 * emit_llvm_file:
9589 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
9590 * tools.
9592 static gboolean
9593 emit_llvm_file (MonoAotCompile *acfg)
9595 char *command, *opts, *tempbc, *optbc, *output_fname;
9597 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
9598 if (acfg->aot_opts.no_opt)
9599 tempbc = g_strdup (acfg->aot_opts.llvm_outfile);
9600 else
9601 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9602 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
9603 } else {
9604 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9605 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
9608 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
9610 if (acfg->aot_opts.no_opt)
9611 return TRUE;
9613 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
9614 * a lot of time, and doesn't seem to save much space.
9615 * The following optimizations cannot be enabled:
9616 * - 'tailcallelim'
9617 * - 'jump-threading' changes our blockaddress references to int constants.
9618 * - 'basiccg' fails because it contains:
9619 * if (CS && !isa<IntrinsicInst>(II)) {
9620 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
9621 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
9622 * The opt list below was produced by taking the output of:
9623 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
9624 * then removing tailcallelim + the global opts.
9625 * strip-dead-prototypes deletes unused intrinsics definitions.
9627 /* The dse pass is disabled because of #13734 and #17616 */
9629 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
9630 * // If we have no DataLayout information around, then the size of the store
9631 * // is inferrable from the pointee type. If they are the same type, then
9632 * // we know that the store is safe.
9633 * if (AA.getDataLayout() == 0 &&
9634 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
9635 * return OverwriteComplete;
9636 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
9638 if (acfg->aot_opts.llvm_only) {
9639 // FIXME: This doesn't work yet
9640 opts = g_strdup ("");
9641 } else {
9642 opts = g_strdup ("-O2 -disable-tail-calls -place-safepoints -spp-all-backedges");
9645 if (acfg->aot_opts.llvm_opts) {
9646 opts = g_strdup_printf ("%s %s", opts, acfg->aot_opts.llvm_opts);
9649 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
9650 aot_printf (acfg, "Executing opt: %s\n", command);
9651 if (execute_system (command) != 0)
9652 return FALSE;
9653 g_free (opts);
9655 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
9656 /* Nothing else to do */
9657 return TRUE;
9659 if (acfg->aot_opts.llvm_only) {
9660 /* Use the stock clang from xcode */
9661 // FIXME: arch
9662 command = g_strdup_printf ("%s -fexceptions -fpic -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.clangxx, acfg->llvm_ofile, acfg->tmpbasename);
9664 aot_printf (acfg, "Executing clang: %s\n", command);
9665 if (execute_system (command) != 0)
9666 return FALSE;
9667 return TRUE;
9670 if (!acfg->llc_args)
9671 acfg->llc_args = g_string_new ("");
9673 /* Verbose asm slows down llc greatly */
9674 g_string_append (acfg->llc_args, " -asm-verbose=false");
9676 if (acfg->aot_opts.mtriple)
9677 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
9679 #if defined(TARGET_X86_64_WIN32_MSVC)
9680 if (!acfg->aot_opts.mtriple)
9681 g_string_append_printf (acfg->llc_args, " -mtriple=%s", "x86_64-pc-windows-msvc");
9682 #endif
9684 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
9686 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
9688 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
9690 #if defined(TARGET_AMD64) || defined(TARGET_X86)
9691 /* This generates stack adjustments in the middle of functions breaking unwind info */
9692 g_string_append_printf (acfg->llc_args, " -no-x86-call-frame-opt");
9693 #endif
9695 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS) || defined(TARGET_X86_64_WIN32_MSVC)
9696 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9697 #else
9698 if (llvm_acfg->aot_opts.static_link)
9699 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
9700 else
9701 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9702 #endif
9704 if (acfg->llvm_owriter) {
9705 /* Emit an object file directly */
9706 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
9707 g_string_append_printf (acfg->llc_args, " -filetype=obj");
9708 } else {
9709 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
9712 if (acfg->aot_opts.llvm_llc) {
9713 g_string_append_printf (acfg->llc_args, " %s", acfg->aot_opts.llvm_llc);
9716 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
9717 g_free (output_fname);
9719 aot_printf (acfg, "Executing llc: %s\n", command);
9721 if (execute_system (command) != 0)
9722 return FALSE;
9723 return TRUE;
9725 #endif
9727 /* Set the skip flag for methods which do not need to be emitted because of dedup */
9728 static void
9729 dedup_skip_methods (MonoAotCompile *acfg)
9731 int oindex, i;
9733 if (acfg->aot_opts.llvm_only)
9734 return;
9736 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9737 MonoCompile *cfg;
9738 MonoMethod *method;
9740 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9742 cfg = acfg->cfgs [i];
9744 if (!cfg)
9745 continue;
9747 method = cfg->orig_method;
9749 gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
9750 gboolean dedupable = mono_aot_can_dedup (method);
9752 // cfg->skip is vital for LLVM to work, can't just continue in this loop
9753 if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
9754 mono_dedup_cache_method (acfg, method);
9756 // Don't compile inflated methods if we're in first phase of
9757 // dedup
9759 // In second phase, we emit methods that
9760 // are dedupable. We also emit later methods
9761 // which are referenced by them and added later.
9762 // For this reason, when in the dedup_include mode,
9763 // we never set skip.
9764 if (acfg->aot_opts.dedup)
9765 cfg->skip = TRUE;
9768 // Don't compile anything in this mode
9769 if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
9770 cfg->skip = TRUE;
9772 // Compile everything in this mode
9773 if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
9774 cfg->skip = FALSE;
9776 /*if (dedup_collect) {*/
9777 /*char *name = mono_aot_get_mangled_method_name (method);*/
9779 /*if (ignore_cfg (cfg))*/
9780 /*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
9781 /*else*/
9782 /*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
9784 /*g_free (name);*/
9785 /*}*/
9789 static void
9790 emit_code (MonoAotCompile *acfg)
9792 int oindex, i, prev_index;
9793 gboolean saved_unbox_info = FALSE; // See mono_aot_get_unbox_trampoline.
9794 char symbol [MAX_SYMBOL_SIZE];
9796 if (acfg->aot_opts.llvm_only)
9797 return;
9799 #if defined(TARGET_POWERPC64)
9800 sprintf (symbol, ".Lgot_addr");
9801 emit_section_change (acfg, ".text", 0);
9802 emit_alignment (acfg, 8);
9803 emit_label (acfg, symbol);
9804 emit_pointer (acfg, acfg->got_symbol);
9805 #endif
9808 * This global symbol is used to compute the address of each method using the
9809 * code_offsets array. It is also used to compute the memory ranges occupied by
9810 * AOT code, so it must be equal to the address of the first emitted method.
9812 emit_section_change (acfg, ".text", 0);
9813 emit_alignment_code (acfg, 8);
9814 emit_info_symbol (acfg, "jit_code_start", TRUE);
9817 * Emit some padding so the local symbol for the first method doesn't have the
9818 * same address as 'methods'.
9820 emit_padding (acfg, 16);
9822 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9823 MonoCompile *cfg;
9824 MonoMethod *method;
9826 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9828 cfg = acfg->cfgs [i];
9830 if (!cfg)
9831 continue;
9833 method = cfg->orig_method;
9835 if (ignore_cfg (cfg))
9836 continue;
9838 /* Emit unbox trampoline */
9839 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9840 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
9842 emit_section_change (acfg, ".text", 0);
9844 if (acfg->thumb_mixed && cfg->compile_llvm) {
9845 emit_set_thumb_mode (acfg);
9846 fprintf (acfg->fp, "\n.thumb_func\n");
9849 emit_label (acfg, symbol);
9851 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
9853 if (acfg->thumb_mixed && cfg->compile_llvm)
9854 emit_set_arm_mode (acfg);
9856 if (!saved_unbox_info) {
9857 char user_symbol [128];
9858 GSList *unwind_ops;
9859 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
9861 emit_label (acfg, "ut_end");
9863 unwind_ops = mono_unwind_get_cie_program ();
9864 save_unwind_info (acfg, user_symbol, unwind_ops);
9865 mono_free_unwind_info (unwind_ops);
9867 /* Save the unbox trampoline size */
9868 #ifdef TARGET_AMD64
9869 // LLVM unbox trampolines vary in size, 6 or 9 bytes,
9870 // due to the last instruction being 2 or 5 bytes.
9871 // There is no need to describe interior bytes of instructions
9872 // however, so state the size as if the last instruction is size 1.
9873 emit_int32 (acfg, 5);
9874 #else
9875 emit_symbol_diff (acfg, "ut_end", symbol, 0);
9876 #endif
9877 saved_unbox_info = TRUE;
9881 if (cfg->compile_llvm) {
9882 acfg->stats.llvm_count ++;
9883 } else {
9884 emit_method_code (acfg, cfg);
9888 emit_section_change (acfg, ".text", 0);
9889 emit_alignment_code (acfg, 8);
9890 emit_info_symbol (acfg, "jit_code_end", TRUE);
9892 /* To distinguish it from the next symbol */
9893 emit_padding (acfg, 4);
9896 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
9897 * from optimizing them away, since it doesn't see that code_offsets references them.
9898 * JITted methods don't need this since they are referenced using assembler local
9899 * symbols.
9900 * FIXME: This is why write-symbols doesn't work on OSX ?
9902 if (acfg->llvm && acfg->need_no_dead_strip) {
9903 fprintf (acfg->fp, "\n");
9904 for (i = 0; i < acfg->nmethods; ++i) {
9905 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
9906 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
9911 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
9912 * This is PIE code, and the linker can update it if needed.
9915 sprintf (symbol, "method_addresses");
9916 emit_section_change (acfg, ".text", 1);
9917 emit_alignment_code (acfg, 8);
9918 emit_info_symbol (acfg, symbol, TRUE);
9919 if (acfg->aot_opts.write_symbols)
9920 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
9921 emit_unset_mode (acfg);
9922 if (acfg->need_no_dead_strip)
9923 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
9925 for (i = 0; i < acfg->nmethods; ++i) {
9926 #ifdef MONO_ARCH_AOT_SUPPORTED
9927 int call_size;
9929 if (!ignore_cfg (acfg->cfgs [i])) {
9930 arch_emit_label_address (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
9931 } else {
9932 arch_emit_label_address (acfg, symbol, FALSE, FALSE, NULL, &call_size);
9934 #endif
9937 sprintf (symbol, "method_addresses_end");
9938 emit_label (acfg, symbol);
9939 emit_line (acfg);
9941 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
9942 sprintf (symbol, "unbox_trampolines");
9943 emit_section_change (acfg, RODATA_SECT, 0);
9944 emit_alignment (acfg, 8);
9945 emit_info_symbol (acfg, symbol, FALSE);
9947 prev_index = -1;
9948 for (i = 0; i < acfg->nmethods; ++i) {
9949 MonoCompile *cfg;
9950 MonoMethod *method;
9951 int index;
9953 cfg = acfg->cfgs [i];
9954 if (ignore_cfg (cfg))
9955 continue;
9957 method = cfg->orig_method;
9959 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9960 index = get_method_index (acfg, method);
9962 emit_int32 (acfg, index);
9963 /* Make sure the table is sorted by index */
9964 g_assert (index > prev_index);
9965 prev_index = index;
9968 sprintf (symbol, "unbox_trampolines_end");
9969 emit_info_symbol (acfg, symbol, FALSE);
9970 emit_int32 (acfg, 0);
9972 /* Emit a separate table with the trampoline addresses/offsets */
9973 sprintf (symbol, "unbox_trampoline_addresses");
9974 emit_section_change (acfg, ".text", 0);
9975 emit_alignment_code (acfg, 8);
9976 emit_info_symbol (acfg, symbol, TRUE);
9978 for (i = 0; i < acfg->nmethods; ++i) {
9979 MonoCompile *cfg;
9980 MonoMethod *method;
9982 cfg = acfg->cfgs [i];
9983 if (ignore_cfg (cfg))
9984 continue;
9986 method = cfg->orig_method;
9987 (void)method;
9989 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9990 #ifdef MONO_ARCH_AOT_SUPPORTED
9991 int call_size;
9993 const int index = get_method_index (acfg, method);
9994 sprintf (symbol, "ut_%d", index);
9996 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
9997 #endif
10000 emit_int32 (acfg, 0);
10003 static void
10004 emit_info (MonoAotCompile *acfg)
10006 int oindex, i;
10007 gint32 *offsets;
10009 offsets = g_new0 (gint32, acfg->nmethods);
10011 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
10012 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
10014 if (acfg->cfgs [i]) {
10015 emit_method_info (acfg, acfg->cfgs [i]);
10016 offsets [i] = acfg->cfgs [i]->method_info_offset;
10017 } else {
10018 offsets [i] = 0;
10022 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10024 g_free (offsets);
10027 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
10029 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
10030 #define mix(a,b,c) { \
10031 a -= c; a ^= rot(c, 4); c += b; \
10032 b -= a; b ^= rot(a, 6); a += c; \
10033 c -= b; c ^= rot(b, 8); b += a; \
10034 a -= c; a ^= rot(c,16); c += b; \
10035 b -= a; b ^= rot(a,19); a += c; \
10036 c -= b; c ^= rot(b, 4); b += a; \
10038 #define mono_final(a,b,c) { \
10039 c ^= b; c -= rot(b,14); \
10040 a ^= c; a -= rot(c,11); \
10041 b ^= a; b -= rot(a,25); \
10042 c ^= b; c -= rot(b,16); \
10043 a ^= c; a -= rot(c,4); \
10044 b ^= a; b -= rot(a,14); \
10045 c ^= b; c -= rot(b,24); \
10048 static guint
10049 mono_aot_type_hash (MonoType *t1)
10051 guint hash = t1->type;
10053 hash |= t1->byref << 6; /* do not collide with t1->type values */
10054 switch (t1->type) {
10055 case MONO_TYPE_VALUETYPE:
10056 case MONO_TYPE_CLASS:
10057 case MONO_TYPE_SZARRAY:
10058 /* check if the distribution is good enough */
10059 return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.klass));
10060 case MONO_TYPE_PTR:
10061 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
10062 case MONO_TYPE_ARRAY:
10063 return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass));
10064 case MONO_TYPE_GENERICINST:
10065 return ((hash << 5) - hash) ^ 0;
10066 default:
10067 return hash;
10072 * mono_aot_method_hash:
10074 * Return a hash code for methods which only depends on metadata.
10076 guint32
10077 mono_aot_method_hash (MonoMethod *method)
10079 MonoMethodSignature *sig;
10080 MonoClass *klass;
10081 int i, hindex;
10082 int hashes_count;
10083 guint32 *hashes_start, *hashes;
10084 guint32 a, b, c;
10085 MonoGenericInst *class_ginst = NULL;
10086 MonoGenericInst *ginst = NULL;
10088 /* Similar to the hash in mono_method_get_imt_slot () */
10090 sig = mono_method_signature_internal (method);
10092 if (mono_class_is_ginst (method->klass))
10093 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
10094 if (method->is_inflated)
10095 ginst = ((MonoMethodInflated*)method)->context.method_inst;
10097 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
10098 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
10099 hashes = hashes_start;
10101 /* Some wrappers are assigned to random classes */
10102 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
10103 klass = method->klass;
10104 else
10105 klass = mono_defaults.object_class;
10107 if (!method->wrapper_type) {
10108 char *full_name;
10110 if (mono_class_is_ginst (klass))
10111 full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
10112 else
10113 full_name = mono_type_full_name (m_class_get_byval_arg (klass));
10115 hashes [0] = mono_metadata_str_hash (full_name);
10116 hashes [1] = 0;
10117 g_free (full_name);
10118 } else {
10119 hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
10120 hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
10122 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
10123 /* The method name includes a stringified pointer */
10124 hashes [2] = 0;
10125 else
10126 hashes [2] = mono_metadata_str_hash (method->name);
10127 hashes [3] = method->wrapper_type;
10128 hashes [4] = mono_aot_type_hash (sig->ret);
10129 hindex = 5;
10130 for (i = 0; i < sig->param_count; i++) {
10131 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
10133 if (class_ginst) {
10134 for (i = 0; i < class_ginst->type_argc; ++i)
10135 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
10137 if (ginst) {
10138 for (i = 0; i < ginst->type_argc; ++i)
10139 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
10141 g_assert (hindex == hashes_count);
10143 /* Setup internal state */
10144 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
10146 /* Handle most of the hashes */
10147 while (hashes_count > 3) {
10148 a += hashes [0];
10149 b += hashes [1];
10150 c += hashes [2];
10151 mix (a,b,c);
10152 hashes_count -= 3;
10153 hashes += 3;
10156 /* Handle the last 3 hashes (all the case statements fall through) */
10157 switch (hashes_count) {
10158 case 3 : c += hashes [2];
10159 case 2 : b += hashes [1];
10160 case 1 : a += hashes [0];
10161 mono_final (a,b,c);
10162 case 0: /* nothing left to add */
10163 break;
10166 g_free (hashes_start);
10168 return c;
10170 #undef rot
10171 #undef mix
10172 #undef mono_final
10175 * mono_aot_get_array_helper_from_wrapper;
10177 * Get the helper method in Array called by an array wrapper method.
10179 MonoMethod*
10180 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
10182 MonoMethod *m;
10183 const char *prefix;
10184 MonoGenericContext ctx;
10185 MonoType *args [16];
10186 char *mname, *iname, *s, *s2, *helper_name = NULL;
10188 prefix = "System.Collections.Generic";
10189 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
10190 s2 = strstr (s, "`1.");
10191 g_assert (s2);
10192 s2 [0] = '\0';
10193 iname = s;
10194 mname = s2 + 3;
10196 //printf ("X: %s %s\n", iname, mname);
10198 if (!strcmp (iname, "IList"))
10199 helper_name = g_strdup_printf ("InternalArray__%s", mname);
10200 else
10201 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
10202 m = get_method_nofail (mono_defaults.array_class, helper_name, mono_method_signature_internal (method)->param_count, 0);
10203 g_assert (m);
10204 g_free (helper_name);
10205 g_free (s);
10207 if (m->is_generic) {
10208 ERROR_DECL (error);
10209 memset (&ctx, 0, sizeof (ctx));
10210 args [0] = m_class_get_byval_arg (m_class_get_element_class (method->klass));
10211 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
10212 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
10213 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
10216 return m;
10219 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
10221 typedef struct HashEntry {
10222 guint32 key, value, index;
10223 struct HashEntry *next;
10224 } HashEntry;
10227 * emit_extra_methods:
10229 * Emit methods which are not in the METHOD table, like wrappers.
10231 static void
10232 emit_extra_methods (MonoAotCompile *acfg)
10234 int i, table_size, buf_size;
10235 guint8 *p, *buf;
10236 guint32 *info_offsets;
10237 guint32 hash;
10238 GPtrArray *table;
10239 HashEntry *entry, *new_entry;
10240 int nmethods, max_chain_length;
10241 int *chain_lengths;
10243 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
10245 /* Emit method info */
10246 nmethods = 0;
10247 for (i = 0; i < acfg->extra_methods->len; ++i) {
10248 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10249 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
10251 if (ignore_cfg (cfg))
10252 continue;
10254 buf_size = 10240;
10255 p = buf = (guint8 *)g_malloc (buf_size);
10257 nmethods ++;
10259 method = cfg->method_to_register;
10261 encode_method_ref (acfg, method, p, &p);
10263 g_assert ((p - buf) < buf_size);
10265 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10266 g_free (buf);
10270 * Construct a chained hash table for mapping indexes in extra_method_info to
10271 * method indexes.
10273 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
10274 table = g_ptr_array_sized_new (table_size);
10275 for (i = 0; i < table_size; ++i)
10276 g_ptr_array_add (table, NULL);
10277 chain_lengths = g_new0 (int, table_size);
10278 max_chain_length = 0;
10279 for (i = 0; i < acfg->extra_methods->len; ++i) {
10280 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10281 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
10282 guint32 key, value;
10284 if (ignore_cfg (cfg))
10285 continue;
10287 key = info_offsets [i];
10288 value = get_method_index (acfg, method);
10290 hash = mono_aot_method_hash (method) % table_size;
10291 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
10293 chain_lengths [hash] ++;
10294 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
10296 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
10297 new_entry->key = key;
10298 new_entry->value = value;
10300 entry = (HashEntry *)g_ptr_array_index (table, hash);
10301 if (entry == NULL) {
10302 new_entry->index = hash;
10303 g_ptr_array_index (table, hash) = new_entry;
10304 } else {
10305 while (entry->next)
10306 entry = entry->next;
10308 entry->next = new_entry;
10309 new_entry->index = table->len;
10310 g_ptr_array_add (table, new_entry);
10313 g_free (chain_lengths);
10315 //printf ("MAX: %d\n", max_chain_length);
10317 buf_size = table->len * 12 + 4;
10318 p = buf = (guint8 *)g_malloc (buf_size);
10319 encode_int (table_size, p, &p);
10321 for (i = 0; i < table->len; ++i) {
10322 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
10324 if (entry == NULL) {
10325 encode_int (0, p, &p);
10326 encode_int (0, p, &p);
10327 encode_int (0, p, &p);
10328 } else {
10329 //g_assert (entry->key > 0);
10330 encode_int (entry->key, p, &p);
10331 encode_int (entry->value, p, &p);
10332 if (entry->next)
10333 encode_int (entry->next->index, p, &p);
10334 else
10335 encode_int (0, p, &p);
10338 g_assert (p - buf <= buf_size);
10340 /* Emit the table */
10341 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
10343 g_free (buf);
10346 * Emit a table reverse mapping method indexes to their index in extra_method_info.
10347 * This is used by mono_aot_find_jit_info ().
10349 buf_size = acfg->extra_methods->len * 8 + 4;
10350 p = buf = (guint8 *)g_malloc (buf_size);
10351 encode_int (acfg->extra_methods->len, p, &p);
10352 for (i = 0; i < acfg->extra_methods->len; ++i) {
10353 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10355 encode_int (get_method_index (acfg, method), p, &p);
10356 encode_int (info_offsets [i], p, &p);
10358 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
10360 g_free (buf);
10361 g_free (info_offsets);
10362 g_ptr_array_free (table, TRUE);
10365 static void
10366 generate_aotid (guint8* aotid)
10368 gpointer rand_handle;
10369 ERROR_DECL (error);
10371 mono_rand_open ();
10372 rand_handle = mono_rand_init (NULL, 0);
10374 mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
10375 mono_error_assert_ok (error);
10377 mono_rand_close (rand_handle);
10380 static void
10381 emit_exception_info (MonoAotCompile *acfg)
10383 int i;
10384 gint32 *offsets;
10385 SeqPointData sp_data;
10386 gboolean seq_points_to_file = FALSE;
10388 offsets = g_new0 (gint32, acfg->nmethods);
10389 for (i = 0; i < acfg->nmethods; ++i) {
10390 if (acfg->cfgs [i]) {
10391 MonoCompile *cfg = acfg->cfgs [i];
10393 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
10394 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
10395 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
10396 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
10397 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
10399 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
10400 offsets [i] = cfg->ex_info_offset;
10402 if (method_seq_points_to_file) {
10403 if (!seq_points_to_file) {
10404 mono_seq_point_data_init (&sp_data, acfg->nmethods);
10405 seq_points_to_file = TRUE;
10407 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
10409 } else {
10410 offsets [i] = 0;
10414 if (seq_points_to_file) {
10415 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
10416 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
10417 char *image_basename = g_path_get_basename (acfg->image->name);
10418 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
10419 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
10421 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
10422 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
10423 exit (1);
10426 mono_seq_point_data_write (&sp_data, aot_file_path);
10427 mono_seq_point_data_free (&sp_data);
10429 g_free (aotid);
10430 g_free (dir);
10431 g_free (image_basename);
10432 g_free (aot_file);
10433 g_free (aot_file_path);
10436 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10437 g_free (offsets);
10440 static void
10441 emit_unwind_info (MonoAotCompile *acfg)
10443 int i;
10444 char symbol [128];
10446 if (acfg->aot_opts.llvm_only) {
10447 g_assert (acfg->unwind_ops->len == 0);
10448 return;
10452 * The unwind info contains a lot of duplicates so we emit each unique
10453 * entry once, and only store the offset from the start of the table in the
10454 * exception info.
10457 sprintf (symbol, "unwind_info");
10458 emit_section_change (acfg, RODATA_SECT, 1);
10459 emit_alignment (acfg, 8);
10460 emit_info_symbol (acfg, symbol, TRUE);
10462 for (i = 0; i < acfg->unwind_ops->len; ++i) {
10463 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
10464 guint8 *unwind_info;
10465 guint32 unwind_info_len;
10466 guint8 buf [16];
10467 guint8 *p;
10469 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
10471 p = buf;
10472 encode_value (unwind_info_len, p, &p);
10473 emit_bytes (acfg, buf, p - buf);
10474 emit_bytes (acfg, unwind_info, unwind_info_len);
10476 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
10480 static void
10481 emit_class_info (MonoAotCompile *acfg)
10483 int i;
10484 gint32 *offsets;
10486 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
10487 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
10488 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
10490 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);
10491 g_free (offsets);
10494 typedef struct ClassNameTableEntry {
10495 guint32 token, index;
10496 struct ClassNameTableEntry *next;
10497 } ClassNameTableEntry;
10499 static void
10500 emit_class_name_table (MonoAotCompile *acfg)
10502 int i, table_size, buf_size;
10503 guint32 token, hash;
10504 MonoClass *klass;
10505 GPtrArray *table;
10506 char *full_name;
10507 guint8 *buf, *p;
10508 ClassNameTableEntry *entry, *new_entry;
10511 * Construct a chained hash table for mapping class names to typedef tokens.
10513 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
10514 table = g_ptr_array_sized_new (table_size);
10515 for (i = 0; i < table_size; ++i)
10516 g_ptr_array_add (table, NULL);
10517 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
10518 ERROR_DECL (error);
10519 token = MONO_TOKEN_TYPE_DEF | (i + 1);
10520 klass = mono_class_get_checked (acfg->image, token, error);
10521 if (!klass) {
10522 mono_error_cleanup (error);
10523 continue;
10525 full_name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
10526 hash = mono_metadata_str_hash (full_name) % table_size;
10527 g_free (full_name);
10529 /* FIXME: Allocate from the mempool */
10530 new_entry = g_new0 (ClassNameTableEntry, 1);
10531 new_entry->token = token;
10533 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
10534 if (entry == NULL) {
10535 new_entry->index = hash;
10536 g_ptr_array_index (table, hash) = new_entry;
10537 } else {
10538 while (entry->next)
10539 entry = entry->next;
10541 entry->next = new_entry;
10542 new_entry->index = table->len;
10543 g_ptr_array_add (table, new_entry);
10547 /* Emit the table */
10548 buf_size = table->len * 4 + 4;
10549 p = buf = (guint8 *)g_malloc0 (buf_size);
10551 /* FIXME: Optimize memory usage */
10552 g_assert (table_size < 65000);
10553 encode_int16 (table_size, p, &p);
10554 g_assert (table->len < 65000);
10555 for (i = 0; i < table->len; ++i) {
10556 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
10558 if (entry == NULL) {
10559 encode_int16 (0, p, &p);
10560 encode_int16 (0, p, &p);
10561 } else {
10562 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
10563 if (entry->next)
10564 encode_int16 (entry->next->index, p, &p);
10565 else
10566 encode_int16 (0, p, &p);
10568 g_free (entry);
10570 g_assert (p - buf <= buf_size);
10571 g_ptr_array_free (table, TRUE);
10573 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
10575 g_free (buf);
10578 static void
10579 emit_image_table (MonoAotCompile *acfg)
10581 int i, buf_size;
10582 guint8 *buf, *p;
10585 * The image table is small but referenced in a lot of places.
10586 * So we emit it at once, and reference its elements by an index.
10588 buf_size = acfg->image_table->len * 28 + 4;
10589 for (i = 0; i < acfg->image_table->len; i++) {
10590 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10591 MonoAssemblyName *aname = &image->assembly->aname;
10593 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
10596 buf = p = (guint8 *)g_malloc0 (buf_size);
10597 encode_int (acfg->image_table->len, p, &p);
10598 for (i = 0; i < acfg->image_table->len; i++) {
10599 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10600 MonoAssemblyName *aname = &image->assembly->aname;
10602 /* FIXME: Support multi-module assemblies */
10603 g_assert (image->assembly->image == image);
10605 encode_string (image->assembly_name, p, &p);
10606 encode_string (image->guid, p, &p);
10607 encode_string (aname->culture ? aname->culture : "", p, &p);
10608 encode_string ((const char*)aname->public_key_token, p, &p);
10610 while (GPOINTER_TO_UINT (p) % 8 != 0)
10611 p ++;
10613 encode_int (aname->flags, p, &p);
10614 encode_int (aname->major, p, &p);
10615 encode_int (aname->minor, p, &p);
10616 encode_int (aname->build, p, &p);
10617 encode_int (aname->revision, p, &p);
10619 g_assert (p - buf <= buf_size);
10621 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
10623 g_free (buf);
10626 static void
10627 emit_weak_field_indexes (MonoAotCompile *acfg)
10629 GHashTable *indexes;
10630 GHashTableIter iter;
10631 gpointer key, value;
10632 int buf_size;
10633 guint8 *buf, *p;
10635 /* Emit a table of weak field indexes, since computing these at runtime is expensive */
10636 mono_assembly_init_weak_fields (acfg->image);
10637 indexes = acfg->image->weak_field_indexes;
10638 g_assert (indexes);
10640 buf_size = (g_hash_table_size (indexes) + 1) * 4;
10641 buf = p = (guint8 *)g_malloc0 (buf_size);
10643 encode_int (g_hash_table_size (indexes), p, &p);
10644 g_hash_table_iter_init (&iter, indexes);
10645 while (g_hash_table_iter_next (&iter, &key, &value)) {
10646 guint32 index = GPOINTER_TO_UINT (key);
10647 encode_int (index, p, &p);
10649 g_assert (p - buf <= buf_size);
10651 emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
10653 g_free (buf);
10656 static void
10657 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
10659 int i, first_plt_got_patch = 0, buf_size;
10660 guint8 *p, *buf;
10661 guint32 *got_info_offsets;
10662 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
10664 /* Add the patches needed by the PLT to the GOT */
10665 if (!llvm) {
10666 acfg->plt_got_offset_base = acfg->got_offset;
10667 first_plt_got_patch = info->got_patches->len;
10668 for (i = 1; i < acfg->plt_offset; ++i) {
10669 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10671 g_ptr_array_add (info->got_patches, plt_entry->ji);
10673 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
10676 acfg->got_offset += acfg->plt_offset;
10680 * FIXME:
10681 * - optimize offsets table.
10682 * - reduce number of exported symbols.
10683 * - emit info for a klass only once.
10684 * - determine when a method uses a GOT slot which is guaranteed to be already
10685 * initialized.
10686 * - clean up and document the code.
10687 * - use String.Empty in class libs.
10690 /* Encode info required to decode shared GOT entries */
10691 buf_size = info->got_patches->len * 128;
10692 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
10693 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
10694 if (!llvm) {
10695 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
10696 /* Unused */
10697 if (acfg->plt_offset)
10698 acfg->plt_got_info_offsets [0] = 0;
10700 for (i = 0; i < info->got_patches->len; ++i) {
10701 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
10702 guint8 *p2;
10704 p = buf;
10706 encode_value (ji->type, p, &p);
10707 p2 = p;
10708 encode_patch (acfg, ji, p, &p);
10709 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
10710 g_assert (p - buf <= buf_size);
10711 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10713 if (!llvm && i >= first_plt_got_patch)
10714 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
10715 acfg->stats.got_info_size += p - buf;
10718 /* Emit got_info_offsets table */
10720 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
10721 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);
10724 static void
10725 emit_got (MonoAotCompile *acfg)
10727 char symbol [MAX_SYMBOL_SIZE];
10729 if (acfg->aot_opts.llvm_only)
10730 return;
10732 /* Don't make GOT global so accesses to it don't need relocations */
10733 sprintf (symbol, "%s", acfg->got_symbol);
10735 #ifdef TARGET_MACH
10736 emit_unset_mode (acfg);
10737 fprintf (acfg->fp, ".section __DATA, __bss\n");
10738 emit_alignment (acfg, 8);
10739 if (acfg->llvm)
10740 emit_info_symbol (acfg, "jit_got", FALSE);
10741 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10742 #else
10743 emit_section_change (acfg, ".bss", 0);
10744 emit_alignment (acfg, 8);
10745 if (acfg->aot_opts.write_symbols)
10746 emit_local_symbol (acfg, symbol, "got_end", FALSE);
10747 emit_label (acfg, symbol);
10748 if (acfg->llvm)
10749 emit_info_symbol (acfg, "jit_got", FALSE);
10750 if (acfg->got_offset > 0)
10751 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10752 #endif
10754 sprintf (symbol, "got_end");
10755 emit_label (acfg, symbol);
10758 typedef struct GlobalsTableEntry {
10759 guint32 value, index;
10760 struct GlobalsTableEntry *next;
10761 } GlobalsTableEntry;
10763 #ifdef TARGET_WIN32_MSVC
10764 #define DLL_ENTRY_POINT "DllMain"
10766 static void
10767 emit_library_info (MonoAotCompile *acfg)
10769 // Only include for shared libraries linked directly from generated object.
10770 if (link_shared_library (acfg)) {
10771 char *name = NULL;
10772 char symbol [MAX_SYMBOL_SIZE];
10774 // Ask linker to export all global symbols.
10775 emit_section_change (acfg, ".drectve", 0);
10776 for (guint i = 0; i < acfg->globals->len; ++i) {
10777 name = (char *)g_ptr_array_index (acfg->globals, i);
10778 g_assert (name != NULL);
10779 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
10780 emit_string (acfg, symbol);
10783 // Emit DLLMain function, needed by MSVC linker for DLL's.
10784 // NOTE, DllMain should not go into exports above.
10785 emit_section_change (acfg, ".text", 0);
10786 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
10787 emit_label (acfg, DLL_ENTRY_POINT);
10789 // Simple implementation of DLLMain, just returning TRUE.
10790 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
10791 fprintf (acfg->fp, "movl $1, %%eax\n");
10792 fprintf (acfg->fp, "ret\n");
10794 // Inform linker about our dll entry function.
10795 emit_section_change (acfg, ".drectve", 0);
10796 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
10797 return;
10801 #else
10803 static inline void
10804 emit_library_info (MonoAotCompile *acfg)
10806 return;
10808 #endif
10810 static void
10811 emit_globals (MonoAotCompile *acfg)
10813 int i, table_size;
10814 guint32 hash;
10815 GPtrArray *table;
10816 char symbol [1024];
10817 GlobalsTableEntry *entry, *new_entry;
10819 if (!acfg->aot_opts.static_link)
10820 return;
10822 if (acfg->aot_opts.llvm_only) {
10823 g_assert (acfg->globals->len == 0);
10824 return;
10828 * When static linking, we emit a table containing our globals.
10832 * Construct a chained hash table for mapping global names to their index in
10833 * the globals table.
10835 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
10836 table = g_ptr_array_sized_new (table_size);
10837 for (i = 0; i < table_size; ++i)
10838 g_ptr_array_add (table, NULL);
10839 for (i = 0; i < acfg->globals->len; ++i) {
10840 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10842 hash = mono_metadata_str_hash (name) % table_size;
10844 /* FIXME: Allocate from the mempool */
10845 new_entry = g_new0 (GlobalsTableEntry, 1);
10846 new_entry->value = i;
10848 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
10849 if (entry == NULL) {
10850 new_entry->index = hash;
10851 g_ptr_array_index (table, hash) = new_entry;
10852 } else {
10853 while (entry->next)
10854 entry = entry->next;
10856 entry->next = new_entry;
10857 new_entry->index = table->len;
10858 g_ptr_array_add (table, new_entry);
10862 /* Emit the table */
10863 sprintf (symbol, ".Lglobals_hash");
10864 emit_section_change (acfg, RODATA_SECT, 0);
10865 emit_alignment (acfg, 8);
10866 emit_label (acfg, symbol);
10868 /* FIXME: Optimize memory usage */
10869 g_assert (table_size < 65000);
10870 emit_int16 (acfg, table_size);
10871 for (i = 0; i < table->len; ++i) {
10872 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
10874 if (entry == NULL) {
10875 emit_int16 (acfg, 0);
10876 emit_int16 (acfg, 0);
10877 } else {
10878 emit_int16 (acfg, entry->value + 1);
10879 if (entry->next)
10880 emit_int16 (acfg, entry->next->index);
10881 else
10882 emit_int16 (acfg, 0);
10886 /* Emit the names */
10887 for (i = 0; i < acfg->globals->len; ++i) {
10888 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10890 sprintf (symbol, "name_%d", i);
10891 emit_section_change (acfg, RODATA_SECT, 1);
10892 #ifdef TARGET_MACH
10893 emit_alignment (acfg, 4);
10894 #endif
10895 emit_label (acfg, symbol);
10896 emit_string (acfg, name);
10899 /* Emit the globals table */
10900 sprintf (symbol, "globals");
10901 emit_section_change (acfg, ".data", 0);
10902 /* This is not a global, since it is accessed by the init function */
10903 emit_alignment (acfg, 8);
10904 emit_info_symbol (acfg, symbol, FALSE);
10906 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
10907 emit_pointer (acfg, symbol);
10909 for (i = 0; i < acfg->globals->len; ++i) {
10910 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10912 sprintf (symbol, "name_%d", i);
10913 emit_pointer (acfg, symbol);
10915 g_assert (strlen (name) < sizeof (symbol));
10916 sprintf (symbol, "%s", name);
10917 emit_pointer (acfg, symbol);
10919 /* Null terminate the table */
10920 emit_int32 (acfg, 0);
10921 emit_int32 (acfg, 0);
10924 static void
10925 emit_mem_end (MonoAotCompile *acfg)
10927 char symbol [128];
10929 if (acfg->aot_opts.llvm_only)
10930 return;
10932 sprintf (symbol, "mem_end");
10933 emit_section_change (acfg, ".text", 1);
10934 emit_alignment_code (acfg, 8);
10935 emit_label (acfg, symbol);
10938 static void
10939 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10941 int i;
10943 info->version = MONO_AOT_FILE_VERSION;
10944 info->plt_got_offset_base = acfg->plt_got_offset_base;
10945 info->got_size = acfg->got_offset * sizeof (target_mgreg_t);
10946 info->plt_size = acfg->plt_offset;
10947 info->nmethods = acfg->nmethods;
10948 info->nextra_methods = acfg->nextra_methods;
10949 info->flags = acfg->flags;
10950 info->opts = acfg->opts;
10951 info->simd_opts = acfg->simd_opts;
10952 info->gc_name_index = acfg->gc_name_offset;
10953 info->datafile_size = acfg->datafile_offset;
10954 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10955 info->table_offsets [i] = acfg->table_offsets [i];
10956 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10957 info->num_trampolines [i] = acfg->num_trampolines [i];
10958 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10959 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
10960 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10961 info->trampoline_size [i] = acfg->trampoline_size [i];
10962 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
10964 int card_table_shift_bits = 0;
10965 target_mgreg_t card_table_mask = 0;
10967 mono_gc_get_target_card_table (&card_table_shift_bits, &card_table_mask);
10970 * Sanity checking variables used to make sure the host and target
10971 * environment matches when cross compiling.
10973 info->double_align = MONO_ABI_ALIGNOF (double);
10974 info->long_align = MONO_ABI_ALIGNOF (gint64);
10975 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
10976 info->card_table_shift_bits = card_table_shift_bits;
10977 info->card_table_mask = card_table_mask;
10979 info->tramp_page_size = acfg->tramp_page_size;
10980 info->nshared_got_entries = acfg->nshared_got_entries;
10981 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10982 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
10984 memcpy(&info->aotid, acfg->image->aotid, 16);
10987 static void
10988 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10990 char symbol [MAX_SYMBOL_SIZE];
10991 int i, sindex;
10992 const char **symbols;
10994 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10995 sindex = 0;
10996 symbols [sindex ++] = acfg->got_symbol;
10997 if (acfg->llvm) {
10998 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
10999 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
11000 } else {
11001 symbols [sindex ++] = NULL;
11002 symbols [sindex ++] = NULL;
11004 /* llvm_get_method */
11005 symbols [sindex ++] = NULL;
11006 /* llvm_get_unbox_tramp */
11007 symbols [sindex ++] = NULL;
11008 if (!acfg->aot_opts.llvm_only) {
11009 symbols [sindex ++] = "jit_code_start";
11010 symbols [sindex ++] = "jit_code_end";
11011 symbols [sindex ++] = "method_addresses";
11012 } else {
11013 symbols [sindex ++] = NULL;
11014 symbols [sindex ++] = NULL;
11015 symbols [sindex ++] = NULL;
11017 symbols [sindex ++] = NULL;
11018 symbols [sindex ++] = NULL;
11020 if (acfg->data_outfile) {
11021 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
11022 symbols [sindex ++] = NULL;
11023 } else {
11024 symbols [sindex ++] = "blob";
11025 symbols [sindex ++] = "class_name_table";
11026 symbols [sindex ++] = "class_info_offsets";
11027 symbols [sindex ++] = "method_info_offsets";
11028 symbols [sindex ++] = "ex_info_offsets";
11029 symbols [sindex ++] = "extra_method_info_offsets";
11030 symbols [sindex ++] = "extra_method_table";
11031 symbols [sindex ++] = "got_info_offsets";
11032 if (acfg->llvm)
11033 symbols [sindex ++] = "llvm_got_info_offsets";
11034 else
11035 symbols [sindex ++] = NULL;
11036 symbols [sindex ++] = "image_table";
11037 symbols [sindex ++] = "weak_field_indexes";
11040 symbols [sindex ++] = "mem_end";
11041 symbols [sindex ++] = "assembly_guid";
11042 symbols [sindex ++] = "runtime_version";
11043 if (acfg->num_trampoline_got_entries) {
11044 symbols [sindex ++] = "specific_trampolines";
11045 symbols [sindex ++] = "static_rgctx_trampolines";
11046 symbols [sindex ++] = "imt_trampolines";
11047 symbols [sindex ++] = "gsharedvt_arg_trampolines";
11048 symbols [sindex ++] = "ftnptr_arg_trampolines";
11049 symbols [sindex ++] = "unbox_arbitrary_trampolines";
11050 } else {
11051 symbols [sindex ++] = NULL;
11052 symbols [sindex ++] = NULL;
11053 symbols [sindex ++] = NULL;
11054 symbols [sindex ++] = NULL;
11055 symbols [sindex ++] = NULL;
11056 symbols [sindex ++] = NULL;
11058 if (acfg->aot_opts.static_link) {
11059 symbols [sindex ++] = "globals";
11060 } else {
11061 symbols [sindex ++] = NULL;
11063 symbols [sindex ++] = "assembly_name";
11064 symbols [sindex ++] = "plt";
11065 symbols [sindex ++] = "plt_end";
11066 symbols [sindex ++] = "unwind_info";
11067 if (!acfg->aot_opts.llvm_only) {
11068 symbols [sindex ++] = "unbox_trampolines";
11069 symbols [sindex ++] = "unbox_trampolines_end";
11070 symbols [sindex ++] = "unbox_trampoline_addresses";
11071 } else {
11072 symbols [sindex ++] = NULL;
11073 symbols [sindex ++] = NULL;
11074 symbols [sindex ++] = NULL;
11077 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
11079 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
11080 emit_section_change (acfg, ".data", 0);
11081 emit_alignment (acfg, 8);
11082 emit_label (acfg, symbol);
11083 if (!acfg->aot_opts.static_link)
11084 emit_global (acfg, symbol, FALSE);
11086 /* The data emitted here must match MonoAotFileInfo. */
11088 emit_int32 (acfg, info->version);
11089 emit_int32 (acfg, info->dummy);
11092 * We emit pointers to our data structures instead of emitting global symbols which
11093 * point to them, to reduce the number of globals, and because using globals leads to
11094 * various problems (i.e. arm/thumb).
11096 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
11097 emit_pointer (acfg, symbols [i]);
11099 emit_int32 (acfg, info->plt_got_offset_base);
11100 emit_int32 (acfg, info->got_size);
11101 emit_int32 (acfg, info->plt_size);
11102 emit_int32 (acfg, info->nmethods);
11103 emit_int32 (acfg, info->nextra_methods);
11104 emit_int32 (acfg, info->flags);
11105 emit_int32 (acfg, info->opts);
11106 emit_int32 (acfg, info->simd_opts);
11107 emit_int32 (acfg, info->gc_name_index);
11108 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
11109 emit_int32 (acfg, info->double_align);
11110 emit_int32 (acfg, info->long_align);
11111 emit_int32 (acfg, info->generic_tramp_num);
11112 emit_int32 (acfg, info->card_table_shift_bits);
11113 emit_int32 (acfg, info->card_table_mask);
11114 emit_int32 (acfg, info->tramp_page_size);
11115 emit_int32 (acfg, info->nshared_got_entries);
11116 emit_int32 (acfg, info->datafile_size);
11117 emit_int32 (acfg, 0);
11118 emit_int32 (acfg, 0);
11120 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
11121 emit_int32 (acfg, info->table_offsets [i]);
11122 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11123 emit_int32 (acfg, info->num_trampolines [i]);
11124 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11125 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
11126 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11127 emit_int32 (acfg, info->trampoline_size [i]);
11128 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11129 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
11131 emit_bytes (acfg, info->aotid, 16);
11133 if (acfg->aot_opts.static_link) {
11134 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
11135 emit_alignment (acfg, sizeof (target_mgreg_t));
11136 emit_label (acfg, acfg->static_linking_symbol);
11137 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
11142 * Emit a structure containing all the information not stored elsewhere.
11144 static void
11145 emit_file_info (MonoAotCompile *acfg)
11147 char *build_info;
11148 MonoAotFileInfo *info;
11150 if (acfg->aot_opts.bind_to_runtime_version) {
11151 build_info = mono_get_runtime_build_info ();
11152 emit_string_symbol (acfg, "runtime_version", build_info);
11153 g_free (build_info);
11154 } else {
11155 emit_string_symbol (acfg, "runtime_version", "");
11158 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
11160 /* Emit a string holding the assembly name */
11161 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
11163 info = g_new0 (MonoAotFileInfo, 1);
11164 init_aot_file_info (acfg, info);
11166 if (acfg->aot_opts.static_link) {
11167 char symbol [MAX_SYMBOL_SIZE];
11168 char *p;
11171 * Emit a global symbol which can be passed by an embedding app to
11172 * mono_aot_register_module (). The symbol points to a pointer to the the file info
11173 * structure.
11175 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
11177 /* Get rid of characters which cannot occur in symbols */
11178 p = symbol;
11179 for (p = symbol; *p; ++p) {
11180 if (!(isalnum (*p) || *p == '_'))
11181 *p = '_';
11183 acfg->static_linking_symbol = g_strdup (symbol);
11186 if (acfg->llvm)
11187 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
11188 else
11189 emit_aot_file_info (acfg, info);
11192 static void
11193 emit_blob (MonoAotCompile *acfg)
11195 acfg->blob_closed = TRUE;
11197 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
11200 static void
11201 emit_objc_selectors (MonoAotCompile *acfg)
11203 int i;
11204 char symbol [128];
11206 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
11207 return;
11210 * From
11211 * cat > foo.m << EOF
11212 * void *ret ()
11214 * return @selector(print:);
11216 * EOF
11219 mono_img_writer_emit_unset_mode (acfg->w);
11220 g_assert (acfg->fp);
11221 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
11222 fprintf (acfg->fp, ".align 3\n");
11223 for (i = 0; i < acfg->objc_selectors->len; ++i) {
11224 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
11225 emit_label (acfg, symbol);
11226 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
11227 emit_pointer (acfg, symbol);
11230 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
11231 for (i = 0; i < acfg->objc_selectors->len; ++i) {
11232 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
11233 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
11236 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
11237 fprintf (acfg->fp, ".align 3\n");
11238 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
11239 fprintf (acfg->fp, ".long 0\n");
11240 fprintf (acfg->fp, ".long 16\n");
11243 static void
11244 emit_dwarf_info (MonoAotCompile *acfg)
11246 #ifdef EMIT_DWARF_INFO
11247 int i;
11248 char symbol2 [128];
11250 /* DIEs for methods */
11251 for (i = 0; i < acfg->nmethods; ++i) {
11252 MonoCompile *cfg = acfg->cfgs [i];
11254 if (ignore_cfg (cfg))
11255 continue;
11257 // FIXME: LLVM doesn't define .Lme_...
11258 if (cfg->compile_llvm)
11259 continue;
11261 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
11263 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 ()));
11265 #endif
11268 #ifdef EMIT_WIN32_CODEVIEW_INFO
11269 typedef struct _CodeViewSubSectionData
11271 gchar *start_section;
11272 gchar *end_section;
11273 gchar *start_section_record;
11274 gchar *end_section_record;
11275 int section_type;
11276 int section_record_type;
11277 int section_id;
11278 } CodeViewSubsectionData;
11280 typedef struct _CodeViewCompilerVersion
11282 gint major;
11283 gint minor;
11284 gint revision;
11285 gint patch;
11286 } CodeViewCompilerVersion;
11288 #define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
11289 #define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
11290 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
11291 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
11292 #define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
11293 #define CODEVIEW_CPU_TYPE 0x0
11294 #define CODEVIEW_MAGIC_HEADER 0x4
11296 static void
11297 codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
11299 g_free (section_data->start_section);
11300 g_free (section_data->end_section);
11301 g_free (section_data->start_section_record);
11302 g_free (section_data->end_section_record);
11304 memset (section_data, 0, sizeof (CodeViewSubsectionData));
11307 static void
11308 codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
11310 gint values[4] = { 0 };
11311 gint *value = values;
11313 while (*version && (value < values + G_N_ELEMENTS (values))) {
11314 if (isdigit (*version)) {
11315 *value *= 10;
11316 *value += *version - '0';
11318 else if (*version == '.') {
11319 value++;
11322 version++;
11325 data->major = values[0];
11326 data->minor = values[1];
11327 data->revision = values[2];
11328 data->patch = values[3];
11331 static void
11332 emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
11334 // Starting a new subsection, clear old data.
11335 codeview_clear_subsection_data (section_data);
11337 // Keep subsection data.
11338 section_data->section_id = section_id;
11339 section_data->section_type = section_type;
11340 section_data->section_record_type = section_record_type;
11342 // Allocate all labels used in subsection.
11343 section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
11344 section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
11345 section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
11346 section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
11348 // Subsection type, function symbol.
11349 emit_int32 (acfg, section_data->section_type);
11351 // Subsection size.
11352 emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
11353 emit_label (acfg, section_data->start_section);
11355 // Subsection record size.
11356 fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
11357 emit_label (acfg, section_data->start_section_record);
11359 // Subsection record type.
11360 emit_int16 (acfg, section_record_type);
11363 static void
11364 emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11366 g_assert (section_data->start_section);
11367 g_assert (section_data->end_section);
11368 g_assert (section_data->start_section_record);
11369 g_assert (section_data->end_section_record);
11371 emit_label (acfg, section_data->end_section_record);
11373 if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
11374 // Emit record length.
11375 emit_int16 (acfg, 2);
11377 // Emit specific record type end.
11378 emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
11381 emit_label (acfg, section_data->end_section);
11383 // Next subsection needs to be 4 byte aligned.
11384 emit_alignment (acfg, 4);
11386 *section_id = section_data->section_id + 1;
11387 codeview_clear_subsection_data (section_data);
11390 inline static void
11391 emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
11393 emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
11396 inline static void
11397 emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11399 emit_codeview_end_subsection (acfg, section_data, section_id);
11402 static void
11403 emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
11405 CodeViewSubsectionData section_data = { 0 };
11406 CodeViewCompilerVersion compiler_version = { 0 };
11408 // Start new compiler record subsection.
11409 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, &section_data);
11411 emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
11412 emit_int16 (acfg, CODEVIEW_CPU_TYPE);
11414 // Get compiler version information.
11415 codeview_parse_compiler_version (VERSION, &compiler_version);
11417 // Compiler frontend version, 4 digits.
11418 emit_int16 (acfg, compiler_version.major);
11419 emit_int16 (acfg, compiler_version.minor);
11420 emit_int16 (acfg, compiler_version.revision);
11421 emit_int16 (acfg, compiler_version.patch);
11423 // Compiler backend version, 4 digits (currently same as frontend).
11424 emit_int16 (acfg, compiler_version.major);
11425 emit_int16 (acfg, compiler_version.minor);
11426 emit_int16 (acfg, compiler_version.revision);
11427 emit_int16 (acfg, compiler_version.patch);
11429 // Compiler string.
11430 emit_string (acfg, "Mono AOT compiler");
11432 // Done with section.
11433 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11436 static void
11437 emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
11439 CodeViewSubsectionData section_data = { 0 };
11440 gchar *full_method_name = NULL;
11442 // Start new function record subsection.
11443 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, &section_data);
11445 // Emit 3 int 0 byte padding, currently not used.
11446 emit_zero_bytes (acfg, sizeof (int) * 3);
11448 // Emit size of function.
11449 emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
11451 // Emit 3 int 0 byte padding, currently not used.
11452 emit_zero_bytes (acfg, sizeof (int) * 3);
11454 // Emit reallocation info.
11455 fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
11456 fprintf (acfg->fp, "\t.secidx %s\n", symbol);
11458 // Emit flag, currently not used.
11459 emit_zero_bytes (acfg, 1);
11461 // Emit function name, exclude signature since it should be described by own metadata.
11462 full_method_name = mono_method_full_name (method, FALSE);
11463 emit_string (acfg, full_method_name ? full_method_name : "");
11464 g_free (full_method_name);
11466 // Done with section.
11467 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11470 static void
11471 emit_codeview_info (MonoAotCompile *acfg)
11473 int i;
11474 int section_id = 0;
11475 gchar symbol_buffer[MAX_SYMBOL_SIZE];
11477 // Emit codeview debug info section
11478 emit_section_change (acfg, ".debug$S", 0);
11480 // Emit magic header.
11481 emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
11483 emit_codeview_compiler_info (acfg, &section_id);
11485 for (i = 0; i < acfg->nmethods; ++i) {
11486 MonoCompile *cfg = acfg->cfgs[i];
11488 if (!cfg || COMPILE_LLVM (cfg))
11489 continue;
11491 int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
11492 if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
11493 emit_codeview_function_info (acfg, cfg->method, &section_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
11496 #else
11497 static void
11498 emit_codeview_info (MonoAotCompile *acfg)
11501 #endif /* EMIT_WIN32_CODEVIEW_INFO */
11503 #ifdef EMIT_WIN32_UNWIND_INFO
11504 static UnwindInfoSectionCacheItem *
11505 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11507 UnwindInfoSectionCacheItem *item = NULL;
11509 if (!acfg->unwind_info_section_cache)
11510 acfg->unwind_info_section_cache = g_list_alloc ();
11512 PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
11514 // Search for unwind info in cache.
11515 GList *list = acfg->unwind_info_section_cache;
11516 int list_size = 0;
11517 while (list && list->data) {
11518 item = (UnwindInfoSectionCacheItem*)list->data;
11519 if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
11520 // Cache hit, return cached item.
11521 return item;
11523 list = list->next;
11524 list_size++;
11527 // Add to cache.
11528 if (acfg->unwind_info_section_cache) {
11529 item = g_new0 (UnwindInfoSectionCacheItem, 1);
11530 if (item) {
11531 // Format .xdata section label for function, used to get unwind info address RVA.
11532 // Since the unwind info is similar for most functions, the symbol will be reused.
11533 item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
11535 // Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
11536 //over ownership of unwind info.
11537 item->unwind_info = unwind_info;
11539 // Needs to be emitted once.
11540 item->xdata_section_emitted = FALSE;
11542 // Prepend to beginning of list to speed up inserts.
11543 acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
11547 return item;
11550 static void
11551 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
11553 GList *list = acfg->unwind_info_section_cache;
11555 while (list) {
11556 UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
11557 if (item) {
11558 g_free (item->xdata_section_label);
11559 mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
11561 g_free (item);
11562 list->data = NULL;
11565 list = list->next;
11568 g_list_free (acfg->unwind_info_section_cache);
11569 acfg->unwind_info_section_cache = NULL;
11572 static void
11573 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
11575 // Emit the unwind info struct.
11576 emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
11578 // Emit all unwind codes encoded in unwind info struct.
11579 PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
11580 PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
11582 while (current_unwind_node < last_unwind_node) {
11583 guint8 node_count = 0;
11584 switch (current_unwind_node->UnwindOp) {
11585 case UWOP_PUSH_NONVOL:
11586 case UWOP_ALLOC_SMALL:
11587 case UWOP_SET_FPREG:
11588 case UWOP_PUSH_MACHFRAME:
11589 node_count = 1;
11590 break;
11591 case UWOP_SAVE_NONVOL:
11592 case UWOP_SAVE_XMM128:
11593 node_count = 2;
11594 break;
11595 case UWOP_SAVE_NONVOL_FAR:
11596 case UWOP_SAVE_XMM128_FAR:
11597 node_count = 3;
11598 break;
11599 case UWOP_ALLOC_LARGE:
11600 if (current_unwind_node->OpInfo == 0)
11601 node_count = 2;
11602 else
11603 node_count = 3;
11604 break;
11605 default:
11606 g_assert (!"Unknown unwind opcode.");
11609 while (node_count > 0) {
11610 g_assert (current_unwind_node < last_unwind_node);
11612 //Emit current node.
11613 emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
11615 node_count--;
11616 current_unwind_node++;
11621 // Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
11622 // .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
11623 // UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
11624 // .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
11625 static void
11626 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11628 char *pdata_section_label = NULL;
11630 int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
11631 if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
11632 temp_prefix_len = 0;
11635 // Format .pdata section label for function.
11636 pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
11638 UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
11639 g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
11641 // Emit .pdata section.
11642 emit_section_change (acfg, ".pdata", 0);
11643 emit_alignment (acfg, sizeof (DWORD));
11644 emit_label (acfg, pdata_section_label);
11646 // Emit function start address RVA.
11647 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
11649 // Emit function end address RVA.
11650 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
11652 // Emit unwind info address RVA.
11653 fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
11655 if (!cache_item->xdata_section_emitted) {
11656 // Emit .xdata section.
11657 emit_section_change (acfg, ".xdata", 0);
11658 emit_alignment (acfg, sizeof (DWORD));
11659 emit_label (acfg, cache_item->xdata_section_label);
11661 // Emit unwind info into .xdata section.
11662 emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
11663 cache_item->xdata_section_emitted = TRUE;
11666 g_free (pdata_section_label);
11668 #endif
11670 static gboolean
11671 should_emit_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
11673 #ifdef TARGET_WASM
11674 if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Vector`1"))
11675 /* The SIMD fallback code in Vector<T> is very large, and not likely to be used */
11676 return FALSE;
11677 #endif
11678 if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Volatile"))
11679 /* Read<T>/Write<T> are not needed and cause JIT failures */
11680 return FALSE;
11681 return TRUE;
11684 static gboolean
11685 collect_methods (MonoAotCompile *acfg)
11687 int mindex, i;
11688 MonoImage *image = acfg->image;
11690 /* Collect methods */
11691 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
11692 ERROR_DECL (error);
11693 MonoMethod *method;
11694 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
11696 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11698 if (!method) {
11699 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11700 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11701 mono_error_cleanup (error);
11702 return FALSE;
11705 /* Load all methods eagerly to skip the slower lazy loading code */
11706 mono_class_setup_methods (method->klass);
11708 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
11709 /* Compile the wrapper instead */
11710 /* We do this here instead of add_wrappers () because it is easy to do it here */
11711 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
11712 method = wrapper;
11715 /* FIXME: Some mscorlib methods don't have debug info */
11717 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
11718 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
11719 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
11720 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
11721 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
11722 if (!mono_debug_lookup_method (method)) {
11723 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
11724 exit (1);
11730 if (method->is_generic || mono_class_is_gtd (method->klass)) {
11731 /* Compile the ref shared version instead */
11732 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
11733 if (!method) {
11734 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11735 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11736 mono_error_cleanup (error);
11737 return FALSE;
11741 /* Since we add the normal methods first, their index will be equal to their zero based token index */
11742 add_method_with_index (acfg, method, i, FALSE);
11743 acfg->method_index ++;
11746 /* gsharedvt methods */
11747 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
11748 ERROR_DECL (error);
11749 MonoMethod *method;
11750 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
11752 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
11753 continue;
11755 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11756 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
11758 if ((method->is_generic || mono_class_is_gtd (method->klass)) && should_emit_gsharedvt_method (acfg, method)) {
11759 MonoMethod *gshared;
11761 gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
11762 mono_error_assert_ok (error);
11764 add_extra_method (acfg, gshared);
11768 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11769 add_generic_instances (acfg);
11771 if (mono_aot_mode_is_full (&acfg->aot_opts))
11772 add_wrappers (acfg);
11773 return TRUE;
11776 static void
11777 compile_methods (MonoAotCompile *acfg)
11779 int i, methods_len;
11781 if (acfg->aot_opts.nthreads > 0) {
11782 GPtrArray *frag;
11783 int len, j;
11784 GPtrArray *threads;
11785 MonoThreadHandle *thread_handle;
11786 gpointer *user_data;
11787 MonoMethod **methods;
11789 methods_len = acfg->methods->len;
11791 len = acfg->methods->len / acfg->aot_opts.nthreads;
11792 g_assert (len > 0);
11794 * Partition the list of methods into fragments, and hand it to threads to
11795 * process.
11797 threads = g_ptr_array_new ();
11798 /* Make a copy since acfg->methods is modified by compile_method () */
11799 methods = g_new0 (MonoMethod*, methods_len);
11800 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
11801 for (i = 0; i < methods_len; ++i)
11802 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
11803 i = 0;
11804 while (i < methods_len) {
11805 ERROR_DECL (error);
11806 MonoInternalThread *thread;
11808 frag = g_ptr_array_new ();
11809 for (j = 0; j < len; ++j) {
11810 if (i < methods_len) {
11811 g_ptr_array_add (frag, methods [i]);
11812 i ++;
11816 user_data = g_new0 (gpointer, 3);
11817 user_data [0] = acfg;
11818 user_data [1] = frag;
11820 thread = mono_thread_create_internal (mono_domain_get (), (gpointer)compile_thread_main, user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
11821 mono_error_assert_ok (error);
11823 thread_handle = mono_threads_open_thread_handle (thread->handle);
11824 g_ptr_array_add (threads, thread_handle);
11826 g_free (methods);
11828 for (i = 0; i < threads->len; ++i) {
11829 mono_thread_info_wait_one_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
11830 mono_threads_close_thread_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i));
11832 } else {
11833 methods_len = 0;
11836 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
11837 for (i = methods_len; i < acfg->methods->len; ++i) {
11838 /* This can add new methods to acfg->methods */
11839 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
11842 #ifdef ENABLE_LLVM
11843 if (acfg->llvm)
11844 mono_llvm_fixup_aot_module ();
11845 #endif
11848 static int
11849 compile_asm (MonoAotCompile *acfg)
11851 char *command, *objfile;
11852 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
11853 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
11854 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
11856 #ifdef TARGET_WIN32_MSVC
11857 #define AS_OPTIONS "-c -x assembler"
11858 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
11859 #define AS_OPTIONS "--64"
11860 #elif defined(TARGET_POWERPC64)
11861 #define AS_OPTIONS "-a64 -mppc64"
11862 #elif defined(sparc) && TARGET_SIZEOF_VOID_P == 8
11863 #define AS_OPTIONS "-xarch=v9"
11864 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11865 #define AS_OPTIONS "-arch i386"
11866 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11867 #define AS_OPTIONS "--32"
11868 #else
11869 #define AS_OPTIONS ""
11870 #endif
11872 #if defined(TARGET_OSX)
11873 #define AS_NAME "clang"
11874 #elif defined(TARGET_WIN32_MSVC)
11875 #define AS_NAME "clang.exe"
11876 #else
11877 #define AS_NAME "as"
11878 #endif
11880 #ifdef TARGET_WIN32_MSVC
11881 #define AS_OBJECT_FILE_SUFFIX "obj"
11882 #else
11883 #define AS_OBJECT_FILE_SUFFIX "o"
11884 #endif
11886 #if defined(sparc)
11887 #define LD_NAME "ld"
11888 #define LD_OPTIONS "-shared -G"
11889 #elif defined(__ppc__) && defined(TARGET_MACH)
11890 #define LD_NAME "gcc"
11891 #define LD_OPTIONS "-dynamiclib"
11892 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
11893 #define LD_NAME "clang"
11894 #define LD_OPTIONS "--shared"
11895 #elif defined(TARGET_WIN32_MSVC)
11896 #define LD_NAME "link.exe"
11897 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
11898 #define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
11899 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
11900 #define LD_NAME "gcc"
11901 #define LD_OPTIONS "-shared"
11902 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11903 #define LD_NAME "clang"
11904 #define LD_OPTIONS "-m32 -dynamiclib"
11905 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11906 #define LD_OPTIONS "-m elf_i386"
11907 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
11908 #define LD_NAME "gcc"
11909 #define LD_OPTIONS "--shared"
11910 #elif defined(TARGET_POWERPC64)
11911 #define LD_OPTIONS "-m elf64ppc"
11912 #endif
11914 #ifndef LD_OPTIONS
11915 #define LD_OPTIONS ""
11916 #endif
11918 if (acfg->aot_opts.asm_only) {
11919 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
11920 if (acfg->aot_opts.static_link)
11921 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11922 if (acfg->llvm)
11923 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
11924 return 0;
11927 if (acfg->aot_opts.static_link) {
11928 if (acfg->aot_opts.outfile)
11929 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11930 else
11931 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
11932 } else {
11933 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
11936 #ifdef TARGET_OSX
11937 g_string_append (acfg->as_args, "-c -x assembler");
11938 #endif
11940 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11941 acfg->as_args ? acfg->as_args->str : "",
11942 wrap_path (objfile), wrap_path (acfg->tmpfname));
11943 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11944 if (execute_system (command) != 0) {
11945 g_free (command);
11946 g_free (objfile);
11947 return 1;
11950 if (acfg->llvm && !acfg->llvm_owriter) {
11951 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11952 acfg->as_args ? acfg->as_args->str : "",
11953 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
11954 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11955 if (execute_system (command) != 0) {
11956 g_free (command);
11957 g_free (objfile);
11958 return 1;
11962 g_free (command);
11964 if (acfg->aot_opts.static_link) {
11965 aot_printf (acfg, "Output file: '%s'.\n", objfile);
11966 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11967 g_free (objfile);
11968 return 0;
11971 if (acfg->aot_opts.outfile)
11972 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11973 else
11974 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
11976 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
11978 if (acfg->llvm) {
11979 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
11980 } else {
11981 llvm_ofile = g_strdup ("");
11984 /* replace the ; flags separators with spaces */
11985 g_strdelimit (ld_flags, ';', ' ');
11987 if (acfg->aot_opts.llvm_only)
11988 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
11990 #ifdef TARGET_WIN32_MSVC
11991 g_assert (tmp_outfile_name != NULL);
11992 g_assert (objfile != NULL);
11993 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:%s %s %s", tool_prefix, LD_NAME,
11994 acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, wrap_path (tmp_outfile_name), wrap_path (objfile), wrap_path (llvm_ofile));
11995 #elif defined(LD_NAME)
11996 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
11997 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11998 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11999 #else
12000 // Default (linux)
12001 if (acfg->aot_opts.tool_prefix) {
12002 /* Cross compiling */
12003 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
12004 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12005 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12006 } else {
12007 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
12008 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12009 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12011 if (acfg->aot_opts.llvm_only) {
12012 command = g_strdup_printf ("%s %s", acfg->aot_opts.clangxx, args);
12013 } else {
12014 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
12016 g_free (args);
12018 #endif
12019 aot_printf (acfg, "Executing the native linker: %s\n", command);
12020 if (execute_system (command) != 0) {
12021 g_free (tmp_outfile_name);
12022 g_free (outfile_name);
12023 g_free (command);
12024 g_free (objfile);
12025 g_free (ld_flags);
12026 return 1;
12029 g_free (command);
12031 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
12032 printf ("Stripping the binary: %s\n", com);
12033 execute_system (com);
12034 g_free (com);*/
12036 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
12038 * gas generates 'mapping symbols' each time code and data is mixed, which
12039 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
12041 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
12042 aot_printf (acfg, "Stripping the binary: %s\n", command);
12043 if (execute_system (command) != 0) {
12044 g_free (tmp_outfile_name);
12045 g_free (outfile_name);
12046 g_free (command);
12047 g_free (objfile);
12048 return 1;
12050 #endif
12052 if (0 != rename (tmp_outfile_name, outfile_name)) {
12053 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
12054 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
12055 unlink (outfile_name);
12056 rename (tmp_outfile_name, outfile_name);
12060 #if defined(TARGET_MACH)
12061 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
12062 aot_printf (acfg, "Executing dsymutil: %s\n", command);
12063 if (execute_system (command) != 0) {
12064 return 1;
12066 #endif
12068 if (!acfg->aot_opts.save_temps)
12069 unlink (objfile);
12071 g_free (tmp_outfile_name);
12072 g_free (outfile_name);
12073 g_free (objfile);
12075 if (acfg->aot_opts.save_temps)
12076 aot_printf (acfg, "Retained input file.\n");
12077 else
12078 unlink (acfg->tmpfname);
12080 return 0;
12083 static guint8
12084 profread_byte (FILE *infile)
12086 guint8 i;
12087 int res;
12089 res = fread (&i, 1, 1, infile);
12090 g_assert (res == 1);
12091 return i;
12094 static int
12095 profread_int (FILE *infile)
12097 int i, res;
12099 res = fread (&i, 4, 1, infile);
12100 g_assert (res == 1);
12101 return i;
12104 static char*
12105 profread_string (FILE *infile)
12107 int len, res;
12108 char *pbuf;
12110 len = profread_int (infile);
12111 pbuf = (char*)g_malloc (len + 1);
12112 res = fread (pbuf, 1, len, infile);
12113 g_assert (res == len);
12114 pbuf [len] = '\0';
12115 return pbuf;
12118 static void
12119 load_profile_file (MonoAotCompile *acfg, char *filename)
12121 FILE *infile;
12122 char buf [1024];
12123 int res, len, version;
12124 char magic [32];
12126 infile = fopen (filename, "rb");
12127 if (!infile) {
12128 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
12129 exit (1);
12132 printf ("Using profile data file '%s'\n", filename);
12134 sprintf (magic, AOT_PROFILER_MAGIC);
12135 len = strlen (magic);
12136 res = fread (buf, 1, len, infile);
12137 magic [len] = '\0';
12138 buf [len] = '\0';
12139 if ((res != len) || strcmp (buf, magic) != 0) {
12140 printf ("Profile file has wrong header: '%s'.\n", buf);
12141 fclose (infile);
12142 exit (1);
12144 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
12145 version = profread_int (infile);
12146 if (version != expected_version) {
12147 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
12148 fclose (infile);
12149 exit (1);
12152 ProfileData *data = g_new0 (ProfileData, 1);
12153 data->images = g_hash_table_new (NULL, NULL);
12154 data->classes = g_hash_table_new (NULL, NULL);
12155 data->ginsts = g_hash_table_new (NULL, NULL);
12156 data->methods = g_hash_table_new (NULL, NULL);
12158 while (TRUE) {
12159 int type = profread_byte (infile);
12160 int id = profread_int (infile);
12162 if (type == AOTPROF_RECORD_NONE)
12163 break;
12165 switch (type) {
12166 case AOTPROF_RECORD_IMAGE: {
12167 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
12168 idata->name = profread_string (infile);
12169 char *mvid = profread_string (infile);
12170 g_free (mvid);
12171 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
12172 break;
12174 case AOTPROF_RECORD_GINST: {
12175 int i;
12176 int len = profread_int (infile);
12178 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
12179 gdata->argc = len;
12180 gdata->argv = g_new0 (ClassProfileData*, len);
12182 for (i = 0; i < len; ++i) {
12183 int class_id = profread_int (infile);
12185 gdata->argv [i] = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
12186 g_assert (gdata->argv [i]);
12188 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
12189 break;
12191 case AOTPROF_RECORD_TYPE: {
12192 int type = profread_byte (infile);
12194 switch (type) {
12195 case MONO_TYPE_CLASS: {
12196 int image_id = profread_int (infile);
12197 int ginst_id = profread_int (infile);
12198 char *class_name = profread_string (infile);
12200 ImageProfileData *image = (ImageProfileData*)g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
12201 g_assert (image);
12203 char *p = strrchr (class_name, '.');
12204 g_assert (p);
12205 *p = '\0';
12207 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
12208 cdata->image = image;
12209 cdata->ns = g_strdup (class_name);
12210 cdata->name = g_strdup (p + 1);
12212 if (ginst_id != -1) {
12213 cdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
12214 g_assert (cdata->inst);
12216 g_free (class_name);
12218 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
12219 break;
12221 #if 0
12222 case MONO_TYPE_SZARRAY: {
12223 int elem_id = profread_int (infile);
12224 // FIXME:
12225 break;
12227 #endif
12228 default:
12229 g_assert_not_reached ();
12230 break;
12232 break;
12234 case AOTPROF_RECORD_METHOD: {
12235 int class_id = profread_int (infile);
12236 int ginst_id = profread_int (infile);
12237 int param_count = profread_int (infile);
12238 char *method_name = profread_string (infile);
12239 char *sig = profread_string (infile);
12241 ClassProfileData *klass = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
12242 g_assert (klass);
12244 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
12245 mdata->id = id;
12246 mdata->klass = klass;
12247 mdata->name = method_name;
12248 mdata->signature = sig;
12249 mdata->param_count = param_count;
12251 if (ginst_id != -1) {
12252 mdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
12253 g_assert (mdata->inst);
12255 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
12256 break;
12258 default:
12259 printf ("%d\n", type);
12260 g_assert_not_reached ();
12261 break;
12265 fclose (infile);
12266 acfg->profile_data = g_list_append (acfg->profile_data, data);
12269 static void
12270 resolve_class (ClassProfileData *cdata);
12272 static void
12273 resolve_ginst (GInstProfileData *inst_data)
12275 int i;
12277 if (inst_data->inst)
12278 return;
12280 for (i = 0; i < inst_data->argc; ++i) {
12281 resolve_class (inst_data->argv [i]);
12282 if (!inst_data->argv [i]->klass)
12283 return;
12285 MonoType **args = g_new0 (MonoType*, inst_data->argc);
12286 for (i = 0; i < inst_data->argc; ++i)
12287 args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
12289 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
12292 static void
12293 resolve_class (ClassProfileData *cdata)
12295 ERROR_DECL (error);
12296 MonoClass *klass;
12298 if (!cdata->image->image)
12299 return;
12301 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
12302 if (!klass) {
12303 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
12304 return;
12306 if (cdata->inst) {
12307 resolve_ginst (cdata->inst);
12308 if (!cdata->inst->inst)
12309 return;
12310 MonoGenericContext ctx;
12312 memset (&ctx, 0, sizeof (ctx));
12313 ctx.class_inst = cdata->inst->inst;
12314 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
12315 } else {
12316 cdata->klass = klass;
12321 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
12323 static void
12324 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data, MonoAssembly* current)
12326 GHashTableIter iter;
12327 gpointer key, value;
12328 int i;
12330 if (!data)
12331 return;
12333 /* Images */
12334 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
12335 g_hash_table_iter_init (&iter, data->images);
12336 while (g_hash_table_iter_next (&iter, &key, &value)) {
12337 ImageProfileData *idata = (ImageProfileData*)value;
12339 if (!strcmp (current->aname.name, idata->name)) {
12340 idata->image = current->image;
12341 break;
12344 for (i = 0; i < assemblies->len; ++i) {
12345 MonoAssembly *ass = (MonoAssembly*)g_ptr_array_index (assemblies, i);
12347 if (!strcmp (ass->aname.name, idata->name)) {
12348 idata->image = ass->image;
12349 break;
12353 g_ptr_array_free (assemblies, TRUE);
12355 /* Classes */
12356 g_hash_table_iter_init (&iter, data->classes);
12357 while (g_hash_table_iter_next (&iter, &key, &value)) {
12358 ClassProfileData *cdata = (ClassProfileData*)value;
12360 if (!cdata->image->image) {
12361 if (acfg->aot_opts.verbose)
12362 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
12363 continue;
12366 resolve_class (cdata);
12368 if (cdata->klass)
12369 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
12373 /* Methods */
12374 g_hash_table_iter_init (&iter, data->methods);
12375 while (g_hash_table_iter_next (&iter, &key, &value)) {
12376 MethodProfileData *mdata = (MethodProfileData*)value;
12377 MonoClass *klass;
12378 MonoMethod *m;
12379 gpointer miter;
12381 resolve_class (mdata->klass);
12382 klass = mdata->klass->klass;
12383 if (!klass) {
12384 if (acfg->aot_opts.verbose)
12385 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
12386 continue;
12388 miter = NULL;
12389 while ((m = mono_class_get_methods (klass, &miter))) {
12390 ERROR_DECL (error);
12392 if (strcmp (m->name, mdata->name))
12393 continue;
12394 MonoMethodSignature *sig = mono_method_signature_internal (m);
12395 if (!sig)
12396 continue;
12397 if (sig->param_count != mdata->param_count)
12398 continue;
12399 if (mdata->inst) {
12400 resolve_ginst (mdata->inst);
12401 if (!mdata->inst->inst)
12402 continue;
12403 MonoGenericContext ctx;
12405 memset (&ctx, 0, sizeof (ctx));
12406 ctx.method_inst = mdata->inst->inst;
12408 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
12409 if (!m)
12410 continue;
12411 sig = mono_method_signature_checked (m, error);
12412 if (!is_ok (error)) {
12413 mono_error_cleanup (error);
12414 continue;
12417 char *sig_str = mono_signature_full_name (sig);
12418 gboolean match = !strcmp (sig_str, mdata->signature);
12419 g_free (sig_str);
12420 if (!match)
12422 continue;
12423 //printf ("%s\n", mono_method_full_name (m, 1));
12424 mdata->method = m;
12425 break;
12427 if (!mdata->method) {
12428 if (acfg->aot_opts.verbose)
12429 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
12434 static gboolean
12435 inst_references_image (MonoGenericInst *inst, MonoImage *image)
12437 int i;
12439 for (i = 0; i < inst->type_argc; ++i) {
12440 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12441 if (m_class_get_image (k) == image)
12442 return TRUE;
12443 if (mono_class_is_ginst (k)) {
12444 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
12445 if (inst_references_image (kinst, image))
12446 return TRUE;
12449 return FALSE;
12452 static gboolean
12453 is_local_inst (MonoGenericInst *inst, MonoImage *image)
12455 int i;
12457 for (i = 0; i < inst->type_argc; ++i) {
12458 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12459 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
12460 return FALSE;
12462 return TRUE;
12465 static void
12466 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
12468 GHashTableIter iter;
12469 gpointer key, value;
12470 int count = 0;
12472 if (!data)
12473 return;
12475 if (acfg->aot_opts.profile_only) {
12476 /* Add methods referenced by the profile */
12477 g_hash_table_iter_init (&iter, data->methods);
12478 while (g_hash_table_iter_next (&iter, &key, &value)) {
12479 MethodProfileData *mdata = (MethodProfileData*)value;
12480 MonoMethod *m = mdata->method;
12482 if (!m)
12483 continue;
12484 if (m->is_inflated)
12485 continue;
12486 add_extra_method (acfg, m);
12487 g_hash_table_insert (acfg->profile_methods, m, m);
12488 count ++;
12493 * Add method instances 'related' to this assembly to the AOT image.
12495 g_hash_table_iter_init (&iter, data->methods);
12496 while (g_hash_table_iter_next (&iter, &key, &value)) {
12497 MethodProfileData *mdata = (MethodProfileData*)value;
12498 MonoMethod *m = mdata->method;
12499 MonoGenericContext *ctx;
12501 if (!m)
12502 continue;
12503 if (!m->is_inflated)
12504 continue;
12506 ctx = mono_method_get_context (m);
12507 /* For simplicity, add instances which reference the assembly we are compiling */
12508 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
12509 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
12510 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12511 //printf ("%s\n", mono_method_full_name (m, TRUE));
12512 add_extra_method (acfg, m);
12513 count ++;
12514 } else if (m_class_get_image (m->klass) == acfg->image &&
12515 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
12516 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
12517 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12518 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
12519 //printf ("%s\n", mono_method_full_name (m, TRUE));
12520 add_extra_method (acfg, m);
12521 count ++;
12524 * FIXME: We might skip some instances, for example:
12525 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
12526 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
12530 printf ("Added %d methods from profile.\n", count);
12533 static void
12534 init_got_info (GotInfo *info)
12536 int i;
12538 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12539 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12540 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12541 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12542 info->got_patches = g_ptr_array_new ();
12545 static MonoAotCompile*
12546 acfg_create (MonoAssembly *ass, guint32 opts)
12548 MonoImage *image = ass->image;
12549 MonoAotCompile *acfg;
12551 acfg = g_new0 (MonoAotCompile, 1);
12552 acfg->methods = g_ptr_array_new ();
12553 acfg->method_indexes = g_hash_table_new (NULL, NULL);
12554 acfg->method_depth = g_hash_table_new (NULL, NULL);
12555 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
12556 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12557 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
12558 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
12559 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12560 acfg->method_to_external_icall_symbol_name = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12561 acfg->image_hash = g_hash_table_new (NULL, NULL);
12562 acfg->image_table = g_ptr_array_new ();
12563 acfg->globals = g_ptr_array_new ();
12564 acfg->image = image;
12565 acfg->opts = opts;
12566 /* TODO: Write out set of SIMD instructions used, rather than just those available */
12567 #ifndef MONO_CROSS_COMPILE
12568 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
12569 #endif
12570 acfg->mempool = mono_mempool_new ();
12571 acfg->extra_methods = g_ptr_array_new ();
12572 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
12573 acfg->unwind_ops = g_ptr_array_new ();
12574 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
12575 acfg->method_order = g_ptr_array_new ();
12576 acfg->export_names = g_hash_table_new (NULL, NULL);
12577 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
12578 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
12579 acfg->ginst_blob_hash = g_hash_table_new (mono_metadata_generic_inst_hash, mono_metadata_generic_inst_equal);
12580 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
12581 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12582 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12583 acfg->profile_methods = g_hash_table_new (NULL, NULL);
12584 mono_os_mutex_init_recursive (&acfg->mutex);
12586 init_got_info (&acfg->got_info);
12587 init_got_info (&acfg->llvm_got_info);
12589 method_to_external_icall_symbol_name = acfg->method_to_external_icall_symbol_name;
12590 return acfg;
12593 static void
12594 got_info_free (GotInfo *info)
12596 int i;
12598 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12599 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
12600 g_free (info->patch_to_got_offset_by_type);
12601 g_hash_table_destroy (info->patch_to_got_offset);
12602 g_ptr_array_free (info->got_patches, TRUE);
12605 static void
12606 acfg_free (MonoAotCompile *acfg)
12608 int i;
12610 mono_img_writer_destroy (acfg->w);
12611 for (i = 0; i < acfg->nmethods; ++i)
12612 if (acfg->cfgs [i])
12613 mono_destroy_compile (acfg->cfgs [i]);
12615 g_free (acfg->cfgs);
12617 g_free (acfg->static_linking_symbol);
12618 g_free (acfg->got_symbol);
12619 g_free (acfg->plt_symbol);
12620 g_ptr_array_free (acfg->methods, TRUE);
12621 g_ptr_array_free (acfg->image_table, TRUE);
12622 g_ptr_array_free (acfg->globals, TRUE);
12623 g_ptr_array_free (acfg->unwind_ops, TRUE);
12624 g_hash_table_destroy (acfg->method_indexes);
12625 g_hash_table_destroy (acfg->method_depth);
12626 g_hash_table_destroy (acfg->plt_offset_to_entry);
12627 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12628 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
12629 g_free (acfg->patch_to_plt_entry);
12630 g_hash_table_destroy (acfg->method_to_cfg);
12631 g_hash_table_destroy (acfg->token_info_hash);
12632 g_hash_table_destroy (acfg->method_to_pinvoke_import);
12633 g_hash_table_destroy (acfg->method_to_external_icall_symbol_name);
12634 g_hash_table_destroy (acfg->image_hash);
12635 g_hash_table_destroy (acfg->unwind_info_offsets);
12636 g_hash_table_destroy (acfg->method_label_hash);
12637 g_hash_table_destroy (acfg->typespec_classes);
12638 g_hash_table_destroy (acfg->export_names);
12639 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
12640 g_hash_table_destroy (acfg->klass_blob_hash);
12641 g_hash_table_destroy (acfg->method_blob_hash);
12642 got_info_free (&acfg->got_info);
12643 got_info_free (&acfg->llvm_got_info);
12644 arch_free_unwind_info_section_cache (acfg);
12645 mono_mempool_destroy (acfg->mempool);
12647 method_to_external_icall_symbol_name = NULL;
12648 g_free (acfg);
12651 #define WRAPPER(e,n) n,
12652 static const char* const
12653 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
12654 #include "mono/metadata/wrapper-types.h"
12655 NULL
12658 static G_GNUC_UNUSED const char*
12659 get_wrapper_type_name (int type)
12661 return wrapper_type_names [type];
12664 //#define DUMP_PLT
12665 //#define DUMP_GOT
12667 static void aot_dump (MonoAotCompile *acfg)
12669 FILE *dumpfile;
12670 char * dumpname;
12672 JsonWriter writer;
12673 mono_json_writer_init (&writer);
12675 mono_json_writer_object_begin(&writer);
12677 // Methods
12678 mono_json_writer_indent (&writer);
12679 mono_json_writer_object_key(&writer, "methods");
12680 mono_json_writer_array_begin (&writer);
12682 int i;
12683 for (i = 0; i < acfg->nmethods; ++i) {
12684 MonoCompile *cfg;
12685 MonoMethod *method;
12686 MonoClass *klass;
12688 cfg = acfg->cfgs [i];
12689 if (ignore_cfg (cfg))
12690 continue;
12692 method = cfg->orig_method;
12694 mono_json_writer_indent (&writer);
12695 mono_json_writer_object_begin(&writer);
12697 mono_json_writer_indent (&writer);
12698 mono_json_writer_object_key(&writer, "name");
12699 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
12701 mono_json_writer_indent (&writer);
12702 mono_json_writer_object_key(&writer, "signature");
12703 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
12705 mono_json_writer_indent (&writer);
12706 mono_json_writer_object_key(&writer, "code_size");
12707 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
12709 klass = method->klass;
12711 mono_json_writer_indent (&writer);
12712 mono_json_writer_object_key(&writer, "class");
12713 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
12715 mono_json_writer_indent (&writer);
12716 mono_json_writer_object_key(&writer, "namespace");
12717 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
12719 mono_json_writer_indent (&writer);
12720 mono_json_writer_object_key(&writer, "wrapper_type");
12721 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
12723 mono_json_writer_indent_pop (&writer);
12724 mono_json_writer_indent (&writer);
12725 mono_json_writer_object_end (&writer);
12726 mono_json_writer_printf (&writer, ",\n");
12729 mono_json_writer_indent_pop (&writer);
12730 mono_json_writer_indent (&writer);
12731 mono_json_writer_array_end (&writer);
12732 mono_json_writer_printf (&writer, ",\n");
12734 // PLT entries
12735 #ifdef DUMP_PLT
12736 mono_json_writer_indent_push (&writer);
12737 mono_json_writer_indent (&writer);
12738 mono_json_writer_object_key(&writer, "plt");
12739 mono_json_writer_array_begin (&writer);
12741 for (i = 0; i < acfg->plt_offset; ++i) {
12742 MonoPltEntry *plt_entry = NULL;
12743 MonoJumpInfo *ji;
12745 if (i == 0)
12747 * The first plt entry is unused.
12749 continue;
12751 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
12752 ji = plt_entry->ji;
12754 mono_json_writer_indent (&writer);
12755 mono_json_writer_printf (&writer, "{ ");
12756 mono_json_writer_object_key(&writer, "symbol");
12757 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
12760 mono_json_writer_indent_pop (&writer);
12761 mono_json_writer_indent (&writer);
12762 mono_json_writer_array_end (&writer);
12763 mono_json_writer_printf (&writer, ",\n");
12764 #endif
12766 // GOT entries
12767 #ifdef DUMP_GOT
12768 mono_json_writer_indent_push (&writer);
12769 mono_json_writer_indent (&writer);
12770 mono_json_writer_object_key(&writer, "got");
12771 mono_json_writer_array_begin (&writer);
12773 mono_json_writer_indent_push (&writer);
12774 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
12775 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
12777 mono_json_writer_indent (&writer);
12778 mono_json_writer_printf (&writer, "{ ");
12779 mono_json_writer_object_key(&writer, "patch_name");
12780 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
12783 mono_json_writer_indent_pop (&writer);
12784 mono_json_writer_indent (&writer);
12785 mono_json_writer_array_end (&writer);
12786 mono_json_writer_printf (&writer, ",\n");
12787 #endif
12789 mono_json_writer_indent_pop (&writer);
12790 mono_json_writer_indent (&writer);
12791 mono_json_writer_object_end (&writer);
12793 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
12794 dumpfile = fopen (dumpname, "w+");
12795 g_free (dumpname);
12797 fprintf (dumpfile, "%s", writer.text->str);
12798 fclose (dumpfile);
12800 mono_json_writer_destroy (&writer);
12803 static const MonoJitICallId preinited_jit_icalls [] = {
12804 MONO_JIT_ICALL_mini_llvm_init_method,
12805 MONO_JIT_ICALL_mini_llvm_init_gshared_method_this,
12806 MONO_JIT_ICALL_mini_llvm_init_gshared_method_mrgctx,
12807 MONO_JIT_ICALL_mini_llvm_init_gshared_method_vtable,
12808 MONO_JIT_ICALL_mini_llvmonly_throw_nullref_exception,
12809 MONO_JIT_ICALL_mono_llvm_throw_corlib_exception,
12810 MONO_JIT_ICALL_mono_threads_state_poll,
12811 MONO_JIT_ICALL_mini_llvmonly_init_vtable_slot,
12812 MONO_JIT_ICALL_mono_helper_ldstr_mscorlib,
12813 MONO_JIT_ICALL_mono_fill_method_rgctx,
12814 MONO_JIT_ICALL_mono_fill_class_rgctx
12817 static void
12818 add_preinit_slot (MonoAotCompile *acfg, MonoJumpInfo *ji)
12820 if (!acfg->aot_opts.llvm_only)
12821 get_got_offset (acfg, FALSE, ji);
12822 get_got_offset (acfg, TRUE, ji);
12825 static void
12826 add_preinit_got_slots (MonoAotCompile *acfg)
12828 MonoJumpInfo *ji;
12829 int i;
12832 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
12833 * during method initialization etc.
12836 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12837 ji->type = MONO_PATCH_INFO_IMAGE;
12838 ji->data.image = acfg->image;
12839 add_preinit_slot (acfg, ji);
12841 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12842 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
12843 add_preinit_slot (acfg, ji);
12845 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12846 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
12847 add_preinit_slot (acfg, ji);
12849 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12850 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
12851 add_preinit_slot (acfg, ji);
12853 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12854 ji->type = MONO_PATCH_INFO_AOT_MODULE;
12855 add_preinit_slot (acfg, ji);
12857 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12858 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
12859 add_preinit_slot (acfg, ji);
12861 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12862 ji->type = MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG;
12863 add_preinit_slot (acfg, ji);
12865 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12866 ji->type = MONO_PATCH_INFO_GC_SAFE_POINT_FLAG;
12867 add_preinit_slot (acfg, ji);
12869 if (!acfg->aot_opts.llvm_only) {
12870 for (i = 0; i < TLS_KEY_NUM; i++) {
12871 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12872 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12873 ji->data.jit_icall_id = mono_get_tls_key_to_jit_icall_id (i);
12874 add_preinit_slot (acfg, ji);
12878 /* Called by native-to-managed wrappers on possibly unattached threads */
12879 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12880 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12881 ji->data.jit_icall_id = MONO_JIT_ICALL_mono_threads_attach_coop;
12882 add_preinit_slot (acfg, ji);
12884 for (i = 0; i < G_N_ELEMENTS (preinited_jit_icalls); ++i) {
12885 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12886 ji->type = MONO_PATCH_INFO_JIT_ICALL_ID;
12887 ji->data.jit_icall_id = preinited_jit_icalls [i];
12888 add_preinit_slot (acfg, ji);
12891 if (acfg->aot_opts.llvm_only)
12892 acfg->nshared_got_entries = acfg->llvm_got_offset;
12893 else
12894 acfg->nshared_got_entries = acfg->got_offset;
12895 g_assert (acfg->nshared_got_entries);
12898 static void
12899 mono_dedup_log_stats (MonoAotCompile *acfg)
12901 GHashTableIter iter;
12902 g_assert (acfg->dedup_stats);
12904 if (!acfg->dedup_emit_mode)
12905 return;
12907 // If dedup_emit_mode, acfg is the dummy dedup module that consolidates
12908 // deduped modules
12909 g_hash_table_iter_init (&iter, acfg->method_to_cfg);
12910 MonoCompile *dcfg = NULL;
12911 MonoMethod *method = NULL;
12913 size_t wrappers_size_saved = 0;
12914 size_t inflated_size_saved = 0;
12915 size_t copied_singles = 0;
12916 int wrappers_saved = 0;
12917 int instances_saved = 0;
12918 int copied = 0;
12920 while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
12921 gchar *dedup_name = mono_aot_get_mangled_method_name (method);
12922 guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
12924 if (count == 0)
12925 continue;
12927 if (acfg->dedup_emit_mode) {
12928 // Size *saved* is the size due to things not emitted.
12929 if (count < 2) {
12930 // Just moved, didn't save space / dedup
12931 copied ++;
12932 copied_singles += dcfg->code_len;
12933 } else if (method->wrapper_type != MONO_WRAPPER_NONE) {
12934 wrappers_saved ++;
12935 wrappers_size_saved += dcfg->code_len * (count - 1);
12936 } else {
12937 instances_saved ++;
12938 inflated_size_saved += dcfg->code_len * (count - 1);
12941 if (acfg->aot_opts.dedup) {
12942 if (method->wrapper_type != MONO_WRAPPER_NONE) {
12943 wrappers_saved ++;
12944 wrappers_size_saved += dcfg->code_len * count;
12945 } else {
12946 instances_saved ++;
12947 inflated_size_saved += dcfg->code_len * count;
12952 aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%d methods, %zu bytes\n", wrappers_saved, wrappers_size_saved);
12953 aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%d methods, %zu bytes\n", instances_saved, inflated_size_saved);
12954 if (acfg->dedup_emit_mode)
12955 aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%d methods, %zu bytes\n", copied, copied_singles);
12957 g_hash_table_destroy (acfg->dedup_stats);
12958 acfg->dedup_stats = NULL;
12961 // Flush the cache to tell future calls what to skip
12962 static void
12963 mono_flush_method_cache (MonoAotCompile *acfg)
12965 GHashTable *method_cache = acfg->dedup_cache;
12966 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12967 if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
12968 g_free (filename);
12969 return;
12972 acfg->dedup_cache = NULL;
12974 FILE *cache = fopen (filename, "w");
12976 if (!cache)
12977 g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
12979 GHashTableIter iter;
12980 gchar *name = NULL;
12981 g_hash_table_iter_init (&iter, method_cache);
12982 gboolean cont = TRUE;
12983 while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
12984 int res = fprintf (cache, "%s\n", name);
12985 cont = res >= 0;
12987 // FIXME: don't assert if error when flushing
12988 g_assert (cont);
12990 fclose (cache);
12991 g_free (filename);
12993 // The keys are all in the imageset, nothing to free
12994 // Values are just pointers to memory owned elsewhere, or sentinels
12995 g_hash_table_destroy (method_cache);
12998 // Read in what has been emitted by previous invocations,
12999 // what can be skipped
13000 static void
13001 mono_read_method_cache (MonoAotCompile *acfg)
13003 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
13004 // Only do once, when dedup_cache is null
13005 if (acfg->dedup_cache)
13006 goto early_exit;
13008 if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
13009 g_assert (acfg->dedup_stats);
13011 // only in skip mode
13012 if (!acfg->aot_opts.dedup)
13013 goto early_exit;
13015 g_assert (acfg->dedup_cache);
13017 FILE *cache;
13018 cache = fopen (filename, "r");
13019 if (!cache)
13020 goto early_exit;
13022 // Since we do pointer comparisons, and it can't be allocated at
13023 // the address 0x1 due to alignment, we use this as a sentinel
13024 gpointer other_acfg_sentinel;
13025 other_acfg_sentinel = GINT_TO_POINTER (0x1);
13027 if (fseek (cache, 0L, SEEK_END))
13028 goto cleanup;
13030 size_t fileLength;
13031 fileLength = ftell (cache);
13032 g_assert (fileLength > 0);
13034 if (fseek (cache, 0L, SEEK_SET))
13035 goto cleanup;
13037 // Avoid thousands of new malloc entries
13038 // FIXME: allocate into imageset, so we don't need to free.
13039 // put the other mangled names there too.
13040 char *bulk;
13041 bulk = g_malloc0 (fileLength * sizeof (char));
13042 size_t offset;
13043 offset = 0;
13045 while (fgets (&bulk [offset], fileLength - offset, cache)) {
13046 // strip newline
13047 char *line = &bulk [offset];
13048 size_t len = strlen (line);
13049 if (len == 0)
13050 break;
13052 if (len >= 0 && line [len] == '\n')
13053 line [len] = '\0';
13054 offset += strlen (line) + 1;
13055 g_assert (fileLength >= offset);
13057 g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
13060 cleanup:
13061 fclose (cache);
13063 early_exit:
13064 g_free (filename);
13065 return;
13068 typedef struct {
13069 GHashTable *cache;
13070 GHashTable *stats;
13071 gboolean emit_inflated_methods;
13072 MonoAssembly *inflated_assembly;
13073 } MonoAotState;
13075 static MonoAotState *
13076 alloc_aot_state (void)
13078 MonoAotState *state = g_malloc (sizeof (MonoAotState));
13079 // FIXME: Should this own the memory?
13080 state->cache = g_hash_table_new (g_str_hash, g_str_equal);
13081 state->stats = g_hash_table_new (g_str_hash, g_str_equal);
13082 // Start in "collect mode"
13083 state->emit_inflated_methods = FALSE;
13084 state->inflated_assembly = NULL;
13085 return state;
13088 static void
13089 free_aot_state (MonoAotState *astate)
13091 g_hash_table_destroy (astate->cache);
13092 g_free (astate);
13095 static void
13096 mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
13098 GHashTableIter iter;
13099 gchar *name = NULL;
13100 MonoMethod *method = NULL;
13102 acfg->dedup_emit_mode = TRUE;
13104 g_hash_table_iter_init (&iter, astate->cache);
13105 while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
13106 add_method_full (acfg, method, TRUE, 0);
13108 return;
13111 static void
13112 mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
13114 if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
13115 return;
13117 if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
13118 // Thread the state through when making the inflate pass
13119 *astate = *global_aot_state;
13122 if (!*astate) {
13123 *astate = alloc_aot_state ();
13124 *global_aot_state = *astate;
13127 acfg->dedup_cache = (*astate)->cache;
13128 acfg->dedup_stats = (*astate)->stats;
13130 // fills out acfg->dedup_cache
13131 if (acfg->aot_opts.dedup)
13132 mono_read_method_cache (acfg);
13134 if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
13135 gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
13136 gchar *asm_file = NULL;
13138 // Get the last part of the path, the filename
13139 for (int i=0; asm_path [i] != NULL; i++)
13140 asm_file = asm_path [i];
13142 if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
13143 // Save
13144 *is_dedup_dummy = TRUE;
13145 (*astate)->inflated_assembly = ass;
13147 g_strfreev (asm_path);
13148 } else if ((*astate)->inflated_assembly) {
13149 *is_dedup_dummy = (ass == (*astate)->inflated_assembly);
13153 int
13154 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13156 // create assembly, loop and add extra_methods
13157 // in add_generic_instances , rip out what's in that for loop
13158 // and apply that to this aot_state inside of mono_compile_assembly
13159 MonoAotState *astate;
13160 astate = *(MonoAotState **)aot_state;
13161 g_assert (astate);
13163 // FIXME: allow suffixes?
13164 if (!astate->inflated_assembly) {
13165 const char* inflate = strstr (aot_options, "dedup-inflate");
13166 if (!inflate)
13167 return 0;
13168 else
13169 g_error ("Error: mono was not given an assembly with the provided inflate name\n");
13172 // Switch modes
13173 astate->emit_inflated_methods = TRUE;
13175 int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
13177 *aot_state = NULL;
13178 free_aot_state (astate);
13180 return res;
13183 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13184 static MonoMethodSignature * const * const interp_in_static_sigs [] = {
13185 &mono_icall_sig_bool_ptr_int32_ptrref,
13186 &mono_icall_sig_bool_ptr_ptrref,
13187 &mono_icall_sig_int32_int32_ptrref,
13188 &mono_icall_sig_int32_int32_ptr_ptrref,
13189 &mono_icall_sig_int32_ptr_int32_ptr,
13190 &mono_icall_sig_int32_ptr_int32_ptrref,
13191 &mono_icall_sig_int32_ptr_ptrref,
13192 &mono_icall_sig_object_object_ptr_ptr_ptr,
13193 &mono_icall_sig_object,
13194 &mono_icall_sig_ptr_int32_ptrref,
13195 &mono_icall_sig_ptr_ptr_int32_ptr_ptr_ptrref,
13196 &mono_icall_sig_ptr_ptr_int32_ptr_ptrref,
13197 &mono_icall_sig_ptr_ptr_int32_ptrref,
13198 &mono_icall_sig_ptr_ptr_ptr_int32_ptrref,
13199 &mono_icall_sig_ptr_ptr_ptr_ptrref_ptrref,
13200 &mono_icall_sig_ptr_ptr_ptr_ptr_ptrref,
13201 &mono_icall_sig_ptr_ptr_ptr_ptrref,
13202 &mono_icall_sig_ptr_ptr_ptrref,
13203 &mono_icall_sig_ptr_ptr_uint32_ptrref,
13204 &mono_icall_sig_ptr_uint32_ptrref,
13205 &mono_icall_sig_void_object_ptr_ptr_ptr,
13206 &mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref_ptr_ptrref,
13207 &mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref,
13208 &mono_icall_sig_void_ptr_ptr_ptrref,
13209 &mono_icall_sig_void_ptr_ptrref,
13210 &mono_icall_sig_void_ptr,
13211 &mono_icall_sig_void_int32_ptrref,
13212 &mono_icall_sig_void_uint32_ptrref,
13213 &mono_icall_sig_void,
13215 #else
13216 // Common signatures for which we use interp in wrappers even in fullaot + trampolines mode
13217 // for increased performance
13218 static MonoMethodSignature *const * const interp_in_static_common_sigs [] = {
13219 &mono_icall_sig_void,
13220 &mono_icall_sig_ptr,
13221 &mono_icall_sig_void_ptr,
13222 &mono_icall_sig_ptr_ptr,
13223 &mono_icall_sig_void_ptr_ptr,
13224 &mono_icall_sig_ptr_ptr_ptr,
13225 &mono_icall_sig_void_ptr_ptr_ptr,
13226 &mono_icall_sig_ptr_ptr_ptr_ptr,
13227 &mono_icall_sig_void_ptr_ptr_ptr_ptr,
13228 &mono_icall_sig_ptr_ptr_ptr_ptr_ptr,
13229 &mono_icall_sig_void_ptr_ptr_ptr_ptr_ptr,
13230 &mono_icall_sig_ptr_ptr_ptr_ptr_ptr_ptr,
13231 &mono_icall_sig_void_ptr_ptr_ptr_ptr_ptr_ptr,
13232 &mono_icall_sig_ptr_ptr_ptr_ptr_ptr_ptr_ptr,
13234 #endif
13236 static void
13237 add_interp_in_wrapper_for_sig (MonoAotCompile *acfg, MonoMethodSignature *sig)
13239 MonoMethod *wrapper;
13241 sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
13242 sig->pinvoke = FALSE;
13243 wrapper = mini_get_interp_in_wrapper (sig);
13244 add_method (acfg, wrapper);
13248 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
13250 MonoImage *image = ass->image;
13251 int res;
13252 MonoAotCompile *acfg;
13253 char *p;
13254 TV_DECLARE (atv);
13255 TV_DECLARE (btv);
13257 acfg = acfg_create (ass, opts);
13259 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
13260 acfg->aot_opts.write_symbols = TRUE;
13261 acfg->aot_opts.ntrampolines = 4096;
13262 acfg->aot_opts.nrgctx_trampolines = 4096;
13263 acfg->aot_opts.nimt_trampolines = 512;
13264 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
13265 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
13266 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13267 acfg->aot_opts.nftnptr_arg_trampolines = 128;
13268 #endif
13269 acfg->aot_opts.nunbox_arbitrary_trampolines = 256;
13270 if (!acfg->aot_opts.llvm_path)
13271 acfg->aot_opts.llvm_path = g_strdup ("");
13272 acfg->aot_opts.temp_path = g_strdup ("");
13273 #ifdef MONOTOUCH
13274 acfg->aot_opts.use_trampolines_page = TRUE;
13275 #endif
13276 acfg->aot_opts.clangxx = g_strdup ("clang++");
13278 mono_aot_parse_options (aot_options, &acfg->aot_opts);
13280 // start dedup
13281 MonoAotState *astate = NULL;
13282 gboolean is_dedup_dummy = FALSE;
13283 mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
13285 // Process later
13286 if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
13287 return 0;
13289 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13290 acfg->dedup_collect_only = TRUE;
13291 // end dedup
13293 if (acfg->aot_opts.logfile) {
13294 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
13297 if (acfg->aot_opts.data_outfile) {
13298 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
13299 if (!acfg->data_outfile) {
13300 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
13301 return 1;
13303 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
13306 //acfg->aot_opts.print_skipped_methods = TRUE;
13308 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
13309 if (acfg->opts & MONO_OPT_GSHAREDVT) {
13310 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
13311 return 1;
13313 if (acfg->aot_opts.llvm_only) {
13314 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
13315 return 1;
13317 #else
13318 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13319 acfg->opts |= MONO_OPT_GSHAREDVT;
13320 #endif
13322 #if !defined(ENABLE_LLVM)
13323 if (acfg->aot_opts.llvm_only) {
13324 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
13325 return 1;
13327 #endif
13329 if (acfg->opts & MONO_OPT_GSHAREDVT)
13330 mono_set_generic_sharing_vt_supported (TRUE);
13332 if (!acfg->dedup_collect_only)
13333 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
13335 if (!acfg->aot_opts.deterministic)
13336 generate_aotid ((guint8*) &acfg->image->aotid);
13338 char *aotid = mono_guid_to_string (acfg->image->aotid);
13339 if (!acfg->dedup_collect_only)
13340 aot_printf (acfg, "AOTID %s\n", aotid);
13341 g_free (aotid);
13343 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
13344 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13345 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
13346 return 1;
13348 #endif
13350 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
13351 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
13352 return 1;
13355 if (acfg->aot_opts.static_link)
13356 acfg->aot_opts.asm_writer = TRUE;
13358 if (acfg->aot_opts.soft_debug) {
13359 mini_debug_options.mdb_optimizations = TRUE;
13360 mini_debug_options.gen_sdb_seq_points = TRUE;
13362 if (!mono_debug_enabled ()) {
13363 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
13364 return 1;
13366 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
13369 if (acfg->aot_opts.try_llvm)
13370 acfg->aot_opts.llvm = mini_llvm_init ();
13372 if (mono_use_llvm || acfg->aot_opts.llvm) {
13373 acfg->llvm = TRUE;
13374 acfg->aot_opts.asm_writer = TRUE;
13375 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
13377 if (acfg->aot_opts.soft_debug) {
13378 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
13379 return 1;
13382 mini_llvm_init ();
13384 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
13385 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
13386 return 1;
13390 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13391 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
13392 acfg->is_full_aot = TRUE;
13395 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
13396 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_INTERP);
13397 acfg->is_full_aot = TRUE;
13400 if (mini_safepoints_enabled ())
13401 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
13403 // The methods in dedup-emit amodules must be available on runtime startup
13404 // Note: Only one such amodule can have this attribute
13405 if (astate && astate->emit_inflated_methods)
13406 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
13409 if (acfg->aot_opts.instances_logfile_path) {
13410 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
13411 if (!acfg->instances_logfile) {
13412 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
13413 return 1;
13417 if (acfg->aot_opts.profile_files) {
13418 GList *l;
13420 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
13421 load_profile_file (acfg, (char*)l->data);
13425 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13426 for (int method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index)
13427 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
13430 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
13431 #ifdef MONO_ARCH_GSHARED_SUPPORTED
13432 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
13433 #endif
13434 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
13435 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
13436 if (acfg->opts & MONO_OPT_GSHAREDVT)
13437 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
13438 #endif
13439 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13440 acfg->num_trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = mono_aot_mode_is_interp (&acfg->aot_opts) ? acfg->aot_opts.nftnptr_arg_trampolines : 0;
13441 #endif
13442 acfg->num_trampolines [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = mono_aot_mode_is_interp (&acfg->aot_opts) && mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nunbox_arbitrary_trampolines : 0;
13444 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
13446 arch_init (acfg);
13448 if (mono_use_llvm || acfg->aot_opts.llvm) {
13450 * Emit all LLVM code into a separate assembly/object file and link with it
13451 * normally.
13453 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
13454 acfg->llvm_owriter = TRUE;
13455 } else if (acfg->aot_opts.llvm_outfile) {
13456 int len = strlen (acfg->aot_opts.llvm_outfile);
13458 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
13459 acfg->llvm_owriter = TRUE;
13463 if (acfg->llvm && acfg->thumb_mixed)
13464 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
13465 if (acfg->aot_opts.llvm_only)
13466 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
13468 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
13469 /* Get rid of characters which cannot occur in symbols */
13470 for (p = acfg->assembly_name_sym; *p; ++p) {
13471 if (!(isalnum (*p) || *p == '_'))
13472 *p = '_';
13475 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
13476 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
13477 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
13478 if (acfg->llvm) {
13479 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
13480 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
13483 acfg->method_index = 1;
13485 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13486 mono_set_partial_sharing_supported (TRUE);
13488 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13489 res = collect_methods (acfg);
13490 if (!res)
13491 return 1;
13494 // If we're emitting all of the inflated methods into a dummy
13495 // Assembly, then after extra_methods is set up, we're done
13496 // in this function.
13497 if (astate && astate->emit_inflated_methods)
13498 mono_add_deferred_extra_methods (acfg, astate);
13501 GList *l;
13503 for (l = acfg->profile_data; l; l = l->next)
13504 resolve_profile_data (acfg, (ProfileData*)l->data, ass);
13505 for (l = acfg->profile_data; l; l = l->next)
13506 add_profile_instances (acfg, (ProfileData*)l->data);
13509 acfg->cfgs_size = acfg->methods->len + 32;
13510 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
13512 /* PLT offset 0 is reserved for the PLT trampoline */
13513 acfg->plt_offset = 1;
13514 add_preinit_got_slots (acfg);
13516 #ifdef ENABLE_LLVM
13517 if (acfg->llvm) {
13518 llvm_acfg = acfg;
13519 LLVMModuleFlags flags = (LLVMModuleFlags)0;
13520 #ifdef EMIT_DWARF_INFO
13521 flags = LLVM_MODULE_FLAG_DWARF;
13522 #endif
13523 #ifdef EMIT_WIN32_CODEVIEW_INFO
13524 flags = LLVM_MODULE_FLAG_CODEVIEW;
13525 #endif
13526 if (acfg->aot_opts.static_link)
13527 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_STATIC);
13528 if (acfg->aot_opts.llvm_only)
13529 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_LLVM_ONLY);
13530 if (acfg->aot_opts.interp)
13531 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_INTERP);
13532 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, flags);
13534 add_lazy_init_wrappers (acfg);
13536 #endif
13538 if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
13539 MonoMethod *wrapper = mini_get_interp_lmf_wrapper ("mono_interp_to_native_trampoline", (gpointer) mono_interp_to_native_trampoline);
13540 add_method (acfg, wrapper);
13542 wrapper = mini_get_interp_lmf_wrapper ("mono_interp_entry_from_trampoline", (gpointer) mono_interp_entry_from_trampoline);
13543 add_method (acfg, wrapper);
13545 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13546 for (int i = 0; i < G_N_ELEMENTS (interp_in_static_sigs); i++)
13547 add_interp_in_wrapper_for_sig (acfg, *interp_in_static_sigs [i]);
13548 #else
13549 for (int i = 0; i < G_N_ELEMENTS (interp_in_static_common_sigs); i++)
13550 add_interp_in_wrapper_for_sig (acfg, *interp_in_static_common_sigs [i]);
13551 #endif
13553 /* required for mixed mode */
13554 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
13555 add_gc_wrappers (acfg);
13557 for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
13558 add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
13562 TV_GETTIME (atv);
13564 compile_methods (acfg);
13566 TV_GETTIME (btv);
13568 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
13570 dedup_skip_methods (acfg);
13572 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13573 /* We only collected methods from this assembly */
13574 return 0;
13576 return emit_aot_image (acfg);
13579 static void
13580 print_stats (MonoAotCompile *acfg)
13582 int i;
13583 gint64 all_sizes;
13584 char llvm_stats_msg [256];
13586 if (acfg->llvm && !acfg->aot_opts.llvm_only)
13587 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
13588 else
13589 strcpy (llvm_stats_msg, "");
13591 all_sizes = acfg->stats.code_size + acfg->stats.method_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;
13593 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, BLOB: %d\n",
13594 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
13595 (int)acfg->stats.method_info_size, (int)(acfg->stats.method_info_size * 100 / all_sizes),
13596 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
13597 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
13598 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
13599 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,
13600 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
13601 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
13602 (int)(acfg->got_offset * sizeof (target_mgreg_t)),
13603 (int)acfg->stats.blob_size);
13604 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
13605 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
13606 llvm_stats_msg,
13607 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
13608 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
13609 if (acfg->stats.genericcount)
13610 aot_printf (acfg, "%d methods failed gsharing (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
13611 if (acfg->stats.abscount)
13612 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
13613 if (acfg->stats.lmfcount)
13614 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
13615 if (acfg->stats.ocount)
13616 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
13618 aot_printf (acfg, "GOT slot distribution:\n");
13619 int nslots = 0;
13620 int size = 0;
13621 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
13622 nslots += acfg->stats.got_slot_types [i];
13623 size += acfg->stats.got_slot_info_sizes [i];
13624 if (acfg->stats.got_slot_types [i])
13625 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]);
13627 aot_printf (acfg, "GOT SLOTS: %d, INFO SIZE: %d\n", nslots, size);
13629 aot_printf (acfg, "\nEncoding stats:\n");
13630 aot_printf (acfg, "\tMethod ref: %d (%dk)\n", acfg->stats.method_ref_count, acfg->stats.method_ref_size / 1024);
13631 aot_printf (acfg, "\tClass ref: %d (%dk)\n", acfg->stats.class_ref_count, acfg->stats.class_ref_size / 1024);
13632 aot_printf (acfg, "\tGinst: %d (%dk)\n", acfg->stats.ginst_count, acfg->stats.ginst_size / 1024);
13634 aot_printf (acfg, "\nMethod stats:\n");
13635 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
13636 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
13637 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
13638 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
13640 if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
13641 mono_dedup_log_stats (acfg);
13644 static void
13645 create_depfile (MonoAotCompile *acfg)
13647 FILE *depfile;
13649 // FIXME: Support other configurations
13650 g_assert (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only && acfg->aot_opts.llvm_outfile);
13652 depfile = fopen (acfg->aot_opts.depfile, "w");
13653 g_assert (depfile);
13655 int ntargets = 1;
13656 char **targets = g_new0 (char*, ntargets);
13657 targets [0] = acfg->aot_opts.llvm_outfile;
13658 for (int tindex = 0; tindex < ntargets; ++tindex) {
13659 fprintf (depfile, "%s: ", targets [tindex]);
13660 for (int i = 0; i < acfg->image_table->len; i++) {
13661 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
13662 fprintf (depfile, " %s", image->filename);
13664 fprintf (depfile, "\n");
13666 g_free (targets);
13667 fclose (depfile);
13670 static int
13671 emit_aot_image (MonoAotCompile *acfg)
13673 int i, res;
13674 TV_DECLARE (atv);
13675 TV_DECLARE (btv);
13677 TV_GETTIME (atv);
13679 #ifdef ENABLE_LLVM
13680 if (acfg->llvm) {
13681 if (acfg->aot_opts.asm_only) {
13682 if (acfg->aot_opts.outfile) {
13683 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13684 acfg->tmpbasename = g_strdup (acfg->tmpfname);
13685 } else {
13686 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
13687 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13689 g_assert (acfg->aot_opts.llvm_outfile);
13690 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13691 if (acfg->llvm_owriter)
13692 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
13693 else
13694 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13695 } else {
13696 gchar *temp_path;
13697 if (strcmp (acfg->aot_opts.temp_path, "") != 0) {
13698 temp_path = g_strdup (acfg->aot_opts.temp_path);
13699 } else {
13700 temp_path = g_mkdtemp (g_strdup ("mono_aot_XXXXXX"));
13701 g_assertf (temp_path, "mkdtemp failed, error = (%d) %s", errno, g_strerror (errno));
13702 acfg->temp_dir_to_delete = g_strdup (temp_path);
13705 acfg->tmpbasename = g_build_filename (temp_path, "temp", NULL);
13706 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13707 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
13708 acfg->llvm_ofile = g_strdup_printf ("%s-llvm." AS_OBJECT_FILE_SUFFIX, acfg->tmpbasename);
13710 g_free (temp_path);
13713 #endif
13715 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
13716 if (acfg->aot_opts.outfile)
13717 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13718 else
13719 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
13720 acfg->fp = fopen (acfg->tmpfname, "w+");
13721 } else {
13722 if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
13723 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
13724 acfg->fp = fdopen (i, "w+");
13725 } else {
13726 acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
13727 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13728 acfg->fp = fopen (acfg->tmpfname, "w+");
13731 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
13732 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
13733 return 1;
13735 if (acfg->fp)
13736 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
13738 /* Compute symbols for methods */
13739 for (i = 0; i < acfg->nmethods; ++i) {
13740 if (acfg->cfgs [i]) {
13741 MonoCompile *cfg = acfg->cfgs [i];
13742 int method_index = get_method_index (acfg, cfg->orig_method);
13744 if (cfg->asm_symbol) {
13745 // Set by method emitter in backend
13746 if (acfg->llvm_label_prefix) {
13747 char *old_symbol = cfg->asm_symbol;
13748 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->asm_symbol);
13749 g_free (old_symbol);
13751 } else if (COMPILE_LLVM (cfg)) {
13752 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
13753 } else if (acfg->global_symbols || acfg->llvm) {
13754 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
13755 } else {
13756 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
13758 cfg->asm_debug_symbol = cfg->asm_symbol;
13762 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
13764 * CLANG supports GAS .file/.loc directives, so emit line number information this way
13766 acfg->gas_line_numbers = TRUE;
13769 #ifdef EMIT_DWARF_INFO
13770 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
13771 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
13772 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
13773 return 1;
13775 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
13777 #endif /* EMIT_DWARF_INFO */
13779 if (acfg->w)
13780 mono_img_writer_emit_start (acfg->w);
13782 if (acfg->dwarf)
13783 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
13785 if (acfg->aot_opts.dedup)
13786 mono_flush_method_cache (acfg);
13788 emit_code (acfg);
13790 emit_info (acfg);
13792 emit_extra_methods (acfg);
13794 emit_trampolines (acfg);
13796 emit_class_name_table (acfg);
13798 emit_got_info (acfg, FALSE);
13799 if (acfg->llvm)
13800 emit_got_info (acfg, TRUE);
13802 emit_exception_info (acfg);
13804 emit_unwind_info (acfg);
13806 emit_class_info (acfg);
13808 emit_plt (acfg);
13810 emit_image_table (acfg);
13812 emit_weak_field_indexes (acfg);
13814 emit_got (acfg);
13818 * The managed allocators are GC specific, so can't use an AOT image created by one GC
13819 * in another.
13821 const char *gc_name = mono_gc_get_gc_name ();
13822 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
13825 emit_blob (acfg);
13827 emit_objc_selectors (acfg);
13829 emit_globals (acfg);
13831 emit_file_info (acfg);
13833 if (acfg->dwarf) {
13834 emit_dwarf_info (acfg);
13835 mono_dwarf_writer_close (acfg->dwarf);
13836 } else {
13837 if (!acfg->aot_opts.nodebug)
13838 emit_codeview_info (acfg);
13841 emit_mem_end (acfg);
13843 if (acfg->need_pt_gnu_stack) {
13844 /* This is required so the .so doesn't have an executable stack */
13845 /* The bin writer already emits this */
13846 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
13849 if (acfg->aot_opts.data_outfile)
13850 fclose (acfg->data_outfile);
13852 #ifdef ENABLE_LLVM
13853 if (acfg->llvm) {
13854 gboolean res;
13856 res = emit_llvm_file (acfg);
13857 if (!res)
13858 return 1;
13860 #endif
13862 emit_library_info (acfg);
13864 TV_GETTIME (btv);
13866 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
13868 if (!acfg->aot_opts.stats)
13869 aot_printf (acfg, "Compiled: %d/%d\n", acfg->stats.ccount, acfg->stats.mcount);
13871 TV_GETTIME (atv);
13872 if (acfg->w) {
13873 res = mono_img_writer_emit_writeout (acfg->w);
13874 if (res != 0) {
13875 acfg_free (acfg);
13876 return res;
13878 res = compile_asm (acfg);
13879 if (res != 0) {
13880 acfg_free (acfg);
13881 return res;
13884 TV_GETTIME (btv);
13885 acfg->stats.link_time = TV_ELAPSED (atv, btv);
13887 if (acfg->aot_opts.stats)
13888 print_stats (acfg);
13890 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);
13892 if (acfg->aot_opts.depfile)
13893 create_depfile (acfg);
13895 if (acfg->aot_opts.dump_json)
13896 aot_dump (acfg);
13898 if (!acfg->aot_opts.save_temps && acfg->temp_dir_to_delete) {
13899 char *command = g_strdup_printf ("rm -r %s", acfg->temp_dir_to_delete);
13900 execute_system (command);
13901 g_free (command);
13904 acfg_free (acfg);
13906 return 0;
13909 #else
13911 /* AOT disabled */
13913 void*
13914 mono_aot_readonly_field_override (MonoClassField *field)
13916 return NULL;
13920 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
13922 return 0;
13925 gboolean
13926 mono_aot_is_shared_got_offset (int offset)
13928 return FALSE;
13932 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13934 g_assert_not_reached ();
13935 return 0;
13938 gboolean
13939 mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
13941 g_assert_not_reached ();
13942 return 0;
13945 #endif