Merge pull request #16323 from EgorBo/ffast-math
[mono-project.git] / mono / mini / aot-compiler.c
blob38dfc73b2ee351c0749e83fab58714e4bca4ef60
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 (is_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 if (mono_use_fast_math) {
1120 // same parameters are passed to opt and LLVM JIT
1121 g_string_append (acfg->llc_args, " -fp-contract=fast -enable-no-infs-fp-math -enable-no-nans-fp-math -enable-no-signed-zeros-fp-math -enable-no-trapping-fp-math -enable-unsafe-fp-math");
1124 #ifdef TARGET_ARM
1125 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
1126 g_string_append (acfg->llc_args, "-mattr=+v6");
1127 } else {
1128 if (!(acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb")))
1129 g_string_append (acfg->llc_args, " -march=arm");
1131 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "ios")) {
1132 g_string_append (acfg->llc_args, " -mattr=+v7");
1133 g_string_append (acfg->llc_args, " -exception-model=dwarf -disable-fp-elim");
1136 #if defined(ARM_FPU_VFP_HARD)
1137 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
1138 g_string_append (acfg->as_args, " -mfpu=vfp3");
1139 #elif defined(ARM_FPU_VFP)
1140 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1141 g_string_append (acfg->as_args, " -mfpu=vfp3");
1142 #else
1143 g_string_append (acfg->llc_args, " -mattr=+soft-float");
1144 #endif
1146 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1147 acfg->thumb_mixed = TRUE;
1149 if (acfg->aot_opts.mtriple)
1150 mono_arch_set_target (acfg->aot_opts.mtriple);
1151 #endif
1153 #ifdef TARGET_ARM64
1154 g_string_append (acfg->llc_args, " -march=aarch64");
1155 acfg->inst_directive = ".inst";
1156 if (acfg->aot_opts.mtriple)
1157 mono_arch_set_target (acfg->aot_opts.mtriple);
1158 #endif
1160 #ifdef TARGET_MACH
1161 acfg->user_symbol_prefix = "_";
1162 acfg->llvm_label_prefix = "_";
1163 acfg->inst_directive = ".word";
1164 acfg->need_no_dead_strip = TRUE;
1165 acfg->aot_opts.gnu_asm = TRUE;
1166 #endif
1168 #if defined(__linux__) && !defined(TARGET_ARM)
1169 acfg->need_pt_gnu_stack = TRUE;
1170 #endif
1172 #ifdef TARGET_RISCV
1173 if (acfg->aot_opts.mtriple)
1174 mono_arch_set_target (acfg->aot_opts.mtriple);
1176 #ifdef TARGET_RISCV64
1178 g_string_append (acfg->as_args, " -march=rv64i ");
1179 #ifdef RISCV_FPABI_DOUBLE
1180 g_string_append (acfg->as_args, " -mabi=lp64d");
1181 #else
1182 g_string_append (acfg->as_args, " -mabi=lp64");
1183 #endif
1185 #else
1187 g_string_append (acfg->as_args, " -march=rv32i ");
1188 #ifdef RISCV_FPABI_DOUBLE
1189 g_string_append (acfg->as_args, " -mabi=ilp32d ");
1190 #else
1191 g_string_append (acfg->as_args, " -mabi=ilp32 ");
1192 #endif
1194 #endif
1196 #endif
1198 #ifdef MONOTOUCH
1199 acfg->global_symbols = TRUE;
1200 #endif
1202 #ifdef TARGET_ANDROID
1203 acfg->llvm_owriter_supported = FALSE;
1204 #endif
1207 #ifdef TARGET_ARM64
1210 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1211 static void
1212 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1214 int offset;
1216 g_assert (acfg->fp);
1217 emit_unset_mode (acfg);
1218 /* r16==ip0 */
1219 offset = (int)(got_slot * sizeof (target_mgreg_t));
1220 #ifdef TARGET_MACH
1221 /* clang's integrated assembler */
1222 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1223 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1224 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1225 #else
1226 /* Linux GAS */
1227 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1228 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1229 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1230 #endif
1233 static void
1234 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1236 int reg;
1238 g_assert (acfg->fp);
1239 emit_unset_mode (acfg);
1241 /* ldr rt, target */
1242 reg = arm_get_ldr_lit_reg (code);
1244 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1245 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1246 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1248 *code_size = 12;
1251 static void
1252 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1254 g_assert (acfg->fp);
1255 emit_unset_mode (acfg);
1256 if (ji && ji->relocation == MONO_R_ARM64_B) {
1257 fprintf (acfg->fp, "b %s\n", target);
1258 } else {
1259 if (ji)
1260 g_assert (ji->relocation == MONO_R_ARM64_BL);
1261 fprintf (acfg->fp, "bl %s\n", target);
1263 *call_size = 4;
1266 static void
1267 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1269 int reg;
1271 /* ldr rt, target */
1272 reg = arm_get_ldr_lit_reg (code);
1273 arm64_emit_load_got_slot (acfg, reg, got_slot);
1274 *code_size = 12;
1277 static void
1278 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1280 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (target_mgreg_t));
1281 fprintf (acfg->fp, "br x16\n");
1282 /* Used by mono_aot_get_plt_info_offset () */
1283 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1286 static void
1287 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1289 guint8 buf [256];
1290 guint8 *code;
1291 int imm;
1293 /* The common code */
1294 code = buf;
1295 imm = pagesize;
1296 /* The trampoline address is in IP0 */
1297 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1298 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1299 /* Compute the data slot address */
1300 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1301 /* Trampoline argument */
1302 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1303 /* Address */
1304 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1305 arm_brx (code, ARMREG_IP0);
1307 /* Emit it */
1308 emit_code_bytes (acfg, buf, code - buf);
1310 *size = code - buf;
1313 static void
1314 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1316 guint8 buf [256];
1317 guint8 *code;
1318 int i, count;
1320 count = (pagesize - common_tramp_size) / specific_tramp_size;
1321 for (i = 0; i < count; ++i) {
1322 code = buf;
1323 arm_adrx (code, ARMREG_IP0, code);
1324 /* Branch to the generic code */
1325 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1326 /* This has to be 2 pointers long */
1327 arm_nop (code);
1328 arm_nop (code);
1329 g_assert (code - buf == specific_tramp_size);
1330 emit_code_bytes (acfg, buf, code - buf);
1334 static void
1335 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1337 guint8 buf [128];
1338 guint8 *code;
1339 guint8 *labels [16];
1340 int common_tramp_size;
1341 int specific_tramp_size = 2 * 8;
1342 int imm, pagesize;
1343 char symbol [128];
1345 if (!acfg->aot_opts.use_trampolines_page)
1346 return;
1348 #ifdef TARGET_MACH
1349 /* Have to match the target pagesize */
1350 pagesize = 16384;
1351 #else
1352 pagesize = mono_pagesize ();
1353 #endif
1354 acfg->tramp_page_size = pagesize;
1356 /* The specific trampolines */
1357 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1358 emit_alignment (acfg, pagesize);
1359 emit_global (acfg, symbol, TRUE);
1360 emit_label (acfg, symbol);
1362 /* The common code */
1363 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1364 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1366 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1368 /* The rgctx trampolines */
1369 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1370 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1371 emit_alignment (acfg, pagesize);
1372 emit_global (acfg, symbol, TRUE);
1373 emit_label (acfg, symbol);
1375 /* The common code */
1376 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1377 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1379 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1381 /* The gsharedvt arg trampolines */
1382 /* These are the same as the specific trampolines */
1383 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1384 emit_alignment (acfg, pagesize);
1385 emit_global (acfg, symbol, TRUE);
1386 emit_label (acfg, symbol);
1388 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1389 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1391 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1393 /* Unbox arbitrary trampolines */
1394 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
1395 emit_alignment (acfg, pagesize);
1396 emit_global (acfg, symbol, TRUE);
1397 emit_label (acfg, symbol);
1399 code = buf;
1400 imm = pagesize;
1402 /* Unbox this arg */
1403 arm_addx_imm (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
1405 /* The trampoline address is in IP0 */
1406 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1407 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1408 /* Compute the data slot address */
1409 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1410 /* Address */
1411 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1412 arm_brx (code, ARMREG_IP0);
1414 /* Emit it */
1415 emit_code_bytes (acfg, buf, code - buf);
1417 common_tramp_size = code - buf;
1418 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = common_tramp_size;
1420 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1422 /* The IMT trampolines */
1423 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1424 emit_alignment (acfg, pagesize);
1425 emit_global (acfg, symbol, TRUE);
1426 emit_label (acfg, symbol);
1428 code = buf;
1429 imm = pagesize;
1430 /* The trampoline address is in IP0 */
1431 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1432 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1433 /* Compute the data slot address */
1434 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1435 /* Trampoline argument */
1436 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1438 /* Same as arch_emit_imt_trampoline () */
1439 labels [0] = code;
1440 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1441 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1442 labels [1] = code;
1443 arm_bcc (code, ARMCOND_EQ, 0);
1445 /* End-of-loop check */
1446 labels [2] = code;
1447 arm_cbzx (code, ARMREG_IP0, 0);
1449 /* Loop footer */
1450 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1451 arm_b (code, labels [0]);
1453 /* Match */
1454 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1455 /* Load vtable slot addr */
1456 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1457 /* Load vtable slot */
1458 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1459 arm_brx (code, ARMREG_IP0);
1461 /* No match */
1462 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1463 /* Load fail addr */
1464 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1465 arm_brx (code, ARMREG_IP0);
1467 emit_code_bytes (acfg, buf, code - buf);
1469 common_tramp_size = code - buf;
1470 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1472 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1475 static void
1476 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1478 /* Load argument from second GOT slot */
1479 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1480 /* Load generic trampoline address from first GOT slot */
1481 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1482 fprintf (acfg->fp, "br x16\n");
1483 *tramp_size = 7 * 4;
1486 static void
1487 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1489 emit_unset_mode (acfg);
1490 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
1491 fprintf (acfg->fp, "b %s\n", call_target);
1494 static void
1495 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1497 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1499 /* Load argument from first GOT slot */
1500 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1501 /* Load generic trampoline address from second GOT slot */
1502 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1503 fprintf (acfg->fp, "br x16\n");
1504 *tramp_size = 7 * 4;
1507 static void
1508 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1510 guint8 buf [128];
1511 guint8 *code, *labels [16];
1513 /* Load parameter from GOT slot into ip1 */
1514 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1516 code = buf;
1517 labels [0] = code;
1518 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1519 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1520 labels [1] = code;
1521 arm_bcc (code, ARMCOND_EQ, 0);
1523 /* End-of-loop check */
1524 labels [2] = code;
1525 arm_cbzx (code, ARMREG_IP0, 0);
1527 /* Loop footer */
1528 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1529 arm_b (code, labels [0]);
1531 /* Match */
1532 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1533 /* Load vtable slot addr */
1534 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1535 /* Load vtable slot */
1536 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1537 arm_brx (code, ARMREG_IP0);
1539 /* No match */
1540 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1541 /* Load fail addr */
1542 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1543 arm_brx (code, ARMREG_IP0);
1545 emit_code_bytes (acfg, buf, code - buf);
1547 *tramp_size = code - buf + (3 * 4);
1550 static void
1551 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1553 /* Similar to the specific trampolines, but the address is in the second slot */
1554 /* Load argument from first GOT slot */
1555 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1556 /* Load generic trampoline address from second GOT slot */
1557 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1558 fprintf (acfg->fp, "br x16\n");
1559 *tramp_size = 7 * 4;
1563 #endif
1565 #ifdef MONO_ARCH_AOT_SUPPORTED
1567 * arch_emit_direct_call:
1569 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1570 * calling code.
1572 static void
1573 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1575 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1576 /* Need to make sure this is exactly 5 bytes long */
1577 emit_unset_mode (acfg);
1578 fprintf (acfg->fp, "call %s\n", target);
1579 *call_size = 5;
1580 #elif defined(TARGET_ARM)
1581 emit_unset_mode (acfg);
1582 if (thumb)
1583 fprintf (acfg->fp, "blx %s\n", target);
1584 else
1585 fprintf (acfg->fp, "bl %s\n", target);
1586 *call_size = 4;
1587 #elif defined(TARGET_ARM64)
1588 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1589 #elif defined(TARGET_POWERPC)
1590 emit_unset_mode (acfg);
1591 fprintf (acfg->fp, "bl %s\n", target);
1592 *call_size = 4;
1593 #else
1594 g_assert_not_reached ();
1595 #endif
1597 #endif
1600 * PPC32 design:
1601 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1602 * the GOT pointer.
1603 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1604 * in in the 2. slot of every GOT, and require every method to place the GOT
1605 * address in r30, even when it doesn't access the GOT otherwise. This way,
1606 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1610 * PPC64 design:
1611 * PPC64 uses function descriptors which greatly complicate all code, since
1612 * these are used very inconsistently in the runtime. Some functions like
1613 * mono_compile_method () return ftn descriptors, while others like the
1614 * trampoline creation functions do not.
1615 * We assume that all GOT slots contain function descriptors, and create
1616 * descriptors in aot-runtime.c when needed.
1617 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1618 * from function descriptors, we could do the same, but it would require
1619 * rewriting all the ppc/aot code to handle function descriptors properly.
1620 * So instead, we use the same approach as on PPC32.
1621 * This is a horrible mess, but fixing it would probably lead to an even bigger
1622 * one.
1626 * X86 design:
1627 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1630 #ifdef MONO_ARCH_AOT_SUPPORTED
1632 * arch_emit_got_offset:
1634 * The memory pointed to by CODE should hold native code for computing the GOT
1635 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1636 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1638 static void
1639 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1641 #if defined(TARGET_POWERPC64)
1642 emit_unset_mode (acfg);
1644 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1645 * unsupported relocations. So we store the got address into the .Lgot_addr
1646 * symbol which is in the text segment, compute its address, and load it.
1648 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1649 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1650 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1651 fprintf (acfg->fp, "add 30, 30, 0\n");
1652 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1653 acfg->label_generator ++;
1654 *code_size = 16;
1655 #elif defined(TARGET_POWERPC)
1656 emit_unset_mode (acfg);
1657 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1658 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1659 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1660 acfg->label_generator ++;
1661 *code_size = 8;
1662 #else
1663 guint32 offset = mono_arch_get_patch_offset (code);
1664 emit_bytes (acfg, code, offset);
1665 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1667 *code_size = offset + 4;
1668 #endif
1672 * arch_emit_got_access:
1674 * The memory pointed to by CODE should hold native code for loading a GOT
1675 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1676 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1678 static void
1679 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1681 #ifdef TARGET_AMD64
1682 /* mov reg, got+offset(%rip) */
1683 if (acfg->llvm) {
1684 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1685 int dreg;
1686 int rex_r;
1688 /* Decode reg, see amd64_mov_reg_membase () */
1689 rex_r = code [0] & AMD64_REX_R;
1690 g_assert (code [0] == 0x49 + rex_r);
1691 g_assert (code [1] == 0x8b);
1692 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1694 emit_unset_mode (acfg);
1695 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
1696 *code_size = 7;
1697 } else {
1698 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1699 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t)) - 4));
1700 *code_size = mono_arch_get_patch_offset (code) + 4;
1702 #elif defined(TARGET_X86)
1703 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1704 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (target_mgreg_t))));
1705 *code_size = mono_arch_get_patch_offset (code) + 4;
1706 #elif defined(TARGET_ARM)
1707 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1708 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t))) - 12);
1709 *code_size = mono_arch_get_patch_offset (code) + 4;
1710 #elif defined(TARGET_ARM64)
1711 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1712 arm64_emit_got_access (acfg, code, got_slot, code_size);
1713 #elif defined(TARGET_POWERPC)
1715 guint8 buf [32];
1717 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1718 code = buf;
1719 ppc_load32 (code, ppc_r0, got_slot * sizeof (target_mgreg_t));
1720 g_assert (code - buf == 8);
1721 emit_bytes (acfg, buf, code - buf);
1722 *code_size = code - buf;
1724 #else
1725 g_assert_not_reached ();
1726 #endif
1729 #endif
1731 #ifdef MONO_ARCH_AOT_SUPPORTED
1733 * arch_emit_objc_selector_ref:
1735 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1737 static void
1738 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1740 #if defined(TARGET_ARM)
1741 char symbol1 [MAX_SYMBOL_SIZE];
1742 char symbol2 [MAX_SYMBOL_SIZE];
1743 int lindex = acfg->objc_selector_index_2 ++;
1745 /* Emit ldr.imm/b */
1746 emit_bytes (acfg, code, 8);
1748 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1749 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1751 emit_label (acfg, symbol1);
1752 mono_img_writer_emit_unset_mode (acfg->w);
1753 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1755 *code_size = 12;
1756 #elif defined(TARGET_ARM64)
1757 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1758 #else
1759 g_assert_not_reached ();
1760 #endif
1762 #endif
1765 * arch_emit_plt_entry:
1767 * Emit code for the PLT entry.
1768 * The plt entry should look like this:
1769 * <indirect jump to GOT_SYMBOL + OFFSET>
1770 * <INFO_OFFSET embedded into the instruction stream>
1772 static void
1773 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1775 #if defined(TARGET_X86)
1776 /* jmp *<offset>(%ebx) */
1777 emit_byte (acfg, 0xff);
1778 emit_byte (acfg, 0xa3);
1779 emit_int32 (acfg, offset);
1780 /* Used by mono_aot_get_plt_info_offset */
1781 emit_int32 (acfg, info_offset);
1782 #elif defined(TARGET_AMD64)
1783 emit_unset_mode (acfg);
1784 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1785 /* Used by mono_aot_get_plt_info_offset */
1786 emit_int32 (acfg, info_offset);
1787 acfg->stats.plt_size += 10;
1788 #elif defined(TARGET_ARM)
1789 guint8 buf [256];
1790 guint8 *code;
1792 code = buf;
1793 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1794 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1795 emit_bytes (acfg, buf, code - buf);
1796 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1797 /* Used by mono_aot_get_plt_info_offset */
1798 emit_int32 (acfg, info_offset);
1799 #elif defined(TARGET_ARM64)
1800 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1801 #elif defined(TARGET_POWERPC)
1802 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1803 emit_unset_mode (acfg);
1804 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1805 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1806 fprintf (acfg->fp, "add 11, 11, 30\n");
1807 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1808 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1809 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
1810 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1811 #endif
1812 fprintf (acfg->fp, "mtctr 11\n");
1813 fprintf (acfg->fp, "bctr\n");
1814 emit_int32 (acfg, info_offset);
1815 #else
1816 g_assert_not_reached ();
1817 #endif
1821 * arch_emit_llvm_plt_entry:
1823 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1824 * This is only needed on arm to handle thumb interop.
1826 static void
1827 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1829 #if defined(TARGET_ARM)
1830 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1831 /* The caller already transitioned to thumb */
1832 /* The code below should be 12 bytes long */
1833 /* clang has trouble encoding these instructions, so emit the binary */
1834 #if 0
1835 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1836 /* thumb can't encode ld pc, [pc, ip] */
1837 fprintf (acfg->fp, "add ip, pc, ip\n");
1838 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1839 fprintf (acfg->fp, "bx ip\n");
1840 #endif
1841 emit_set_thumb_mode (acfg);
1842 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1843 fprintf (acfg->fp, ".2byte 0x44fc\n");
1844 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1845 fprintf (acfg->fp, ".2byte 0x4760\n");
1846 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1847 emit_int32 (acfg, info_offset);
1848 emit_unset_mode (acfg);
1849 emit_set_arm_mode (acfg);
1850 #else
1851 g_assert_not_reached ();
1852 #endif
1855 /* Save unwind_info in the module and emit the offset to the information at symbol */
1856 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1858 guint32 uw_offset, encoded_len;
1859 guint8 *encoded;
1861 emit_section_change (acfg, RODATA_SECT, 0);
1862 emit_global (acfg, symbol, FALSE);
1863 emit_label (acfg, symbol);
1865 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1866 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1867 g_free (encoded);
1868 emit_int32 (acfg, uw_offset);
1872 * arch_emit_specific_trampoline_pages:
1874 * Emits a page full of trampolines: each trampoline uses its own address to
1875 * lookup both the generic trampoline code and the data argument.
1876 * This page can be remapped in process multiple times so we can get an
1877 * unlimited number of trampolines.
1878 * Specifically this implementation uses the following trick: two memory pages
1879 * are allocated, with the first containing the data and the second containing the trampolines.
1880 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1881 * implementation does all the lifting.
1882 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1883 * on the arm 32 bit system.
1885 static void
1886 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1888 #if defined(TARGET_ARM)
1889 guint8 buf [128];
1890 guint8 *code;
1891 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1892 int i;
1893 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1894 GSList *unwind_ops = NULL;
1895 #define COMMON_TRAMP_SIZE 16
1896 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1897 int imm8, rot_amount;
1898 char symbol [128];
1900 if (!acfg->aot_opts.use_trampolines_page)
1901 return;
1903 acfg->tramp_page_size = pagesize;
1905 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1906 emit_alignment (acfg, pagesize);
1907 emit_global (acfg, symbol, TRUE);
1908 emit_label (acfg, symbol);
1910 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1911 code = buf;
1912 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1913 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1914 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1915 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1916 ARM_NOP (code);
1917 g_assert (code - buf == COMMON_TRAMP_SIZE);
1919 /* Emit it */
1920 emit_bytes (acfg, buf, code - buf);
1922 for (i = 0; i < count; ++i) {
1923 code = buf;
1924 ARM_PUSH (code, 0x5fff);
1925 ARM_BL (code, 0);
1926 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1927 g_assert (code - buf == 8);
1928 emit_bytes (acfg, buf, code - buf);
1931 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1932 * the instruction pointer address, so the generic trampoline at the start of the page
1933 * subtracts 4096 to get to the data page and loads the values
1934 * We again fit the generic trampiline in 16 bytes.
1936 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1937 emit_global (acfg, symbol, TRUE);
1938 emit_label (acfg, symbol);
1939 code = buf;
1940 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1941 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1942 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1943 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1944 ARM_NOP (code);
1945 g_assert (code - buf == COMMON_TRAMP_SIZE);
1947 /* Emit it */
1948 emit_bytes (acfg, buf, code - buf);
1950 for (i = 0; i < count; ++i) {
1951 code = buf;
1952 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1953 ARM_B (code, 0);
1954 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1955 g_assert (code - buf == 8);
1956 emit_bytes (acfg, buf, code - buf);
1960 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1962 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1963 emit_global (acfg, symbol, TRUE);
1964 emit_label (acfg, symbol);
1965 code = buf;
1966 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1967 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1968 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1969 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1970 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1971 g_assert (code - buf == COMMON_TRAMP_SIZE);
1972 /* Emit it */
1973 emit_bytes (acfg, buf, code - buf);
1975 for (i = 0; i < count; ++i) {
1976 code = buf;
1977 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1978 ARM_B (code, 0);
1979 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1980 g_assert (code - buf == 8);
1981 emit_bytes (acfg, buf, code - buf);
1984 /* now the unbox arbitrary trampolines: each specific trampolines puts in the ip register
1985 * the instruction pointer address, so the generic trampoline at the start of the page
1986 * subtracts 4096 to get to the data page and loads the target addr.
1987 * We again fit the generic trampoline in 16 bytes.
1989 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
1990 emit_global (acfg, symbol, TRUE);
1991 emit_label (acfg, symbol);
1992 code = buf;
1994 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
1995 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1996 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1997 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1998 ARM_NOP (code);
1999 g_assert (code - buf == COMMON_TRAMP_SIZE);
2001 /* Emit it */
2002 emit_bytes (acfg, buf, code - buf);
2004 for (i = 0; i < count; ++i) {
2005 code = buf;
2006 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
2007 ARM_B (code, 0);
2008 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
2009 g_assert (code - buf == 8);
2010 emit_bytes (acfg, buf, code - buf);
2013 /* now the imt trampolines: each specific trampolines puts in the ip register
2014 * the instruction pointer address, so the generic trampoline at the start of the page
2015 * subtracts 4096 to get to the data page and loads the values
2017 #define IMT_TRAMP_SIZE 72
2018 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
2019 emit_global (acfg, symbol, TRUE);
2020 emit_label (acfg, symbol);
2021 code = buf;
2022 /* Need at least two free registers, plus a slot for storing the pc */
2023 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2025 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
2026 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
2027 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
2029 /* The IMT method is in v5, r0 has the imt array address */
2031 loop_start = code;
2032 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2033 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2034 imt_found_check = code;
2035 ARM_B_COND (code, ARMCOND_EQ, 0);
2037 /* End-of-loop check */
2038 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2039 loop_end_check = code;
2040 ARM_B_COND (code, ARMCOND_EQ, 0);
2042 /* Loop footer */
2043 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2044 loop_branch_back = code;
2045 ARM_B (code, 0);
2046 arm_patch (loop_branch_back, loop_start);
2048 /* Match */
2049 arm_patch (imt_found_check, code);
2050 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2051 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2052 /* Save it to the third stack slot */
2053 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2054 /* Restore the registers and branch */
2055 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2057 /* No match */
2058 arm_patch (loop_end_check, code);
2059 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2060 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2061 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2062 ARM_NOP (code);
2064 /* Emit it */
2065 g_assert (code - buf == IMT_TRAMP_SIZE);
2066 emit_bytes (acfg, buf, code - buf);
2068 for (i = 0; i < count; ++i) {
2069 code = buf;
2070 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
2071 ARM_B (code, 0);
2072 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
2073 g_assert (code - buf == 8);
2074 emit_bytes (acfg, buf, code - buf);
2077 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
2078 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
2079 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
2080 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
2081 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = 16;
2083 /* Unwind info for specifc trampolines */
2084 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
2085 /* We unwind to the original caller, from the stack, since lr is clobbered */
2086 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (target_mgreg_t));
2087 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
2088 save_unwind_info (acfg, symbol, unwind_ops);
2089 mono_free_unwind_info (unwind_ops);
2091 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
2092 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2093 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (target_mgreg_t));
2094 save_unwind_info (acfg, symbol, unwind_ops);
2095 mono_free_unwind_info (unwind_ops);
2097 /* Unwind info for rgctx trampolines */
2098 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
2099 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2100 save_unwind_info (acfg, symbol, unwind_ops);
2102 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
2103 save_unwind_info (acfg, symbol, unwind_ops);
2104 mono_free_unwind_info (unwind_ops);
2106 /* Unwind info for gsharedvt trampolines */
2107 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2108 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2109 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (target_mgreg_t));
2110 save_unwind_info (acfg, symbol, unwind_ops);
2111 mono_free_unwind_info (unwind_ops);
2113 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2114 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2115 save_unwind_info (acfg, symbol, unwind_ops);
2116 mono_free_unwind_info (unwind_ops);
2118 /* Unwind info for unbox arbitrary trampolines */
2119 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_gen_p", acfg->user_symbol_prefix);
2120 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2121 save_unwind_info (acfg, symbol, unwind_ops);
2123 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_sp_p", acfg->user_symbol_prefix);
2124 save_unwind_info (acfg, symbol, unwind_ops);
2125 mono_free_unwind_info (unwind_ops);
2127 /* Unwind info for imt trampolines */
2128 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2129 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2130 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (target_mgreg_t));
2131 save_unwind_info (acfg, symbol, unwind_ops);
2132 mono_free_unwind_info (unwind_ops);
2134 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2135 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2136 save_unwind_info (acfg, symbol, unwind_ops);
2137 mono_free_unwind_info (unwind_ops);
2138 #elif defined(TARGET_ARM64)
2139 arm64_emit_specific_trampoline_pages (acfg);
2140 #endif
2144 * arch_emit_specific_trampoline:
2146 * Emit code for a specific trampoline. OFFSET is the offset of the first of
2147 * two GOT slots which contain the generic trampoline address and the trampoline
2148 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
2150 static void
2151 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2154 * The trampolines created here are variations of the specific
2155 * trampolines created in mono_arch_create_specific_trampoline (). The
2156 * differences are:
2157 * - the generic trampoline address is taken from a got slot.
2158 * - the offset of the got slot where the trampoline argument is stored
2159 * is embedded in the instruction stream, and the generic trampoline
2160 * can load the argument by loading the offset, adding it to the
2161 * address of the trampoline to get the address of the got slot, and
2162 * loading the argument from there.
2163 * - all the trampolines should be of the same length.
2165 #if defined(TARGET_AMD64)
2166 /* This should be exactly 8 bytes long */
2167 *tramp_size = 8;
2168 /* call *<offset>(%rip) */
2169 if (acfg->llvm) {
2170 emit_unset_mode (acfg);
2171 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2172 emit_zero_bytes (acfg, 2);
2173 } else {
2174 emit_byte (acfg, '\x41');
2175 emit_byte (acfg, '\xff');
2176 emit_byte (acfg, '\x15');
2177 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2178 emit_zero_bytes (acfg, 1);
2180 #elif defined(TARGET_ARM)
2181 guint8 buf [128];
2182 guint8 *code;
2184 /* This should be exactly 20 bytes long */
2185 *tramp_size = 20;
2186 code = buf;
2187 ARM_PUSH (code, 0x5fff);
2188 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
2189 /* Load the value from the GOT */
2190 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2191 /* Branch to it */
2192 ARM_BLX_REG (code, ARMREG_R1);
2194 g_assert (code - buf == 16);
2196 /* Emit it */
2197 emit_bytes (acfg, buf, code - buf);
2199 * Only one offset is needed, since the second one would be equal to the
2200 * first one.
2202 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 4);
2203 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 8);
2204 #elif defined(TARGET_ARM64)
2205 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
2206 #elif defined(TARGET_POWERPC)
2207 guint8 buf [128];
2208 guint8 *code;
2210 *tramp_size = 4;
2211 code = buf;
2214 * PPC has no ip relative addressing, so we need to compute the address
2215 * of the mscorlib got. That is slow and complex, so instead, we store it
2216 * in the second got slot of every aot image. The caller already computed
2217 * the address of its got and placed it into r30.
2219 emit_unset_mode (acfg);
2220 /* Load mscorlib got address */
2221 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2222 /* Load generic trampoline address */
2223 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2224 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2225 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2226 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2227 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2228 #endif
2229 fprintf (acfg->fp, "mtctr 11\n");
2230 /* Load trampoline argument */
2231 /* On ppc, we pass it normally to the generic trampoline */
2232 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2233 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2234 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2235 /* Branch to generic trampoline */
2236 fprintf (acfg->fp, "bctr\n");
2238 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2239 *tramp_size = 10 * 4;
2240 #else
2241 *tramp_size = 9 * 4;
2242 #endif
2243 #elif defined(TARGET_X86)
2244 guint8 buf [128];
2245 guint8 *code;
2247 /* Similar to the PPC code above */
2249 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2251 code = buf;
2252 /* Load mscorlib got address */
2253 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2254 /* Push trampoline argument */
2255 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2256 /* Load generic trampoline address */
2257 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2258 /* Branch to generic trampoline */
2259 x86_jump_reg (code, X86_ECX);
2261 emit_bytes (acfg, buf, code - buf);
2263 *tramp_size = 17;
2264 g_assert (code - buf == *tramp_size);
2265 #else
2266 g_assert_not_reached ();
2267 #endif
2271 * arch_emit_unbox_trampoline:
2273 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2274 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2276 * See mono_aot_get_unbox_trampoline.
2278 static void
2279 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2281 #if defined(TARGET_AMD64)
2282 guint8 buf [32];
2283 guint8 *code;
2284 int this_reg;
2286 this_reg = mono_arch_get_this_arg_reg (NULL);
2287 code = buf;
2288 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2290 emit_bytes (acfg, buf, code - buf);
2291 /* jump <method> */
2292 if (acfg->llvm) {
2293 emit_unset_mode (acfg);
2294 fprintf (acfg->fp, "jmp %s\n", call_target);
2295 } else {
2296 emit_byte (acfg, '\xe9');
2297 emit_symbol_diff (acfg, call_target, ".", -4);
2299 #elif defined(TARGET_X86)
2300 guint8 buf [32];
2301 guint8 *code;
2302 int this_pos = 4;
2304 code = buf;
2306 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, MONO_ABI_SIZEOF (MonoObject));
2308 emit_bytes (acfg, buf, code - buf);
2310 /* jump <method> */
2311 emit_byte (acfg, '\xe9');
2312 emit_symbol_diff (acfg, call_target, ".", -4);
2313 #elif defined(TARGET_ARM)
2314 guint8 buf [128];
2315 guint8 *code;
2317 if (acfg->thumb_mixed && cfg->compile_llvm) {
2318 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)MONO_ABI_SIZEOF (MonoObject));
2319 fprintf (acfg->fp, "b %s\n", call_target);
2320 fprintf (acfg->fp, ".arm\n");
2321 fprintf (acfg->fp, ".align 2\n");
2322 return;
2325 code = buf;
2327 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2329 emit_bytes (acfg, buf, code - buf);
2330 /* jump to method */
2331 if (acfg->thumb_mixed && cfg->compile_llvm)
2332 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2333 else
2334 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2335 #elif defined(TARGET_ARM64)
2336 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2337 #elif defined(TARGET_POWERPC)
2338 int this_pos = 3;
2340 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)MONO_ABI_SIZEOF (MonoObject));
2341 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2342 #else
2343 g_assert_not_reached ();
2344 #endif
2348 * arch_emit_static_rgctx_trampoline:
2350 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2351 * two GOT slots which contain the rgctx argument, and the method to jump to.
2352 * TRAMP_SIZE is set to the size of the emitted trampoline.
2353 * These kinds of trampolines cannot be enumerated statically, since there could
2354 * be one trampoline per method instantiation, so we emit the same code for all
2355 * trampolines, and parameterize them using two GOT slots.
2357 static void
2358 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2360 #if defined(TARGET_AMD64)
2361 /* This should be exactly 13 bytes long */
2362 *tramp_size = 13;
2364 if (acfg->llvm) {
2365 emit_unset_mode (acfg);
2366 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2367 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (target_mgreg_t)));
2368 } else {
2369 /* mov <OFFSET>(%rip), %r10 */
2370 emit_byte (acfg, '\x4d');
2371 emit_byte (acfg, '\x8b');
2372 emit_byte (acfg, '\x15');
2373 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2375 /* jmp *<offset>(%rip) */
2376 emit_byte (acfg, '\xff');
2377 emit_byte (acfg, '\x25');
2378 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4);
2380 #elif defined(TARGET_ARM)
2381 guint8 buf [128];
2382 guint8 *code;
2384 /* This should be exactly 24 bytes long */
2385 *tramp_size = 24;
2386 code = buf;
2387 /* Load rgctx value */
2388 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2389 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2390 /* Load branch addr + branch */
2391 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2392 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2394 g_assert (code - buf == 16);
2396 /* Emit it */
2397 emit_bytes (acfg, buf, code - buf);
2398 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 8);
2399 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 4);
2400 #elif defined(TARGET_ARM64)
2401 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2402 #elif defined(TARGET_POWERPC)
2403 guint8 buf [128];
2404 guint8 *code;
2406 *tramp_size = 4;
2407 code = buf;
2410 * PPC has no ip relative addressing, so we need to compute the address
2411 * of the mscorlib got. That is slow and complex, so instead, we store it
2412 * in the second got slot of every aot image. The caller already computed
2413 * the address of its got and placed it into r30.
2415 emit_unset_mode (acfg);
2416 /* Load mscorlib got address */
2417 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2418 /* Load rgctx */
2419 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2420 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2421 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2422 /* Load target address */
2423 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2424 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2425 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2426 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2427 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2428 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2429 #endif
2430 fprintf (acfg->fp, "mtctr 11\n");
2431 /* Branch to the target address */
2432 fprintf (acfg->fp, "bctr\n");
2434 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2435 *tramp_size = 11 * 4;
2436 #else
2437 *tramp_size = 9 * 4;
2438 #endif
2440 #elif defined(TARGET_X86)
2441 guint8 buf [128];
2442 guint8 *code;
2444 /* Similar to the PPC code above */
2446 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2448 code = buf;
2449 /* Load mscorlib got address */
2450 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2451 /* Load arg */
2452 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2453 /* Branch to the target address */
2454 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2456 emit_bytes (acfg, buf, code - buf);
2458 *tramp_size = 15;
2459 g_assert (code - buf == *tramp_size);
2460 #else
2461 g_assert_not_reached ();
2462 #endif
2466 * arch_emit_imt_trampoline:
2468 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2469 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2470 * key is the IMT key, and ptr holds the address of a memory location holding
2471 * the address to branch to if the IMT arg matches the key. The array is
2472 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2473 * fail_tramp.
2474 * TRAMP_SIZE is set to the size of the emitted trampoline.
2476 static void
2477 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2479 #if defined(TARGET_AMD64)
2480 guint8 *buf, *code;
2481 guint8 *labels [16];
2482 guint8 mov_buf[3];
2483 guint8 *mov_buf_ptr = mov_buf;
2485 const int kSizeOfMove = 7;
2487 code = buf = (guint8 *)g_malloc (256);
2489 /* FIXME: Optimize this, i.e. use binary search etc. */
2490 /* Maybe move the body into a separate function (slower, but much smaller) */
2492 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2494 if (acfg->llvm) {
2495 emit_unset_mode (acfg);
2496 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));
2499 labels [0] = code;
2500 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2501 labels [1] = code;
2502 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2504 /* Check key */
2505 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (target_mgreg_t));
2506 labels [2] = code;
2507 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2509 /* Loop footer */
2510 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (target_mgreg_t));
2511 amd64_jump_code (code, labels [0]);
2513 /* Match */
2514 mono_amd64_patch (labels [2], code);
2515 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t), sizeof (target_mgreg_t));
2516 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2518 /* No match */
2519 mono_amd64_patch (labels [1], code);
2520 /* Load fail tramp */
2521 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t));
2522 /* Check if there is a fail tramp */
2523 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2524 labels [3] = code;
2525 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2526 /* Jump to fail tramp */
2527 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2529 /* Fail */
2530 mono_amd64_patch (labels [3], code);
2531 x86_breakpoint (code);
2533 if (!acfg->llvm) {
2534 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2535 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2536 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2537 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2538 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2539 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2541 emit_bytes (acfg, buf, code - buf);
2543 *tramp_size = code - buf + kSizeOfMove;
2545 g_free (buf);
2547 #elif defined(TARGET_X86)
2548 guint8 *buf, *code;
2549 guint8 *labels [16];
2551 code = buf = g_malloc (256);
2553 /* Allocate a temporary stack slot */
2554 x86_push_reg (code, X86_EAX);
2555 /* Save EAX */
2556 x86_push_reg (code, X86_EAX);
2558 /* Load mscorlib got address */
2559 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2560 /* Load arg */
2561 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (target_mgreg_t), 4);
2563 labels [0] = code;
2564 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2565 labels [1] = code;
2566 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2568 /* Check key */
2569 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2570 labels [2] = code;
2571 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2573 /* Loop footer */
2574 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (target_mgreg_t));
2575 x86_jump_code (code, labels [0]);
2577 /* Match */
2578 mono_x86_patch (labels [2], code);
2579 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2580 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2581 /* Save the target address to the temporary stack location */
2582 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2583 /* Restore EAX */
2584 x86_pop_reg (code, X86_EAX);
2585 /* Jump to the target address */
2586 x86_ret (code);
2588 /* No match */
2589 mono_x86_patch (labels [1], code);
2590 /* Load fail tramp */
2591 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2592 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2593 labels [3] = code;
2594 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2595 /* Jump to fail tramp */
2596 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2597 x86_pop_reg (code, X86_EAX);
2598 x86_ret (code);
2600 /* Fail */
2601 mono_x86_patch (labels [3], code);
2602 x86_breakpoint (code);
2604 emit_bytes (acfg, buf, code - buf);
2606 *tramp_size = code - buf;
2608 g_free (buf);
2610 #elif defined(TARGET_ARM)
2611 guint8 buf [128];
2612 guint8 *code, *code2, *labels [16];
2614 code = buf;
2616 /* The IMT method is in v5 */
2618 /* Need at least two free registers, plus a slot for storing the pc */
2619 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2620 labels [0] = code;
2621 /* Load the parameter from the GOT */
2622 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2623 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2625 labels [1] = code;
2626 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2627 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2628 labels [2] = code;
2629 ARM_B_COND (code, ARMCOND_EQ, 0);
2631 /* End-of-loop check */
2632 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2633 labels [3] = code;
2634 ARM_B_COND (code, ARMCOND_EQ, 0);
2636 /* Loop footer */
2637 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2638 labels [4] = code;
2639 ARM_B (code, 0);
2640 arm_patch (labels [4], labels [1]);
2642 /* Match */
2643 arm_patch (labels [2], code);
2644 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2645 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2646 /* Save it to the third stack slot */
2647 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2648 /* Restore the registers and branch */
2649 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2651 /* No match */
2652 arm_patch (labels [3], code);
2653 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2654 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2655 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2657 /* Fixup offset */
2658 code2 = labels [0];
2659 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2661 emit_bytes (acfg, buf, code - buf);
2662 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (labels [0] + 8)) - 4);
2664 *tramp_size = code - buf + 4;
2665 #elif defined(TARGET_ARM64)
2666 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2667 #elif defined(TARGET_POWERPC)
2668 guint8 buf [128];
2669 guint8 *code, *labels [16];
2671 code = buf;
2673 /* Load the mscorlib got address */
2674 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r30);
2675 /* Load the parameter from the GOT */
2676 ppc_load (code, ppc_r0, offset * sizeof (target_mgreg_t));
2677 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2679 /* Load and check key */
2680 labels [1] = code;
2681 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2682 ppc_cmp (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2683 labels [2] = code;
2684 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2686 /* End-of-loop check */
2687 ppc_cmpi (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, 0);
2688 labels [3] = code;
2689 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2691 /* Loop footer */
2692 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (target_mgreg_t));
2693 labels [4] = code;
2694 ppc_b (code, 0);
2695 mono_ppc_patch (labels [4], labels [1]);
2697 /* Match */
2698 mono_ppc_patch (labels [2], code);
2699 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r12);
2700 /* r12 now contains the value of the vtable slot */
2701 /* this is not a function descriptor on ppc64 */
2702 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2703 ppc_mtctr (code, ppc_r12);
2704 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2706 /* Fail */
2707 mono_ppc_patch (labels [3], code);
2708 /* FIXME: */
2709 ppc_break (code);
2711 *tramp_size = code - buf;
2713 emit_bytes (acfg, buf, code - buf);
2714 #else
2715 g_assert_not_reached ();
2716 #endif
2720 #if defined (TARGET_AMD64)
2722 static void
2723 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2726 g_assert (acfg->fp);
2727 emit_unset_mode (acfg);
2729 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
2732 #endif
2736 * arch_emit_gsharedvt_arg_trampoline:
2738 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2739 * two GOT slots which contain the argument, and the code to jump to.
2740 * TRAMP_SIZE is set to the size of the emitted trampoline.
2741 * These kinds of trampolines cannot be enumerated statically, since there could
2742 * be one trampoline per method instantiation, so we emit the same code for all
2743 * trampolines, and parameterize them using two GOT slots.
2745 static void
2746 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2748 #if defined(TARGET_X86)
2749 guint8 buf [128];
2750 guint8 *code;
2752 /* Similar to the PPC code above */
2754 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2756 code = buf;
2757 /* Load mscorlib got address */
2758 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2759 /* Load arg */
2760 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2761 /* Branch to the target address */
2762 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2764 emit_bytes (acfg, buf, code - buf);
2766 *tramp_size = 15;
2767 g_assert (code - buf == *tramp_size);
2768 #elif defined(TARGET_ARM)
2769 guint8 buf [128];
2770 guint8 *code;
2772 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2773 /* Similar to arch_emit_specific_trampoline () */
2774 *tramp_size = 24;
2775 code = buf;
2776 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2777 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2778 /* Load the arg value from the GOT */
2779 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2780 /* Load the addr from the GOT */
2781 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2782 /* Branch to it */
2783 ARM_BX (code, ARMREG_R1);
2785 g_assert (code - buf == 20);
2787 /* Emit it */
2788 emit_bytes (acfg, buf, code - buf);
2789 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4);
2790 #elif defined(TARGET_ARM64)
2791 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2792 #elif defined (TARGET_AMD64)
2794 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2795 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2796 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2797 fprintf (acfg->fp, "jmp *%%r11\n");
2799 *tramp_size = 0x11;
2800 #else
2801 g_assert_not_reached ();
2802 #endif
2805 static void
2806 arch_emit_ftnptr_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2808 #if defined(TARGET_ARM)
2809 guint8 buf [128];
2810 guint8 *code;
2812 *tramp_size = 32;
2813 code = buf;
2815 /* Load target address and push it on stack */
2816 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 16);
2817 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2818 ARM_PUSH (code, 1 << ARMREG_IP);
2819 /* Load argument in ARMREG_IP */
2820 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2821 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2822 /* Branch */
2823 ARM_POP (code, 1 << ARMREG_PC);
2825 g_assert (code - buf == 24);
2827 /* Emit it */
2828 emit_bytes (acfg, buf, code - buf);
2829 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) + 12); // offset from ldr pc to addr
2830 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4); // offset from ldr pc to arg
2831 #else
2832 g_assert_not_reached ();
2833 #endif
2836 static void
2837 arch_emit_unbox_arbitrary_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2839 #if defined(TARGET_ARM64)
2840 emit_unset_mode (acfg);
2841 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
2842 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
2843 fprintf (acfg->fp, "br x17\n");
2844 *tramp_size = 5 * 4;
2845 #elif defined (TARGET_AMD64)
2846 guint8 buf [32];
2847 guint8 *code;
2848 int this_reg;
2850 this_reg = mono_arch_get_this_arg_reg (NULL);
2851 code = buf;
2852 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2853 emit_bytes (acfg, buf, code - buf);
2855 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2856 fprintf (acfg->fp, "jmp *%%rax\n");
2858 *tramp_size = 13;
2859 #elif defined (TARGET_ARM)
2860 guint8 buf [32];
2861 guint8 *code, *label;
2863 code = buf;
2864 /* Unbox */
2865 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2867 label = code;
2868 /* Calculate GOT slot */
2869 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
2870 /* Load target addr into PC*/
2871 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2873 g_assert (code - buf == 12);
2875 /* Emit it */
2876 emit_bytes (acfg, buf, code - buf);
2877 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (label + 8)) - 4);
2878 *tramp_size = 4 * 4;
2879 #else
2880 g_error ("NOT IMPLEMENTED: needed for AOT<>interp mixed mode transition");
2881 #endif
2884 /* END OF ARCH SPECIFIC CODE */
2886 static guint32
2887 mono_get_field_token (MonoClassField *field)
2889 MonoClass *klass = field->parent;
2890 int i;
2892 int fcount = mono_class_get_field_count (klass);
2893 MonoClassField *klass_fields = m_class_get_fields (klass);
2894 for (i = 0; i < fcount; ++i) {
2895 if (field == &klass_fields [i])
2896 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2899 g_assert_not_reached ();
2900 return 0;
2903 static inline void
2904 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2906 guint8 *p = buf;
2908 //printf ("ENCODE: %d 0x%x.\n", value, value);
2911 * Same encoding as the one used in the metadata, extended to handle values
2912 * greater than 0x1fffffff.
2914 if ((value >= 0) && (value <= 127))
2915 *p++ = value;
2916 else if ((value >= 0) && (value <= 16383)) {
2917 p [0] = 0x80 | (value >> 8);
2918 p [1] = value & 0xff;
2919 p += 2;
2920 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2921 p [0] = (value >> 24) | 0xc0;
2922 p [1] = (value >> 16) & 0xff;
2923 p [2] = (value >> 8) & 0xff;
2924 p [3] = value & 0xff;
2925 p += 4;
2927 else {
2928 p [0] = 0xff;
2929 p [1] = (value >> 24) & 0xff;
2930 p [2] = (value >> 16) & 0xff;
2931 p [3] = (value >> 8) & 0xff;
2932 p [4] = value & 0xff;
2933 p += 5;
2935 if (endbuf)
2936 *endbuf = p;
2939 static void
2940 stream_init (MonoDynamicStream *sh)
2942 sh->index = 0;
2943 sh->alloc_size = 4096;
2944 sh->data = (char *)g_malloc (4096);
2946 /* So offsets are > 0 */
2947 sh->data [0] = 0;
2948 sh->index ++;
2951 static void
2952 make_room_in_stream (MonoDynamicStream *stream, int size)
2954 if (size <= stream->alloc_size)
2955 return;
2957 while (stream->alloc_size <= size) {
2958 if (stream->alloc_size < 4096)
2959 stream->alloc_size = 4096;
2960 else
2961 stream->alloc_size *= 2;
2964 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2967 static guint32
2968 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2970 guint32 idx;
2972 make_room_in_stream (stream, stream->index + len);
2973 memcpy (stream->data + stream->index, data, len);
2974 idx = stream->index;
2975 stream->index += len;
2976 return idx;
2980 * add_to_blob:
2982 * Add data to the binary blob inside the aot image. Returns the offset inside the
2983 * blob where the data was stored.
2985 static guint32
2986 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2988 g_assert (!acfg->blob_closed);
2990 if (acfg->blob.alloc_size == 0)
2991 stream_init (&acfg->blob);
2993 acfg->stats.blob_size += data_len;
2995 return add_stream_data (&acfg->blob, (char*)data, data_len);
2998 static guint32
2999 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
3001 char buf [4] = {0};
3002 guint32 count;
3004 if (acfg->blob.alloc_size == 0)
3005 stream_init (&acfg->blob);
3007 count = acfg->blob.index % align;
3009 /* we assume the stream data will be aligned */
3010 if (count)
3011 add_stream_data (&acfg->blob, buf, 4 - count);
3013 return add_stream_data (&acfg->blob, (char*)data, data_len);
3016 /* Emit a table of data into the aot image */
3017 static void
3018 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
3020 if (acfg->data_outfile) {
3021 acfg->table_offsets [(int)table] = acfg->datafile_offset;
3022 fwrite (data,1, size, acfg->data_outfile);
3023 acfg->datafile_offset += size;
3024 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
3025 int align = 8 - size % 8;
3026 acfg->datafile_offset += align;
3027 guint8 align_buf [16];
3028 memset (&align_buf, 0, sizeof (align_buf));
3029 fwrite (align_buf, align, 1, acfg->data_outfile);
3030 } else if (acfg->llvm) {
3031 mono_llvm_emit_aot_data (symbol, data, size);
3032 } else {
3033 emit_section_change (acfg, RODATA_SECT, 0);
3034 emit_alignment (acfg, 8);
3035 emit_label (acfg, symbol);
3036 emit_bytes (acfg, data, size);
3041 * emit_offset_table:
3043 * Emit a table of increasing offsets in a compact form using differential encoding.
3044 * There is an index entry for each GROUP_SIZE number of entries. The greater the
3045 * group size, the more compact the table becomes, but the slower it becomes to compute
3046 * a given entry. Returns the size of the table.
3048 static guint32
3049 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
3051 gint32 current_offset;
3052 int i, buf_size, ngroups, index_entry_size;
3053 guint8 *p, *buf;
3054 guint8 *data_p, *data_buf;
3055 guint32 *index_offsets;
3057 ngroups = (noffsets + (group_size - 1)) / group_size;
3059 index_offsets = g_new0 (guint32, ngroups);
3061 buf_size = noffsets * 4;
3062 p = buf = (guint8 *)g_malloc0 (buf_size);
3064 current_offset = 0;
3065 for (i = 0; i < noffsets; ++i) {
3066 //printf ("D: %d -> %d\n", i, offsets [i]);
3067 if ((i % group_size) == 0) {
3068 index_offsets [i / group_size] = p - buf;
3069 /* Emit the full value for these entries */
3070 encode_value (offsets [i], p, &p);
3071 } else {
3072 /* The offsets are allowed to be non-increasing */
3073 //g_assert (offsets [i] >= current_offset);
3074 encode_value (offsets [i] - current_offset, p, &p);
3076 current_offset = offsets [i];
3078 data_buf = buf;
3079 data_p = p;
3081 if (ngroups && index_offsets [ngroups - 1] < 65000)
3082 index_entry_size = 2;
3083 else
3084 index_entry_size = 4;
3086 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
3087 p = buf = (guint8 *)g_malloc0 (buf_size);
3089 /* Emit the header */
3090 encode_int (noffsets, p, &p);
3091 encode_int (group_size, p, &p);
3092 encode_int (ngroups, p, &p);
3093 encode_int (index_entry_size, p, &p);
3095 /* Emit the index */
3096 for (i = 0; i < ngroups; ++i) {
3097 if (index_entry_size == 2)
3098 encode_int16 (index_offsets [i], p, &p);
3099 else
3100 encode_int (index_offsets [i], p, &p);
3102 /* Emit the data */
3103 memcpy (p, data_buf, data_p - data_buf);
3104 p += data_p - data_buf;
3106 g_assert (p - buf <= buf_size);
3108 emit_aot_data (acfg, table, symbol, buf, p - buf);
3110 g_free (buf);
3111 g_free (data_buf);
3113 return (int)(p - buf);
3116 static guint32
3117 get_image_index (MonoAotCompile *cfg, MonoImage *image)
3119 guint32 index;
3121 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
3122 if (index)
3123 return index - 1;
3124 else {
3125 index = g_hash_table_size (cfg->image_hash);
3126 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
3127 g_ptr_array_add (cfg->image_table, image);
3128 return index;
3132 static guint32
3133 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
3135 int i;
3136 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
3138 /* FIXME: Search referenced images as well */
3139 if (!acfg->typespec_classes) {
3140 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
3141 for (i = 0; i < len; i++) {
3142 ERROR_DECL (error);
3143 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
3144 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
3145 if (!is_ok (error)) {
3146 mono_error_cleanup (error);
3147 continue;
3149 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
3152 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
3155 static void
3156 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
3158 static void
3159 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
3161 static void
3162 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
3164 static void
3165 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
3167 static guint32
3168 get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst);
3170 static void
3171 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3173 guint8 *p = buf;
3176 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
3177 * information.
3180 if (mono_class_is_ginst (klass)) {
3181 guint32 token;
3182 g_assert (m_class_get_type_token (klass));
3184 /* Find a typespec for a class if possible */
3185 token = find_typespec_for_class (acfg, klass);
3186 if (token) {
3187 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
3188 encode_value (token, p, &p);
3189 } else {
3190 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
3191 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
3192 static int count = 0;
3193 guint8 *p1 = p;
3195 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
3196 encode_klass_ref (acfg, gclass, p, &p);
3197 guint32 offset = get_shared_ginst_ref (acfg, inst);
3198 encode_value (offset, p, &p);
3200 count += p - p1;
3202 } else if (m_class_get_type_token (klass)) {
3203 int iindex = get_image_index (acfg, m_class_get_image (klass));
3205 g_assert (mono_metadata_token_code (m_class_get_type_token (klass)) == MONO_TOKEN_TYPE_DEF);
3206 if (iindex == 0) {
3207 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
3208 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3209 } else {
3210 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
3211 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3212 encode_value (get_image_index (acfg, m_class_get_image (klass)), p, &p);
3214 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3215 MonoGenericContainer *container = mono_type_get_generic_param_owner (m_class_get_byval_arg (klass));
3216 MonoGenericParam *par = m_class_get_byval_arg (klass)->data.generic_param;
3218 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
3220 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
3221 if (par->gshared_constraint) {
3222 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
3223 encode_type (acfg, par->gshared_constraint, p, &p);
3224 encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
3225 } else {
3226 encode_value (m_class_get_byval_arg (klass)->type, p, &p);
3227 encode_value (mono_type_get_generic_param_num (m_class_get_byval_arg (klass)), p, &p);
3229 encode_value (container->is_anonymous ? 0 : 1, p, &p);
3231 if (!container->is_anonymous) {
3232 encode_value (container->is_method, p, &p);
3233 if (container->is_method)
3234 encode_method_ref (acfg, container->owner.method, p, &p);
3235 else
3236 encode_klass_ref (acfg, container->owner.klass, p, &p);
3239 } else if (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR) {
3240 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
3241 encode_type (acfg, m_class_get_byval_arg (klass), p, &p);
3242 } else {
3243 /* Array class */
3244 g_assert (m_class_get_rank (klass) > 0);
3245 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
3246 encode_value (m_class_get_rank (klass), p, &p);
3247 encode_klass_ref (acfg, m_class_get_element_class (klass), p, &p);
3250 acfg->stats.class_ref_count++;
3251 acfg->stats.class_ref_size += p - buf;
3253 *endbuf = p;
3256 static guint32
3257 get_shared_klass_ref (MonoAotCompile *acfg, MonoClass *klass)
3259 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
3260 guint8 *buf2, *p;
3262 if (!offset) {
3263 buf2 = (guint8 *)g_malloc (1024);
3264 p = buf2;
3266 encode_klass_ref_inner (acfg, klass, p, &p);
3267 g_assert (p - buf2 < 1024);
3269 offset = add_to_blob (acfg, buf2, p - buf2);
3270 g_free (buf2);
3272 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
3273 } else {
3274 offset --;
3277 return offset;
3281 * encode_klass_ref:
3283 * Encode a reference to KLASS. We use our home-grown encoding instead of the
3284 * standard metadata encoding.
3286 static void
3287 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3289 gboolean shared = FALSE;
3292 * The encoding of generic instances is large so emit them only once.
3294 if (mono_class_is_ginst (klass)) {
3295 guint32 token;
3296 g_assert (m_class_get_type_token (klass));
3298 /* Find a typespec for a class if possible */
3299 token = find_typespec_for_class (acfg, klass);
3300 if (!token)
3301 shared = TRUE;
3302 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3303 shared = TRUE;
3306 if (shared) {
3307 guint8 *p;
3308 guint32 offset = get_shared_klass_ref (acfg, klass);
3310 p = buf;
3311 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
3312 encode_value (offset, p, &p);
3313 *endbuf = p;
3314 return;
3317 encode_klass_ref_inner (acfg, klass, buf, endbuf);
3320 static void
3321 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
3323 guint32 token = mono_get_field_token (field);
3324 guint8 *p = buf;
3326 encode_klass_ref (cfg, field->parent, p, &p);
3327 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
3328 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
3329 *endbuf = p;
3332 static void
3333 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3335 guint8 *p = buf;
3336 int i;
3338 encode_value (inst->type_argc, p, &p);
3339 for (i = 0; i < inst->type_argc; ++i)
3340 encode_klass_ref (acfg, mono_class_from_mono_type_internal (inst->type_argv [i]), p, &p);
3342 acfg->stats.ginst_count++;
3343 acfg->stats.ginst_size += p - buf;
3345 *endbuf = p;
3348 static guint32
3349 get_shared_ginst_ref (MonoAotCompile *acfg, MonoGenericInst *ginst)
3351 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->ginst_blob_hash, ginst));
3352 if (!offset) {
3353 guint8 *buf2, *p2;
3355 buf2 = (guint8 *)g_malloc (1024);
3356 p2 = buf2;
3358 encode_ginst (acfg, ginst, p2, &p2);
3359 g_assert (p2 - buf2 < 1024);
3361 offset = add_to_blob (acfg, buf2, p2 - buf2);
3362 g_free (buf2);
3364 g_hash_table_insert (acfg->ginst_blob_hash, ginst, GUINT_TO_POINTER (offset + 1));
3365 } else {
3366 offset --;
3368 return offset;
3371 static void
3372 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3374 guint8 *p = buf;
3375 MonoGenericInst *inst;
3376 guint32 flags = (context->class_inst ? 1 : 0) | (context->method_inst ? 2 : 0);
3378 g_assert (flags);
3380 encode_value (flags, p, &p);
3381 inst = context->class_inst;
3382 if (inst) {
3383 guint32 offset = get_shared_ginst_ref (acfg, inst);
3384 encode_value (offset, p, &p);
3386 inst = context->method_inst;
3387 if (inst) {
3388 guint32 offset = get_shared_ginst_ref (acfg, inst);
3389 encode_value (offset, p, &p);
3391 *endbuf = p;
3394 static void
3395 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3397 guint8 *p = buf;
3399 if (t->has_cmods) {
3400 int count = mono_type_custom_modifier_count (t);
3402 *p = MONO_TYPE_CMOD_REQD;
3403 ++p;
3405 encode_value (count, p, &p);
3406 for (int i = 0; i < count; ++i) {
3407 ERROR_DECL (error);
3408 gboolean required;
3409 MonoType *cmod_type = mono_type_get_custom_modifier (t, i, &required, error);
3410 mono_error_assert_ok (error);
3411 encode_value (required, p, &p);
3412 encode_type (acfg, cmod_type, p, &p);
3416 /* t->attrs can be ignored */
3417 //g_assert (t->attrs == 0);
3419 if (t->pinned) {
3420 *p = MONO_TYPE_PINNED;
3421 ++p;
3423 if (t->byref) {
3424 *p = MONO_TYPE_BYREF;
3425 ++p;
3428 *p = t->type;
3429 p ++;
3431 switch (t->type) {
3432 case MONO_TYPE_VOID:
3433 case MONO_TYPE_BOOLEAN:
3434 case MONO_TYPE_CHAR:
3435 case MONO_TYPE_I1:
3436 case MONO_TYPE_U1:
3437 case MONO_TYPE_I2:
3438 case MONO_TYPE_U2:
3439 case MONO_TYPE_I4:
3440 case MONO_TYPE_U4:
3441 case MONO_TYPE_I8:
3442 case MONO_TYPE_U8:
3443 case MONO_TYPE_R4:
3444 case MONO_TYPE_R8:
3445 case MONO_TYPE_I:
3446 case MONO_TYPE_U:
3447 case MONO_TYPE_STRING:
3448 case MONO_TYPE_OBJECT:
3449 case MONO_TYPE_TYPEDBYREF:
3450 break;
3451 case MONO_TYPE_VALUETYPE:
3452 case MONO_TYPE_CLASS:
3453 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3454 break;
3455 case MONO_TYPE_SZARRAY:
3456 encode_klass_ref (acfg, t->data.klass, p, &p);
3457 break;
3458 case MONO_TYPE_PTR:
3459 encode_type (acfg, t->data.type, p, &p);
3460 break;
3461 case MONO_TYPE_GENERICINST: {
3462 MonoClass *gclass = t->data.generic_class->container_class;
3463 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3465 encode_klass_ref (acfg, gclass, p, &p);
3466 encode_ginst (acfg, inst, p, &p);
3467 break;
3469 case MONO_TYPE_ARRAY: {
3470 MonoArrayType *array = t->data.array;
3471 int i;
3473 encode_klass_ref (acfg, array->eklass, p, &p);
3474 encode_value (array->rank, p, &p);
3475 encode_value (array->numsizes, p, &p);
3476 for (i = 0; i < array->numsizes; ++i)
3477 encode_value (array->sizes [i], p, &p);
3478 encode_value (array->numlobounds, p, &p);
3479 for (i = 0; i < array->numlobounds; ++i)
3480 encode_value (array->lobounds [i], p, &p);
3481 break;
3483 case MONO_TYPE_VAR:
3484 case MONO_TYPE_MVAR:
3485 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3486 break;
3487 default:
3488 g_assert_not_reached ();
3491 *endbuf = p;
3494 static void
3495 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3497 guint8 *p = buf;
3498 guint32 flags = 0;
3499 int i;
3501 /* Similar to the metadata encoding */
3502 if (sig->generic_param_count)
3503 flags |= 0x10;
3504 if (sig->hasthis)
3505 flags |= 0x20;
3506 if (sig->explicit_this)
3507 flags |= 0x40;
3508 flags |= (sig->call_convention & 0x0F);
3510 *p = flags;
3511 ++p;
3512 if (sig->generic_param_count)
3513 encode_value (sig->generic_param_count, p, &p);
3514 encode_value (sig->param_count, p, &p);
3516 encode_type (acfg, sig->ret, p, &p);
3517 for (i = 0; i < sig->param_count; ++i) {
3518 if (sig->sentinelpos == i) {
3519 *p = MONO_TYPE_SENTINEL;
3520 ++p;
3522 encode_type (acfg, sig->params [i], p, &p);
3525 *endbuf = p;
3528 #define MAX_IMAGE_INDEX 250
3530 static void
3531 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3533 guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3534 guint32 token = method->token;
3535 MonoJumpInfoToken *ji;
3536 guint8 *p = buf;
3539 * The encoding for most methods is as follows:
3540 * - image index encoded as a leb128
3541 * - token index encoded as a leb128
3542 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3543 * types of method encodings.
3546 /* Mark methods which can't use aot trampolines because they need the further
3547 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3549 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3550 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3551 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3553 if (method->wrapper_type) {
3554 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3556 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3558 encode_value (method->wrapper_type, p, &p);
3560 switch (method->wrapper_type) {
3561 case MONO_WRAPPER_REMOTING_INVOKE:
3562 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3563 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3564 MonoMethod *m;
3566 m = mono_marshal_method_from_wrapper (method);
3567 g_assert (m);
3568 encode_method_ref (acfg, m, p, &p);
3569 break;
3571 case MONO_WRAPPER_PROXY_ISINST:
3572 case MONO_WRAPPER_LDFLD:
3573 case MONO_WRAPPER_LDFLDA:
3574 case MONO_WRAPPER_STFLD: {
3575 g_assert (info);
3576 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3577 break;
3579 case MONO_WRAPPER_ALLOC: {
3580 /* The GC name is saved once in MonoAotFileInfo */
3581 g_assert (info->d.alloc.alloc_type != -1);
3582 encode_value (info->d.alloc.alloc_type, p, &p);
3583 break;
3585 case MONO_WRAPPER_WRITE_BARRIER: {
3586 g_assert (info);
3587 break;
3589 case MONO_WRAPPER_STELEMREF: {
3590 g_assert (info);
3591 encode_value (info->subtype, p, &p);
3592 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3593 encode_value (info->d.virtual_stelemref.kind, p, &p);
3594 break;
3596 case MONO_WRAPPER_OTHER: {
3597 g_assert (info);
3598 encode_value (info->subtype, p, &p);
3599 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3600 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3601 encode_klass_ref (acfg, method->klass, p, &p);
3602 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3603 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3604 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3605 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3606 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
3607 encode_signature (acfg, info->d.interp_in.sig, p, &p);
3608 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3609 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3610 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3611 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3612 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
3613 encode_value (info->d.icall.jit_icall_id, p, &p);
3614 else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT)
3615 encode_value (info->d.aot_init.subtype, p, &p);
3616 else if (info->subtype == WRAPPER_SUBTYPE_LLVM_FUNC)
3617 encode_value (info->d.llvm_func.subtype, p, &p);
3618 break;
3620 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3621 g_assert (info);
3622 encode_value (info->subtype, p, &p);
3623 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3624 encode_value (info->d.icall.jit_icall_id, p, &p);
3625 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3626 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3627 } else {
3628 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3629 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3631 break;
3633 case MONO_WRAPPER_SYNCHRONIZED: {
3634 MonoMethod *m;
3636 m = mono_marshal_method_from_wrapper (method);
3637 g_assert (m);
3638 g_assert (m != method);
3639 encode_method_ref (acfg, m, p, &p);
3640 break;
3642 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3643 g_assert (info);
3644 encode_value (info->subtype, p, &p);
3646 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3647 encode_value (info->d.element_addr.rank, p, &p);
3648 encode_value (info->d.element_addr.elem_size, p, &p);
3649 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3650 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3651 } else {
3652 g_assert_not_reached ();
3654 break;
3656 case MONO_WRAPPER_CASTCLASS: {
3657 g_assert (info);
3658 encode_value (info->subtype, p, &p);
3659 break;
3661 case MONO_WRAPPER_RUNTIME_INVOKE: {
3662 g_assert (info);
3663 encode_value (info->subtype, p, &p);
3664 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3665 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3666 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3667 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3668 break;
3670 case MONO_WRAPPER_DELEGATE_INVOKE:
3671 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3672 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3673 if (method->is_inflated) {
3674 /* These wrappers are identified by their class */
3675 encode_value (1, p, &p);
3676 encode_klass_ref (acfg, method->klass, p, &p);
3677 } else {
3678 MonoMethodSignature *sig = mono_method_signature_internal (method);
3679 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3681 encode_value (0, p, &p);
3682 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3683 encode_value (info ? info->subtype : 0, p, &p);
3684 encode_signature (acfg, sig, p, &p);
3686 break;
3688 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3689 g_assert (info);
3690 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3691 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3692 break;
3694 default:
3695 g_assert_not_reached ();
3697 } else if (mono_method_signature_internal (method)->is_inflated) {
3699 * This is a generic method, find the original token which referenced it and
3700 * encode that.
3701 * Obtain the token from information recorded by the JIT.
3703 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3704 if (ji) {
3705 image_index = get_image_index (acfg, ji->image);
3706 g_assert (image_index < MAX_IMAGE_INDEX);
3707 token = ji->token;
3709 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3710 encode_value (image_index, p, &p);
3711 encode_value (token, p, &p);
3712 } else if (g_hash_table_lookup (acfg->method_blob_hash, method)) {
3713 /* Already emitted as part of an rgctx fetch */
3714 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
3715 offset --;
3717 encode_value ((MONO_AOT_METHODREF_BLOB_INDEX << 24), p, &p);
3718 encode_value (offset, p, &p);
3719 } else {
3720 MonoMethod *declaring;
3721 MonoGenericContext *context = mono_method_get_context (method);
3723 g_assert (method->is_inflated);
3724 declaring = ((MonoMethodInflated*)method)->declaring;
3727 * This might be a non-generic method of a generic instance, which
3728 * doesn't have a token since the reference is generated by the JIT
3729 * like Nullable:Box/Unbox, or by generic sharing.
3731 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3732 /* Encode the klass */
3733 encode_klass_ref (acfg, method->klass, p, &p);
3734 /* Encode the method */
3735 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3736 g_assert (image_index < MAX_IMAGE_INDEX);
3737 g_assert (declaring->token);
3738 token = declaring->token;
3739 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3740 encode_value (image_index, p, &p);
3741 encode_value (mono_metadata_token_index (token), p, &p);
3742 encode_generic_context (acfg, context, p, &p);
3744 } else if (token == 0) {
3745 /* This might be a method of a constructed type like int[,].Set */
3746 /* Obtain the token from information recorded by the JIT */
3747 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3748 if (ji) {
3749 image_index = get_image_index (acfg, ji->image);
3750 g_assert (image_index < MAX_IMAGE_INDEX);
3751 token = ji->token;
3753 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3754 encode_value (image_index, p, &p);
3755 encode_value (token, p, &p);
3756 } else {
3757 /* Array methods */
3758 g_assert (m_class_get_rank (method->klass));
3760 /* Encode directly */
3761 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3762 encode_klass_ref (acfg, method->klass, p, &p);
3763 if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass))
3764 encode_value (0, p, &p);
3765 else if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass) * 2)
3766 encode_value (1, p, &p);
3767 else if (!strcmp (method->name, "Get"))
3768 encode_value (2, p, &p);
3769 else if (!strcmp (method->name, "Address"))
3770 encode_value (3, p, &p);
3771 else if (!strcmp (method->name, "Set"))
3772 encode_value (4, p, &p);
3773 else
3774 g_assert_not_reached ();
3776 } else {
3777 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3779 if (image_index >= MONO_AOT_METHODREF_MIN) {
3780 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3781 encode_value (image_index, p, &p);
3782 encode_value (mono_metadata_token_index (token), p, &p);
3783 } else {
3784 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3788 acfg->stats.method_ref_count++;
3789 acfg->stats.method_ref_size += p - buf;
3791 *endbuf = p;
3794 static guint32
3795 get_shared_method_ref (MonoAotCompile *acfg, MonoMethod *method)
3797 guint32 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, method));
3798 if (!offset) {
3799 guint8 *buf2, *p2;
3801 buf2 = (guint8 *)g_malloc (1024);
3802 p2 = buf2;
3804 encode_method_ref (acfg, method, p2, &p2);
3805 g_assert (p2 - buf2 < 1024);
3807 offset = add_to_blob (acfg, buf2, p2 - buf2);
3808 g_free (buf2);
3810 g_hash_table_insert (acfg->method_blob_hash, method, GUINT_TO_POINTER (offset + 1));
3811 } else {
3812 offset --;
3814 return offset;
3817 static gint
3818 compare_patches (gconstpointer a, gconstpointer b)
3820 int i, j;
3822 i = (*(MonoJumpInfo**)a)->ip.i;
3823 j = (*(MonoJumpInfo**)b)->ip.i;
3825 if (i < j)
3826 return -1;
3827 else
3828 if (i > j)
3829 return 1;
3830 else
3831 return 0;
3834 static G_GNUC_UNUSED char*
3835 patch_to_string (MonoJumpInfo *patch_info)
3837 GString *str;
3839 str = g_string_new ("");
3841 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3843 switch (patch_info->type) {
3844 case MONO_PATCH_INFO_VTABLE:
3845 mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
3846 break;
3847 default:
3848 break;
3850 g_string_append_printf (str, ")");
3851 return g_string_free (str, FALSE);
3855 * is_plt_patch:
3857 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3858 * PLT entry.
3860 static inline gboolean
3861 is_plt_patch (MonoJumpInfo *patch_info)
3863 switch (patch_info->type) {
3864 case MONO_PATCH_INFO_METHOD:
3865 case MONO_PATCH_INFO_JIT_ICALL_ID:
3866 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3867 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3868 case MONO_PATCH_INFO_RGCTX_FETCH:
3869 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
3870 return TRUE;
3871 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
3872 default:
3873 return FALSE;
3878 * get_plt_symbol:
3880 * Return the symbol identifying the plt entry PLT_OFFSET.
3882 static char*
3883 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3885 #ifdef TARGET_MACH
3887 * The Apple linker reorganizes object files, so it doesn't like branches to local
3888 * labels, since those have no relocations.
3890 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3891 #else
3892 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3893 #endif
3897 * get_plt_entry:
3899 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3901 static MonoPltEntry*
3902 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3904 MonoPltEntry *res;
3905 gboolean synchronized = FALSE;
3906 static int synchronized_symbol_idx;
3908 if (!is_plt_patch (patch_info))
3909 return NULL;
3911 if (!acfg->patch_to_plt_entry [patch_info->type])
3912 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3913 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3915 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3917 * Allocate a separate PLT slot for each such patch, since some plt
3918 * entries will refer to the method itself, and some will refer to the
3919 * wrapper.
3921 res = NULL;
3922 synchronized = TRUE;
3925 if (!res) {
3926 MonoJumpInfo *new_ji;
3928 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3930 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3931 res->plt_offset = acfg->plt_offset;
3932 res->ji = new_ji;
3933 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3934 if (acfg->aot_opts.write_symbols)
3935 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3936 if (synchronized) {
3937 /* Avoid duplicate symbols because we don't cache */
3938 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3939 if (res->debug_sym)
3940 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3941 synchronized_symbol_idx ++;
3944 if (res->debug_sym)
3945 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3946 else
3947 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3948 if (strstr (res->llvm_symbol, acfg->temp_prefix) == res->llvm_symbol) {
3949 /* The llvm symbol shouldn't be temporary, since the llvm generated object file references it */
3950 char *tmp = res->llvm_symbol;
3951 res->llvm_symbol = g_strdup (res->llvm_symbol + strlen (acfg->temp_prefix));
3952 g_free (tmp);
3955 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3957 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3959 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3960 //mono_print_ji (patch_info); printf ("\n");
3961 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3963 acfg->plt_offset ++;
3966 return res;
3969 static guint32
3970 lookup_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3972 guint32 got_offset;
3973 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3975 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3976 if (got_offset)
3977 return got_offset - 1;
3978 g_assert_not_reached ();
3982 * get_got_offset:
3984 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3985 * JI could be found if it exists, otherwise allocates a new one.
3987 static guint32
3988 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3990 guint32 got_offset;
3991 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3993 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3994 if (got_offset)
3995 return got_offset - 1;
3997 if (llvm) {
3998 got_offset = acfg->llvm_got_offset;
3999 acfg->llvm_got_offset ++;
4000 } else {
4001 got_offset = acfg->got_offset;
4002 acfg->got_offset ++;
4005 acfg->stats.got_slots ++;
4006 acfg->stats.got_slot_types [ji->type] ++;
4008 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
4009 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
4010 g_ptr_array_add (info->got_patches, ji);
4012 return got_offset;
4015 /* Add a method to the list of methods which need to be emitted */
4016 static void
4017 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
4019 g_assert (method);
4020 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
4021 g_ptr_array_add (acfg->methods, method);
4022 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
4023 acfg->nmethods = acfg->methods->len + 1;
4026 if (method->wrapper_type || extra) {
4027 int token = mono_metadata_token_index (method->token) - 1;
4028 if (token < 0)
4029 acfg->nextra_methods++;
4030 g_ptr_array_add (acfg->extra_methods, method);
4034 static gboolean
4035 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
4037 /* One instantiation with valuetypes is generated for each async method */
4038 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")))
4039 return TRUE;
4040 else
4041 return FALSE;
4044 static guint32
4045 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
4047 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
4049 g_assert (index);
4051 return index - 1;
4054 static int
4055 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
4057 int index;
4059 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
4060 if (index)
4061 return index - 1;
4063 index = acfg->method_index;
4064 add_method_with_index (acfg, method, index, extra);
4066 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
4068 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
4070 acfg->method_index ++;
4072 return index;
4075 static int
4076 add_method (MonoAotCompile *acfg, MonoMethod *method)
4078 return add_method_full (acfg, method, FALSE, 0);
4081 static void
4082 mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
4084 g_assert (acfg->dedup_stats);
4086 char *name = mono_aot_get_mangled_method_name (method);
4087 g_assert (name);
4089 // For stats
4090 char *stats_name = g_strdup (name);
4092 g_assert (acfg->dedup_cache);
4094 if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
4095 // This AOTCompile owns this method
4096 // We do this to decide whether to write it to disk
4097 // during a dedup run (first phase, where we skip).
4099 // If never changed, then maybe can avoid a recompile
4100 // of the cache.
4102 // Files not read in during last phase.
4103 acfg->dedup_cache_changed = TRUE;
4105 // owns name
4106 g_hash_table_insert (acfg->dedup_cache, name, method);
4107 } else {
4108 // owns name
4109 g_free (name);
4112 guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
4113 count++;
4114 g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
4117 static void
4118 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
4120 ERROR_DECL (error);
4122 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
4123 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
4124 if (!is_ok (error)) {
4125 /* vtype constraint */
4126 mono_error_cleanup (error);
4127 return;
4129 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4130 /* Use the gsharedvt version */
4131 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4132 mono_error_assert_ok (error);
4135 if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
4136 mono_dedup_cache_method (acfg, method);
4138 if (!acfg->dedup_emit_mode)
4139 return;
4142 if (acfg->aot_opts.log_generics)
4143 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4145 add_method_full (acfg, method, TRUE, depth);
4148 static void
4149 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
4151 add_extra_method_with_depth (acfg, method, 0);
4154 static void
4155 add_jit_icall_wrapper (MonoAotCompile *acfg, MonoJitICallInfo *callinfo)
4157 if (!callinfo->sig)
4158 return;
4160 g_assert (callinfo->name && callinfo->func);
4162 add_method (acfg, mono_marshal_get_icall_wrapper (callinfo, TRUE));
4165 #if ENABLE_LLVM
4167 static void
4168 add_lazy_init_wrappers (MonoAotCompile *acfg)
4170 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD));
4171 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_MRGCTX));
4172 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_VTABLE));
4173 add_method (acfg, mono_marshal_get_aot_init_wrapper (AOT_INIT_METHOD_GSHARED_THIS));
4176 #endif
4178 static MonoMethod*
4179 get_runtime_invoke_sig (MonoMethodSignature *sig)
4181 MonoMethodBuilder *mb;
4182 MonoMethod *m;
4184 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
4185 m = mono_mb_create_method (mb, sig, 16);
4186 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
4187 mono_mb_free (mb);
4188 return invoke;
4191 static MonoMethod*
4192 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
4194 return mono_marshal_get_runtime_invoke (method, virtual_);
4197 static gboolean
4198 can_marshal_struct (MonoClass *klass)
4200 MonoClassField *field;
4201 gboolean can_marshal = TRUE;
4202 gpointer iter = NULL;
4203 MonoMarshalType *info;
4204 int i;
4206 if (mono_class_is_auto_layout (klass))
4207 return FALSE;
4209 info = mono_marshal_load_type_info (klass);
4211 /* Only allow a few field types to avoid asserts in the marshalling code */
4212 while ((field = mono_class_get_fields_internal (klass, &iter))) {
4213 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
4214 continue;
4216 switch (field->type->type) {
4217 case MONO_TYPE_I4:
4218 case MONO_TYPE_U4:
4219 case MONO_TYPE_I1:
4220 case MONO_TYPE_U1:
4221 case MONO_TYPE_BOOLEAN:
4222 case MONO_TYPE_I2:
4223 case MONO_TYPE_U2:
4224 case MONO_TYPE_CHAR:
4225 case MONO_TYPE_I8:
4226 case MONO_TYPE_U8:
4227 case MONO_TYPE_I:
4228 case MONO_TYPE_U:
4229 case MONO_TYPE_PTR:
4230 case MONO_TYPE_R4:
4231 case MONO_TYPE_R8:
4232 case MONO_TYPE_STRING:
4233 break;
4234 case MONO_TYPE_VALUETYPE:
4235 if (!m_class_is_enumtype (mono_class_from_mono_type_internal (field->type)) && !can_marshal_struct (mono_class_from_mono_type_internal (field->type)))
4236 can_marshal = FALSE;
4237 break;
4238 case MONO_TYPE_SZARRAY: {
4239 gboolean has_mspec = FALSE;
4241 if (info) {
4242 for (i = 0; i < info->num_fields; ++i) {
4243 if (info->fields [i].field == field && info->fields [i].mspec)
4244 has_mspec = TRUE;
4247 if (!has_mspec)
4248 can_marshal = FALSE;
4249 break;
4251 default:
4252 can_marshal = FALSE;
4253 break;
4257 /* Special cases */
4258 /* Its hard to compute whenever these can be marshalled or not */
4259 if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
4260 return TRUE;
4262 return can_marshal;
4265 static void
4266 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
4268 /* Create a vtype instantiation */
4269 MonoGenericContext shared_context;
4270 MonoType **args;
4271 MonoGenericInst *inst;
4272 MonoGenericContainer *container;
4273 MonoClass **constraints;
4274 int i;
4276 memset (ctx, 0, sizeof (MonoGenericContext));
4278 if (mono_class_is_gtd (method->klass)) {
4279 shared_context = mono_class_get_generic_container (method->klass)->context;
4280 inst = shared_context.class_inst;
4282 args = g_new0 (MonoType*, inst->type_argc);
4283 for (i = 0; i < inst->type_argc; ++i) {
4284 args [i] = mono_get_int_type ();
4286 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4288 if (method->is_generic) {
4289 container = mono_method_get_generic_container (method);
4290 g_assert (!container->is_anonymous && container->is_method);
4291 shared_context = container->context;
4292 inst = shared_context.method_inst;
4294 args = g_new0 (MonoType*, inst->type_argc);
4295 for (i = 0; i < container->type_argc; ++i) {
4296 MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
4297 gboolean ref_only = FALSE;
4299 if (info && info->constraints) {
4300 constraints = info->constraints;
4302 while (*constraints) {
4303 MonoClass *cklass = *constraints;
4304 if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
4305 /* Inflaring the method with our vtype would not be valid */
4306 ref_only = TRUE;
4307 constraints ++;
4311 if (ref_only)
4312 args [i] = mono_get_object_type ();
4313 else
4314 args [i] = mono_get_int_type ();
4316 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4320 static void
4321 add_gc_wrappers (MonoAotCompile *acfg)
4323 MonoMethod *m;
4324 /* Managed Allocators */
4325 int nallocators = mono_gc_get_managed_allocator_types ();
4326 for (int i = 0; i < nallocators; ++i) {
4327 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
4328 add_method (acfg, m);
4329 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
4330 add_method (acfg, m);
4331 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
4332 add_method (acfg, m);
4335 /* write barriers */
4336 if (mono_gc_is_moving ()) {
4337 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4338 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4342 static gboolean
4343 contains_disable_reflection_attribute (MonoCustomAttrInfo *cattr)
4345 for (int i = 0; i < cattr->num_attrs; ++i) {
4346 MonoCustomAttrEntry *attr = &cattr->attrs [i];
4348 if (!attr->ctor)
4349 return FALSE;
4351 if (strcmp (m_class_get_name_space (attr->ctor->klass), "System.Runtime.CompilerServices"))
4352 return FALSE;
4354 if (strcmp (m_class_get_name (attr->ctor->klass), "DisablePrivateReflectionAttribute"))
4355 return FALSE;
4358 return TRUE;
4361 gboolean
4362 mono_aot_can_specialize (MonoMethod *method)
4364 if (!method)
4365 return FALSE;
4367 if (method->wrapper_type != MONO_WRAPPER_NONE)
4368 return FALSE;
4370 // If it's not private, we can't specialize
4371 if ((method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) != METHOD_ATTRIBUTE_PRIVATE)
4372 return FALSE;
4374 // If it has the attribute disabling the specialization, we can't specialize
4376 // Set by linker, indicates that the method can be found through reflection
4377 // and that call-site specialization shouldn't be done.
4379 // Important that this attribute is used for *nothing else*
4381 // If future authors make use of it (to disable more optimizations),
4382 // change this place to use a new attribute.
4383 ERROR_DECL (cattr_error);
4384 MonoCustomAttrInfo *cattr = mono_custom_attrs_from_class_checked (method->klass, cattr_error);
4386 if (!is_ok (cattr_error)) {
4387 mono_error_cleanup (cattr_error);
4388 goto cleanup_false;
4389 } else if (cattr && contains_disable_reflection_attribute (cattr)) {
4390 goto cleanup_true;
4393 cattr = mono_custom_attrs_from_method_checked (method, cattr_error);
4395 if (!is_ok (cattr_error)) {
4396 mono_error_cleanup (cattr_error);
4397 goto cleanup_false;
4398 } else if (cattr && contains_disable_reflection_attribute (cattr)) {
4399 goto cleanup_true;
4400 } else {
4401 goto cleanup_false;
4404 cleanup_false:
4405 if (cattr)
4406 mono_custom_attrs_free (cattr);
4407 return FALSE;
4409 cleanup_true:
4410 if (cattr)
4411 mono_custom_attrs_free (cattr);
4412 return TRUE;
4415 static void
4416 add_wrappers (MonoAotCompile *acfg)
4418 MonoMethod *method, *m;
4419 int i, j;
4420 MonoMethodSignature *sig, *csig;
4421 guint32 token;
4424 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
4425 * so there is only one wrapper of a given type, or inlining their contents into their
4426 * callers.
4428 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4429 ERROR_DECL (error);
4430 MonoMethod *method;
4431 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4432 gboolean skip = FALSE;
4434 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4435 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4437 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4438 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4439 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
4440 skip = TRUE;
4442 /* Skip methods which can not be handled by get_runtime_invoke () */
4443 sig = mono_method_signature_internal (method);
4444 if (!sig)
4445 continue;
4446 if ((sig->ret->type == MONO_TYPE_PTR) ||
4447 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
4448 skip = TRUE;
4449 if (mono_class_is_open_constructed_type (sig->ret))
4450 skip = TRUE;
4452 for (j = 0; j < sig->param_count; j++) {
4453 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
4454 skip = TRUE;
4455 if (mono_class_is_open_constructed_type (sig->params [j]))
4456 skip = TRUE;
4459 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4460 if (!mono_class_is_contextbound (method->klass)) {
4461 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
4462 gboolean has_nullable = FALSE;
4464 for (j = 0; j < sig->param_count; j++) {
4465 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (sig->params [j])))
4466 has_nullable = TRUE;
4469 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
4470 /* Supported by the dynamic runtime-invoke wrapper */
4471 skip = TRUE;
4473 if (info)
4474 mono_arch_dyn_call_free (info);
4476 #endif
4478 if (acfg->aot_opts.llvm_only)
4479 /* Supported by the gsharedvt based runtime-invoke wrapper */
4480 skip = TRUE;
4482 if (!skip) {
4483 //printf ("%s\n", mono_method_full_name (method, TRUE));
4484 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4488 if (mono_is_corlib_image (acfg->image->assembly->image)) {
4489 /* Runtime invoke wrappers */
4491 MonoType *void_type = mono_get_void_type ();
4492 MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
4494 /* void runtime-invoke () [.cctor] */
4495 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4496 csig->ret = void_type;
4497 add_method (acfg, get_runtime_invoke_sig (csig));
4499 /* void runtime-invoke () [Finalize] */
4500 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4501 csig->hasthis = 1;
4502 csig->ret = void_type;
4503 add_method (acfg, get_runtime_invoke_sig (csig));
4505 /* void runtime-invoke (string) [exception ctor] */
4506 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4507 csig->hasthis = 1;
4508 csig->ret = void_type;
4509 csig->params [0] = string_type;
4510 add_method (acfg, get_runtime_invoke_sig (csig));
4512 /* void runtime-invoke (string, string) [exception ctor] */
4513 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4514 csig->hasthis = 1;
4515 csig->ret = void_type;
4516 csig->params [0] = string_type;
4517 csig->params [1] = string_type;
4518 add_method (acfg, get_runtime_invoke_sig (csig));
4520 /* string runtime-invoke () [Exception.ToString ()] */
4521 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4522 csig->hasthis = 1;
4523 csig->ret = string_type;
4524 add_method (acfg, get_runtime_invoke_sig (csig));
4526 /* void runtime-invoke (string, Exception) [exception ctor] */
4527 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4528 csig->hasthis = 1;
4529 csig->ret = void_type;
4530 csig->params [0] = string_type;
4531 csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
4532 add_method (acfg, get_runtime_invoke_sig (csig));
4534 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
4535 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4536 csig->hasthis = 1;
4537 csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4538 csig->params [0] = string_type;
4539 csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4540 csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
4541 add_method (acfg, get_runtime_invoke_sig (csig));
4543 /* runtime-invoke used by finalizers */
4544 add_method (acfg, get_runtime_invoke (acfg, get_method_nofail (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4546 /* This is used by mono_runtime_capture_context () */
4547 method = mono_get_context_capture_method ();
4548 if (method)
4549 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4551 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4552 if (!acfg->aot_opts.llvm_only)
4553 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4554 #endif
4556 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4557 if (acfg->aot_opts.llvm_only) {
4558 int variants;
4560 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4561 for (variants = 0; variants < 4; ++variants) {
4562 for (i = 0; i < 40; ++i) {
4563 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4564 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4566 g_free (sig);
4571 /* stelemref */
4572 add_method (acfg, mono_marshal_get_stelemref ());
4574 add_gc_wrappers (acfg);
4576 /* Stelemref wrappers */
4578 MonoMethod **wrappers;
4579 int nwrappers;
4581 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4582 for (i = 0; i < nwrappers; ++i)
4583 add_method (acfg, wrappers [i]);
4584 g_free (wrappers);
4587 /* castclass_with_check wrapper */
4588 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4589 /* isinst_with_check wrapper */
4590 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4592 /* JIT icall wrappers */
4593 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall data */
4594 for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
4595 add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
4599 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4600 * we use the original method instead at runtime.
4601 * Since full-aot doesn't support remoting, this is not a problem.
4603 #if 0
4604 /* remoting-invoke wrappers */
4605 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4606 ERROR_DECL (error);
4607 MonoMethodSignature *sig;
4609 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4610 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4611 g_assert (is_ok (error)); /* FIXME don't swallow the error */
4613 sig = mono_method_signature_internal (method);
4615 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4616 m = mono_marshal_get_remoting_invoke_with_check (method);
4618 add_method (acfg, m);
4621 #endif
4623 /* delegate-invoke wrappers */
4624 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4625 ERROR_DECL (error);
4626 MonoClass *klass;
4628 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4629 klass = mono_class_get_checked (acfg->image, token, error);
4631 if (!klass) {
4632 mono_error_cleanup (error);
4633 continue;
4636 if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4637 continue;
4639 if (!mono_class_is_gtd (klass)) {
4640 method = mono_get_delegate_invoke_internal (klass);
4642 m = mono_marshal_get_delegate_invoke (method, NULL);
4644 add_method (acfg, m);
4646 method = try_get_method_nofail (klass, "BeginInvoke", -1, 0);
4647 if (method)
4648 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4650 method = try_get_method_nofail (klass, "EndInvoke", -1, 0);
4651 if (method)
4652 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4654 MonoCustomAttrInfo *cattr;
4655 cattr = mono_custom_attrs_from_class_checked (klass, error);
4656 if (!is_ok (error)) {
4657 mono_error_cleanup (error);
4658 g_assert (!cattr);
4659 continue;
4662 if (cattr) {
4663 int j;
4665 for (j = 0; j < cattr->num_attrs; ++j)
4666 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")))
4667 break;
4668 if (j < cattr->num_attrs) {
4669 MonoMethod *invoke;
4670 MonoMethod *wrapper;
4671 MonoMethod *del_invoke;
4673 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4674 invoke = mono_get_delegate_invoke_internal (klass);
4675 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4676 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4677 add_method (acfg, wrapper);
4678 add_method (acfg, del_invoke);
4680 mono_custom_attrs_free (cattr);
4682 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4683 ERROR_DECL (error);
4684 MonoGenericContext ctx;
4685 MonoMethod *inst, *gshared;
4688 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4690 /* Invoke */
4691 method = mono_get_delegate_invoke_internal (klass);
4692 create_gsharedvt_inst (acfg, method, &ctx);
4694 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4695 g_assert (is_ok (error)); /* FIXME don't swallow the error */
4697 m = mono_marshal_get_delegate_invoke (inst, NULL);
4698 g_assert (m->is_inflated);
4700 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4701 mono_error_assert_ok (error);
4703 add_extra_method (acfg, gshared);
4705 /* begin-invoke */
4706 method = mono_get_delegate_begin_invoke_internal (klass);
4707 if (method) {
4708 create_gsharedvt_inst (acfg, method, &ctx);
4710 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4711 g_assert (is_ok (error)); /* FIXME don't swallow the error */
4713 m = mono_marshal_get_delegate_begin_invoke (inst);
4714 g_assert (m->is_inflated);
4716 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4717 mono_error_assert_ok (error);
4719 add_extra_method (acfg, gshared);
4722 /* end-invoke */
4723 method = mono_get_delegate_end_invoke_internal (klass);
4724 if (method) {
4725 create_gsharedvt_inst (acfg, method, &ctx);
4727 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4728 g_assert (is_ok (error)); /* FIXME don't swallow the error */
4730 m = mono_marshal_get_delegate_end_invoke (inst);
4731 g_assert (m->is_inflated);
4733 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4734 mono_error_assert_ok (error);
4736 add_extra_method (acfg, gshared);
4741 /* array access wrappers */
4742 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4743 ERROR_DECL (error);
4744 MonoClass *klass;
4746 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4747 klass = mono_class_get_checked (acfg->image, token, error);
4749 if (!klass) {
4750 mono_error_cleanup (error);
4751 continue;
4754 if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
4755 MonoMethod *m, *wrapper;
4757 /* Add runtime-invoke wrappers too */
4759 m = get_method_nofail (klass, "Get", -1, 0);
4760 g_assert (m);
4761 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4762 add_extra_method (acfg, wrapper);
4763 if (!acfg->aot_opts.llvm_only)
4764 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4766 m = get_method_nofail (klass, "Set", -1, 0);
4767 g_assert (m);
4768 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4769 add_extra_method (acfg, wrapper);
4770 if (!acfg->aot_opts.llvm_only)
4771 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4775 /* Synchronized wrappers */
4776 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4777 ERROR_DECL (error);
4778 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4779 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4780 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4782 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4783 if (method->is_generic) {
4784 // FIXME:
4785 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4786 ERROR_DECL (error);
4787 MonoGenericContext ctx;
4788 MonoMethod *inst, *gshared, *m;
4791 * Create a generic wrapper for a generic instance, and AOT that.
4793 create_gsharedvt_inst (acfg, method, &ctx);
4794 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4795 g_assert (is_ok (error)); /* FIXME don't swallow the error */
4796 m = mono_marshal_get_synchronized_wrapper (inst);
4797 g_assert (m->is_inflated);
4798 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4799 mono_error_assert_ok (error);
4801 add_method (acfg, gshared);
4802 } else {
4803 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4808 /* pinvoke wrappers */
4809 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4810 ERROR_DECL (error);
4811 MonoMethod *method;
4812 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4814 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4815 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4817 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4818 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4819 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4822 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4823 if (acfg->aot_opts.llvm_only) {
4824 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4825 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (method), FALSE, TRUE, FALSE);
4830 /* native-to-managed wrappers */
4831 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4832 ERROR_DECL (error);
4833 MonoMethod *method;
4834 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4835 MonoCustomAttrInfo *cattr;
4836 int j;
4838 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4839 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4842 * Only generate native-to-managed wrappers for methods which have an
4843 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4844 * name to avoid defining a new assembly to contain it.
4846 cattr = mono_custom_attrs_from_method_checked (method, error);
4847 if (!is_ok (error)) {
4848 char *name = mono_method_get_full_name (method);
4849 report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
4850 g_free (name);
4853 if (cattr) {
4854 for (j = 0; j < cattr->num_attrs; ++j)
4855 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
4856 break;
4857 if (j < cattr->num_attrs) {
4858 MonoCustomAttrEntry *e = &cattr->attrs [j];
4859 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
4860 const char *p = (const char*)e->data;
4861 const char *named;
4862 int slen, num_named, named_type;
4863 char *n;
4864 MonoType *t;
4865 MonoClass *klass;
4866 char *export_name = NULL;
4867 MonoMethod *wrapper;
4869 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4870 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4871 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",
4872 mono_method_full_name (method, TRUE));
4873 exit (1);
4876 g_assert (sig->param_count == 1);
4877 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type_internal (sig->params [0])), "Type"));
4880 * Decode the cattr manually since we can't create objects
4881 * during aot compilation.
4884 /* Skip prolog */
4885 p += 2;
4887 /* From load_cattr_value () in reflection.c */
4888 slen = mono_metadata_decode_value (p, &p);
4889 n = (char *)g_memdup (p, slen + 1);
4890 n [slen] = 0;
4891 t = mono_reflection_type_from_name_checked (n, acfg->image, error);
4892 g_assert (t);
4893 mono_error_assert_ok (error);
4894 g_free (n);
4896 klass = mono_class_from_mono_type_internal (t);
4897 g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
4899 p += slen;
4901 num_named = read16 (p);
4902 p += 2;
4904 g_assert (num_named < 2);
4905 if (num_named == 1) {
4906 int name_len;
4907 char *name;
4909 /* parse ExportSymbol attribute */
4910 named = p;
4911 named_type = *named;
4912 named += 1;
4913 /* data_type = *named; */
4914 named += 1;
4916 name_len = mono_metadata_decode_blob_size (named, &named);
4917 name = (char *)g_malloc (name_len + 1);
4918 memcpy (name, named, name_len);
4919 name [name_len] = 0;
4920 named += name_len;
4922 g_assert (named_type == 0x54);
4923 g_assert (!strcmp (name, "ExportSymbol"));
4925 /* load_cattr_value (), string case */
4926 MONO_DISABLE_WARNING (4310) // cast truncates constant value
4927 g_assert (*named != (char)0xFF);
4928 MONO_RESTORE_WARNING
4929 slen = mono_metadata_decode_value (named, &named);
4930 export_name = (char *)g_malloc (slen + 1);
4931 memcpy (export_name, named, slen);
4932 export_name [slen] = 0;
4933 named += slen;
4936 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
4937 mono_error_assert_ok (error);
4939 add_method (acfg, wrapper);
4940 if (export_name)
4941 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4943 g_free (cattr);
4946 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4947 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4948 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4952 /* StructureToPtr/PtrToStructure wrappers */
4953 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4954 ERROR_DECL (error);
4955 MonoClass *klass;
4957 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4958 klass = mono_class_get_checked (acfg->image, token, error);
4960 if (!klass) {
4961 mono_error_cleanup (error);
4962 continue;
4965 if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4966 !(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)))) {
4967 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4968 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4973 static gboolean
4974 has_type_vars (MonoClass *klass)
4976 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
4977 return TRUE;
4978 if (m_class_get_rank (klass))
4979 return has_type_vars (m_class_get_element_class (klass));
4980 if (mono_class_is_ginst (klass)) {
4981 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4982 if (context->class_inst) {
4983 int i;
4985 for (i = 0; i < context->class_inst->type_argc; ++i)
4986 if (has_type_vars (mono_class_from_mono_type_internal (context->class_inst->type_argv [i])))
4987 return TRUE;
4990 if (mono_class_is_gtd (klass))
4991 return TRUE;
4992 return FALSE;
4995 static gboolean
4996 is_vt_inst (MonoGenericInst *inst)
4998 int i;
5000 for (i = 0; i < inst->type_argc; ++i) {
5001 MonoType *t = inst->type_argv [i];
5002 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
5003 return TRUE;
5005 return FALSE;
5008 static gboolean
5009 method_has_type_vars (MonoMethod *method)
5011 if (has_type_vars (method->klass))
5012 return TRUE;
5014 if (method->is_inflated) {
5015 MonoGenericContext *context = mono_method_get_context (method);
5016 if (context->method_inst) {
5017 int i;
5019 for (i = 0; i < context->method_inst->type_argc; ++i)
5020 if (has_type_vars (mono_class_from_mono_type_internal (context->method_inst->type_argv [i])))
5021 return TRUE;
5024 return FALSE;
5027 static
5028 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
5030 return opts->mode == MONO_AOT_MODE_FULL;
5033 static
5034 gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
5036 return opts->interp;
5039 static
5040 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
5042 return opts->mode == MONO_AOT_MODE_HYBRID;
5045 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
5047 static void
5048 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
5050 /* This might lead to a huge code blowup so only do it if neccesary */
5051 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
5052 return;
5054 add_generic_class_with_depth (acfg, klass, 0, ref);
5057 static gboolean
5058 check_type_depth (MonoType *t, int depth)
5060 int i;
5062 if (depth > 8)
5063 return TRUE;
5065 switch (t->type) {
5066 case MONO_TYPE_GENERICINST: {
5067 MonoGenericClass *gklass = t->data.generic_class;
5068 MonoGenericInst *ginst = gklass->context.class_inst;
5070 if (ginst) {
5071 for (i = 0; i < ginst->type_argc; ++i) {
5072 if (check_type_depth (ginst->type_argv [i], depth + 1))
5073 return TRUE;
5076 break;
5078 default:
5079 break;
5082 return FALSE;
5085 static void
5086 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
5089 * add_generic_class:
5091 * Add all methods of a generic class.
5093 static void
5094 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
5096 MonoMethod *method;
5097 MonoClassField *field;
5098 gpointer iter;
5099 gboolean use_gsharedvt = FALSE;
5101 if (!acfg->ginst_hash)
5102 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
5104 mono_class_init_internal (klass);
5106 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
5107 return;
5109 if (has_type_vars (klass))
5110 return;
5112 if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
5113 return;
5115 if (mono_class_has_failure (klass))
5116 return;
5118 if (!acfg->ginst_hash)
5119 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
5121 if (g_hash_table_lookup (acfg->ginst_hash, klass))
5122 return;
5124 if (check_type_depth (m_class_get_byval_arg (klass), 0))
5125 return;
5127 if (acfg->aot_opts.log_generics) {
5128 char *s = mono_type_full_name (m_class_get_byval_arg (klass));
5129 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
5130 g_free (s);
5133 g_hash_table_insert (acfg->ginst_hash, klass, klass);
5136 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
5137 * Enable this only for some classes since gsharedvt might not support all methods.
5139 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) &&
5140 (!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
5141 use_gsharedvt = TRUE;
5143 iter = NULL;
5144 while ((method = mono_class_get_methods (klass, &iter))) {
5145 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
5147 * This is partial sharing, and we can't handle it yet
5149 continue;
5152 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
5153 /* Already added */
5154 add_types_from_method_header (acfg, method);
5155 continue;
5158 if (method->is_generic)
5159 /* FIXME: */
5160 continue;
5163 * FIXME: Instances which are referenced by these methods are not added,
5164 * for example Array.Resize<int> for List<int>.Add ().
5166 add_extra_method_with_depth (acfg, method, depth + 1);
5169 iter = NULL;
5170 while ((field = mono_class_get_fields_internal (klass, &iter))) {
5171 if (field->type->type == MONO_TYPE_GENERICINST)
5172 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (field->type), depth + 1, "field");
5175 if (m_class_is_delegate (klass)) {
5176 method = mono_get_delegate_invoke_internal (klass);
5178 method = mono_marshal_get_delegate_invoke (method, NULL);
5180 if (acfg->aot_opts.log_generics)
5181 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
5183 add_method (acfg, method);
5186 /* Add superclasses */
5187 if (m_class_get_parent (klass))
5188 add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
5190 const char *klass_name = m_class_get_name (klass);
5191 const char *klass_name_space = m_class_get_name_space (klass);
5192 const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
5194 * For ICollection<T>, add instances of the helper methods
5195 * in Array, since a T[] could be cast to ICollection<T>.
5197 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
5198 (!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"))) {
5199 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5200 MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
5201 gpointer iter;
5202 char *name_prefix;
5204 if (!strcmp (klass_name, "IEnumerator`1"))
5205 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
5206 else
5207 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
5209 /* Add the T[]/InternalEnumerator class */
5210 if (!strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IEnumerator`1")) {
5211 ERROR_DECL (error);
5212 MonoClass *nclass;
5214 iter = NULL;
5215 while ((nclass = mono_class_get_nested_types (m_class_get_parent (array_class), &iter))) {
5216 if (!strcmp (m_class_get_name (nclass), "InternalEnumerator`1"))
5217 break;
5219 g_assert (nclass);
5220 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
5221 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5222 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
5225 iter = NULL;
5226 while ((method = mono_class_get_methods (array_class, &iter))) {
5227 if (!strncmp (method->name, name_prefix, strlen (name_prefix))) {
5228 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
5230 if (m->is_inflated && !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE))
5231 add_extra_method_with_depth (acfg, m, depth);
5235 g_free (name_prefix);
5238 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
5239 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5240 ERROR_DECL (error);
5241 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5242 MonoClass *icomparable, *gcomparer, *icomparable_inst;
5243 MonoGenericContext ctx;
5244 MonoType *args [16];
5246 memset (&ctx, 0, sizeof (ctx));
5248 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
5250 args [0] = m_class_get_byval_arg (tclass);
5251 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5253 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
5254 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5256 if (mono_class_is_assignable_from_internal (icomparable_inst, tclass)) {
5257 MonoClass *gcomparer_inst;
5258 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
5259 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5260 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5262 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
5266 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
5267 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5268 ERROR_DECL (error);
5269 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5270 MonoClass *iface, *gcomparer, *iface_inst;
5271 MonoGenericContext ctx;
5272 MonoType *args [16];
5274 memset (&ctx, 0, sizeof (ctx));
5276 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
5277 g_assert (iface);
5278 args [0] = m_class_get_byval_arg (tclass);
5279 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5281 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
5282 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5284 if (mono_class_is_assignable_from_internal (iface_inst, tclass)) {
5285 MonoClass *gcomparer_inst;
5286 ERROR_DECL (error);
5288 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
5289 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5290 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5291 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
5295 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
5296 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5297 MonoClass *enum_comparer;
5298 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5299 MonoGenericContext ctx;
5300 MonoType *args [16];
5302 if (m_class_is_enumtype (tclass)) {
5303 MonoClass *enum_comparer_inst;
5304 ERROR_DECL (error);
5306 memset (&ctx, 0, sizeof (ctx));
5307 args [0] = m_class_get_byval_arg (tclass);
5308 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5310 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5311 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
5312 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5313 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
5317 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
5318 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5319 MonoClass *comparer;
5320 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5321 MonoGenericContext ctx;
5322 MonoType *args [16];
5324 if (m_class_is_enumtype (tclass)) {
5325 MonoClass *comparer_inst;
5326 ERROR_DECL (error);
5328 memset (&ctx, 0, sizeof (ctx));
5329 args [0] = m_class_get_byval_arg (tclass);
5330 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5332 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
5333 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
5334 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5335 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
5340 static void
5341 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
5343 int i;
5344 MonoGenericContext ctx;
5345 MonoType *args [16];
5347 if (acfg->aot_opts.no_instances)
5348 return;
5350 memset (&ctx, 0, sizeof (ctx));
5352 for (i = 0; i < ninsts; ++i) {
5353 ERROR_DECL (error);
5354 MonoClass *generic_inst;
5355 args [0] = insts [i];
5356 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5357 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
5358 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5359 add_generic_class (acfg, generic_inst, force, "");
5363 static void
5364 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
5366 ERROR_DECL (error);
5367 MonoMethodHeader *header;
5368 MonoMethodSignature *sig;
5369 int j, depth;
5371 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5373 sig = mono_method_signature_internal (method);
5375 if (sig) {
5376 for (j = 0; j < sig->param_count; ++j)
5377 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
5378 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (sig->params [j]), depth + 1, "arg");
5381 header = mono_method_get_header_checked (method, error);
5383 if (header) {
5384 for (j = 0; j < header->num_locals; ++j)
5385 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
5386 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (header->locals [j]), depth + 1, "local");
5387 mono_metadata_free_mh (header);
5388 } else {
5389 mono_error_cleanup (error); /* FIXME report the error */
5395 * add_generic_instances:
5397 * Add instances referenced by the METHODSPEC/TYPESPEC table.
5399 static void
5400 add_generic_instances (MonoAotCompile *acfg)
5402 int i;
5403 guint32 token;
5404 MonoMethod *method;
5405 MonoGenericContext *context;
5407 if (acfg->aot_opts.no_instances)
5408 return;
5410 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
5411 ERROR_DECL (error);
5412 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
5413 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
5415 if (!method) {
5416 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
5417 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
5418 mono_error_cleanup (error);
5419 continue;
5422 if (m_class_get_image (method->klass) != acfg->image)
5423 continue;
5425 context = mono_method_get_context (method);
5427 if (context && ((context->class_inst && context->class_inst->is_open)))
5428 continue;
5431 * For open methods, create an instantiation which can be passed to the JIT.
5432 * FIXME: Handle class_inst as well.
5434 if (context && context->method_inst && context->method_inst->is_open) {
5435 ERROR_DECL (error);
5436 MonoGenericContext shared_context;
5437 MonoGenericInst *inst;
5438 MonoType **type_argv;
5439 int i;
5440 MonoMethod *declaring_method;
5441 gboolean supported = TRUE;
5443 /* Check that the context doesn't contain open constructed types */
5444 if (context->class_inst) {
5445 inst = context->class_inst;
5446 for (i = 0; i < inst->type_argc; ++i) {
5447 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)
5448 continue;
5449 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5450 supported = FALSE;
5453 if (context->method_inst) {
5454 inst = context->method_inst;
5455 for (i = 0; i < inst->type_argc; ++i) {
5456 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)
5457 continue;
5458 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5459 supported = FALSE;
5463 if (!supported)
5464 continue;
5466 memset (&shared_context, 0, sizeof (MonoGenericContext));
5468 inst = context->class_inst;
5469 if (inst) {
5470 type_argv = g_new0 (MonoType*, inst->type_argc);
5471 for (i = 0; i < inst->type_argc; ++i) {
5472 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)
5473 type_argv [i] = mono_get_object_type ();
5474 else
5475 type_argv [i] = inst->type_argv [i];
5478 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5479 g_free (type_argv);
5482 inst = context->method_inst;
5483 if (inst) {
5484 type_argv = g_new0 (MonoType*, inst->type_argc);
5485 for (i = 0; i < inst->type_argc; ++i) {
5486 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)
5487 type_argv [i] = mono_get_object_type ();
5488 else
5489 type_argv [i] = inst->type_argv [i];
5492 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5493 g_free (type_argv);
5496 if (method->is_generic || mono_class_is_gtd (method->klass))
5497 declaring_method = method;
5498 else
5499 declaring_method = mono_method_get_declaring_generic_method (method);
5501 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
5502 g_assert (is_ok (error)); /* FIXME don't swallow the error */
5506 * If the method is fully sharable, it was already added in place of its
5507 * generic definition.
5509 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
5510 continue;
5513 * FIXME: Partially shared methods are not shared here, so we end up with
5514 * many identical methods.
5516 add_extra_method (acfg, method);
5519 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
5520 ERROR_DECL (error);
5521 MonoClass *klass;
5523 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
5525 klass = mono_class_get_checked (acfg->image, token, error);
5526 if (!klass || m_class_get_rank (klass)) {
5527 mono_error_cleanup (error);
5528 continue;
5531 add_generic_class (acfg, klass, FALSE, "typespec");
5534 /* Add types of args/locals */
5535 for (i = 0; i < acfg->methods->len; ++i) {
5536 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5537 add_types_from_method_header (acfg, method);
5540 if (acfg->image == mono_defaults.corlib) {
5541 MonoClass *klass;
5542 MonoType *insts [256];
5543 int ninsts = 0;
5545 MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
5546 MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
5547 MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
5548 MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
5549 MonoType *int32_type = mono_get_int32_type ();
5550 MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
5551 MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
5552 MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
5553 MonoType *object_type = mono_get_object_type ();
5555 insts [ninsts ++] = byte_type;
5556 insts [ninsts ++] = sbyte_type;
5557 insts [ninsts ++] = int16_type;
5558 insts [ninsts ++] = uint16_type;
5559 insts [ninsts ++] = int32_type;
5560 insts [ninsts ++] = uint32_type;
5561 insts [ninsts ++] = int64_type;
5562 insts [ninsts ++] = uint64_type;
5563 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
5564 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
5565 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
5566 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
5568 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5569 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5570 if (klass)
5571 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5572 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5573 if (klass)
5574 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5576 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5578 MonoClass *enum_comparer;
5579 MonoType *insts [16];
5580 int ninsts;
5582 ninsts = 0;
5583 insts [ninsts ++] = int32_type;
5584 insts [ninsts ++] = uint32_type;
5585 insts [ninsts ++] = uint16_type;
5586 insts [ninsts ++] = byte_type;
5587 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5588 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5590 ninsts = 0;
5591 insts [ninsts ++] = int16_type;
5592 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5593 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5595 ninsts = 0;
5596 insts [ninsts ++] = sbyte_type;
5597 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5598 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5600 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5601 ninsts = 0;
5602 insts [ninsts ++] = int64_type;
5603 insts [ninsts ++] = uint64_type;
5604 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5607 /* Add instances of the array generic interfaces for primitive types */
5608 /* This will add instances of the InternalArray_ helper methods in Array too */
5609 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5610 if (klass)
5611 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5613 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5614 if (klass)
5615 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5617 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5618 if (klass)
5619 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5622 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5623 * used for all instances of GetGenericValueImpl by the AOT runtime.
5626 ERROR_DECL (error);
5627 MonoGenericContext ctx;
5628 MonoType *args [16];
5629 MonoMethod *get_method;
5630 MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
5632 get_method = mono_class_get_method_from_name_checked (array_klass, "GetGenericValueImpl", 2, 0, error);
5633 mono_error_assert_ok (error);
5635 if (get_method) {
5636 memset (&ctx, 0, sizeof (ctx));
5637 args [0] = object_type;
5638 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5639 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
5640 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5644 /* Same for CompareExchange<T>/Exchange<T> */
5646 MonoGenericContext ctx;
5647 MonoType *args [16];
5648 MonoMethod *m;
5649 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5650 gpointer iter = NULL;
5652 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5653 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5654 ERROR_DECL (error);
5655 memset (&ctx, 0, sizeof (ctx));
5656 args [0] = object_type;
5657 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5658 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5659 g_assert (is_ok (error)); /* FIXME don't swallow the error */
5664 /* object[] accessor wrappers. */
5665 for (i = 1; i < 4; ++i) {
5666 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
5667 MonoMethod *m;
5669 m = get_method_nofail (obj_array_class, "Get", i, 0);
5670 g_assert (m);
5672 m = mono_marshal_get_array_accessor_wrapper (m);
5673 add_extra_method (acfg, m);
5675 m = get_method_nofail (obj_array_class, "Address", i, 0);
5676 g_assert (m);
5678 m = mono_marshal_get_array_accessor_wrapper (m);
5679 add_extra_method (acfg, m);
5681 m = get_method_nofail (obj_array_class, "Set", i + 1, 0);
5682 g_assert (m);
5684 m = mono_marshal_get_array_accessor_wrapper (m);
5685 add_extra_method (acfg, m);
5690 static char *
5691 decode_direct_icall_symbol_name_attribute (MonoMethod *method)
5693 ERROR_DECL (error);
5695 int j = 0;
5696 char *symbol_name = NULL;
5698 MonoCustomAttrInfo *cattr = mono_custom_attrs_from_method_checked (method, error);
5699 if (is_ok(error) && cattr) {
5700 for (j = 0; j < cattr->num_attrs; j++)
5701 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoDirectICallSymbolNameAttribute"))
5702 break;
5704 if (j < cattr->num_attrs) {
5705 MonoCustomAttrEntry *e = &cattr->attrs [j];
5706 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
5707 if (e->data && sig && sig->param_count == 1 && sig->params [0]->type == MONO_TYPE_STRING) {
5709 * Decode the cattr manually since we can't create objects
5710 * during aot compilation.
5713 /* Skip prolog */
5714 const char *p = ((const char*)e->data) + 2;
5715 int slen = mono_metadata_decode_value (p, &p);
5717 symbol_name = (char *)g_memdup (p, slen + 1);
5718 if (symbol_name)
5719 symbol_name [slen] = 0;
5724 return symbol_name;
5726 static const char*
5727 lookup_external_icall_symbol_name_aot (MonoMethod *method)
5729 g_assert (method_to_external_icall_symbol_name);
5731 gpointer key, value;
5732 if (g_hash_table_lookup_extended (method_to_external_icall_symbol_name, method, &key, &value))
5733 return (const char*)value;
5735 char *symbol_name = decode_direct_icall_symbol_name_attribute (method);
5736 g_hash_table_insert (method_to_external_icall_symbol_name, method, symbol_name);
5738 return symbol_name;
5741 static const char*
5742 lookup_icall_symbol_name_aot (MonoMethod *method)
5744 const char * symbol_name = mono_lookup_icall_symbol (method);
5745 if (!symbol_name)
5746 symbol_name = lookup_external_icall_symbol_name_aot (method);
5748 return symbol_name;
5751 gboolean
5752 mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
5754 gboolean enable_icall = FALSE;
5755 if (cfg->compile_aot)
5756 enable_icall = lookup_external_icall_symbol_name_aot (method) ? TRUE : FALSE;
5757 else
5758 enable_icall = FALSE;
5760 return enable_icall;
5764 * is_direct_callable:
5766 * Return whenever the method identified by JI is directly callable without
5767 * going through the PLT.
5769 static gboolean
5770 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5772 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5773 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5774 if (callee_cfg) {
5775 gboolean direct_callable = TRUE;
5777 if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
5778 direct_callable = FALSE;
5780 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)))
5781 direct_callable = FALSE;
5783 if (direct_callable && !strcmp (callee_cfg->method->name, ".cctor"))
5784 direct_callable = FALSE;
5787 // FIXME: Support inflated methods, it asserts in mini_llvm_init_gshared_method_this () because the method is not in
5788 // amodule->extra_methods.
5790 if (direct_callable && callee_cfg->method->is_inflated)
5791 direct_callable = FALSE;
5793 if (direct_callable && (callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5794 // FIXME: Maybe call the wrapper directly ?
5795 direct_callable = FALSE;
5797 if (direct_callable && (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls)) {
5798 /* Disable this so all calls go through load_method (), see the
5799 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5800 * mono_debugger_agent_init ().
5802 direct_callable = FALSE;
5805 if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC))
5806 /* sgen does some initialization when the allocator method is created */
5807 direct_callable = FALSE;
5808 if (direct_callable && (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER))
5809 /* we don't know at compile time whether sgen is concurrent or not */
5810 direct_callable = FALSE;
5812 if (direct_callable)
5813 return TRUE;
5815 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5816 if (acfg->aot_opts.direct_pinvoke)
5817 return TRUE;
5818 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5819 if (acfg->aot_opts.direct_icalls)
5820 return TRUE;
5821 return FALSE;
5824 return FALSE;
5827 #ifdef MONO_ARCH_AOT_SUPPORTED
5828 static const char *
5829 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5831 MonoImage *image = m_class_get_image (method->klass);
5832 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5833 MonoTableInfo *tables = image->tables;
5834 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5835 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5836 guint32 im_cols [MONO_IMPLMAP_SIZE];
5837 char *import;
5839 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5840 if (import != NULL)
5841 return import;
5843 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5844 return NULL;
5846 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5848 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5849 return NULL;
5851 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5853 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5855 return import;
5857 #else
5858 static const char *
5859 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5861 return NULL;
5863 #endif
5865 static gint
5866 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5868 if (a->native_offset == b->native_offset)
5869 return a->il_offset - b->il_offset;
5870 else
5871 return a->native_offset - b->native_offset;
5875 * compute_line_numbers:
5877 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5878 * entry.
5880 static MonoDebugSourceLocation**
5881 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5883 MonoDebugMethodInfo *minfo;
5884 MonoDebugLineNumberEntry *ln_array;
5885 MonoDebugSourceLocation *loc;
5886 int i, prev_line, prev_il_offset;
5887 int *native_to_il_offset = NULL;
5888 MonoDebugSourceLocation **res;
5889 gboolean first;
5891 minfo = mono_debug_lookup_method (method);
5892 if (!minfo)
5893 return NULL;
5894 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5895 if (debug_info->code_size != code_size)
5896 return NULL;
5898 g_assert (code_size);
5900 /* Compute the native->IL offset mapping */
5902 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5903 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5905 mono_qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5907 native_to_il_offset = g_new0 (int, code_size + 1);
5909 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5910 int j;
5911 MonoDebugLineNumberEntry *lne = &ln_array [i];
5913 if (i == 0) {
5914 for (j = 0; j < lne->native_offset; ++j)
5915 native_to_il_offset [j] = -1;
5918 if (i < debug_info->num_line_numbers - 1) {
5919 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5921 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5922 native_to_il_offset [j] = lne->il_offset;
5923 } else {
5924 for (j = lne->native_offset; j < code_size; ++j)
5925 native_to_il_offset [j] = lne->il_offset;
5928 g_free (ln_array);
5930 /* Compute the native->line number mapping */
5931 res = g_new0 (MonoDebugSourceLocation*, code_size);
5932 prev_il_offset = -1;
5933 prev_line = -1;
5934 first = TRUE;
5935 for (i = 0; i < code_size; ++i) {
5936 int il_offset = native_to_il_offset [i];
5938 if (il_offset == -1 || il_offset == prev_il_offset)
5939 continue;
5940 prev_il_offset = il_offset;
5941 loc = mono_debug_method_lookup_location (minfo, il_offset);
5942 if (!(loc && loc->source_file))
5943 continue;
5944 if (loc->row == prev_line) {
5945 mono_debug_free_source_location (loc);
5946 continue;
5948 prev_line = loc->row;
5949 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5950 if (first)
5951 /* This will cover the prolog too */
5952 res [0] = loc;
5953 else
5954 res [i] = loc;
5955 first = FALSE;
5957 return res;
5960 static int
5961 get_file_index (MonoAotCompile *acfg, const char *source_file)
5963 int findex;
5965 // FIXME: Free these
5966 if (!acfg->dwarf_ln_filenames)
5967 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5968 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5969 if (!findex) {
5970 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5971 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5972 emit_unset_mode (acfg);
5973 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5975 return findex;
5978 #ifdef TARGET_ARM64
5979 #define INST_LEN 4
5980 #else
5981 #define INST_LEN 1
5982 #endif
5985 * emit_and_reloc_code:
5987 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5988 * is true, calls are made through the GOT too. This is used for emitting trampolines
5989 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5990 * since trampolines are needed to make PLT work.
5992 static void
5993 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5995 int i, pindex, start_index;
5996 GPtrArray *patches;
5997 MonoJumpInfo *patch_info;
5998 MonoDebugSourceLocation **locs = NULL;
5999 gboolean skip, prologue_end = FALSE;
6000 #ifdef MONO_ARCH_AOT_SUPPORTED
6001 gboolean direct_call, external_call;
6002 guint32 got_slot;
6003 const char *direct_call_target = 0;
6004 const char *direct_pinvoke;
6005 #endif
6007 if (acfg->gas_line_numbers && method && debug_info) {
6008 locs = compute_line_numbers (method, code_len, debug_info);
6009 if (!locs) {
6010 int findex = get_file_index (acfg, "<unknown>");
6011 emit_unset_mode (acfg);
6012 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
6016 /* Collect and sort relocations */
6017 patches = g_ptr_array_new ();
6018 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
6019 g_ptr_array_add (patches, patch_info);
6020 g_ptr_array_sort (patches, compare_patches);
6022 start_index = 0;
6023 for (i = 0; i < code_len; i += INST_LEN) {
6024 patch_info = NULL;
6025 for (pindex = start_index; pindex < patches->len; ++pindex) {
6026 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6027 if (patch_info->ip.i >= i)
6028 break;
6031 if (locs && locs [i]) {
6032 MonoDebugSourceLocation *loc = locs [i];
6033 int findex;
6034 const char *options;
6036 findex = get_file_index (acfg, loc->source_file);
6037 emit_unset_mode (acfg);
6038 if (!prologue_end)
6039 options = " prologue_end";
6040 else
6041 options = "";
6042 prologue_end = TRUE;
6043 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
6044 mono_debug_free_source_location (loc);
6047 skip = FALSE;
6048 #ifdef MONO_ARCH_AOT_SUPPORTED
6049 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
6050 start_index = pindex;
6052 switch (patch_info->type) {
6053 case MONO_PATCH_INFO_NONE:
6054 break;
6055 case MONO_PATCH_INFO_GOT_OFFSET: {
6056 int code_size;
6058 arch_emit_got_offset (acfg, code + i, &code_size);
6059 i += code_size - INST_LEN;
6060 skip = TRUE;
6061 patch_info->type = MONO_PATCH_INFO_NONE;
6062 break;
6064 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
6065 int code_size, index;
6066 char *selector = (char *)patch_info->data.target;
6068 if (!acfg->objc_selector_to_index)
6069 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
6070 if (!acfg->objc_selectors)
6071 acfg->objc_selectors = g_ptr_array_new ();
6072 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
6073 if (index)
6074 index --;
6075 else {
6076 index = acfg->objc_selector_index;
6077 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
6078 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
6079 acfg->objc_selector_index ++;
6082 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
6083 i += code_size - INST_LEN;
6084 skip = TRUE;
6085 patch_info->type = MONO_PATCH_INFO_NONE;
6086 break;
6088 default: {
6090 * If this patch is a call, try emitting a direct call instead of
6091 * through a PLT entry. This is possible if the called method is in
6092 * the same assembly and requires no initialization.
6094 direct_call = FALSE;
6095 external_call = FALSE;
6096 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
6097 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
6098 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
6100 // Don't compile inflated methods if we're doing dedup
6101 if (acfg->aot_opts.dedup && !mono_aot_can_dedup (patch_info->data.method)) {
6102 char *name = mono_aot_get_mangled_method_name (patch_info->data.method);
6103 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
6104 g_free (name);
6106 direct_call = TRUE;
6107 direct_call_target = callee_cfg->asm_symbol;
6108 patch_info->type = MONO_PATCH_INFO_NONE;
6109 acfg->stats.direct_calls ++;
6113 acfg->stats.all_calls ++;
6114 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
6115 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
6116 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
6117 direct_pinvoke = lookup_icall_symbol_name_aot (patch_info->data.method);
6118 else
6119 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
6120 if (direct_pinvoke) {
6121 direct_call = TRUE;
6122 g_assert (strlen (direct_pinvoke) < 1000);
6123 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
6126 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
6127 const char *sym = mono_find_jit_icall_info (patch_info->data.jit_icall_id)->c_symbol;
6128 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
6129 /* Call to a C function implementing a jit icall */
6130 direct_call = TRUE;
6131 external_call = TRUE;
6132 g_assert (strlen (sym) < 1000);
6133 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
6135 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ID) {
6136 MonoJitICallInfo * const info = mono_find_jit_icall_info (patch_info->data.jit_icall_id);
6137 const char * const sym = info->c_symbol;
6138 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
6139 /* Call to a jit icall without a wrapper */
6140 direct_call = TRUE;
6141 external_call = TRUE;
6142 g_assert (strlen (sym) < 1000);
6143 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
6146 if (direct_call) {
6147 patch_info->type = MONO_PATCH_INFO_NONE;
6148 acfg->stats.direct_calls ++;
6151 if (!got_only && !direct_call) {
6152 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
6153 if (plt_entry) {
6154 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
6155 direct_call = TRUE;
6156 direct_call_target = plt_entry->symbol;
6158 /* Nullify the patch */
6159 patch_info->type = MONO_PATCH_INFO_NONE;
6160 plt_entry->jit_used = TRUE;
6164 if (direct_call) {
6165 int call_size;
6167 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
6168 i += call_size - INST_LEN;
6169 } else {
6170 int code_size;
6172 got_slot = get_got_offset (acfg, FALSE, patch_info);
6174 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
6175 i += code_size - INST_LEN;
6177 skip = TRUE;
6181 #endif /* MONO_ARCH_AOT_SUPPORTED */
6183 if (!skip) {
6184 /* Find next patch */
6185 patch_info = NULL;
6186 for (pindex = start_index; pindex < patches->len; ++pindex) {
6187 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6188 if (patch_info->ip.i >= i)
6189 break;
6192 /* Try to emit multiple bytes at once */
6193 if (pindex < patches->len && patch_info->ip.i > i) {
6194 int limit;
6196 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
6197 if (locs && locs [limit])
6198 break;
6201 emit_code_bytes (acfg, code + i, limit - i);
6202 i = limit - INST_LEN;
6203 } else {
6204 emit_code_bytes (acfg, code + i, INST_LEN);
6209 g_ptr_array_free (patches, TRUE);
6210 g_free (locs);
6214 * sanitize_symbol:
6216 * Return a modified version of S which only includes characters permissible in symbols.
6218 static char*
6219 sanitize_symbol (MonoAotCompile *acfg, char *s)
6221 gboolean process = FALSE;
6222 int i, len;
6223 GString *gs;
6224 char *res;
6226 if (!s)
6227 return s;
6229 len = strlen (s);
6230 for (i = 0; i < len; ++i)
6231 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
6232 process = TRUE;
6233 if (!process)
6234 return s;
6236 gs = g_string_sized_new (len);
6237 for (i = 0; i < len; ++i) {
6238 guint8 c = s [i];
6239 if (c <= 0x7f && (isalnum (c) || c == '_')) {
6240 g_string_append_c (gs, c);
6241 } else if (c > 0x7f) {
6242 /* multi-byte utf8 */
6243 g_string_append_printf (gs, "_0x%x", c);
6244 i ++;
6245 c = s [i];
6246 while (c >> 6 == 0x2) {
6247 g_string_append_printf (gs, "%x", c);
6248 i ++;
6249 c = s [i];
6251 g_string_append_printf (gs, "_");
6252 i --;
6253 } else {
6254 g_string_append_c (gs, '_');
6258 res = mono_mempool_strdup (acfg->mempool, gs->str);
6259 g_string_free (gs, TRUE);
6260 return res;
6263 static char*
6264 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
6266 char *name1, *name2, *cached;
6267 int i, j, len, count;
6268 MonoMethod *cached_method;
6270 name1 = mono_method_full_name (method, TRUE);
6272 #ifdef TARGET_MACH
6273 // This is so that we don't accidentally create a local symbol (which starts with 'L')
6274 if ((!prefix || !*prefix) && name1 [0] == 'L')
6275 prefix = "_";
6276 #endif
6278 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6279 char adjustedPrefix [MAX_SYMBOL_SIZE];
6280 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
6281 #endif
6283 len = strlen (name1);
6284 name2 = (char *) g_malloc (strlen (prefix) + len + 16);
6285 memcpy (name2, prefix, strlen (prefix));
6286 j = strlen (prefix);
6287 for (i = 0; i < len; ++i) {
6288 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
6289 name2 [j ++] = '_';
6290 } else if (isalnum (name1 [i])) {
6291 name2 [j ++] = name1 [i];
6292 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
6293 i += 2;
6294 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
6295 name2 [j ++] = '_';
6296 i++;
6297 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
6298 } else
6299 name2 [j ++] = '_';
6301 name2 [j] = '\0';
6303 g_free (name1);
6305 count = 0;
6306 while (TRUE) {
6307 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
6308 if (!(cached_method && cached_method != method))
6309 break;
6310 sprintf (name2 + j, "_%d", count);
6311 count ++;
6314 cached = g_strdup (name2);
6315 g_hash_table_insert (cache, cached, method);
6317 return name2;
6320 static void
6321 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
6323 MonoMethod *method;
6324 int method_index;
6325 guint8 *code;
6326 char *debug_sym = NULL;
6327 char *symbol = NULL;
6328 int func_alignment = AOT_FUNC_ALIGNMENT;
6329 char *export_name;
6331 g_assert (!ignore_cfg (cfg));
6333 method = cfg->orig_method;
6334 code = cfg->native_code;
6336 method_index = get_method_index (acfg, method);
6337 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
6339 /* Make the labels local */
6340 emit_section_change (acfg, ".text", 0);
6341 emit_alignment_code (acfg, func_alignment);
6343 if (acfg->global_symbols && acfg->need_no_dead_strip)
6344 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
6346 emit_label (acfg, cfg->asm_symbol);
6348 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
6350 * Write a C style symbol for every method, this has two uses:
6351 * - it works on platforms where the dwarf debugging info is not
6352 * yet supported.
6353 * - it allows the setting of breakpoints of aot-ed methods.
6356 // Comment out to force dedup to link these symbols and forbid compiling
6357 // in duplicated code. This is an "assert when linking if broken" trick.
6358 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6359 /*debug_sym = mono_aot_get_mangled_method_name (method);*/
6360 /*else*/
6361 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
6363 cfg->asm_debug_symbol = g_strdup (debug_sym);
6365 if (acfg->need_no_dead_strip)
6366 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6368 // Comment out to force dedup to link these symbols and forbid compiling
6369 // in duplicated code. This is an "assert when linking if broken" trick.
6370 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6371 /*emit_global_inner (acfg, debug_sym, TRUE);*/
6372 /*else*/
6373 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
6375 emit_label (acfg, debug_sym);
6378 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
6379 if (export_name) {
6380 /* Emit a global symbol for the method */
6381 emit_global_inner (acfg, export_name, TRUE);
6382 emit_label (acfg, export_name);
6385 if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
6386 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
6388 acfg->stats.code_size += cfg->code_len;
6390 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
6392 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 ()));
6394 emit_line (acfg);
6396 if (acfg->aot_opts.write_symbols) {
6397 if (debug_sym)
6398 emit_symbol_size (acfg, debug_sym, ".");
6399 else
6400 emit_symbol_size (acfg, cfg->asm_symbol, ".");
6401 g_free (debug_sym);
6404 emit_label (acfg, symbol);
6406 arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
6408 g_free (symbol);
6412 * encode_patch:
6414 * Encode PATCH_INFO into its disk representation.
6416 static void
6417 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
6419 guint8 *p = buf;
6421 switch (patch_info->type) {
6422 case MONO_PATCH_INFO_NONE:
6423 break;
6424 case MONO_PATCH_INFO_IMAGE:
6425 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
6426 break;
6427 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
6428 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6429 case MONO_PATCH_INFO_GC_NURSERY_START:
6430 case MONO_PATCH_INFO_GC_NURSERY_BITS:
6431 break;
6432 case MONO_PATCH_INFO_SWITCH: {
6433 gpointer *table = (gpointer *)patch_info->data.table->table;
6434 int k;
6436 encode_value (patch_info->data.table->table_size, p, &p);
6437 for (k = 0; k < patch_info->data.table->table_size; k++)
6438 encode_value ((int)(gssize)table [k], p, &p);
6439 break;
6441 case MONO_PATCH_INFO_METHODCONST:
6442 case MONO_PATCH_INFO_METHOD:
6443 case MONO_PATCH_INFO_METHOD_JUMP:
6444 case MONO_PATCH_INFO_METHOD_FTNDESC:
6445 case MONO_PATCH_INFO_ICALL_ADDR:
6446 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
6447 case MONO_PATCH_INFO_METHOD_RGCTX:
6448 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
6449 encode_method_ref (acfg, patch_info->data.method, p, &p);
6450 break;
6451 case MONO_PATCH_INFO_AOT_JIT_INFO:
6452 case MONO_PATCH_INFO_CASTCLASS_CACHE:
6453 encode_value (patch_info->data.index, p, &p);
6454 break;
6455 case MONO_PATCH_INFO_JIT_ICALL_ID:
6456 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6457 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL:
6458 encode_value (patch_info->data.jit_icall_id, p, &p);
6459 break;
6460 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
6461 encode_value (patch_info->data.uindex, p, &p);
6462 break;
6463 case MONO_PATCH_INFO_LDSTR_LIT: {
6464 guint32 len = strlen (patch_info->data.name);
6465 encode_value (len, p, &p);
6466 memcpy (p, patch_info->data.name, len + 1);
6467 p += len + 1;
6468 break;
6470 case MONO_PATCH_INFO_LDSTR: {
6471 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
6472 guint32 token = patch_info->data.token->token;
6473 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
6474 encode_value (image_index, p, &p);
6475 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
6476 break;
6478 case MONO_PATCH_INFO_RVA:
6479 case MONO_PATCH_INFO_DECLSEC:
6480 case MONO_PATCH_INFO_LDTOKEN:
6481 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
6482 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
6483 encode_value (patch_info->data.token->token, p, &p);
6484 encode_value (patch_info->data.token->has_context, p, &p);
6485 if (patch_info->data.token->has_context)
6486 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
6487 break;
6488 case MONO_PATCH_INFO_EXC_NAME: {
6489 MonoClass *ex_class;
6491 ex_class =
6492 mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
6493 "System", (const char *)patch_info->data.target);
6494 encode_klass_ref (acfg, ex_class, p, &p);
6495 break;
6497 case MONO_PATCH_INFO_R4:
6498 encode_value (*((guint32 *)patch_info->data.target), p, &p);
6499 break;
6500 case MONO_PATCH_INFO_R8:
6501 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
6502 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
6503 break;
6504 case MONO_PATCH_INFO_VTABLE:
6505 case MONO_PATCH_INFO_CLASS:
6506 case MONO_PATCH_INFO_IID:
6507 case MONO_PATCH_INFO_ADJUSTED_IID:
6508 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
6509 break;
6510 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6511 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
6512 if (patch_info->data.del_tramp->method) {
6513 encode_value (1, p, &p);
6514 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
6515 } else {
6516 encode_value (0, p, &p);
6518 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
6519 break;
6520 case MONO_PATCH_INFO_FIELD:
6521 case MONO_PATCH_INFO_SFLDA:
6522 encode_field_info (acfg, patch_info->data.field, p, &p);
6523 break;
6524 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
6525 break;
6526 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
6527 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
6528 break;
6529 case MONO_PATCH_INFO_RGCTX_FETCH:
6530 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6531 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6532 guint32 offset;
6535 * entry->d.klass/method has a lenghtly encoding and multiple rgctx_fetch entries
6536 * reference the same klass/method, so encode it only once.
6537 * For patches which refer to got entries, this sharing is done by get_got_offset, but
6538 * these are not got entries.
6540 if (entry->in_mrgctx) {
6541 offset = get_shared_method_ref (acfg, entry->d.method);
6542 } else {
6543 offset = get_shared_klass_ref (acfg, entry->d.klass);
6546 encode_value (offset, p, &p);
6547 g_assert ((int)entry->info_type < 256);
6548 g_assert (entry->data->type < 256);
6549 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
6550 encode_patch (acfg, entry->data, p, &p);
6551 break;
6553 case MONO_PATCH_INFO_SEQ_POINT_INFO:
6554 case MONO_PATCH_INFO_AOT_MODULE:
6555 break;
6556 case MONO_PATCH_INFO_SIGNATURE:
6557 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
6558 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
6559 break;
6560 case MONO_PATCH_INFO_GSHAREDVT_CALL:
6561 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
6562 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
6563 break;
6564 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
6565 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
6566 int i;
6568 encode_method_ref (acfg, info->method, p, &p);
6569 encode_value (info->num_entries, p, &p);
6570 for (i = 0; i < info->num_entries; ++i) {
6571 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
6573 encode_value (template_->info_type, p, &p);
6574 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
6575 case MONO_PATCH_INFO_CLASS:
6576 encode_klass_ref (acfg, mono_class_from_mono_type_internal ((MonoType *)template_->data), p, &p);
6577 break;
6578 case MONO_PATCH_INFO_FIELD:
6579 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
6580 break;
6581 default:
6582 g_assert_not_reached ();
6583 break;
6586 break;
6588 case MONO_PATCH_INFO_VIRT_METHOD:
6589 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
6590 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
6591 break;
6592 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
6593 break;
6594 default:
6595 g_error ("unable to handle jump info %d", patch_info->type);
6598 *endbuf = p;
6601 static void
6602 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, guint8 *buf, guint8 **endbuf)
6604 guint8 *p = buf;
6605 guint32 pindex, offset;
6606 MonoJumpInfo *patch_info;
6608 encode_value (n_patches, p, &p);
6610 for (pindex = 0; pindex < patches->len; ++pindex) {
6611 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6613 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
6614 /* Nothing to do */
6615 continue;
6616 /* This shouldn't allocate a new offset */
6617 offset = lookup_got_offset (acfg, llvm, patch_info);
6618 encode_value (offset, p, &p);
6621 *endbuf = p;
6624 static void
6625 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6627 MonoMethod *method;
6628 int pindex, buf_size, n_patches;
6629 GPtrArray *patches;
6630 MonoJumpInfo *patch_info;
6631 guint8 *p, *buf;
6632 guint32 offset;
6633 gboolean needs_ctx = FALSE;
6635 method = cfg->orig_method;
6637 (void)get_method_index (acfg, method);
6639 /* Sort relocations */
6640 patches = g_ptr_array_new ();
6641 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6642 g_ptr_array_add (patches, patch_info);
6643 if (!acfg->aot_opts.llvm_only)
6644 g_ptr_array_sort (patches, compare_patches);
6646 /**********************/
6647 /* Encode method info */
6648 /**********************/
6650 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6652 guint32 *got_offsets = g_new0 (guint32, patches->len);
6654 n_patches = 0;
6655 for (pindex = 0; pindex < patches->len; ++pindex) {
6656 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6658 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6659 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6660 patch_info->type = MONO_PATCH_INFO_NONE;
6661 /* Nothing to do */
6662 continue;
6665 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6666 /* Stored in a GOT slot initialized at module load time */
6667 patch_info->type = MONO_PATCH_INFO_NONE;
6668 continue;
6671 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6672 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6673 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6674 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6675 /* Stored in a GOT slot initialized at module load time */
6676 patch_info->type = MONO_PATCH_INFO_NONE;
6677 continue;
6680 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6681 /* Calls are made through the PLT */
6682 patch_info->type = MONO_PATCH_INFO_NONE;
6683 continue;
6686 if (acfg->aot_opts.llvm_only && patch_info->type == MONO_PATCH_INFO_METHOD)
6687 needs_ctx = TRUE;
6689 /* This shouldn't allocate a new offset */
6690 offset = lookup_got_offset (acfg, cfg->compile_llvm, patch_info);
6691 if (offset >= acfg->nshared_got_entries)
6692 got_offsets [n_patches ++] = offset;
6695 if (n_patches)
6696 g_assert (cfg->has_got_slots);
6698 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6699 p = buf = (guint8 *)g_malloc (buf_size);
6701 MonoGenericContext *ctx = mono_method_get_context (cfg->method);
6703 guint8 flags = 0;
6704 if (mono_class_get_cctor (method->klass))
6705 flags |= MONO_AOT_METHOD_FLAG_HAS_CCTOR;
6706 if (mini_jit_info_is_gsharedvt (cfg->jit_info) && mini_is_gsharedvt_variable_signature (mono_method_signature_internal (jinfo_get_method (cfg->jit_info))))
6707 flags |= MONO_AOT_METHOD_FLAG_GSHAREDVT_VARIABLE;
6708 if (n_patches)
6709 flags |= MONO_AOT_METHOD_FLAG_HAS_PATCHES;
6710 if (needs_ctx && ctx)
6711 flags |= MONO_AOT_METHOD_FLAG_HAS_CTX;
6712 encode_value (flags, p, &p);
6713 if (flags & MONO_AOT_METHOD_FLAG_HAS_CCTOR)
6714 encode_klass_ref (acfg, method->klass, p, &p);
6715 if (needs_ctx && ctx)
6716 encode_generic_context (acfg, ctx, p, &p);
6718 if (n_patches) {
6719 encode_value (n_patches, p, &p);
6720 for (int i = 0; i < n_patches; ++i)
6721 encode_value (got_offsets [i], p, &p);
6724 g_ptr_array_free (patches, TRUE);
6725 g_free (got_offsets);
6727 acfg->stats.method_info_size += p - buf;
6729 g_assert (p - buf < buf_size);
6731 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6732 g_free (buf);
6735 static guint32
6736 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6738 guint32 cache_index;
6739 guint32 offset;
6741 /* Reuse the unwind module to canonize and store unwind info entries */
6742 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6744 /* Use +/- 1 to distinguish 0s from missing entries */
6745 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6746 if (offset)
6747 return offset - 1;
6748 else {
6749 guint8 buf [16];
6750 guint8 *p;
6753 * It would be easier to use assembler symbols, but the caller needs an
6754 * offset now.
6756 offset = acfg->unwind_info_offset;
6757 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6758 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6760 p = buf;
6761 encode_value (encoded_len, p, &p);
6763 acfg->unwind_info_offset += encoded_len + (p - buf);
6764 return offset;
6768 static void
6769 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6771 int i, k, buf_size;
6772 guint32 debug_info_size, seq_points_size;
6773 guint8 *code;
6774 MonoMethodHeader *header;
6775 guint8 *p, *buf, *debug_info;
6776 MonoJitInfo *jinfo = cfg->jit_info;
6777 guint32 flags;
6778 gboolean use_unwind_ops = FALSE;
6779 MonoSeqPointInfo *seq_points;
6781 code = cfg->native_code;
6782 header = cfg->header;
6784 if (!acfg->aot_opts.nodebug) {
6785 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6786 } else {
6787 debug_info = NULL;
6788 debug_info_size = 0;
6791 seq_points = cfg->seq_point_info;
6792 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6794 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6795 if (jinfo->has_try_block_holes) {
6796 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6797 buf_size += table->num_holes * 16;
6800 p = buf = (guint8 *)g_malloc (buf_size);
6802 use_unwind_ops = cfg->unwind_ops != NULL;
6804 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);
6806 encode_value (flags, p, &p);
6808 if (use_unwind_ops) {
6809 guint32 encoded_len;
6810 guint8 *encoded;
6811 guint32 unwind_desc;
6813 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6815 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6816 encode_value (unwind_desc, p, &p);
6818 g_free (encoded);
6819 } else {
6820 encode_value (jinfo->unwind_info, p, &p);
6823 /*Encode the number of holes before the number of clauses to make decoding easier*/
6824 if (jinfo->has_try_block_holes) {
6825 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6826 encode_value (table->num_holes, p, &p);
6829 if (jinfo->has_arch_eh_info) {
6831 * In AOT mode, the code length is calculated from the address of the previous method,
6832 * which could include alignment padding, so calculating the start of the epilog as
6833 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6835 encode_value (jinfo->code_size, p, &p);
6838 /* Exception table */
6839 if (cfg->compile_llvm) {
6841 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6842 * since the information is only available to llc. Instead, we let llc save the data
6843 * into the LSDA, and read it from there at runtime.
6845 /* The assembly might be CIL stripped so emit the data ourselves */
6846 if (header->num_clauses)
6847 encode_value (header->num_clauses, p, &p);
6849 for (k = 0; k < header->num_clauses; ++k) {
6850 MonoExceptionClause *clause;
6852 clause = &header->clauses [k];
6854 encode_value (clause->flags, p, &p);
6855 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6856 if (clause->data.catch_class) {
6857 guint8 *buf2, *p2;
6858 int len;
6860 buf2 = (guint8 *)g_malloc (4096);
6861 p2 = buf2;
6862 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6863 len = p2 - buf2;
6864 g_assert (len < 4096);
6865 encode_value (len, p, &p);
6866 memcpy (p, buf2, len);
6867 p += p2 - buf2;
6868 g_free (buf2);
6869 } else {
6870 encode_value (0, p, &p);
6874 /* Emit the IL ranges too, since they might not be available at runtime */
6875 encode_value (clause->try_offset, p, &p);
6876 encode_value (clause->try_len, p, &p);
6877 encode_value (clause->handler_offset, p, &p);
6878 encode_value (clause->handler_len, p, &p);
6880 /* Emit a list of nesting clauses */
6881 for (i = 0; i < header->num_clauses; ++i) {
6882 gint32 cindex1 = k;
6883 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6884 gint32 cindex2 = i;
6885 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6887 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6888 encode_value (i, p, &p);
6890 encode_value (-1, p, &p);
6892 } else {
6893 if (jinfo->num_clauses)
6894 encode_value (jinfo->num_clauses, p, &p);
6896 for (k = 0; k < jinfo->num_clauses; ++k) {
6897 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6899 encode_value (ei->flags, p, &p);
6900 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6901 /* Not used for catch clauses */
6902 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6903 encode_value (ei->exvar_offset, p, &p);
6904 #else
6905 encode_value (ei->exvar_offset, p, &p);
6906 #endif
6908 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6909 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6910 else {
6911 if (ei->data.catch_class) {
6912 guint8 *buf2, *p2;
6913 int len;
6915 buf2 = (guint8 *)g_malloc (4096);
6916 p2 = buf2;
6917 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6918 len = p2 - buf2;
6919 g_assert (len < 4096);
6920 encode_value (len, p, &p);
6921 memcpy (p, buf2, len);
6922 p += p2 - buf2;
6923 g_free (buf2);
6924 } else {
6925 encode_value (0, p, &p);
6929 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6930 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6931 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6935 if (jinfo->has_try_block_holes) {
6936 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6937 for (i = 0; i < table->num_holes; ++i) {
6938 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6939 encode_value (hole->clause, p, &p);
6940 encode_value (hole->length, p, &p);
6941 encode_value (hole->offset, p, &p);
6945 if (jinfo->has_arch_eh_info) {
6946 MonoArchEHJitInfo *eh_info;
6948 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6949 encode_value (eh_info->stack_size, p, &p);
6950 encode_value (eh_info->epilog_size, p, &p);
6953 if (jinfo->has_generic_jit_info) {
6954 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6955 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6956 guint8 *buf2, *p2;
6957 int len;
6959 encode_value (gi->nlocs, p, &p);
6960 if (gi->nlocs) {
6961 for (i = 0; i < gi->nlocs; ++i) {
6962 MonoDwarfLocListEntry *entry = &gi->locations [i];
6964 encode_value (entry->is_reg ? 1 : 0, p, &p);
6965 encode_value (entry->reg, p, &p);
6966 if (!entry->is_reg)
6967 encode_value (entry->offset, p, &p);
6968 if (i == 0)
6969 g_assert (entry->from == 0);
6970 else
6971 encode_value (entry->from, p, &p);
6972 encode_value (entry->to, p, &p);
6974 } else {
6975 if (!cfg->compile_llvm) {
6976 encode_value (gi->has_this ? 1 : 0, p, &p);
6977 encode_value (gi->this_reg, p, &p);
6978 encode_value (gi->this_offset, p, &p);
6983 * Need to encode jinfo->method too, since it is not equal to 'method'
6984 * when using generic sharing.
6986 buf2 = (guint8 *)g_malloc (4096);
6987 p2 = buf2;
6988 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6989 len = p2 - buf2;
6990 g_assert (len < 4096);
6991 encode_value (len, p, &p);
6992 memcpy (p, buf2, len);
6993 p += p2 - buf2;
6994 g_free (buf2);
6996 if (gsctx && gsctx->is_gsharedvt) {
6997 encode_value (1, p, &p);
6998 } else {
6999 encode_value (0, p, &p);
7003 if (seq_points_size)
7004 p += mono_seq_point_info_write (seq_points, p);
7006 g_assert (debug_info_size < buf_size);
7008 encode_value (debug_info_size, p, &p);
7009 if (debug_info_size) {
7010 memcpy (p, debug_info, debug_info_size);
7011 p += debug_info_size;
7012 g_free (debug_info);
7015 /* GC Map */
7016 if (cfg->gc_map) {
7017 encode_value (cfg->gc_map_size, p, &p);
7018 /* The GC map requires 4 bytes of alignment */
7019 while ((gsize)p % 4)
7020 p ++;
7021 memcpy (p, cfg->gc_map, cfg->gc_map_size);
7022 p += cfg->gc_map_size;
7025 acfg->stats.ex_info_size += p - buf;
7027 g_assert (p - buf < buf_size);
7029 /* Emit info */
7030 /* The GC Map requires 4 byte alignment */
7031 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
7032 g_free (buf);
7035 static guint32
7036 emit_klass_info (MonoAotCompile *acfg, guint32 token)
7038 ERROR_DECL (error);
7039 MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
7040 guint8 *p, *buf;
7041 int i, buf_size, res;
7042 gboolean no_special_static, cant_encode;
7043 gpointer iter = NULL;
7045 if (!klass) {
7046 mono_error_cleanup (error);
7048 buf_size = 16;
7050 p = buf = (guint8 *)g_malloc (buf_size);
7052 /* Mark as unusable */
7053 encode_value (-1, p, &p);
7055 res = add_to_blob (acfg, buf, p - buf);
7056 g_free (buf);
7058 return res;
7061 buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
7062 p = buf = (guint8 *)g_malloc (buf_size);
7064 g_assert (klass);
7066 mono_class_init_internal (klass);
7068 mono_class_get_nested_types (klass, &iter);
7069 g_assert (m_class_is_nested_classes_inited (klass));
7071 mono_class_setup_vtable (klass);
7074 * Emit all the information which is required for creating vtables so
7075 * the runtime does not need to create the MonoMethod structures which
7076 * take up a lot of space.
7079 no_special_static = !mono_class_has_special_static_fields (klass);
7081 /* Check whenever we have enough info to encode the vtable */
7082 cant_encode = FALSE;
7083 MonoMethod **klass_vtable = m_class_get_vtable (klass);
7084 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
7085 MonoMethod *cm = klass_vtable [i];
7087 if (cm && mono_method_signature_internal (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
7088 cant_encode = TRUE;
7091 mono_class_has_finalizer (klass);
7092 if (mono_class_has_failure (klass))
7093 cant_encode = TRUE;
7095 if (mono_class_is_gtd (klass) || cant_encode) {
7096 encode_value (-1, p, &p);
7097 } else {
7098 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
7099 encode_value (m_class_get_vtable_size (klass), p, &p);
7100 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);
7101 if (m_class_has_cctor (klass))
7102 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
7103 if (m_class_has_finalize (klass))
7104 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
7106 encode_value (m_class_get_instance_size (klass), p, &p);
7107 encode_value (mono_class_data_size (klass), p, &p);
7108 encode_value (m_class_get_packing_size (klass), p, &p);
7109 encode_value (m_class_get_min_align (klass), p, &p);
7111 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
7112 MonoMethod *cm = klass_vtable [i];
7114 if (cm)
7115 encode_method_ref (acfg, cm, p, &p);
7116 else
7117 encode_value (0, p, &p);
7121 acfg->stats.class_info_size += p - buf;
7123 g_assert (p - buf < buf_size);
7124 res = add_to_blob (acfg, buf, p - buf);
7125 g_free (buf);
7127 return res;
7130 static char*
7131 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
7133 char *debug_sym = NULL;
7134 char *prefix;
7136 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
7137 /* Need to add a prefix to create unique symbols */
7138 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
7139 } else {
7140 #if defined(TARGET_WIN32) && defined(TARGET_X86)
7141 prefix = mangle_symbol_alloc ("plt_");
7142 #else
7143 prefix = g_strdup ("plt_");
7144 #endif
7147 switch (ji->type) {
7148 case MONO_PATCH_INFO_METHOD:
7149 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
7150 break;
7151 case MONO_PATCH_INFO_JIT_ICALL_ID:
7152 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
7153 break;
7154 case MONO_PATCH_INFO_RGCTX_FETCH:
7155 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
7156 break;
7157 case MONO_PATCH_INFO_ICALL_ADDR:
7158 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
7159 char *s = get_debug_sym (ji->data.method, "", cache);
7161 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
7162 g_free (s);
7163 break;
7165 case MONO_PATCH_INFO_SPECIFIC_TRAMPOLINE_LAZY_FETCH_ADDR:
7166 debug_sym = g_strdup_printf ("%s_jit_icall_native_specific_trampoline_lazy_fetch_%lu", prefix, (gulong)ji->data.uindex);
7167 break;
7168 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
7169 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, mono_find_jit_icall_info (ji->data.jit_icall_id)->name);
7170 break;
7171 default:
7172 break;
7175 g_free (prefix);
7177 return sanitize_symbol (acfg, debug_sym);
7181 * Calls made from AOTed code are routed through a table of jumps similar to the
7182 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
7183 * control to the AOT runtime through a trampoline.
7185 static void
7186 emit_plt (MonoAotCompile *acfg)
7188 int i;
7190 if (acfg->aot_opts.llvm_only) {
7191 g_assert (acfg->plt_offset == 1);
7192 return;
7195 emit_line (acfg);
7197 emit_section_change (acfg, ".text", 0);
7198 emit_alignment_code (acfg, 16);
7199 emit_info_symbol (acfg, "plt", TRUE);
7200 emit_label (acfg, acfg->plt_symbol);
7202 for (i = 0; i < acfg->plt_offset; ++i) {
7203 char *debug_sym = NULL;
7204 MonoPltEntry *plt_entry = NULL;
7206 if (i == 0)
7208 * The first plt entry is unused.
7210 continue;
7212 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7214 debug_sym = plt_entry->debug_sym;
7216 if (acfg->thumb_mixed && !plt_entry->jit_used)
7217 /* Emit only a thumb version */
7218 continue;
7220 /* Skip plt entries not actually called */
7221 if (!plt_entry->jit_used && !plt_entry->llvm_used)
7222 continue;
7224 if (acfg->llvm && !acfg->thumb_mixed) {
7225 emit_label (acfg, plt_entry->llvm_symbol);
7226 if (acfg->llvm) {
7227 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7228 #if defined(TARGET_MACH)
7229 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
7230 #endif
7234 if (debug_sym) {
7235 if (acfg->need_no_dead_strip) {
7236 emit_unset_mode (acfg);
7237 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7239 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7240 emit_label (acfg, debug_sym);
7243 emit_label (acfg, plt_entry->symbol);
7245 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
7247 if (debug_sym)
7248 emit_symbol_size (acfg, debug_sym, ".");
7251 if (acfg->thumb_mixed) {
7252 /* Make sure the ARM symbols don't alias the thumb ones */
7253 emit_zero_bytes (acfg, 16);
7256 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
7257 * code.
7259 for (i = 0; i < acfg->plt_offset; ++i) {
7260 char *debug_sym = NULL;
7261 MonoPltEntry *plt_entry = NULL;
7263 if (i == 0)
7264 continue;
7266 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7268 /* Skip plt entries not actually called by LLVM code */
7269 if (!plt_entry->llvm_used)
7270 continue;
7272 if (acfg->aot_opts.write_symbols) {
7273 if (plt_entry->debug_sym)
7274 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
7277 if (debug_sym) {
7278 #if defined(TARGET_MACH)
7279 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
7280 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7281 #endif
7282 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7283 emit_label (acfg, debug_sym);
7285 fprintf (acfg->fp, "\n.thumb_func\n");
7287 emit_label (acfg, plt_entry->llvm_symbol);
7289 if (acfg->llvm)
7290 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7292 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]);
7294 if (debug_sym) {
7295 emit_symbol_size (acfg, debug_sym, ".");
7296 g_free (debug_sym);
7301 emit_symbol_size (acfg, acfg->plt_symbol, ".");
7303 emit_info_symbol (acfg, "plt_end", TRUE);
7305 arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
7309 * emit_trampoline_full:
7311 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
7312 * create_jit_info_for_trampoline ().
7314 static G_GNUC_UNUSED void
7315 emit_trampoline_full (MonoAotCompile *acfg, MonoTrampInfo *info, gboolean emit_tinfo)
7317 char start_symbol [MAX_SYMBOL_SIZE];
7318 char end_symbol [MAX_SYMBOL_SIZE];
7319 char symbol [MAX_SYMBOL_SIZE];
7320 guint32 buf_size, info_offset;
7321 MonoJumpInfo *patch_info;
7322 guint8 *buf, *p;
7323 GPtrArray *patches;
7324 char *name;
7325 guint8 *code;
7326 guint32 code_size;
7327 MonoJumpInfo *ji;
7328 GSList *unwind_ops;
7330 g_assert (info);
7332 name = info->name;
7333 code = info->code;
7334 code_size = info->code_size;
7335 ji = info->ji;
7336 unwind_ops = info->unwind_ops;
7338 /* Emit code */
7340 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
7342 emit_section_change (acfg, ".text", 0);
7343 emit_global (acfg, start_symbol, TRUE);
7344 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7345 emit_label (acfg, start_symbol);
7347 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
7348 emit_label (acfg, symbol);
7351 * The code should access everything through the GOT, so we pass
7352 * TRUE here.
7354 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
7356 emit_symbol_size (acfg, start_symbol, ".");
7358 if (emit_tinfo) {
7359 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
7360 emit_label (acfg, end_symbol);
7363 /* Emit info */
7365 /* Sort relocations */
7366 patches = g_ptr_array_new ();
7367 for (patch_info = ji; patch_info; patch_info = patch_info->next)
7368 if (patch_info->type != MONO_PATCH_INFO_NONE)
7369 g_ptr_array_add (patches, patch_info);
7370 g_ptr_array_sort (patches, compare_patches);
7372 buf_size = patches->len * 128 + 128;
7373 buf = (guint8 *)g_malloc (buf_size);
7374 p = buf;
7376 encode_patch_list (acfg, patches, patches->len, FALSE, p, &p);
7377 g_assert (p - buf < buf_size);
7378 g_ptr_array_free (patches, TRUE);
7380 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
7382 info_offset = add_to_blob (acfg, buf, p - buf);
7384 emit_section_change (acfg, RODATA_SECT, 0);
7385 emit_global (acfg, symbol, FALSE);
7386 emit_label (acfg, symbol);
7388 emit_int32 (acfg, info_offset);
7390 if (emit_tinfo) {
7391 guint8 *encoded;
7392 guint32 encoded_len;
7393 guint32 uw_offset;
7396 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
7398 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
7399 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
7400 g_free (encoded);
7402 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
7403 emit_int32 (acfg, uw_offset);
7406 /* Emit debug info */
7407 if (unwind_ops) {
7408 char symbol2 [MAX_SYMBOL_SIZE];
7410 sprintf (symbol, "%s", name);
7411 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
7413 arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
7415 if (acfg->dwarf)
7416 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
7419 g_free (buf);
7422 static G_GNUC_UNUSED void
7423 emit_trampoline (MonoAotCompile *acfg, MonoTrampInfo *info)
7425 emit_trampoline_full (acfg, info, TRUE);
7428 static void
7429 emit_trampolines (MonoAotCompile *acfg)
7431 char symbol [MAX_SYMBOL_SIZE];
7432 char end_symbol [MAX_SYMBOL_SIZE];
7433 int i, tramp_got_offset;
7434 int ntype;
7435 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7436 int tramp_type;
7437 #endif
7439 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_interp (&acfg->aot_opts))
7440 return;
7441 if (acfg->aot_opts.llvm_only)
7442 return;
7444 g_assert (acfg->image->assembly);
7446 /* Currently, we emit most trampolines into the mscorlib AOT image. */
7447 if (mono_is_corlib_image(acfg->image->assembly->image)) {
7448 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7449 MonoTrampInfo *info;
7452 * Emit the generic trampolines.
7454 * We could save some code by treating the generic trampolines as a wrapper
7455 * method, but that approach has its own complexities, so we choose the simpler
7456 * method.
7458 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
7459 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
7460 #ifdef DISABLE_REMOTING
7461 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
7462 continue;
7463 #endif
7464 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
7465 emit_trampoline (acfg, info);
7466 mono_tramp_info_free (info);
7469 /* Emit the exception related code pieces */
7470 mono_arch_get_restore_context (&info, TRUE);
7471 emit_trampoline (acfg, info);
7472 mono_tramp_info_free (info);
7474 mono_arch_get_call_filter (&info, TRUE);
7475 emit_trampoline (acfg, info);
7476 mono_tramp_info_free (info);
7478 mono_arch_get_throw_exception (&info, TRUE);
7479 emit_trampoline (acfg, info);
7480 mono_tramp_info_free (info);
7482 mono_arch_get_rethrow_exception (&info, TRUE);
7483 emit_trampoline (acfg, info);
7484 mono_tramp_info_free (info);
7486 mono_arch_get_rethrow_preserve_exception (&info, TRUE);
7487 emit_trampoline (acfg, info);
7488 mono_tramp_info_free (info);
7490 mono_arch_get_throw_corlib_exception (&info, TRUE);
7491 emit_trampoline (acfg, info);
7492 mono_tramp_info_free (info);
7494 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
7495 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
7496 emit_trampoline (acfg, info);
7497 mono_tramp_info_free (info);
7499 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
7500 emit_trampoline (acfg, info);
7501 mono_tramp_info_free (info);
7502 #endif
7504 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
7505 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
7506 if (info) {
7507 emit_trampoline_full (acfg, info, TRUE);
7509 /* Create a separate out trampoline for more information in stack traces */
7510 info->name = g_strdup ("gsharedvt_out_trampoline");
7511 emit_trampoline_full (acfg, info, TRUE);
7512 mono_tramp_info_free (info);
7514 #endif
7516 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
7518 GSList *l = mono_arch_get_trampolines (TRUE);
7520 while (l) {
7521 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7523 emit_trampoline (acfg, info);
7524 l = l->next;
7527 #endif
7529 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
7530 int offset;
7532 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
7533 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7534 emit_trampoline (acfg, info);
7535 mono_tramp_info_free (info);
7537 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
7538 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7539 emit_trampoline (acfg, info);
7540 mono_tramp_info_free (info);
7543 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
7544 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
7545 emit_trampoline (acfg, info);
7546 mono_tramp_info_free (info);
7547 #endif
7550 GSList *l;
7552 /* delegate_invoke_impl trampolines */
7553 l = mono_arch_get_delegate_invoke_impls ();
7554 while (l) {
7555 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7557 emit_trampoline (acfg, info);
7558 l = l->next;
7562 if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
7563 mono_arch_get_interp_to_native_trampoline (&info);
7564 emit_trampoline (acfg, info);
7566 #ifdef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
7567 mono_arch_get_native_to_interp_trampoline (&info);
7568 emit_trampoline (acfg, info);
7569 #endif
7572 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
7574 /* Emit trampolines which are numerous */
7577 * These include the following:
7578 * - specific trampolines
7579 * - static rgctx invoke trampolines
7580 * - imt trampolines
7581 * These trampolines have the same code, they are parameterized by GOT
7582 * slots.
7583 * They are defined in this file, in the arch_... routines instead of
7584 * in tramp-<ARCH>.c, since it is easier to do it this way.
7588 * When running in aot-only mode, we can't create specific trampolines at
7589 * runtime, so we create a few, and save them in the AOT file.
7590 * Normal trampolines embed their argument as a literal inside the
7591 * trampoline code, we can't do that here, so instead we embed an offset
7592 * which needs to be added to the trampoline address to get the address of
7593 * the GOT slot which contains the argument value.
7594 * The generated trampolines jump to the generic trampolines using another
7595 * GOT slot, which will be setup by the AOT loader to point to the
7596 * generic trampoline code of the given type.
7600 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
7601 * each class).
7604 emit_section_change (acfg, ".text", 0);
7606 tramp_got_offset = acfg->got_offset;
7608 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
7609 switch (ntype) {
7610 case MONO_AOT_TRAMP_SPECIFIC:
7611 sprintf (symbol, "specific_trampolines");
7612 break;
7613 case MONO_AOT_TRAMP_STATIC_RGCTX:
7614 sprintf (symbol, "static_rgctx_trampolines");
7615 break;
7616 case MONO_AOT_TRAMP_IMT:
7617 sprintf (symbol, "imt_trampolines");
7618 break;
7619 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7620 sprintf (symbol, "gsharedvt_arg_trampolines");
7621 break;
7622 case MONO_AOT_TRAMP_FTNPTR_ARG:
7623 sprintf (symbol, "ftnptr_arg_trampolines");
7624 break;
7625 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7626 sprintf (symbol, "unbox_arbitrary_trampolines");
7627 break;
7628 default:
7629 g_assert_not_reached ();
7632 sprintf (end_symbol, "%s_e", symbol);
7634 if (acfg->aot_opts.write_symbols)
7635 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
7637 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7638 emit_info_symbol (acfg, symbol, TRUE);
7640 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
7642 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
7643 int tramp_size = 0;
7645 switch (ntype) {
7646 case MONO_AOT_TRAMP_SPECIFIC:
7647 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
7648 tramp_got_offset += 2;
7649 break;
7650 case MONO_AOT_TRAMP_STATIC_RGCTX:
7651 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
7652 tramp_got_offset += 2;
7653 break;
7654 case MONO_AOT_TRAMP_IMT:
7655 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
7656 tramp_got_offset += 1;
7657 break;
7658 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7659 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7660 tramp_got_offset += 2;
7661 break;
7662 case MONO_AOT_TRAMP_FTNPTR_ARG:
7663 arch_emit_ftnptr_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7664 tramp_got_offset += 2;
7665 break;
7666 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7667 arch_emit_unbox_arbitrary_trampoline (acfg, tramp_got_offset, &tramp_size);
7668 tramp_got_offset += 1;
7669 break;
7670 default:
7671 g_assert_not_reached ();
7673 if (!acfg->trampoline_size [ntype]) {
7674 g_assert (tramp_size);
7675 acfg->trampoline_size [ntype] = tramp_size;
7679 emit_label (acfg, end_symbol);
7680 emit_int32 (acfg, 0);
7683 arch_emit_specific_trampoline_pages (acfg);
7685 /* Reserve some entries at the end of the GOT for our use */
7686 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
7689 acfg->got_offset += acfg->num_trampoline_got_entries;
7692 static gboolean
7693 str_begins_with (const char *str1, const char *str2)
7695 int len = strlen (str2);
7696 return strncmp (str1, str2, len) == 0;
7699 void*
7700 mono_aot_readonly_field_override (MonoClassField *field)
7702 ReadOnlyValue *rdv;
7703 for (rdv = readonly_values; rdv; rdv = rdv->next) {
7704 char *p = rdv->name;
7705 int len;
7706 len = strlen (m_class_get_name_space (field->parent));
7707 if (strncmp (p, m_class_get_name_space (field->parent), len))
7708 continue;
7709 p += len;
7710 if (*p++ != '.')
7711 continue;
7712 len = strlen (m_class_get_name (field->parent));
7713 if (strncmp (p, m_class_get_name (field->parent), len))
7714 continue;
7715 p += len;
7716 if (*p++ != '.')
7717 continue;
7718 if (strcmp (p, field->name))
7719 continue;
7720 switch (rdv->type) {
7721 case MONO_TYPE_I1:
7722 return &rdv->value.i1;
7723 case MONO_TYPE_I2:
7724 return &rdv->value.i2;
7725 case MONO_TYPE_I4:
7726 return &rdv->value.i4;
7727 default:
7728 break;
7731 return NULL;
7734 static void
7735 add_readonly_value (MonoAotOptions *opts, const char *val)
7737 ReadOnlyValue *rdv;
7738 const char *fval;
7739 const char *tval;
7740 /* the format of val is:
7741 * namespace.typename.fieldname=type/value
7742 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7744 fval = strrchr (val, '/');
7745 if (!fval) {
7746 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7747 exit (1);
7749 tval = strrchr (val, '=');
7750 if (!tval) {
7751 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7752 exit (1);
7754 rdv = g_new0 (ReadOnlyValue, 1);
7755 rdv->name = (char *)g_malloc0 (tval - val + 1);
7756 memcpy (rdv->name, val, tval - val);
7757 tval++;
7758 fval++;
7759 if (strncmp (tval, "i1", 2) == 0) {
7760 rdv->value.i1 = atoi (fval);
7761 rdv->type = MONO_TYPE_I1;
7762 } else if (strncmp (tval, "i2", 2) == 0) {
7763 rdv->value.i2 = atoi (fval);
7764 rdv->type = MONO_TYPE_I2;
7765 } else if (strncmp (tval, "i4", 2) == 0) {
7766 rdv->value.i4 = atoi (fval);
7767 rdv->type = MONO_TYPE_I4;
7768 } else {
7769 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7770 exit (1);
7772 rdv->next = readonly_values;
7773 readonly_values = rdv;
7776 static gchar *
7777 clean_path (gchar * path)
7779 if (!path)
7780 return NULL;
7782 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7783 return path;
7785 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, (const char*)NULL);
7786 g_free (path);
7788 return clean;
7791 static const gchar *
7792 wrap_path (const gchar * path)
7794 int len;
7795 if (!path)
7796 return NULL;
7798 // If the string contains no spaces, just return the original string.
7799 if (strstr (path, " ") == NULL)
7800 return path;
7802 // If the string is already wrapped in quotes, return it.
7803 len = strlen (path);
7804 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7805 return path;
7807 // If the string contains spaces, then wrap it in quotes.
7808 gchar *clean = g_strdup_printf ("\"%s\"", path);
7810 return clean;
7813 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7814 static void
7815 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7817 ptrdiff_t len = end-start;
7818 if (len > 0)
7819 g_ptr_array_add (args, g_strndup (start, len));
7822 static GPtrArray *
7823 mono_aot_split_options (const char *aot_options)
7825 enum MonoAotOptionState {
7826 MONO_AOT_OPTION_STATE_DEFAULT,
7827 MONO_AOT_OPTION_STATE_STRING,
7828 MONO_AOT_OPTION_STATE_ESCAPE,
7831 GPtrArray *args = g_ptr_array_new ();
7832 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7833 gchar const *opt_start = aot_options;
7834 gboolean end_of_string = FALSE;
7835 gchar cur;
7837 g_return_val_if_fail (aot_options != NULL, NULL);
7839 while ((cur = *aot_options) != '\0') {
7840 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7841 goto next;
7843 switch (cur) {
7844 case '"':
7845 // If we find a quote, then if we're in the default case then
7846 // it means we've found the start of a string, if not then it
7847 // means we've found the end of the string and should switch
7848 // back to the default case.
7849 switch (state) {
7850 case MONO_AOT_OPTION_STATE_DEFAULT:
7851 state = MONO_AOT_OPTION_STATE_STRING;
7852 break;
7853 case MONO_AOT_OPTION_STATE_STRING:
7854 state = MONO_AOT_OPTION_STATE_DEFAULT;
7855 break;
7856 case MONO_AOT_OPTION_STATE_ESCAPE:
7857 g_assert_not_reached ();
7858 break;
7860 break;
7861 case '\\':
7862 // If we've found an escaping operator, then this means we
7863 // should not process the next character if inside a string.
7864 if (state == MONO_AOT_OPTION_STATE_STRING)
7865 state = MONO_AOT_OPTION_STATE_ESCAPE;
7866 break;
7867 case ',':
7868 // If we're in the default state then this means we've found
7869 // an option, store it for later processing.
7870 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7871 goto new_opt;
7872 break;
7875 next:
7876 aot_options++;
7877 restart:
7878 // If the next character is end of string, then process the last option.
7879 if (*(aot_options) == '\0') {
7880 end_of_string = TRUE;
7881 goto new_opt;
7883 continue;
7885 new_opt:
7886 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7887 opt_start = ++aot_options;
7888 if (end_of_string)
7889 break;
7890 goto restart; // Check for null and continue loop
7893 return args;
7896 static void
7897 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7899 GPtrArray* args;
7901 args = mono_aot_split_options (aot_options ? aot_options : "");
7902 for (int i = 0; i < args->len; ++i) {
7903 const char *arg = (const char *)g_ptr_array_index (args, i);
7905 if (str_begins_with (arg, "outfile=")) {
7906 opts->outfile = g_strdup (arg + strlen ("outfile="));
7907 } else if (str_begins_with (arg, "llvm-outfile=")) {
7908 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7909 } else if (str_begins_with (arg, "temp-path=")) {
7910 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7911 } else if (str_begins_with (arg, "save-temps")) {
7912 opts->save_temps = TRUE;
7913 } else if (str_begins_with (arg, "keep-temps")) {
7914 opts->save_temps = TRUE;
7915 } else if (str_begins_with (arg, "write-symbols")) {
7916 opts->write_symbols = TRUE;
7917 } else if (str_begins_with (arg, "no-write-symbols")) {
7918 opts->write_symbols = FALSE;
7919 // Intentionally undocumented -- one-off experiment
7920 } else if (str_begins_with (arg, "metadata-only")) {
7921 opts->metadata_only = TRUE;
7922 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7923 opts->bind_to_runtime_version = TRUE;
7924 } else if (str_begins_with (arg, "full")) {
7925 opts->mode = MONO_AOT_MODE_FULL;
7926 } else if (str_begins_with (arg, "hybrid")) {
7927 opts->mode = MONO_AOT_MODE_HYBRID;
7928 } else if (str_begins_with (arg, "interp")) {
7929 opts->interp = TRUE;
7930 } else if (str_begins_with (arg, "threads=")) {
7931 opts->nthreads = atoi (arg + strlen ("threads="));
7932 } else if (str_begins_with (arg, "static")) {
7933 opts->static_link = TRUE;
7934 opts->no_dlsym = TRUE;
7935 } else if (str_begins_with (arg, "asmonly")) {
7936 opts->asm_only = TRUE;
7937 } else if (str_begins_with (arg, "asmwriter")) {
7938 opts->asm_writer = TRUE;
7939 } else if (str_begins_with (arg, "nodebug")) {
7940 opts->nodebug = TRUE;
7941 } else if (str_begins_with (arg, "dwarfdebug")) {
7942 opts->dwarf_debug = TRUE;
7943 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7944 } else if (str_begins_with (arg, "nopagetrampolines")) {
7945 opts->use_trampolines_page = FALSE;
7946 } else if (str_begins_with (arg, "ntrampolines=")) {
7947 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7948 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7949 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7950 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7951 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7952 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7953 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7954 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7955 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7956 } else if (str_begins_with (arg, "nftnptr-arg-trampolines=")) {
7957 opts->nftnptr_arg_trampolines = atoi (arg + strlen ("nftnptr-arg-trampolines="));
7958 } else if (str_begins_with (arg, "nunbox-arbitrary-trampolines=")) {
7959 opts->nunbox_arbitrary_trampolines = atoi (arg + strlen ("unbox-arbitrary-trampolines="));
7960 } else if (str_begins_with (arg, "tool-prefix=")) {
7961 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7962 } else if (str_begins_with (arg, "ld-flags=")) {
7963 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7964 } else if (str_begins_with (arg, "soft-debug")) {
7965 opts->soft_debug = TRUE;
7966 // Intentionally undocumented x2-- deprecated
7967 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7968 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7969 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7970 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7971 } else if (str_begins_with (arg, "msym-dir=")) {
7972 mini_debug_options.no_seq_points_compact_data = FALSE;
7973 opts->gen_msym_dir = TRUE;
7974 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));
7975 } else if (str_begins_with (arg, "direct-pinvoke")) {
7976 opts->direct_pinvoke = TRUE;
7977 } else if (str_begins_with (arg, "direct-icalls")) {
7978 opts->direct_icalls = TRUE;
7979 } else if (str_begins_with (arg, "no-direct-calls")) {
7980 opts->no_direct_calls = TRUE;
7981 } else if (str_begins_with (arg, "print-skipped")) {
7982 opts->print_skipped_methods = TRUE;
7983 } else if (str_begins_with (arg, "stats")) {
7984 opts->stats = TRUE;
7985 // Intentionally undocumented-- has no known function other than to debug the compiler
7986 } else if (str_begins_with (arg, "no-instances")) {
7987 opts->no_instances = TRUE;
7988 // Intentionally undocumented x4-- Used for internal debugging of compiler
7989 } else if (str_begins_with (arg, "log-generics")) {
7990 opts->log_generics = TRUE;
7991 } else if (str_begins_with (arg, "log-instances=")) {
7992 opts->log_instances = TRUE;
7993 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7994 } else if (str_begins_with (arg, "log-instances")) {
7995 opts->log_instances = TRUE;
7996 } else if (str_begins_with (arg, "internal-logfile=")) {
7997 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7998 } else if (str_begins_with (arg, "dedup-skip")) {
7999 opts->dedup = TRUE;
8000 } else if (str_begins_with (arg, "dedup-include=")) {
8001 opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
8002 } else if (str_begins_with (arg, "mtriple=")) {
8003 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
8004 } else if (str_begins_with (arg, "llvm-path=")) {
8005 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
8006 } else if (!strcmp (arg, "try-llvm")) {
8007 // If we can load LLVM, use it
8008 // Note: if you call this function from anywhere but mono_compile_assembly,
8009 // this will only set the try_llvm attribute and not do the probing / set the
8010 // attribute.
8011 opts->try_llvm = TRUE;
8012 } else if (!strcmp (arg, "llvm")) {
8013 opts->llvm = TRUE;
8014 } else if (str_begins_with (arg, "readonly-value=")) {
8015 add_readonly_value (opts, arg + strlen ("readonly-value="));
8016 } else if (str_begins_with (arg, "info")) {
8017 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
8018 exit (0);
8019 // Intentionally undocumented: Used for precise stack maps, which are not available yet
8020 } else if (str_begins_with (arg, "gc-maps")) {
8021 mini_gc_enable_gc_maps_for_aot ();
8022 // Intentionally undocumented: Used for internal debugging
8023 } else if (str_begins_with (arg, "dump")) {
8024 opts->dump_json = TRUE;
8025 } else if (str_begins_with (arg, "llvmonly")) {
8026 opts->mode = MONO_AOT_MODE_FULL;
8027 opts->llvm = TRUE;
8028 opts->llvm_only = TRUE;
8029 } else if (str_begins_with (arg, "data-outfile=")) {
8030 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
8031 } else if (str_begins_with (arg, "profile=")) {
8032 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
8033 } else if (!strcmp (arg, "profile-only")) {
8034 opts->profile_only = TRUE;
8035 } else if (!strcmp (arg, "verbose")) {
8036 opts->verbose = TRUE;
8037 } else if (str_begins_with (arg, "llvmopts=")){
8038 if (opts->llvm_opts) {
8039 char *s = g_strdup_printf ("%s %s", opts->llvm_opts, arg + strlen ("llvmopts="));
8040 g_free (opts->llvm_opts);
8041 opts->llvm_opts = s;
8042 } else {
8043 opts->llvm_opts = g_strdup (arg + strlen ("llvmopts="));
8045 } else if (str_begins_with (arg, "llvmllc=")){
8046 opts->llvm_llc = g_strdup (arg + strlen ("llvmllc="));
8047 } else if (!strcmp (arg, "deterministic")) {
8048 opts->deterministic = TRUE;
8049 } else if (!strcmp (arg, "no-opt")) {
8050 opts->no_opt = TRUE;
8051 } else if (str_begins_with (arg, "clangxx=")) {
8052 opts->clangxx = g_strdup (arg + strlen ("clangxx="));
8053 } else if (str_begins_with (arg, "depfile=")) {
8054 opts->depfile = g_strdup (arg + strlen ("depfile="));
8055 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
8056 printf ("Supported options for --aot:\n");
8057 printf (" asmonly\n");
8058 printf (" bind-to-runtime-version\n");
8059 printf (" bitcode\n");
8060 printf (" data-outfile=\n");
8061 printf (" direct-icalls\n");
8062 printf (" direct-pinvoke\n");
8063 printf (" dwarfdebug\n");
8064 printf (" full\n");
8065 printf (" hybrid\n");
8066 printf (" info\n");
8067 printf (" keep-temps\n");
8068 printf (" llvm\n");
8069 printf (" llvmonly\n");
8070 printf (" llvm-outfile=\n");
8071 printf (" llvm-path=\n");
8072 printf (" msym-dir=\n");
8073 printf (" mtriple\n");
8074 printf (" nimt-trampolines=\n");
8075 printf (" nodebug\n");
8076 printf (" no-direct-calls\n");
8077 printf (" no-write-symbols\n");
8078 printf (" nrgctx-trampolines=\n");
8079 printf (" nrgctx-fetch-trampolines=\n");
8080 printf (" ngsharedvt-trampolines=\n");
8081 printf (" nftnptr-arg-trampolines=\n");
8082 printf (" nunbox-arbitrary-trampolines=\n");
8083 printf (" ntrampolines=\n");
8084 printf (" outfile=\n");
8085 printf (" profile=\n");
8086 printf (" profile-only\n");
8087 printf (" print-skipped-methods\n");
8088 printf (" readonly-value=\n");
8089 printf (" save-temps\n");
8090 printf (" soft-debug\n");
8091 printf (" static\n");
8092 printf (" stats\n");
8093 printf (" temp-path=\n");
8094 printf (" tool-prefix=\n");
8095 printf (" threads=\n");
8096 printf (" write-symbols\n");
8097 printf (" verbose\n");
8098 printf (" no-opt\n");
8099 printf (" llvmopts=\n");
8100 printf (" llvmllc=\n");
8101 printf (" clangxx=\n");
8102 printf (" depfile=\n");
8103 printf (" help/?\n");
8104 exit (0);
8105 } else {
8106 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
8107 exit (1);
8110 g_free ((gpointer) arg);
8113 if (opts->use_trampolines_page) {
8114 opts->ntrampolines = 0;
8115 opts->nrgctx_trampolines = 0;
8116 opts->nimt_trampolines = 0;
8117 opts->ngsharedvt_arg_trampolines = 0;
8118 opts->nftnptr_arg_trampolines = 0;
8119 opts->nunbox_arbitrary_trampolines = 0;
8122 g_ptr_array_free (args, /*free_seg=*/TRUE);
8125 static void
8126 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
8128 MonoMethod *method = (MonoMethod*)key;
8129 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
8130 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
8131 MonoJumpInfoToken *new_ji;
8133 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
8134 new_ji->image = ji->image;
8135 new_ji->token = ji->token;
8136 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
8139 static gboolean
8140 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
8142 if (m_class_get_type_token (klass))
8143 return TRUE;
8144 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))
8145 return TRUE;
8146 if (m_class_get_rank (klass))
8147 return can_encode_class (acfg, m_class_get_element_class (klass));
8148 return FALSE;
8151 static gboolean
8152 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
8154 if (method->wrapper_type) {
8155 switch (method->wrapper_type) {
8156 case MONO_WRAPPER_NONE:
8157 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8158 case MONO_WRAPPER_XDOMAIN_INVOKE:
8159 case MONO_WRAPPER_STFLD:
8160 case MONO_WRAPPER_LDFLD:
8161 case MONO_WRAPPER_LDFLDA:
8162 case MONO_WRAPPER_STELEMREF:
8163 case MONO_WRAPPER_PROXY_ISINST:
8164 case MONO_WRAPPER_ALLOC:
8165 case MONO_WRAPPER_REMOTING_INVOKE:
8166 case MONO_WRAPPER_OTHER:
8167 case MONO_WRAPPER_WRITE_BARRIER:
8168 case MONO_WRAPPER_DELEGATE_INVOKE:
8169 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8170 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8171 case MONO_WRAPPER_SYNCHRONIZED:
8172 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8173 break;
8174 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8175 case MONO_WRAPPER_CASTCLASS: {
8176 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8178 if (info)
8179 return TRUE;
8180 else
8181 return FALSE;
8182 break;
8184 default:
8185 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
8186 return FALSE;
8188 } else {
8189 if (!method->token) {
8190 /* The method is part of a constructed type like Int[,].Set (). */
8191 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
8192 if (m_class_get_rank (method->klass))
8193 return TRUE;
8194 return FALSE;
8198 return TRUE;
8201 static gboolean
8202 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
8204 switch (patch_info->type) {
8205 case MONO_PATCH_INFO_METHOD:
8206 case MONO_PATCH_INFO_METHOD_FTNDESC:
8207 case MONO_PATCH_INFO_METHODCONST:
8208 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
8209 MonoMethod *method = patch_info->data.method;
8211 return can_encode_method (acfg, method);
8213 case MONO_PATCH_INFO_VTABLE:
8214 case MONO_PATCH_INFO_CLASS:
8215 case MONO_PATCH_INFO_IID:
8216 case MONO_PATCH_INFO_ADJUSTED_IID:
8217 if (!can_encode_class (acfg, patch_info->data.klass)) {
8218 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
8219 return FALSE;
8221 break;
8222 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
8223 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
8224 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
8225 return FALSE;
8227 break;
8229 case MONO_PATCH_INFO_RGCTX_FETCH:
8230 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
8231 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
8233 if (entry->in_mrgctx) {
8234 if (!can_encode_method (acfg, entry->d.method))
8235 return FALSE;
8236 } else {
8237 if (!can_encode_class (acfg, entry->d.klass))
8238 return FALSE;
8240 if (!can_encode_patch (acfg, entry->data))
8241 return FALSE;
8242 break;
8244 default:
8245 break;
8248 return TRUE;
8251 static gboolean
8252 is_concrete_type (MonoType *t)
8254 MonoClass *klass;
8255 int i;
8257 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
8258 return FALSE;
8259 if (t->type == MONO_TYPE_GENERICINST) {
8260 MonoGenericContext *orig_ctx;
8261 MonoGenericInst *inst;
8262 MonoType *arg;
8264 if (!MONO_TYPE_ISSTRUCT (t))
8265 return TRUE;
8266 klass = mono_class_from_mono_type_internal (t);
8267 orig_ctx = &mono_class_get_generic_class (klass)->context;
8269 inst = orig_ctx->class_inst;
8270 if (inst) {
8271 for (i = 0; i < inst->type_argc; ++i) {
8272 arg = mini_get_underlying_type (inst->type_argv [i]);
8273 if (!is_concrete_type (arg))
8274 return FALSE;
8277 inst = orig_ctx->method_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;
8286 return TRUE;
8289 static MonoMethodSignature*
8290 get_concrete_sig (MonoMethodSignature *sig)
8292 gboolean concrete = TRUE;
8294 if (!sig->has_type_parameters)
8295 return sig;
8297 /* For signatures created during generic sharing, convert them to a concrete signature if possible */
8298 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
8299 int i;
8301 //printf ("%s\n", mono_signature_full_name (sig));
8303 if (sig->ret->byref)
8304 copy->ret = m_class_get_this_arg (mono_defaults.int_class);
8305 else
8306 copy->ret = mini_get_underlying_type (sig->ret);
8307 if (!is_concrete_type (copy->ret))
8308 concrete = FALSE;
8309 for (i = 0; i < sig->param_count; ++i) {
8310 if (sig->params [i]->byref) {
8311 MonoType *t = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->params [i]));
8312 t = mini_get_underlying_type (t);
8313 copy->params [i] = m_class_get_this_arg (mono_class_from_mono_type_internal (t));
8314 } else {
8315 copy->params [i] = mini_get_underlying_type (sig->params [i]);
8317 if (!is_concrete_type (copy->params [i]))
8318 concrete = FALSE;
8320 copy->has_type_parameters = 0;
8321 if (!concrete)
8322 return NULL;
8323 return copy;
8326 /* LOCKING: Assumes the loader lock is held */
8327 static void
8328 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
8330 MonoMethod *wrapper;
8331 gboolean add_in = gsharedvt_in;
8332 gboolean add_out = gsharedvt_out;
8334 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
8335 add_in = FALSE;
8336 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
8337 add_out = FALSE;
8339 if (!add_in && !add_out)
8340 return;
8342 if (mini_is_gsharedvt_variable_signature (sig))
8343 return;
8345 if (add_in)
8346 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
8347 if (add_out)
8348 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
8350 sig = get_concrete_sig (sig);
8351 if (!sig)
8352 return;
8353 //printf ("%s\n", mono_signature_full_name (sig));
8355 if (gsharedvt_in) {
8356 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
8357 add_extra_method (acfg, wrapper);
8359 if (gsharedvt_out) {
8360 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
8361 add_extra_method (acfg, wrapper);
8364 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
8365 if (interp_in) {
8366 wrapper = mini_get_interp_in_wrapper (sig);
8367 add_extra_method (acfg, wrapper);
8368 //printf ("X: %s\n", mono_method_full_name (wrapper, 1));
8370 #endif
8374 * compile_method:
8376 * AOT compile a given method.
8377 * This function might be called by multiple threads, so it must be thread-safe.
8379 static void
8380 compile_method (MonoAotCompile *acfg, MonoMethod *method)
8382 MonoCompile *cfg;
8383 MonoJumpInfo *patch_info;
8384 gboolean skip;
8385 int index, depth;
8386 MonoMethod *wrapped;
8387 gint64 jit_time_start;
8388 JitFlags flags;
8390 if (acfg->aot_opts.metadata_only)
8391 return;
8393 mono_acfg_lock (acfg);
8394 index = get_method_index (acfg, method);
8395 mono_acfg_unlock (acfg);
8397 /* fixme: maybe we can also precompile wrapper methods */
8398 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8399 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8400 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
8401 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
8402 return;
8405 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8406 return;
8408 wrapped = mono_marshal_method_from_wrapper (method);
8409 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
8410 // FIXME: The wrapper should be generic too, but it is not
8411 return;
8413 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
8414 return;
8416 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
8417 return;
8419 mono_atomic_inc_i32 (&acfg->stats.mcount);
8421 #if 0
8422 if (method->is_generic || mono_class_is_gtd (method->klass)) {
8423 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8424 return;
8426 #endif
8428 //acfg->aot_opts.print_skipped_methods = TRUE;
8431 * Since these methods are the only ones which are compiled with
8432 * AOT support, and they are not used by runtime startup/shutdown code,
8433 * the runtime will not see AOT methods during AOT compilation,so it
8434 * does not need to support them by creating a fake GOT etc.
8436 flags = JIT_FLAG_AOT;
8437 if (mono_aot_mode_is_full (&acfg->aot_opts))
8438 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
8439 if (acfg->llvm)
8440 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
8441 if (acfg->aot_opts.llvm_only)
8442 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
8443 if (acfg->aot_opts.no_direct_calls)
8444 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
8445 if (acfg->aot_opts.direct_pinvoke)
8446 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
8447 if (acfg->aot_opts.interp)
8448 flags = (JitFlags)(flags | JIT_FLAG_INTERP);
8450 jit_time_start = mono_time_track_start ();
8451 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
8452 mono_time_track_end (&mono_jit_stats.jit_time, jit_time_start);
8454 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
8455 if (acfg->aot_opts.print_skipped_methods)
8456 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
8457 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8458 return;
8460 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
8461 /* Some instances cannot be JITted due to constraints etc. */
8462 if (!method->is_inflated)
8463 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));
8464 /* Let the exception happen at runtime */
8465 return;
8468 if (cfg->disable_aot) {
8469 if (acfg->aot_opts.print_skipped_methods)
8470 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
8471 mono_atomic_inc_i32 (&acfg->stats.ocount);
8472 return;
8474 cfg->method_index = index;
8476 /* Nullify patches which need no aot processing */
8477 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8478 switch (patch_info->type) {
8479 case MONO_PATCH_INFO_LABEL:
8480 case MONO_PATCH_INFO_BB:
8481 patch_info->type = MONO_PATCH_INFO_NONE;
8482 break;
8483 default:
8484 break;
8488 /* Collect method->token associations from the cfg */
8489 mono_acfg_lock (acfg);
8490 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
8491 mono_acfg_unlock (acfg);
8492 g_hash_table_destroy (cfg->token_info_hash);
8493 cfg->token_info_hash = NULL;
8496 * Check for absolute addresses.
8498 skip = FALSE;
8499 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8500 switch (patch_info->type) {
8501 case MONO_PATCH_INFO_ABS:
8502 /* unable to handle this */
8503 skip = TRUE;
8504 break;
8505 default:
8506 break;
8510 if (skip) {
8511 if (acfg->aot_opts.print_skipped_methods)
8512 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
8513 mono_atomic_inc_i32 (&acfg->stats.abscount);
8514 return;
8517 /* Lock for the rest of the code */
8518 mono_acfg_lock (acfg);
8520 if (cfg->gsharedvt)
8521 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
8522 else if (cfg->gshared)
8523 acfg->stats.method_categories [METHOD_CAT_INST] ++;
8524 else if (cfg->method->wrapper_type)
8525 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
8526 else
8527 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
8530 * Check for methods/klasses we can't encode.
8532 skip = FALSE;
8533 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8534 if (!can_encode_patch (acfg, patch_info))
8535 skip = TRUE;
8538 if (skip) {
8539 if (acfg->aot_opts.print_skipped_methods)
8540 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
8541 acfg->stats.ocount++;
8542 mono_acfg_unlock (acfg);
8543 return;
8546 if (!cfg->compile_llvm)
8547 acfg->has_jitted_code = TRUE;
8549 if (method->is_inflated && acfg->aot_opts.log_instances) {
8550 if (acfg->instances_logfile)
8551 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8552 else
8553 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8556 /* Adds generic instances referenced by this method */
8558 * The depth is used to avoid infinite loops when generic virtual recursion is
8559 * encountered.
8561 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
8562 if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8563 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8564 switch (patch_info->type) {
8565 case MONO_PATCH_INFO_RGCTX_FETCH:
8566 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
8567 case MONO_PATCH_INFO_METHOD:
8568 case MONO_PATCH_INFO_METHOD_FTNDESC:
8569 case MONO_PATCH_INFO_METHOD_RGCTX: {
8570 MonoMethod *m = NULL;
8572 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
8573 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
8575 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE || e->info_type == MONO_RGCTX_INFO_METHOD_FTNDESC)
8576 m = e->data->data.method;
8577 } else {
8578 m = patch_info->data.method;
8581 if (!m)
8582 break;
8583 if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8584 if (!(mono_class_generic_sharing_enabled (m->klass) &&
8585 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
8586 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
8587 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8588 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
8589 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
8590 } else {
8591 add_extra_method_with_depth (acfg, m, depth + 1);
8592 add_types_from_method_header (acfg, m);
8595 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
8597 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
8598 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
8600 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
8601 add_extra_method_with_depth (acfg, m, depth + 1);
8603 break;
8605 case MONO_PATCH_INFO_VTABLE: {
8606 MonoClass *klass = patch_info->data.klass;
8608 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
8609 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
8610 break;
8612 case MONO_PATCH_INFO_SFLDA: {
8613 MonoClass *klass = patch_info->data.field->parent;
8615 /* The .cctor needs to run at runtime. */
8616 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))
8617 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
8618 break;
8620 default:
8621 break;
8626 /* Determine whenever the method has GOT slots */
8627 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8628 switch (patch_info->type) {
8629 case MONO_PATCH_INFO_GOT_OFFSET:
8630 case MONO_PATCH_INFO_NONE:
8631 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
8632 case MONO_PATCH_INFO_GC_NURSERY_START:
8633 case MONO_PATCH_INFO_GC_NURSERY_BITS:
8634 break;
8635 case MONO_PATCH_INFO_IMAGE:
8636 /* The assembly is stored in GOT slot 0 */
8637 if (patch_info->data.image != acfg->image)
8638 cfg->has_got_slots = TRUE;
8639 break;
8640 default:
8641 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
8642 cfg->has_got_slots = TRUE;
8643 break;
8647 if (!cfg->has_got_slots)
8648 mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
8650 /* Add gsharedvt wrappers for signatures used by the method */
8651 if (acfg->aot_opts.llvm_only) {
8652 GSList *l;
8654 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8655 /* These only need out wrappers */
8656 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, FALSE);
8658 for (l = cfg->signatures; l; l = l->next) {
8659 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8661 /* These only need in wrappers */
8662 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8665 for (l = cfg->interp_in_signatures; l; l = l->next) {
8666 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8668 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8670 } else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
8671 /* The interpreter uses these wrappers to call aot-ed code */
8672 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8673 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, TRUE);
8676 if (cfg->llvm_only)
8677 acfg->stats.llvm_count ++;
8680 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
8682 /* Make a copy of the patch info which is in the mempool */
8684 MonoJumpInfo *patches = NULL, *patches_end = NULL;
8686 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8687 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
8689 if (!patches)
8690 patches = new_patch_info;
8691 else
8692 patches_end->next = new_patch_info;
8693 patches_end = new_patch_info;
8695 cfg->patch_info = patches;
8697 /* Make a copy of the unwind info */
8699 GSList *l, *unwind_ops;
8700 MonoUnwindOp *op;
8702 unwind_ops = NULL;
8703 for (l = cfg->unwind_ops; l; l = l->next) {
8704 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
8705 memcpy (op, l->data, sizeof (MonoUnwindOp));
8706 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
8708 cfg->unwind_ops = g_slist_reverse (unwind_ops);
8710 /* Make a copy of the argument/local info */
8712 ERROR_DECL (error);
8713 MonoInst **args, **locals;
8714 MonoMethodSignature *sig;
8715 MonoMethodHeader *header;
8716 int i;
8718 sig = mono_method_signature_internal (method);
8719 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
8720 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
8721 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8722 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
8724 cfg->args = args;
8726 header = mono_method_get_header_checked (method, error);
8727 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8728 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
8729 for (i = 0; i < header->num_locals; ++i) {
8730 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8731 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
8733 mono_metadata_free_mh (header);
8734 cfg->locals = locals;
8737 /* Free some fields used by cfg to conserve memory */
8738 mono_empty_compile (cfg);
8740 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
8742 while (index >= acfg->cfgs_size) {
8743 MonoCompile **new_cfgs;
8744 int new_size;
8746 new_size = acfg->cfgs_size * 2;
8747 new_cfgs = g_new0 (MonoCompile*, new_size);
8748 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
8749 g_free (acfg->cfgs);
8750 acfg->cfgs = new_cfgs;
8751 acfg->cfgs_size = new_size;
8753 acfg->cfgs [index] = cfg;
8755 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
8757 /* Update global stats while holding a lock. */
8758 mono_update_jit_stats (cfg);
8761 if (cfg->orig_method->wrapper_type)
8762 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
8765 mono_acfg_unlock (acfg);
8767 mono_atomic_inc_i32 (&acfg->stats.ccount);
8770 static mono_thread_start_return_t WINAPI
8771 compile_thread_main (gpointer user_data)
8773 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
8774 GPtrArray *methods = ((GPtrArray **)user_data) [1];
8775 int i;
8777 mono_thread_set_name_constant_ignore_error (mono_thread_internal_current (), "AOT compiler", MonoSetThreadNameFlag_Permanent);
8779 for (i = 0; i < methods->len; ++i)
8780 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
8782 return 0;
8785 /* Used by the LLVM backend */
8786 guint32
8787 mono_aot_get_got_offset (MonoJumpInfo *ji)
8789 return get_got_offset (llvm_acfg, TRUE, ji);
8793 * mono_aot_is_shared_got_offset:
8795 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8796 * when the AOT image is loaded.
8798 gboolean
8799 mono_aot_is_shared_got_offset (int offset)
8801 return offset < llvm_acfg->nshared_got_entries;
8804 char*
8805 mono_aot_get_method_name (MonoCompile *cfg)
8807 MonoMethod *method = cfg->orig_method;
8809 /* Use the mangled name if possible */
8810 if (method->wrapper_type == MONO_WRAPPER_OTHER) {
8811 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8812 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8813 return mono_aot_get_mangled_method_name (method);
8816 if (llvm_acfg->aot_opts.static_link)
8817 /* Include the assembly name too to avoid duplicate symbol errors */
8818 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8819 else
8820 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8823 static gboolean
8824 append_mangled_type (GString *s, MonoType *t)
8826 if (t->byref)
8827 g_string_append_printf (s, "b");
8828 switch (t->type) {
8829 case MONO_TYPE_VOID:
8830 g_string_append_printf (s, "void");
8831 break;
8832 case MONO_TYPE_I1:
8833 g_string_append_printf (s, "i1");
8834 break;
8835 case MONO_TYPE_U1:
8836 g_string_append_printf (s, "u1");
8837 break;
8838 case MONO_TYPE_I2:
8839 g_string_append_printf (s, "i2");
8840 break;
8841 case MONO_TYPE_U2:
8842 g_string_append_printf (s, "u2");
8843 break;
8844 case MONO_TYPE_I4:
8845 g_string_append_printf (s, "i4");
8846 break;
8847 case MONO_TYPE_U4:
8848 g_string_append_printf (s, "u4");
8849 break;
8850 case MONO_TYPE_I8:
8851 g_string_append_printf (s, "i8");
8852 break;
8853 case MONO_TYPE_U8:
8854 g_string_append_printf (s, "u8");
8855 break;
8856 case MONO_TYPE_I:
8857 g_string_append_printf (s, "ii");
8858 break;
8859 case MONO_TYPE_U:
8860 g_string_append_printf (s, "ui");
8861 break;
8862 case MONO_TYPE_R4:
8863 g_string_append_printf (s, "fl");
8864 break;
8865 case MONO_TYPE_R8:
8866 g_string_append_printf (s, "do");
8867 break;
8868 case MONO_TYPE_OBJECT:
8869 g_string_append_printf (s, "obj");
8870 break;
8871 default: {
8872 char *fullname = mono_type_full_name (t);
8873 GString *temp;
8874 char *temps;
8875 int i, len;
8878 * Have to create a mangled name which is:
8879 * - a valid symbol
8880 * - unique
8882 temp = g_string_new ("");
8883 len = strlen (fullname);
8884 for (i = 0; i < len; ++i) {
8885 char c = fullname [i];
8886 if (isalnum (c)) {
8887 g_string_append_c (temp, c);
8888 } else if (c == '_') {
8889 g_string_append_c (temp, '_');
8890 g_string_append_c (temp, '_');
8891 } else {
8892 g_string_append_c (temp, '_');
8893 g_string_append_printf (temp, "%x", (int)c);
8896 temps = g_string_free (temp, FALSE);
8897 /* Include the length to avoid different length type names aliasing each other */
8898 g_string_append_printf (s, "cl%x_%s_", (int)strlen (temps), temps);
8899 g_free (temps);
8902 if (t->attrs)
8903 g_string_append_printf (s, "_attrs_%d", t->attrs);
8904 return TRUE;
8907 static gboolean
8908 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8910 int i;
8911 gboolean supported;
8913 if (sig->pinvoke)
8914 g_string_append_printf (s, "pinvoke_");
8915 supported = append_mangled_type (s, sig->ret);
8916 if (!supported)
8917 return FALSE;
8918 g_string_append_printf (s, "_");
8919 if (sig->hasthis)
8920 g_string_append_printf (s, "this_");
8921 for (i = 0; i < sig->param_count; ++i) {
8922 supported = append_mangled_type (s, sig->params [i]);
8923 if (!supported)
8924 return FALSE;
8927 return TRUE;
8930 static void
8931 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8933 const char *label;
8935 switch (wrapper_type) {
8936 case MONO_WRAPPER_REMOTING_INVOKE:
8937 label = "remoting_invoke";
8938 break;
8939 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8940 label = "remoting_invoke_check";
8941 break;
8942 case MONO_WRAPPER_XDOMAIN_INVOKE:
8943 label = "remoting_invoke_xdomain";
8944 break;
8945 case MONO_WRAPPER_PROXY_ISINST:
8946 label = "proxy_isinst";
8947 break;
8948 case MONO_WRAPPER_LDFLD:
8949 label = "ldfld";
8950 break;
8951 case MONO_WRAPPER_LDFLDA:
8952 label = "ldflda";
8953 break;
8954 case MONO_WRAPPER_STFLD:
8955 label = "stfld";
8956 break;
8957 case MONO_WRAPPER_ALLOC:
8958 label = "alloc";
8959 break;
8960 case MONO_WRAPPER_WRITE_BARRIER:
8961 label = "write_barrier";
8962 break;
8963 case MONO_WRAPPER_STELEMREF:
8964 label = "stelemref";
8965 break;
8966 case MONO_WRAPPER_OTHER:
8967 label = "unknown";
8968 break;
8969 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8970 label = "man2native";
8971 break;
8972 case MONO_WRAPPER_SYNCHRONIZED:
8973 label = "synch";
8974 break;
8975 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8976 label = "man2man";
8977 break;
8978 case MONO_WRAPPER_CASTCLASS:
8979 label = "castclass";
8980 break;
8981 case MONO_WRAPPER_RUNTIME_INVOKE:
8982 label = "run_invoke";
8983 break;
8984 case MONO_WRAPPER_DELEGATE_INVOKE:
8985 label = "del_inv";
8986 break;
8987 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8988 label = "del_beg_inv";
8989 break;
8990 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8991 label = "del_end_inv";
8992 break;
8993 case MONO_WRAPPER_NATIVE_TO_MANAGED:
8994 label = "native2man";
8995 break;
8996 default:
8997 g_assert_not_reached ();
9000 g_string_append_printf (s, "%s_", label);
9003 static void
9004 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
9006 const char *label;
9008 switch (subtype)
9010 case WRAPPER_SUBTYPE_NONE:
9011 return;
9012 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
9013 label = "elem_addr";
9014 break;
9015 case WRAPPER_SUBTYPE_STRING_CTOR:
9016 label = "str_ctor";
9017 break;
9018 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
9019 label = "virt_stelem";
9020 break;
9021 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
9022 label = "fast_mon_enter";
9023 break;
9024 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
9025 label = "fast_mon_enter_4";
9026 break;
9027 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
9028 label = "fast_monitor_exit";
9029 break;
9030 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
9031 label = "ptr2struct";
9032 break;
9033 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
9034 label = "struct2ptr";
9035 break;
9036 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
9037 label = "castclass_w_cache";
9038 break;
9039 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
9040 label = "isinst_w_cache";
9041 break;
9042 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
9043 label = "run_inv_norm";
9044 break;
9045 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
9046 label = "run_inv_dyn";
9047 break;
9048 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
9049 label = "run_inv_dir";
9050 break;
9051 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
9052 label = "run_inv_vir";
9053 break;
9054 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
9055 label = "icall";
9056 break;
9057 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
9058 label = "native_func_aot";
9059 break;
9060 case WRAPPER_SUBTYPE_PINVOKE:
9061 label = "pinvoke";
9062 break;
9063 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
9064 label = "synch_inner";
9065 break;
9066 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
9067 label = "gshared_in";
9068 break;
9069 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
9070 label = "gshared_out";
9071 break;
9072 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
9073 label = "array_acc";
9074 break;
9075 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
9076 label = "generic_arry_help";
9077 break;
9078 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
9079 label = "del_inv_virt";
9080 break;
9081 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
9082 label = "del_inv_bound";
9083 break;
9084 case WRAPPER_SUBTYPE_INTERP_IN:
9085 label = "interp_in";
9086 break;
9087 case WRAPPER_SUBTYPE_INTERP_LMF:
9088 label = "interp_lmf";
9089 break;
9090 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
9091 label = "gsharedvt_in_sig";
9092 break;
9093 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
9094 label = "gsharedvt_out_sig";
9095 break;
9096 case WRAPPER_SUBTYPE_AOT_INIT:
9097 label = "aot_init";
9098 break;
9099 default:
9100 g_assert_not_reached ();
9103 g_string_append_printf (s, "%s_", label);
9106 static char *
9107 sanitize_mangled_string (const char *input)
9109 GString *s = g_string_new ("");
9111 for (int i=0; input [i] != '\0'; i++) {
9112 char c = input [i];
9113 switch (c) {
9114 case '.':
9115 g_string_append (s, "_dot_");
9116 break;
9117 case ' ':
9118 g_string_append (s, "_");
9119 break;
9120 case '`':
9121 g_string_append (s, "_bt_");
9122 break;
9123 case '<':
9124 g_string_append (s, "_le_");
9125 break;
9126 case '>':
9127 g_string_append (s, "_gt_");
9128 break;
9129 case '/':
9130 g_string_append (s, "_sl_");
9131 break;
9132 case '[':
9133 g_string_append (s, "_lbrack_");
9134 break;
9135 case ']':
9136 g_string_append (s, "_rbrack_");
9137 break;
9138 case '(':
9139 g_string_append (s, "_lparen_");
9140 break;
9141 case '-':
9142 g_string_append (s, "_dash_");
9143 break;
9144 case ')':
9145 g_string_append (s, "_rparen_");
9146 break;
9147 case ',':
9148 g_string_append (s, "_comma_");
9149 break;
9150 case ':':
9151 g_string_append (s, "_colon_");
9152 break;
9153 default:
9154 g_string_append_c (s, c);
9158 return g_string_free (s, FALSE);
9161 static gboolean
9162 append_mangled_klass (GString *s, MonoClass *klass)
9164 char *klass_desc = mono_class_full_name (klass);
9165 g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
9166 g_free (klass_desc);
9168 // Success
9169 return TRUE;
9172 static gboolean
9173 append_mangled_method (GString *s, MonoMethod *method);
9175 static gboolean
9176 append_mangled_wrapper (GString *s, MonoMethod *method)
9178 gboolean success = TRUE;
9179 gboolean append_sig = TRUE;
9180 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9181 g_string_append_printf (s, "wrapper_");
9182 /* Most wrappers are in mscorlib */
9183 if (m_class_get_image (method->klass) != mono_get_corlib ())
9184 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9186 if (method->wrapper_type != MONO_WRAPPER_OTHER && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)
9187 append_mangled_wrapper_type (s, method->wrapper_type);
9189 switch (method->wrapper_type) {
9190 case MONO_WRAPPER_REMOTING_INVOKE:
9191 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
9192 case MONO_WRAPPER_XDOMAIN_INVOKE: {
9193 MonoMethod *m = mono_marshal_method_from_wrapper (method);
9194 g_assert (m);
9195 success = success && append_mangled_method (s, m);
9196 break;
9198 case MONO_WRAPPER_PROXY_ISINST:
9199 case MONO_WRAPPER_LDFLD:
9200 case MONO_WRAPPER_LDFLDA:
9201 case MONO_WRAPPER_STFLD: {
9202 g_assert (info);
9203 success = success && append_mangled_klass (s, info->d.proxy.klass);
9204 break;
9206 case MONO_WRAPPER_ALLOC: {
9207 /* The GC name is saved once in MonoAotFileInfo */
9208 g_assert (info->d.alloc.alloc_type != -1);
9209 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
9210 // SlowAlloc, etc
9211 g_string_append_printf (s, "%s_", method->name);
9212 break;
9214 case MONO_WRAPPER_WRITE_BARRIER: {
9215 g_string_append_printf (s, "%s_", method->name);
9216 break;
9218 case MONO_WRAPPER_STELEMREF: {
9219 append_mangled_wrapper_subtype (s, info->subtype);
9220 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
9221 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
9222 break;
9224 case MONO_WRAPPER_OTHER: {
9225 append_mangled_wrapper_subtype (s, info->subtype);
9226 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
9227 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
9228 success = success && append_mangled_klass (s, method->klass);
9229 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
9230 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
9231 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
9232 success = success && append_mangled_method (s, info->d.array_accessor.method);
9233 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
9234 append_mangled_signature (s, info->d.interp_in.sig);
9235 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG) {
9236 append_mangled_signature (s, info->d.gsharedvt.sig);
9237 append_sig = FALSE;
9238 } else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG) {
9239 append_mangled_signature (s, info->d.gsharedvt.sig);
9240 append_sig = FALSE;
9241 } else if (info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)
9242 g_string_append_printf (s, "%s", method->name);
9243 else if (info->subtype == WRAPPER_SUBTYPE_AOT_INIT) {
9244 g_string_append_printf (s, "%s_%d_", m_class_get_image (method->klass)->assembly->aname.name, info->d.aot_init.subtype);
9245 append_sig = FALSE;
9247 break;
9249 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
9250 append_mangled_wrapper_subtype (s, info->subtype);
9251 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
9252 const char *name = method->name;
9253 const char *prefix = "__icall_wrapper_";
9254 if (strstr (name, prefix) == name)
9255 name += strlen (prefix);
9256 g_string_append_printf (s, "%s", name);
9257 append_sig = FALSE;
9258 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
9259 success = success && append_mangled_method (s, info->d.managed_to_native.method);
9260 } else {
9261 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
9262 success = success && append_mangled_method (s, info->d.managed_to_native.method);
9264 break;
9266 case MONO_WRAPPER_SYNCHRONIZED: {
9267 MonoMethod *m;
9269 m = mono_marshal_method_from_wrapper (method);
9270 g_assert (m);
9271 g_assert (m != method);
9272 success = success && append_mangled_method (s, m);
9273 break;
9275 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
9276 append_mangled_wrapper_subtype (s, info->subtype);
9278 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
9279 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
9280 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
9281 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
9282 success = success && append_mangled_method (s, info->d.string_ctor.method);
9283 } else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
9284 success = success && append_mangled_method (s, info->d.generic_array_helper.method);
9285 } else {
9286 success = FALSE;
9288 break;
9290 case MONO_WRAPPER_CASTCLASS: {
9291 append_mangled_wrapper_subtype (s, info->subtype);
9292 break;
9294 case MONO_WRAPPER_RUNTIME_INVOKE: {
9295 append_mangled_wrapper_subtype (s, info->subtype);
9296 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
9297 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
9298 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
9299 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
9300 break;
9302 case MONO_WRAPPER_DELEGATE_INVOKE:
9303 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
9304 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
9305 if (method->is_inflated) {
9306 /* These wrappers are identified by their class */
9307 g_string_append_printf (s, "i_");
9308 success = success && append_mangled_klass (s, method->klass);
9309 } else {
9310 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
9312 g_string_append_printf (s, "u_");
9313 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
9314 append_mangled_wrapper_subtype (s, info->subtype);
9315 g_string_append_printf (s, "u_sigstart");
9317 break;
9319 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
9320 g_assert (info);
9321 success = success && append_mangled_method (s, info->d.native_to_managed.method);
9322 success = success && append_mangled_klass (s, method->klass);
9323 break;
9325 default:
9326 g_assert_not_reached ();
9328 if (success && append_sig)
9329 success = append_mangled_signature (s, mono_method_signature_internal (method));
9330 return success;
9333 static void
9334 append_mangled_ginst (GString *str, MonoGenericInst *ginst)
9336 int i;
9338 for (i = 0; i < ginst->type_argc; ++i) {
9339 if (i > 0)
9340 g_string_append (str, ", ");
9341 MonoType *type = ginst->type_argv [i];
9342 switch (type->type) {
9343 case MONO_TYPE_VAR:
9344 case MONO_TYPE_MVAR: {
9345 MonoType *constraint = NULL;
9346 if (type->data.generic_param)
9347 constraint = type->data.generic_param->gshared_constraint;
9348 if (constraint) {
9349 g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
9350 g_string_append (str, "gshared:");
9351 mono_type_get_desc (str, constraint, TRUE);
9352 break;
9354 // Else falls through to common case
9356 default:
9357 mono_type_get_desc (str, type, TRUE);
9362 static void
9363 append_mangled_context (GString *str, MonoGenericContext *context)
9365 GString *res = g_string_new ("");
9367 g_string_append_printf (res, "gens_");
9368 g_string_append (res, "00");
9370 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
9371 good = good || (context->method_inst && context->method_inst->type_argc > 0);
9372 g_assert (good);
9374 if (context->class_inst)
9375 append_mangled_ginst (res, context->class_inst);
9376 if (context->method_inst) {
9377 if (context->class_inst)
9378 g_string_append (res, "11");
9379 append_mangled_ginst (res, context->method_inst);
9381 g_string_append_printf (str, "gens_%s", res->str);
9382 g_free (res);
9385 static gboolean
9386 append_mangled_method (GString *s, MonoMethod *method)
9388 if (method->wrapper_type)
9389 return append_mangled_wrapper (s, method);
9391 if (method->is_inflated) {
9392 g_string_append_printf (s, "inflated_");
9393 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
9394 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
9396 append_mangled_context (s, &imethod->context);
9397 g_string_append_printf (s, "_declared_by_%s_", m_class_get_image (imethod->declaring->klass)->assembly->aname.name);
9398 append_mangled_method (s, imethod->declaring);
9399 } else if (method->is_generic) {
9400 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9402 g_string_append_printf (s, "generic_");
9403 append_mangled_klass (s, method->klass);
9404 g_string_append_printf (s, "_%s_", method->name);
9406 MonoGenericContainer *container = mono_method_get_generic_container (method);
9407 g_string_append_printf (s, "_");
9408 append_mangled_context (s, &container->context);
9410 return append_mangled_signature (s, mono_method_signature_internal (method));
9411 } else {
9412 g_string_append_printf (s, "%s", m_class_get_image (method->klass)->assembly->aname.name);
9413 append_mangled_klass (s, method->klass);
9414 g_string_append_printf (s, "_%s_", method->name);
9415 if (!append_mangled_signature (s, mono_method_signature_internal (method))) {
9416 g_string_free (s, TRUE);
9417 return FALSE;
9421 return TRUE;
9425 * mono_aot_get_mangled_method_name:
9427 * Return a unique mangled name for METHOD, or NULL.
9429 char*
9430 mono_aot_get_mangled_method_name (MonoMethod *method)
9432 // FIXME: use static cache (mempool?)
9433 // We call this a *lot*
9435 GString *s = g_string_new ("aot_");
9436 if (!append_mangled_method (s, method)) {
9437 g_string_free (s, TRUE);
9438 return NULL;
9439 } else {
9440 char *out = g_string_free (s, FALSE);
9441 // Scrub method and class names
9442 char *cleaned = sanitize_mangled_string (out);
9443 g_free (out);
9444 return cleaned;
9448 gboolean
9449 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
9451 return is_direct_callable (llvm_acfg, NULL, patch_info);
9454 void
9455 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
9457 MonoPltEntry *plt_entry;
9459 plt_entry = get_plt_entry (llvm_acfg, patch_info);
9460 plt_entry->llvm_used = FALSE;
9463 char*
9464 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
9466 const char *sym = NULL;
9468 if (llvm_acfg->aot_opts.direct_icalls) {
9469 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9470 /* Call to a C function implementing a jit icall */
9471 sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
9472 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9473 MonoMethod *method = (MonoMethod *)data;
9474 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9475 sym = lookup_icall_symbol_name_aot (method);
9476 else if (llvm_acfg->aot_opts.direct_pinvoke)
9477 sym = get_pinvoke_import (llvm_acfg, method);
9478 } else if (type == MONO_PATCH_INFO_JIT_ICALL_ID) {
9479 MonoJitICallInfo const * const info = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data);
9480 char const * const name = info->c_symbol;
9481 if (name && info->func == info->wrapper)
9482 sym = name;
9484 if (sym)
9485 return g_strdup (sym);
9487 return NULL;
9490 char*
9491 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
9493 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
9494 MonoPltEntry *plt_entry;
9495 const char *sym = NULL;
9497 ji->type = type;
9498 ji->data.target = data;
9500 if (!can_encode_patch (llvm_acfg, ji))
9501 return NULL;
9503 if (llvm_acfg->aot_opts.direct_icalls) {
9504 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9505 /* Call to a C function implementing a jit icall */
9506 sym = mono_find_jit_icall_info ((MonoJitICallId)(gsize)data)->c_symbol;
9507 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9508 MonoMethod *method = (MonoMethod *)data;
9509 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9510 sym = lookup_icall_symbol_name_aot (method);
9512 if (sym)
9513 return g_strdup (sym);
9516 plt_entry = get_plt_entry (llvm_acfg, ji);
9517 plt_entry->llvm_used = TRUE;
9519 #if defined(TARGET_MACH)
9520 return g_strdup (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
9521 #else
9522 return g_strdup (plt_entry->llvm_symbol);
9523 #endif
9527 mono_aot_get_method_index (MonoMethod *method)
9529 g_assert (llvm_acfg);
9530 return get_method_index (llvm_acfg, method);
9533 MonoJumpInfo*
9534 mono_aot_patch_info_dup (MonoJumpInfo* ji)
9536 MonoJumpInfo *res;
9538 mono_acfg_lock (llvm_acfg);
9539 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
9540 mono_acfg_unlock (llvm_acfg);
9542 return res;
9545 static int
9546 execute_system (const char * command)
9548 int status = 0;
9550 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
9551 // We need an extra set of quotes around the whole command to properly handle commands
9552 // with spaces since internally the command is called through "cmd /c.
9553 char * quoted_command = g_strdup_printf ("\"%s\"", command);
9555 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
9556 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
9557 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
9558 status = _wsystem (wstr);
9559 g_free (wstr);
9561 g_free (quoted_command);
9562 #elif defined (HAVE_SYSTEM)
9563 status = system (command);
9564 #else
9565 g_assert_not_reached ();
9566 #endif
9568 return status;
9571 #ifdef ENABLE_LLVM
9574 * emit_llvm_file:
9576 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
9577 * tools.
9579 static gboolean
9580 emit_llvm_file (MonoAotCompile *acfg)
9582 char *command, *opts, *tempbc, *optbc, *output_fname;
9584 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
9585 if (acfg->aot_opts.no_opt)
9586 tempbc = g_strdup (acfg->aot_opts.llvm_outfile);
9587 else
9588 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9589 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
9590 } else {
9591 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9592 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
9595 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
9597 if (acfg->aot_opts.no_opt)
9598 return TRUE;
9600 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
9601 * a lot of time, and doesn't seem to save much space.
9602 * The following optimizations cannot be enabled:
9603 * - 'tailcallelim'
9604 * - 'jump-threading' changes our blockaddress references to int constants.
9605 * - 'basiccg' fails because it contains:
9606 * if (CS && !isa<IntrinsicInst>(II)) {
9607 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
9608 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
9609 * The opt list below was produced by taking the output of:
9610 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
9611 * then removing tailcallelim + the global opts.
9612 * strip-dead-prototypes deletes unused intrinsics definitions.
9614 /* The dse pass is disabled because of #13734 and #17616 */
9616 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
9617 * // If we have no DataLayout information around, then the size of the store
9618 * // is inferrable from the pointee type. If they are the same type, then
9619 * // we know that the store is safe.
9620 * if (AA.getDataLayout() == 0 &&
9621 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
9622 * return OverwriteComplete;
9623 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
9625 if (acfg->aot_opts.llvm_only) {
9626 // FIXME: This doesn't work yet
9627 opts = g_strdup ("");
9628 } else {
9629 opts = g_strdup ("-O2 -disable-tail-calls -place-safepoints -spp-all-backedges");
9632 if (acfg->aot_opts.llvm_opts) {
9633 opts = g_strdup_printf ("%s %s", opts, acfg->aot_opts.llvm_opts);
9636 if (mono_use_fast_math) {
9637 // same parameters are passed to llc and LLVM JIT
9638 opts = g_strdup_printf ("%s -fp-contract=fast -enable-no-infs-fp-math -enable-no-nans-fp-math -enable-no-signed-zeros-fp-math -enable-no-trapping-fp-math -enable-unsafe-fp-math", opts);
9641 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
9642 aot_printf (acfg, "Executing opt: %s\n", command);
9643 if (execute_system (command) != 0)
9644 return FALSE;
9645 g_free (opts);
9647 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
9648 /* Nothing else to do */
9649 return TRUE;
9651 if (acfg->aot_opts.llvm_only) {
9652 /* Use the stock clang from xcode */
9653 // FIXME: arch
9654 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);
9656 aot_printf (acfg, "Executing clang: %s\n", command);
9657 if (execute_system (command) != 0)
9658 return FALSE;
9659 return TRUE;
9662 if (!acfg->llc_args)
9663 acfg->llc_args = g_string_new ("");
9665 /* Verbose asm slows down llc greatly */
9666 g_string_append (acfg->llc_args, " -asm-verbose=false");
9668 if (acfg->aot_opts.mtriple)
9669 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
9671 #if defined(TARGET_X86_64_WIN32_MSVC)
9672 if (!acfg->aot_opts.mtriple)
9673 g_string_append_printf (acfg->llc_args, " -mtriple=%s", "x86_64-pc-windows-msvc");
9674 #endif
9676 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
9678 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
9680 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
9682 #if defined(TARGET_AMD64) || defined(TARGET_X86)
9683 /* This generates stack adjustments in the middle of functions breaking unwind info */
9684 g_string_append_printf (acfg->llc_args, " -no-x86-call-frame-opt");
9685 #endif
9687 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS) || defined(TARGET_X86_64_WIN32_MSVC)
9688 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9689 #else
9690 if (llvm_acfg->aot_opts.static_link)
9691 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
9692 else
9693 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9694 #endif
9696 if (acfg->llvm_owriter) {
9697 /* Emit an object file directly */
9698 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
9699 g_string_append_printf (acfg->llc_args, " -filetype=obj");
9700 } else {
9701 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
9704 if (acfg->aot_opts.llvm_llc) {
9705 g_string_append_printf (acfg->llc_args, " %s", acfg->aot_opts.llvm_llc);
9708 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
9709 g_free (output_fname);
9711 aot_printf (acfg, "Executing llc: %s\n", command);
9713 if (execute_system (command) != 0)
9714 return FALSE;
9715 return TRUE;
9717 #endif
9719 /* Set the skip flag for methods which do not need to be emitted because of dedup */
9720 static void
9721 dedup_skip_methods (MonoAotCompile *acfg)
9723 int oindex, i;
9725 if (acfg->aot_opts.llvm_only)
9726 return;
9728 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9729 MonoCompile *cfg;
9730 MonoMethod *method;
9732 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9734 cfg = acfg->cfgs [i];
9736 if (!cfg)
9737 continue;
9739 method = cfg->orig_method;
9741 gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
9742 gboolean dedupable = mono_aot_can_dedup (method);
9744 // cfg->skip is vital for LLVM to work, can't just continue in this loop
9745 if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
9746 mono_dedup_cache_method (acfg, method);
9748 // Don't compile inflated methods if we're in first phase of
9749 // dedup
9751 // In second phase, we emit methods that
9752 // are dedupable. We also emit later methods
9753 // which are referenced by them and added later.
9754 // For this reason, when in the dedup_include mode,
9755 // we never set skip.
9756 if (acfg->aot_opts.dedup)
9757 cfg->skip = TRUE;
9760 // Don't compile anything in this mode
9761 if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
9762 cfg->skip = TRUE;
9764 // Compile everything in this mode
9765 if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
9766 cfg->skip = FALSE;
9768 /*if (dedup_collect) {*/
9769 /*char *name = mono_aot_get_mangled_method_name (method);*/
9771 /*if (ignore_cfg (cfg))*/
9772 /*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
9773 /*else*/
9774 /*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
9776 /*g_free (name);*/
9777 /*}*/
9781 static void
9782 emit_code (MonoAotCompile *acfg)
9784 int oindex, i, prev_index;
9785 gboolean saved_unbox_info = FALSE; // See mono_aot_get_unbox_trampoline.
9786 char symbol [MAX_SYMBOL_SIZE];
9788 if (acfg->aot_opts.llvm_only)
9789 return;
9791 #if defined(TARGET_POWERPC64)
9792 sprintf (symbol, ".Lgot_addr");
9793 emit_section_change (acfg, ".text", 0);
9794 emit_alignment (acfg, 8);
9795 emit_label (acfg, symbol);
9796 emit_pointer (acfg, acfg->got_symbol);
9797 #endif
9800 * This global symbol is used to compute the address of each method using the
9801 * code_offsets array. It is also used to compute the memory ranges occupied by
9802 * AOT code, so it must be equal to the address of the first emitted method.
9804 emit_section_change (acfg, ".text", 0);
9805 emit_alignment_code (acfg, 8);
9806 emit_info_symbol (acfg, "jit_code_start", TRUE);
9809 * Emit some padding so the local symbol for the first method doesn't have the
9810 * same address as 'methods'.
9812 emit_padding (acfg, 16);
9814 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9815 MonoCompile *cfg;
9816 MonoMethod *method;
9818 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9820 cfg = acfg->cfgs [i];
9822 if (!cfg)
9823 continue;
9825 method = cfg->orig_method;
9827 if (ignore_cfg (cfg))
9828 continue;
9830 /* Emit unbox trampoline */
9831 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9832 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
9834 emit_section_change (acfg, ".text", 0);
9836 if (acfg->thumb_mixed && cfg->compile_llvm) {
9837 emit_set_thumb_mode (acfg);
9838 fprintf (acfg->fp, "\n.thumb_func\n");
9841 emit_label (acfg, symbol);
9843 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
9845 if (acfg->thumb_mixed && cfg->compile_llvm)
9846 emit_set_arm_mode (acfg);
9848 if (!saved_unbox_info) {
9849 char user_symbol [128];
9850 GSList *unwind_ops;
9851 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
9853 emit_label (acfg, "ut_end");
9855 unwind_ops = mono_unwind_get_cie_program ();
9856 save_unwind_info (acfg, user_symbol, unwind_ops);
9857 mono_free_unwind_info (unwind_ops);
9859 /* Save the unbox trampoline size */
9860 #ifdef TARGET_AMD64
9861 // LLVM unbox trampolines vary in size, 6 or 9 bytes,
9862 // due to the last instruction being 2 or 5 bytes.
9863 // There is no need to describe interior bytes of instructions
9864 // however, so state the size as if the last instruction is size 1.
9865 emit_int32 (acfg, 5);
9866 #else
9867 emit_symbol_diff (acfg, "ut_end", symbol, 0);
9868 #endif
9869 saved_unbox_info = TRUE;
9873 if (cfg->compile_llvm) {
9874 acfg->stats.llvm_count ++;
9875 } else {
9876 emit_method_code (acfg, cfg);
9880 emit_section_change (acfg, ".text", 0);
9881 emit_alignment_code (acfg, 8);
9882 emit_info_symbol (acfg, "jit_code_end", TRUE);
9884 /* To distinguish it from the next symbol */
9885 emit_padding (acfg, 4);
9888 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
9889 * from optimizing them away, since it doesn't see that code_offsets references them.
9890 * JITted methods don't need this since they are referenced using assembler local
9891 * symbols.
9892 * FIXME: This is why write-symbols doesn't work on OSX ?
9894 if (acfg->llvm && acfg->need_no_dead_strip) {
9895 fprintf (acfg->fp, "\n");
9896 for (i = 0; i < acfg->nmethods; ++i) {
9897 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
9898 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
9903 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
9904 * This is PIE code, and the linker can update it if needed.
9907 sprintf (symbol, "method_addresses");
9908 emit_section_change (acfg, ".text", 1);
9909 emit_alignment_code (acfg, 8);
9910 emit_info_symbol (acfg, symbol, TRUE);
9911 if (acfg->aot_opts.write_symbols)
9912 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
9913 emit_unset_mode (acfg);
9914 if (acfg->need_no_dead_strip)
9915 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
9917 for (i = 0; i < acfg->nmethods; ++i) {
9918 #ifdef MONO_ARCH_AOT_SUPPORTED
9919 int call_size;
9921 if (!ignore_cfg (acfg->cfgs [i])) {
9922 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
9923 } else {
9924 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
9926 #endif
9929 sprintf (symbol, "method_addresses_end");
9930 emit_label (acfg, symbol);
9931 emit_line (acfg);
9933 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
9934 sprintf (symbol, "unbox_trampolines");
9935 emit_section_change (acfg, RODATA_SECT, 0);
9936 emit_alignment (acfg, 8);
9937 emit_info_symbol (acfg, symbol, FALSE);
9939 prev_index = -1;
9940 for (i = 0; i < acfg->nmethods; ++i) {
9941 MonoCompile *cfg;
9942 MonoMethod *method;
9943 int index;
9945 cfg = acfg->cfgs [i];
9946 if (ignore_cfg (cfg))
9947 continue;
9949 method = cfg->orig_method;
9951 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9952 index = get_method_index (acfg, method);
9954 emit_int32 (acfg, index);
9955 /* Make sure the table is sorted by index */
9956 g_assert (index > prev_index);
9957 prev_index = index;
9960 sprintf (symbol, "unbox_trampolines_end");
9961 emit_info_symbol (acfg, symbol, FALSE);
9962 emit_int32 (acfg, 0);
9964 /* Emit a separate table with the trampoline addresses/offsets */
9965 sprintf (symbol, "unbox_trampoline_addresses");
9966 emit_section_change (acfg, ".text", 0);
9967 emit_alignment_code (acfg, 8);
9968 emit_info_symbol (acfg, symbol, TRUE);
9970 for (i = 0; i < acfg->nmethods; ++i) {
9971 MonoCompile *cfg;
9972 MonoMethod *method;
9974 cfg = acfg->cfgs [i];
9975 if (ignore_cfg (cfg))
9976 continue;
9978 method = cfg->orig_method;
9979 (void)method;
9981 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9982 #ifdef MONO_ARCH_AOT_SUPPORTED
9983 int call_size;
9985 const int index = get_method_index (acfg, method);
9986 sprintf (symbol, "ut_%d", index);
9988 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
9989 #endif
9992 emit_int32 (acfg, 0);
9995 static void
9996 emit_info (MonoAotCompile *acfg)
9998 int oindex, i;
9999 gint32 *offsets;
10001 offsets = g_new0 (gint32, acfg->nmethods);
10003 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
10004 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
10006 if (acfg->cfgs [i]) {
10007 emit_method_info (acfg, acfg->cfgs [i]);
10008 offsets [i] = acfg->cfgs [i]->method_info_offset;
10009 } else {
10010 offsets [i] = 0;
10014 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10016 g_free (offsets);
10019 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
10021 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
10022 #define mix(a,b,c) { \
10023 a -= c; a ^= rot(c, 4); c += b; \
10024 b -= a; b ^= rot(a, 6); a += c; \
10025 c -= b; c ^= rot(b, 8); b += a; \
10026 a -= c; a ^= rot(c,16); c += b; \
10027 b -= a; b ^= rot(a,19); a += c; \
10028 c -= b; c ^= rot(b, 4); b += a; \
10030 #define mono_final(a,b,c) { \
10031 c ^= b; c -= rot(b,14); \
10032 a ^= c; a -= rot(c,11); \
10033 b ^= a; b -= rot(a,25); \
10034 c ^= b; c -= rot(b,16); \
10035 a ^= c; a -= rot(c,4); \
10036 b ^= a; b -= rot(a,14); \
10037 c ^= b; c -= rot(b,24); \
10040 static guint
10041 mono_aot_type_hash (MonoType *t1)
10043 guint hash = t1->type;
10045 hash |= t1->byref << 6; /* do not collide with t1->type values */
10046 switch (t1->type) {
10047 case MONO_TYPE_VALUETYPE:
10048 case MONO_TYPE_CLASS:
10049 case MONO_TYPE_SZARRAY:
10050 /* check if the distribution is good enough */
10051 return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.klass));
10052 case MONO_TYPE_PTR:
10053 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
10054 case MONO_TYPE_ARRAY:
10055 return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass));
10056 case MONO_TYPE_GENERICINST:
10057 return ((hash << 5) - hash) ^ 0;
10058 default:
10059 return hash;
10064 * mono_aot_method_hash:
10066 * Return a hash code for methods which only depends on metadata.
10068 guint32
10069 mono_aot_method_hash (MonoMethod *method)
10071 MonoMethodSignature *sig;
10072 MonoClass *klass;
10073 int i, hindex;
10074 int hashes_count;
10075 guint32 *hashes_start, *hashes;
10076 guint32 a, b, c;
10077 MonoGenericInst *class_ginst = NULL;
10078 MonoGenericInst *ginst = NULL;
10080 /* Similar to the hash in mono_method_get_imt_slot () */
10082 sig = mono_method_signature_internal (method);
10084 if (mono_class_is_ginst (method->klass))
10085 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
10086 if (method->is_inflated)
10087 ginst = ((MonoMethodInflated*)method)->context.method_inst;
10089 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
10090 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
10091 hashes = hashes_start;
10093 /* Some wrappers are assigned to random classes */
10094 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
10095 klass = method->klass;
10096 else
10097 klass = mono_defaults.object_class;
10099 if (!method->wrapper_type) {
10100 char *full_name;
10102 if (mono_class_is_ginst (klass))
10103 full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
10104 else
10105 full_name = mono_type_full_name (m_class_get_byval_arg (klass));
10107 hashes [0] = mono_metadata_str_hash (full_name);
10108 hashes [1] = 0;
10109 g_free (full_name);
10110 } else {
10111 hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
10112 hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
10114 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
10115 /* The method name includes a stringified pointer */
10116 hashes [2] = 0;
10117 else
10118 hashes [2] = mono_metadata_str_hash (method->name);
10119 hashes [3] = method->wrapper_type;
10120 hashes [4] = mono_aot_type_hash (sig->ret);
10121 hindex = 5;
10122 for (i = 0; i < sig->param_count; i++) {
10123 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
10125 if (class_ginst) {
10126 for (i = 0; i < class_ginst->type_argc; ++i)
10127 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
10129 if (ginst) {
10130 for (i = 0; i < ginst->type_argc; ++i)
10131 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
10133 g_assert (hindex == hashes_count);
10135 /* Setup internal state */
10136 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
10138 /* Handle most of the hashes */
10139 while (hashes_count > 3) {
10140 a += hashes [0];
10141 b += hashes [1];
10142 c += hashes [2];
10143 mix (a,b,c);
10144 hashes_count -= 3;
10145 hashes += 3;
10148 /* Handle the last 3 hashes (all the case statements fall through) */
10149 switch (hashes_count) {
10150 case 3 : c += hashes [2];
10151 case 2 : b += hashes [1];
10152 case 1 : a += hashes [0];
10153 mono_final (a,b,c);
10154 case 0: /* nothing left to add */
10155 break;
10158 g_free (hashes_start);
10160 return c;
10162 #undef rot
10163 #undef mix
10164 #undef mono_final
10167 * mono_aot_get_array_helper_from_wrapper;
10169 * Get the helper method in Array called by an array wrapper method.
10171 MonoMethod*
10172 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
10174 MonoMethod *m;
10175 const char *prefix;
10176 MonoGenericContext ctx;
10177 MonoType *args [16];
10178 char *mname, *iname, *s, *s2, *helper_name = NULL;
10180 prefix = "System.Collections.Generic";
10181 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
10182 s2 = strstr (s, "`1.");
10183 g_assert (s2);
10184 s2 [0] = '\0';
10185 iname = s;
10186 mname = s2 + 3;
10188 //printf ("X: %s %s\n", iname, mname);
10190 if (!strcmp (iname, "IList"))
10191 helper_name = g_strdup_printf ("InternalArray__%s", mname);
10192 else
10193 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
10194 m = get_method_nofail (mono_defaults.array_class, helper_name, mono_method_signature_internal (method)->param_count, 0);
10195 g_assert (m);
10196 g_free (helper_name);
10197 g_free (s);
10199 if (m->is_generic) {
10200 ERROR_DECL (error);
10201 memset (&ctx, 0, sizeof (ctx));
10202 args [0] = m_class_get_byval_arg (m_class_get_element_class (method->klass));
10203 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
10204 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
10205 g_assert (is_ok (error)); /* FIXME don't swallow the error */
10208 return m;
10211 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
10213 typedef struct HashEntry {
10214 guint32 key, value, index;
10215 struct HashEntry *next;
10216 } HashEntry;
10219 * emit_extra_methods:
10221 * Emit methods which are not in the METHOD table, like wrappers.
10223 static void
10224 emit_extra_methods (MonoAotCompile *acfg)
10226 int i, table_size, buf_size;
10227 guint8 *p, *buf;
10228 guint32 *info_offsets;
10229 guint32 hash;
10230 GPtrArray *table;
10231 HashEntry *entry, *new_entry;
10232 int nmethods, max_chain_length;
10233 int *chain_lengths;
10235 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
10237 /* Emit method info */
10238 nmethods = 0;
10239 for (i = 0; i < acfg->extra_methods->len; ++i) {
10240 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10241 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
10243 if (ignore_cfg (cfg))
10244 continue;
10246 buf_size = 10240;
10247 p = buf = (guint8 *)g_malloc (buf_size);
10249 nmethods ++;
10251 method = cfg->method_to_register;
10253 encode_method_ref (acfg, method, p, &p);
10255 g_assert ((p - buf) < buf_size);
10257 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10258 g_free (buf);
10262 * Construct a chained hash table for mapping indexes in extra_method_info to
10263 * method indexes.
10265 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
10266 table = g_ptr_array_sized_new (table_size);
10267 for (i = 0; i < table_size; ++i)
10268 g_ptr_array_add (table, NULL);
10269 chain_lengths = g_new0 (int, table_size);
10270 max_chain_length = 0;
10271 for (i = 0; i < acfg->extra_methods->len; ++i) {
10272 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10273 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
10274 guint32 key, value;
10276 if (ignore_cfg (cfg))
10277 continue;
10279 key = info_offsets [i];
10280 value = get_method_index (acfg, method);
10282 hash = mono_aot_method_hash (method) % table_size;
10283 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
10285 chain_lengths [hash] ++;
10286 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
10288 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
10289 new_entry->key = key;
10290 new_entry->value = value;
10292 entry = (HashEntry *)g_ptr_array_index (table, hash);
10293 if (entry == NULL) {
10294 new_entry->index = hash;
10295 g_ptr_array_index (table, hash) = new_entry;
10296 } else {
10297 while (entry->next)
10298 entry = entry->next;
10300 entry->next = new_entry;
10301 new_entry->index = table->len;
10302 g_ptr_array_add (table, new_entry);
10305 g_free (chain_lengths);
10307 //printf ("MAX: %d\n", max_chain_length);
10309 buf_size = table->len * 12 + 4;
10310 p = buf = (guint8 *)g_malloc (buf_size);
10311 encode_int (table_size, p, &p);
10313 for (i = 0; i < table->len; ++i) {
10314 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
10316 if (entry == NULL) {
10317 encode_int (0, p, &p);
10318 encode_int (0, p, &p);
10319 encode_int (0, p, &p);
10320 } else {
10321 //g_assert (entry->key > 0);
10322 encode_int (entry->key, p, &p);
10323 encode_int (entry->value, p, &p);
10324 if (entry->next)
10325 encode_int (entry->next->index, p, &p);
10326 else
10327 encode_int (0, p, &p);
10330 g_assert (p - buf <= buf_size);
10332 /* Emit the table */
10333 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
10335 g_free (buf);
10338 * Emit a table reverse mapping method indexes to their index in extra_method_info.
10339 * This is used by mono_aot_find_jit_info ().
10341 buf_size = acfg->extra_methods->len * 8 + 4;
10342 p = buf = (guint8 *)g_malloc (buf_size);
10343 encode_int (acfg->extra_methods->len, p, &p);
10344 for (i = 0; i < acfg->extra_methods->len; ++i) {
10345 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
10347 encode_int (get_method_index (acfg, method), p, &p);
10348 encode_int (info_offsets [i], p, &p);
10350 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
10352 g_free (buf);
10353 g_free (info_offsets);
10354 g_ptr_array_free (table, TRUE);
10357 static void
10358 generate_aotid (guint8* aotid)
10360 gpointer rand_handle;
10361 ERROR_DECL (error);
10363 mono_rand_open ();
10364 rand_handle = mono_rand_init (NULL, 0);
10366 mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
10367 mono_error_assert_ok (error);
10369 mono_rand_close (rand_handle);
10372 static void
10373 emit_exception_info (MonoAotCompile *acfg)
10375 int i;
10376 gint32 *offsets;
10377 SeqPointData sp_data;
10378 gboolean seq_points_to_file = FALSE;
10380 offsets = g_new0 (gint32, acfg->nmethods);
10381 for (i = 0; i < acfg->nmethods; ++i) {
10382 if (acfg->cfgs [i]) {
10383 MonoCompile *cfg = acfg->cfgs [i];
10385 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
10386 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
10387 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
10388 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
10389 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
10391 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
10392 offsets [i] = cfg->ex_info_offset;
10394 if (method_seq_points_to_file) {
10395 if (!seq_points_to_file) {
10396 mono_seq_point_data_init (&sp_data, acfg->nmethods);
10397 seq_points_to_file = TRUE;
10399 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
10401 } else {
10402 offsets [i] = 0;
10406 if (seq_points_to_file) {
10407 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
10408 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, (const char*)NULL);
10409 char *image_basename = g_path_get_basename (acfg->image->name);
10410 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
10411 char *aot_file_path = g_build_filename (dir, aot_file, (const char*)NULL);
10413 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
10414 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
10415 exit (1);
10418 mono_seq_point_data_write (&sp_data, aot_file_path);
10419 mono_seq_point_data_free (&sp_data);
10421 g_free (aotid);
10422 g_free (dir);
10423 g_free (image_basename);
10424 g_free (aot_file);
10425 g_free (aot_file_path);
10428 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10429 g_free (offsets);
10432 static void
10433 emit_unwind_info (MonoAotCompile *acfg)
10435 int i;
10436 char symbol [128];
10438 if (acfg->aot_opts.llvm_only) {
10439 g_assert (acfg->unwind_ops->len == 0);
10440 return;
10444 * The unwind info contains a lot of duplicates so we emit each unique
10445 * entry once, and only store the offset from the start of the table in the
10446 * exception info.
10449 sprintf (symbol, "unwind_info");
10450 emit_section_change (acfg, RODATA_SECT, 1);
10451 emit_alignment (acfg, 8);
10452 emit_info_symbol (acfg, symbol, TRUE);
10454 for (i = 0; i < acfg->unwind_ops->len; ++i) {
10455 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
10456 guint8 *unwind_info;
10457 guint32 unwind_info_len;
10458 guint8 buf [16];
10459 guint8 *p;
10461 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
10463 p = buf;
10464 encode_value (unwind_info_len, p, &p);
10465 emit_bytes (acfg, buf, p - buf);
10466 emit_bytes (acfg, unwind_info, unwind_info_len);
10468 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
10472 static void
10473 emit_class_info (MonoAotCompile *acfg)
10475 int i;
10476 gint32 *offsets;
10478 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
10479 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
10480 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
10482 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);
10483 g_free (offsets);
10486 typedef struct ClassNameTableEntry {
10487 guint32 token, index;
10488 struct ClassNameTableEntry *next;
10489 } ClassNameTableEntry;
10491 static void
10492 emit_class_name_table (MonoAotCompile *acfg)
10494 int i, table_size, buf_size;
10495 guint32 token, hash;
10496 MonoClass *klass;
10497 GPtrArray *table;
10498 char *full_name;
10499 guint8 *buf, *p;
10500 ClassNameTableEntry *entry, *new_entry;
10503 * Construct a chained hash table for mapping class names to typedef tokens.
10505 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
10506 table = g_ptr_array_sized_new (table_size);
10507 for (i = 0; i < table_size; ++i)
10508 g_ptr_array_add (table, NULL);
10509 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
10510 ERROR_DECL (error);
10511 token = MONO_TOKEN_TYPE_DEF | (i + 1);
10512 klass = mono_class_get_checked (acfg->image, token, error);
10513 if (!klass) {
10514 mono_error_cleanup (error);
10515 continue;
10517 full_name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
10518 hash = mono_metadata_str_hash (full_name) % table_size;
10519 g_free (full_name);
10521 /* FIXME: Allocate from the mempool */
10522 new_entry = g_new0 (ClassNameTableEntry, 1);
10523 new_entry->token = token;
10525 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
10526 if (entry == NULL) {
10527 new_entry->index = hash;
10528 g_ptr_array_index (table, hash) = new_entry;
10529 } else {
10530 while (entry->next)
10531 entry = entry->next;
10533 entry->next = new_entry;
10534 new_entry->index = table->len;
10535 g_ptr_array_add (table, new_entry);
10539 /* Emit the table */
10540 buf_size = table->len * 4 + 4;
10541 p = buf = (guint8 *)g_malloc0 (buf_size);
10543 /* FIXME: Optimize memory usage */
10544 g_assert (table_size < 65000);
10545 encode_int16 (table_size, p, &p);
10546 g_assert (table->len < 65000);
10547 for (i = 0; i < table->len; ++i) {
10548 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
10550 if (entry == NULL) {
10551 encode_int16 (0, p, &p);
10552 encode_int16 (0, p, &p);
10553 } else {
10554 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
10555 if (entry->next)
10556 encode_int16 (entry->next->index, p, &p);
10557 else
10558 encode_int16 (0, p, &p);
10560 g_free (entry);
10562 g_assert (p - buf <= buf_size);
10563 g_ptr_array_free (table, TRUE);
10565 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
10567 g_free (buf);
10570 static void
10571 emit_image_table (MonoAotCompile *acfg)
10573 int i, buf_size;
10574 guint8 *buf, *p;
10577 * The image table is small but referenced in a lot of places.
10578 * So we emit it at once, and reference its elements by an index.
10580 buf_size = acfg->image_table->len * 28 + 4;
10581 for (i = 0; i < acfg->image_table->len; i++) {
10582 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10583 MonoAssemblyName *aname = &image->assembly->aname;
10585 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
10588 buf = p = (guint8 *)g_malloc0 (buf_size);
10589 encode_int (acfg->image_table->len, p, &p);
10590 for (i = 0; i < acfg->image_table->len; i++) {
10591 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10592 MonoAssemblyName *aname = &image->assembly->aname;
10594 /* FIXME: Support multi-module assemblies */
10595 g_assert (image->assembly->image == image);
10597 encode_string (image->assembly_name, p, &p);
10598 encode_string (image->guid, p, &p);
10599 encode_string (aname->culture ? aname->culture : "", p, &p);
10600 encode_string ((const char*)aname->public_key_token, p, &p);
10602 while (GPOINTER_TO_UINT (p) % 8 != 0)
10603 p ++;
10605 encode_int (aname->flags, p, &p);
10606 encode_int (aname->major, p, &p);
10607 encode_int (aname->minor, p, &p);
10608 encode_int (aname->build, p, &p);
10609 encode_int (aname->revision, p, &p);
10611 g_assert (p - buf <= buf_size);
10613 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
10615 g_free (buf);
10618 static void
10619 emit_weak_field_indexes (MonoAotCompile *acfg)
10621 GHashTable *indexes;
10622 GHashTableIter iter;
10623 gpointer key, value;
10624 int buf_size;
10625 guint8 *buf, *p;
10627 /* Emit a table of weak field indexes, since computing these at runtime is expensive */
10628 mono_assembly_init_weak_fields (acfg->image);
10629 indexes = acfg->image->weak_field_indexes;
10630 g_assert (indexes);
10632 buf_size = (g_hash_table_size (indexes) + 1) * 4;
10633 buf = p = (guint8 *)g_malloc0 (buf_size);
10635 encode_int (g_hash_table_size (indexes), p, &p);
10636 g_hash_table_iter_init (&iter, indexes);
10637 while (g_hash_table_iter_next (&iter, &key, &value)) {
10638 guint32 index = GPOINTER_TO_UINT (key);
10639 encode_int (index, p, &p);
10641 g_assert (p - buf <= buf_size);
10643 emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
10645 g_free (buf);
10648 static void
10649 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
10651 int i, first_plt_got_patch = 0, buf_size;
10652 guint8 *p, *buf;
10653 guint32 *got_info_offsets;
10654 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
10656 /* Add the patches needed by the PLT to the GOT */
10657 if (!llvm) {
10658 acfg->plt_got_offset_base = acfg->got_offset;
10659 first_plt_got_patch = info->got_patches->len;
10660 for (i = 1; i < acfg->plt_offset; ++i) {
10661 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10663 g_ptr_array_add (info->got_patches, plt_entry->ji);
10665 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
10668 acfg->got_offset += acfg->plt_offset;
10672 * FIXME:
10673 * - optimize offsets table.
10674 * - reduce number of exported symbols.
10675 * - emit info for a klass only once.
10676 * - determine when a method uses a GOT slot which is guaranteed to be already
10677 * initialized.
10678 * - clean up and document the code.
10679 * - use String.Empty in class libs.
10682 /* Encode info required to decode shared GOT entries */
10683 buf_size = info->got_patches->len * 128;
10684 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
10685 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
10686 if (!llvm) {
10687 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
10688 /* Unused */
10689 if (acfg->plt_offset)
10690 acfg->plt_got_info_offsets [0] = 0;
10692 for (i = 0; i < info->got_patches->len; ++i) {
10693 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
10694 guint8 *p2;
10696 p = buf;
10698 encode_value (ji->type, p, &p);
10699 p2 = p;
10700 encode_patch (acfg, ji, p, &p);
10701 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
10702 g_assert (p - buf <= buf_size);
10703 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10705 if (!llvm && i >= first_plt_got_patch)
10706 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
10707 acfg->stats.got_info_size += p - buf;
10710 /* Emit got_info_offsets table */
10712 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
10713 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);
10716 static void
10717 emit_got (MonoAotCompile *acfg)
10719 char symbol [MAX_SYMBOL_SIZE];
10721 if (acfg->aot_opts.llvm_only)
10722 return;
10724 /* Don't make GOT global so accesses to it don't need relocations */
10725 sprintf (symbol, "%s", acfg->got_symbol);
10727 #ifdef TARGET_MACH
10728 emit_unset_mode (acfg);
10729 fprintf (acfg->fp, ".section __DATA, __bss\n");
10730 emit_alignment (acfg, 8);
10731 if (acfg->llvm)
10732 emit_info_symbol (acfg, "jit_got", FALSE);
10733 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10734 #else
10735 emit_section_change (acfg, ".bss", 0);
10736 emit_alignment (acfg, 8);
10737 if (acfg->aot_opts.write_symbols)
10738 emit_local_symbol (acfg, symbol, "got_end", FALSE);
10739 emit_label (acfg, symbol);
10740 if (acfg->llvm)
10741 emit_info_symbol (acfg, "jit_got", FALSE);
10742 if (acfg->got_offset > 0)
10743 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10744 #endif
10746 sprintf (symbol, "got_end");
10747 emit_label (acfg, symbol);
10750 typedef struct GlobalsTableEntry {
10751 guint32 value, index;
10752 struct GlobalsTableEntry *next;
10753 } GlobalsTableEntry;
10755 #ifdef TARGET_WIN32_MSVC
10756 #define DLL_ENTRY_POINT "DllMain"
10758 static void
10759 emit_library_info (MonoAotCompile *acfg)
10761 // Only include for shared libraries linked directly from generated object.
10762 if (link_shared_library (acfg)) {
10763 char *name = NULL;
10764 char symbol [MAX_SYMBOL_SIZE];
10766 // Ask linker to export all global symbols.
10767 emit_section_change (acfg, ".drectve", 0);
10768 for (guint i = 0; i < acfg->globals->len; ++i) {
10769 name = (char *)g_ptr_array_index (acfg->globals, i);
10770 g_assert (name != NULL);
10771 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
10772 emit_string (acfg, symbol);
10775 // Emit DLLMain function, needed by MSVC linker for DLL's.
10776 // NOTE, DllMain should not go into exports above.
10777 emit_section_change (acfg, ".text", 0);
10778 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
10779 emit_label (acfg, DLL_ENTRY_POINT);
10781 // Simple implementation of DLLMain, just returning TRUE.
10782 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
10783 fprintf (acfg->fp, "movl $1, %%eax\n");
10784 fprintf (acfg->fp, "ret\n");
10786 // Inform linker about our dll entry function.
10787 emit_section_change (acfg, ".drectve", 0);
10788 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
10789 return;
10793 #else
10795 static inline void
10796 emit_library_info (MonoAotCompile *acfg)
10798 return;
10800 #endif
10802 static void
10803 emit_globals (MonoAotCompile *acfg)
10805 int i, table_size;
10806 guint32 hash;
10807 GPtrArray *table;
10808 char symbol [1024];
10809 GlobalsTableEntry *entry, *new_entry;
10811 if (!acfg->aot_opts.static_link)
10812 return;
10814 if (acfg->aot_opts.llvm_only) {
10815 g_assert (acfg->globals->len == 0);
10816 return;
10820 * When static linking, we emit a table containing our globals.
10824 * Construct a chained hash table for mapping global names to their index in
10825 * the globals table.
10827 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
10828 table = g_ptr_array_sized_new (table_size);
10829 for (i = 0; i < table_size; ++i)
10830 g_ptr_array_add (table, NULL);
10831 for (i = 0; i < acfg->globals->len; ++i) {
10832 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10834 hash = mono_metadata_str_hash (name) % table_size;
10836 /* FIXME: Allocate from the mempool */
10837 new_entry = g_new0 (GlobalsTableEntry, 1);
10838 new_entry->value = i;
10840 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
10841 if (entry == NULL) {
10842 new_entry->index = hash;
10843 g_ptr_array_index (table, hash) = new_entry;
10844 } else {
10845 while (entry->next)
10846 entry = entry->next;
10848 entry->next = new_entry;
10849 new_entry->index = table->len;
10850 g_ptr_array_add (table, new_entry);
10854 /* Emit the table */
10855 sprintf (symbol, ".Lglobals_hash");
10856 emit_section_change (acfg, RODATA_SECT, 0);
10857 emit_alignment (acfg, 8);
10858 emit_label (acfg, symbol);
10860 /* FIXME: Optimize memory usage */
10861 g_assert (table_size < 65000);
10862 emit_int16 (acfg, table_size);
10863 for (i = 0; i < table->len; ++i) {
10864 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
10866 if (entry == NULL) {
10867 emit_int16 (acfg, 0);
10868 emit_int16 (acfg, 0);
10869 } else {
10870 emit_int16 (acfg, entry->value + 1);
10871 if (entry->next)
10872 emit_int16 (acfg, entry->next->index);
10873 else
10874 emit_int16 (acfg, 0);
10878 /* Emit the names */
10879 for (i = 0; i < acfg->globals->len; ++i) {
10880 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10882 sprintf (symbol, "name_%d", i);
10883 emit_section_change (acfg, RODATA_SECT, 1);
10884 #ifdef TARGET_MACH
10885 emit_alignment (acfg, 4);
10886 #endif
10887 emit_label (acfg, symbol);
10888 emit_string (acfg, name);
10891 /* Emit the globals table */
10892 sprintf (symbol, "globals");
10893 emit_section_change (acfg, ".data", 0);
10894 /* This is not a global, since it is accessed by the init function */
10895 emit_alignment (acfg, 8);
10896 emit_info_symbol (acfg, symbol, FALSE);
10898 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
10899 emit_pointer (acfg, symbol);
10901 for (i = 0; i < acfg->globals->len; ++i) {
10902 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10904 sprintf (symbol, "name_%d", i);
10905 emit_pointer (acfg, symbol);
10907 g_assert (strlen (name) < sizeof (symbol));
10908 sprintf (symbol, "%s", name);
10909 emit_pointer (acfg, symbol);
10911 /* Null terminate the table */
10912 emit_int32 (acfg, 0);
10913 emit_int32 (acfg, 0);
10916 static void
10917 emit_mem_end (MonoAotCompile *acfg)
10919 char symbol [128];
10921 if (acfg->aot_opts.llvm_only)
10922 return;
10924 sprintf (symbol, "mem_end");
10925 emit_section_change (acfg, ".text", 1);
10926 emit_alignment_code (acfg, 8);
10927 emit_label (acfg, symbol);
10930 static void
10931 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10933 int i;
10935 info->version = MONO_AOT_FILE_VERSION;
10936 info->plt_got_offset_base = acfg->plt_got_offset_base;
10937 info->got_size = acfg->got_offset * sizeof (target_mgreg_t);
10938 info->plt_size = acfg->plt_offset;
10939 info->nmethods = acfg->nmethods;
10940 info->nextra_methods = acfg->nextra_methods;
10941 info->flags = acfg->flags;
10942 info->opts = acfg->opts;
10943 info->simd_opts = acfg->simd_opts;
10944 info->gc_name_index = acfg->gc_name_offset;
10945 info->datafile_size = acfg->datafile_offset;
10946 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10947 info->table_offsets [i] = acfg->table_offsets [i];
10948 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10949 info->num_trampolines [i] = acfg->num_trampolines [i];
10950 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10951 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
10952 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10953 info->trampoline_size [i] = acfg->trampoline_size [i];
10954 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
10956 int card_table_shift_bits = 0;
10957 target_mgreg_t card_table_mask = 0;
10959 mono_gc_get_target_card_table (&card_table_shift_bits, &card_table_mask);
10962 * Sanity checking variables used to make sure the host and target
10963 * environment matches when cross compiling.
10965 info->double_align = MONO_ABI_ALIGNOF (double);
10966 info->long_align = MONO_ABI_ALIGNOF (gint64);
10967 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
10968 info->card_table_shift_bits = card_table_shift_bits;
10969 info->card_table_mask = card_table_mask;
10971 info->tramp_page_size = acfg->tramp_page_size;
10972 info->nshared_got_entries = acfg->nshared_got_entries;
10973 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10974 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
10976 memcpy(&info->aotid, acfg->image->aotid, 16);
10979 static void
10980 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10982 char symbol [MAX_SYMBOL_SIZE];
10983 int i, sindex;
10984 const char **symbols;
10986 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10987 sindex = 0;
10988 symbols [sindex ++] = acfg->got_symbol;
10989 if (acfg->llvm) {
10990 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
10991 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
10992 } else {
10993 symbols [sindex ++] = NULL;
10994 symbols [sindex ++] = NULL;
10996 /* llvm_get_method */
10997 symbols [sindex ++] = NULL;
10998 /* llvm_get_unbox_tramp */
10999 symbols [sindex ++] = NULL;
11000 if (!acfg->aot_opts.llvm_only) {
11001 symbols [sindex ++] = "jit_code_start";
11002 symbols [sindex ++] = "jit_code_end";
11003 symbols [sindex ++] = "method_addresses";
11004 } else {
11005 symbols [sindex ++] = NULL;
11006 symbols [sindex ++] = NULL;
11007 symbols [sindex ++] = NULL;
11009 symbols [sindex ++] = NULL;
11010 symbols [sindex ++] = NULL;
11012 if (acfg->data_outfile) {
11013 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
11014 symbols [sindex ++] = NULL;
11015 } else {
11016 symbols [sindex ++] = "blob";
11017 symbols [sindex ++] = "class_name_table";
11018 symbols [sindex ++] = "class_info_offsets";
11019 symbols [sindex ++] = "method_info_offsets";
11020 symbols [sindex ++] = "ex_info_offsets";
11021 symbols [sindex ++] = "extra_method_info_offsets";
11022 symbols [sindex ++] = "extra_method_table";
11023 symbols [sindex ++] = "got_info_offsets";
11024 if (acfg->llvm)
11025 symbols [sindex ++] = "llvm_got_info_offsets";
11026 else
11027 symbols [sindex ++] = NULL;
11028 symbols [sindex ++] = "image_table";
11029 symbols [sindex ++] = "weak_field_indexes";
11032 symbols [sindex ++] = "mem_end";
11033 symbols [sindex ++] = "assembly_guid";
11034 symbols [sindex ++] = "runtime_version";
11035 if (acfg->num_trampoline_got_entries) {
11036 symbols [sindex ++] = "specific_trampolines";
11037 symbols [sindex ++] = "static_rgctx_trampolines";
11038 symbols [sindex ++] = "imt_trampolines";
11039 symbols [sindex ++] = "gsharedvt_arg_trampolines";
11040 symbols [sindex ++] = "ftnptr_arg_trampolines";
11041 symbols [sindex ++] = "unbox_arbitrary_trampolines";
11042 } else {
11043 symbols [sindex ++] = NULL;
11044 symbols [sindex ++] = NULL;
11045 symbols [sindex ++] = NULL;
11046 symbols [sindex ++] = NULL;
11047 symbols [sindex ++] = NULL;
11048 symbols [sindex ++] = NULL;
11050 if (acfg->aot_opts.static_link) {
11051 symbols [sindex ++] = "globals";
11052 } else {
11053 symbols [sindex ++] = NULL;
11055 symbols [sindex ++] = "assembly_name";
11056 symbols [sindex ++] = "plt";
11057 symbols [sindex ++] = "plt_end";
11058 symbols [sindex ++] = "unwind_info";
11059 if (!acfg->aot_opts.llvm_only) {
11060 symbols [sindex ++] = "unbox_trampolines";
11061 symbols [sindex ++] = "unbox_trampolines_end";
11062 symbols [sindex ++] = "unbox_trampoline_addresses";
11063 } else {
11064 symbols [sindex ++] = NULL;
11065 symbols [sindex ++] = NULL;
11066 symbols [sindex ++] = NULL;
11069 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
11071 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
11072 emit_section_change (acfg, ".data", 0);
11073 emit_alignment (acfg, 8);
11074 emit_label (acfg, symbol);
11075 if (!acfg->aot_opts.static_link)
11076 emit_global (acfg, symbol, FALSE);
11078 /* The data emitted here must match MonoAotFileInfo. */
11080 emit_int32 (acfg, info->version);
11081 emit_int32 (acfg, info->dummy);
11084 * We emit pointers to our data structures instead of emitting global symbols which
11085 * point to them, to reduce the number of globals, and because using globals leads to
11086 * various problems (i.e. arm/thumb).
11088 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
11089 emit_pointer (acfg, symbols [i]);
11091 emit_int32 (acfg, info->plt_got_offset_base);
11092 emit_int32 (acfg, info->got_size);
11093 emit_int32 (acfg, info->plt_size);
11094 emit_int32 (acfg, info->nmethods);
11095 emit_int32 (acfg, info->nextra_methods);
11096 emit_int32 (acfg, info->flags);
11097 emit_int32 (acfg, info->opts);
11098 emit_int32 (acfg, info->simd_opts);
11099 emit_int32 (acfg, info->gc_name_index);
11100 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
11101 emit_int32 (acfg, info->double_align);
11102 emit_int32 (acfg, info->long_align);
11103 emit_int32 (acfg, info->generic_tramp_num);
11104 emit_int32 (acfg, info->card_table_shift_bits);
11105 emit_int32 (acfg, info->card_table_mask);
11106 emit_int32 (acfg, info->tramp_page_size);
11107 emit_int32 (acfg, info->nshared_got_entries);
11108 emit_int32 (acfg, info->datafile_size);
11109 emit_int32 (acfg, 0);
11110 emit_int32 (acfg, 0);
11112 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
11113 emit_int32 (acfg, info->table_offsets [i]);
11114 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11115 emit_int32 (acfg, info->num_trampolines [i]);
11116 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11117 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
11118 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11119 emit_int32 (acfg, info->trampoline_size [i]);
11120 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
11121 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
11123 emit_bytes (acfg, info->aotid, 16);
11125 if (acfg->aot_opts.static_link) {
11126 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
11127 emit_alignment (acfg, sizeof (target_mgreg_t));
11128 emit_label (acfg, acfg->static_linking_symbol);
11129 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
11134 * Emit a structure containing all the information not stored elsewhere.
11136 static void
11137 emit_file_info (MonoAotCompile *acfg)
11139 char *build_info;
11140 MonoAotFileInfo *info;
11142 if (acfg->aot_opts.bind_to_runtime_version) {
11143 build_info = mono_get_runtime_build_info ();
11144 emit_string_symbol (acfg, "runtime_version", build_info);
11145 g_free (build_info);
11146 } else {
11147 emit_string_symbol (acfg, "runtime_version", "");
11150 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
11152 /* Emit a string holding the assembly name */
11153 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
11155 info = g_new0 (MonoAotFileInfo, 1);
11156 init_aot_file_info (acfg, info);
11158 if (acfg->aot_opts.static_link) {
11159 char symbol [MAX_SYMBOL_SIZE];
11160 char *p;
11163 * Emit a global symbol which can be passed by an embedding app to
11164 * mono_aot_register_module (). The symbol points to a pointer to the the file info
11165 * structure.
11167 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
11169 /* Get rid of characters which cannot occur in symbols */
11170 p = symbol;
11171 for (p = symbol; *p; ++p) {
11172 if (!(isalnum (*p) || *p == '_'))
11173 *p = '_';
11175 acfg->static_linking_symbol = g_strdup (symbol);
11178 if (acfg->llvm)
11179 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
11180 else
11181 emit_aot_file_info (acfg, info);
11184 static void
11185 emit_blob (MonoAotCompile *acfg)
11187 acfg->blob_closed = TRUE;
11189 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
11192 static void
11193 emit_objc_selectors (MonoAotCompile *acfg)
11195 int i;
11196 char symbol [128];
11198 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
11199 return;
11202 * From
11203 * cat > foo.m << EOF
11204 * void *ret ()
11206 * return @selector(print:);
11208 * EOF
11211 mono_img_writer_emit_unset_mode (acfg->w);
11212 g_assert (acfg->fp);
11213 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
11214 fprintf (acfg->fp, ".align 3\n");
11215 for (i = 0; i < acfg->objc_selectors->len; ++i) {
11216 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
11217 emit_label (acfg, symbol);
11218 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
11219 emit_pointer (acfg, symbol);
11222 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
11223 for (i = 0; i < acfg->objc_selectors->len; ++i) {
11224 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
11225 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
11228 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
11229 fprintf (acfg->fp, ".align 3\n");
11230 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
11231 fprintf (acfg->fp, ".long 0\n");
11232 fprintf (acfg->fp, ".long 16\n");
11235 static void
11236 emit_dwarf_info (MonoAotCompile *acfg)
11238 #ifdef EMIT_DWARF_INFO
11239 int i;
11240 char symbol2 [128];
11242 /* DIEs for methods */
11243 for (i = 0; i < acfg->nmethods; ++i) {
11244 MonoCompile *cfg = acfg->cfgs [i];
11246 if (ignore_cfg (cfg))
11247 continue;
11249 // FIXME: LLVM doesn't define .Lme_...
11250 if (cfg->compile_llvm)
11251 continue;
11253 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
11255 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 ()));
11257 #endif
11260 #ifdef EMIT_WIN32_CODEVIEW_INFO
11261 typedef struct _CodeViewSubSectionData
11263 gchar *start_section;
11264 gchar *end_section;
11265 gchar *start_section_record;
11266 gchar *end_section_record;
11267 int section_type;
11268 int section_record_type;
11269 int section_id;
11270 } CodeViewSubsectionData;
11272 typedef struct _CodeViewCompilerVersion
11274 gint major;
11275 gint minor;
11276 gint revision;
11277 gint patch;
11278 } CodeViewCompilerVersion;
11280 #define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
11281 #define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
11282 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
11283 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
11284 #define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
11285 #define CODEVIEW_CPU_TYPE 0x0
11286 #define CODEVIEW_MAGIC_HEADER 0x4
11288 static void
11289 codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
11291 g_free (section_data->start_section);
11292 g_free (section_data->end_section);
11293 g_free (section_data->start_section_record);
11294 g_free (section_data->end_section_record);
11296 memset (section_data, 0, sizeof (CodeViewSubsectionData));
11299 static void
11300 codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
11302 gint values[4] = { 0 };
11303 gint *value = values;
11305 while (*version && (value < values + G_N_ELEMENTS (values))) {
11306 if (isdigit (*version)) {
11307 *value *= 10;
11308 *value += *version - '0';
11310 else if (*version == '.') {
11311 value++;
11314 version++;
11317 data->major = values[0];
11318 data->minor = values[1];
11319 data->revision = values[2];
11320 data->patch = values[3];
11323 static void
11324 emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
11326 // Starting a new subsection, clear old data.
11327 codeview_clear_subsection_data (section_data);
11329 // Keep subsection data.
11330 section_data->section_id = section_id;
11331 section_data->section_type = section_type;
11332 section_data->section_record_type = section_record_type;
11334 // Allocate all labels used in subsection.
11335 section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
11336 section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
11337 section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
11338 section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
11340 // Subsection type, function symbol.
11341 emit_int32 (acfg, section_data->section_type);
11343 // Subsection size.
11344 emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
11345 emit_label (acfg, section_data->start_section);
11347 // Subsection record size.
11348 fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
11349 emit_label (acfg, section_data->start_section_record);
11351 // Subsection record type.
11352 emit_int16 (acfg, section_record_type);
11355 static void
11356 emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11358 g_assert (section_data->start_section);
11359 g_assert (section_data->end_section);
11360 g_assert (section_data->start_section_record);
11361 g_assert (section_data->end_section_record);
11363 emit_label (acfg, section_data->end_section_record);
11365 if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
11366 // Emit record length.
11367 emit_int16 (acfg, 2);
11369 // Emit specific record type end.
11370 emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
11373 emit_label (acfg, section_data->end_section);
11375 // Next subsection needs to be 4 byte aligned.
11376 emit_alignment (acfg, 4);
11378 *section_id = section_data->section_id + 1;
11379 codeview_clear_subsection_data (section_data);
11382 inline static void
11383 emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
11385 emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
11388 inline static void
11389 emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11391 emit_codeview_end_subsection (acfg, section_data, section_id);
11394 static void
11395 emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
11397 CodeViewSubsectionData section_data = { 0 };
11398 CodeViewCompilerVersion compiler_version = { 0 };
11400 // Start new compiler record subsection.
11401 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, &section_data);
11403 emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
11404 emit_int16 (acfg, CODEVIEW_CPU_TYPE);
11406 // Get compiler version information.
11407 codeview_parse_compiler_version (VERSION, &compiler_version);
11409 // Compiler frontend version, 4 digits.
11410 emit_int16 (acfg, compiler_version.major);
11411 emit_int16 (acfg, compiler_version.minor);
11412 emit_int16 (acfg, compiler_version.revision);
11413 emit_int16 (acfg, compiler_version.patch);
11415 // Compiler backend version, 4 digits (currently same as frontend).
11416 emit_int16 (acfg, compiler_version.major);
11417 emit_int16 (acfg, compiler_version.minor);
11418 emit_int16 (acfg, compiler_version.revision);
11419 emit_int16 (acfg, compiler_version.patch);
11421 // Compiler string.
11422 emit_string (acfg, "Mono AOT compiler");
11424 // Done with section.
11425 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11428 static void
11429 emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
11431 CodeViewSubsectionData section_data = { 0 };
11432 gchar *full_method_name = NULL;
11434 // Start new function record subsection.
11435 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, &section_data);
11437 // Emit 3 int 0 byte padding, currently not used.
11438 emit_zero_bytes (acfg, sizeof (int) * 3);
11440 // Emit size of function.
11441 emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
11443 // Emit 3 int 0 byte padding, currently not used.
11444 emit_zero_bytes (acfg, sizeof (int) * 3);
11446 // Emit reallocation info.
11447 fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
11448 fprintf (acfg->fp, "\t.secidx %s\n", symbol);
11450 // Emit flag, currently not used.
11451 emit_zero_bytes (acfg, 1);
11453 // Emit function name, exclude signature since it should be described by own metadata.
11454 full_method_name = mono_method_full_name (method, FALSE);
11455 emit_string (acfg, full_method_name ? full_method_name : "");
11456 g_free (full_method_name);
11458 // Done with section.
11459 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11462 static void
11463 emit_codeview_info (MonoAotCompile *acfg)
11465 int i;
11466 int section_id = 0;
11467 gchar symbol_buffer[MAX_SYMBOL_SIZE];
11469 // Emit codeview debug info section
11470 emit_section_change (acfg, ".debug$S", 0);
11472 // Emit magic header.
11473 emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
11475 emit_codeview_compiler_info (acfg, &section_id);
11477 for (i = 0; i < acfg->nmethods; ++i) {
11478 MonoCompile *cfg = acfg->cfgs[i];
11480 if (!cfg || COMPILE_LLVM (cfg))
11481 continue;
11483 int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
11484 if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
11485 emit_codeview_function_info (acfg, cfg->method, &section_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
11488 #else
11489 static void
11490 emit_codeview_info (MonoAotCompile *acfg)
11493 #endif /* EMIT_WIN32_CODEVIEW_INFO */
11495 #ifdef EMIT_WIN32_UNWIND_INFO
11496 static UnwindInfoSectionCacheItem *
11497 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11499 UnwindInfoSectionCacheItem *item = NULL;
11501 if (!acfg->unwind_info_section_cache)
11502 acfg->unwind_info_section_cache = g_list_alloc ();
11504 PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
11506 // Search for unwind info in cache.
11507 GList *list = acfg->unwind_info_section_cache;
11508 int list_size = 0;
11509 while (list && list->data) {
11510 item = (UnwindInfoSectionCacheItem*)list->data;
11511 if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
11512 // Cache hit, return cached item.
11513 return item;
11515 list = list->next;
11516 list_size++;
11519 // Add to cache.
11520 if (acfg->unwind_info_section_cache) {
11521 item = g_new0 (UnwindInfoSectionCacheItem, 1);
11522 if (item) {
11523 // Format .xdata section label for function, used to get unwind info address RVA.
11524 // Since the unwind info is similar for most functions, the symbol will be reused.
11525 item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
11527 // Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
11528 //over ownership of unwind info.
11529 item->unwind_info = unwind_info;
11531 // Needs to be emitted once.
11532 item->xdata_section_emitted = FALSE;
11534 // Prepend to beginning of list to speed up inserts.
11535 acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
11539 return item;
11542 static void
11543 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
11545 GList *list = acfg->unwind_info_section_cache;
11547 while (list) {
11548 UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
11549 if (item) {
11550 g_free (item->xdata_section_label);
11551 mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
11553 g_free (item);
11554 list->data = NULL;
11557 list = list->next;
11560 g_list_free (acfg->unwind_info_section_cache);
11561 acfg->unwind_info_section_cache = NULL;
11564 static void
11565 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
11567 // Emit the unwind info struct.
11568 emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
11570 // Emit all unwind codes encoded in unwind info struct.
11571 PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
11572 PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
11574 while (current_unwind_node < last_unwind_node) {
11575 guint8 node_count = 0;
11576 switch (current_unwind_node->UnwindOp) {
11577 case UWOP_PUSH_NONVOL:
11578 case UWOP_ALLOC_SMALL:
11579 case UWOP_SET_FPREG:
11580 case UWOP_PUSH_MACHFRAME:
11581 node_count = 1;
11582 break;
11583 case UWOP_SAVE_NONVOL:
11584 case UWOP_SAVE_XMM128:
11585 node_count = 2;
11586 break;
11587 case UWOP_SAVE_NONVOL_FAR:
11588 case UWOP_SAVE_XMM128_FAR:
11589 node_count = 3;
11590 break;
11591 case UWOP_ALLOC_LARGE:
11592 if (current_unwind_node->OpInfo == 0)
11593 node_count = 2;
11594 else
11595 node_count = 3;
11596 break;
11597 default:
11598 g_assert (!"Unknown unwind opcode.");
11601 while (node_count > 0) {
11602 g_assert (current_unwind_node < last_unwind_node);
11604 //Emit current node.
11605 emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
11607 node_count--;
11608 current_unwind_node++;
11613 // Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
11614 // .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
11615 // UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
11616 // .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
11617 static void
11618 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11620 char *pdata_section_label = NULL;
11622 int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
11623 if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
11624 temp_prefix_len = 0;
11627 // Format .pdata section label for function.
11628 pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
11630 UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
11631 g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
11633 // Emit .pdata section.
11634 emit_section_change (acfg, ".pdata", 0);
11635 emit_alignment (acfg, sizeof (DWORD));
11636 emit_label (acfg, pdata_section_label);
11638 // Emit function start address RVA.
11639 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
11641 // Emit function end address RVA.
11642 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
11644 // Emit unwind info address RVA.
11645 fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
11647 if (!cache_item->xdata_section_emitted) {
11648 // Emit .xdata section.
11649 emit_section_change (acfg, ".xdata", 0);
11650 emit_alignment (acfg, sizeof (DWORD));
11651 emit_label (acfg, cache_item->xdata_section_label);
11653 // Emit unwind info into .xdata section.
11654 emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
11655 cache_item->xdata_section_emitted = TRUE;
11658 g_free (pdata_section_label);
11660 #endif
11662 static gboolean
11663 should_emit_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
11665 #ifdef TARGET_WASM
11666 if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Vector`1"))
11667 /* The SIMD fallback code in Vector<T> is very large, and not likely to be used */
11668 return FALSE;
11669 #endif
11670 if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Volatile"))
11671 /* Read<T>/Write<T> are not needed and cause JIT failures */
11672 return FALSE;
11673 return TRUE;
11676 static gboolean
11677 collect_methods (MonoAotCompile *acfg)
11679 int mindex, i;
11680 MonoImage *image = acfg->image;
11682 /* Collect methods */
11683 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
11684 ERROR_DECL (error);
11685 MonoMethod *method;
11686 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
11688 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11690 if (!method) {
11691 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11692 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11693 mono_error_cleanup (error);
11694 return FALSE;
11697 /* Load all methods eagerly to skip the slower lazy loading code */
11698 mono_class_setup_methods (method->klass);
11700 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
11701 /* Compile the wrapper instead */
11702 /* We do this here instead of add_wrappers () because it is easy to do it here */
11703 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
11704 method = wrapper;
11707 /* FIXME: Some mscorlib methods don't have debug info */
11709 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
11710 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
11711 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
11712 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
11713 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
11714 if (!mono_debug_lookup_method (method)) {
11715 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
11716 exit (1);
11722 if (method->is_generic || mono_class_is_gtd (method->klass)) {
11723 /* Compile the ref shared version instead */
11724 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
11725 if (!method) {
11726 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11727 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11728 mono_error_cleanup (error);
11729 return FALSE;
11733 /* Since we add the normal methods first, their index will be equal to their zero based token index */
11734 add_method_with_index (acfg, method, i, FALSE);
11735 acfg->method_index ++;
11738 /* gsharedvt methods */
11739 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
11740 ERROR_DECL (error);
11741 MonoMethod *method;
11742 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
11744 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
11745 continue;
11747 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11748 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
11750 if ((method->is_generic || mono_class_is_gtd (method->klass)) && should_emit_gsharedvt_method (acfg, method)) {
11751 MonoMethod *gshared;
11753 gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
11754 mono_error_assert_ok (error);
11756 add_extra_method (acfg, gshared);
11760 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11761 add_generic_instances (acfg);
11763 if (mono_aot_mode_is_full (&acfg->aot_opts))
11764 add_wrappers (acfg);
11765 return TRUE;
11768 static void
11769 compile_methods (MonoAotCompile *acfg)
11771 int i, methods_len;
11773 if (acfg->aot_opts.nthreads > 0) {
11774 GPtrArray *frag;
11775 int len, j;
11776 GPtrArray *threads;
11777 MonoThreadHandle *thread_handle;
11778 gpointer *user_data;
11779 MonoMethod **methods;
11781 methods_len = acfg->methods->len;
11783 len = acfg->methods->len / acfg->aot_opts.nthreads;
11784 g_assert (len > 0);
11786 * Partition the list of methods into fragments, and hand it to threads to
11787 * process.
11789 threads = g_ptr_array_new ();
11790 /* Make a copy since acfg->methods is modified by compile_method () */
11791 methods = g_new0 (MonoMethod*, methods_len);
11792 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
11793 for (i = 0; i < methods_len; ++i)
11794 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
11795 i = 0;
11796 while (i < methods_len) {
11797 ERROR_DECL (error);
11798 MonoInternalThread *thread;
11800 frag = g_ptr_array_new ();
11801 for (j = 0; j < len; ++j) {
11802 if (i < methods_len) {
11803 g_ptr_array_add (frag, methods [i]);
11804 i ++;
11808 user_data = g_new0 (gpointer, 3);
11809 user_data [0] = acfg;
11810 user_data [1] = frag;
11812 thread = mono_thread_create_internal (mono_domain_get (), (gpointer)compile_thread_main, user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
11813 mono_error_assert_ok (error);
11815 thread_handle = mono_threads_open_thread_handle (thread->handle);
11816 g_ptr_array_add (threads, thread_handle);
11818 g_free (methods);
11820 for (i = 0; i < threads->len; ++i) {
11821 mono_thread_info_wait_one_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
11822 mono_threads_close_thread_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i));
11824 } else {
11825 methods_len = 0;
11828 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
11829 for (i = methods_len; i < acfg->methods->len; ++i) {
11830 /* This can add new methods to acfg->methods */
11831 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
11834 #ifdef ENABLE_LLVM
11835 if (acfg->llvm)
11836 mono_llvm_fixup_aot_module ();
11837 #endif
11840 static int
11841 compile_asm (MonoAotCompile *acfg)
11843 char *command, *objfile;
11844 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
11845 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
11846 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
11848 #ifdef TARGET_WIN32_MSVC
11849 #define AS_OPTIONS "-c -x assembler"
11850 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
11851 #define AS_OPTIONS "--64"
11852 #elif defined(TARGET_POWERPC64)
11853 #define AS_OPTIONS "-a64 -mppc64"
11854 #elif defined(sparc) && TARGET_SIZEOF_VOID_P == 8
11855 #define AS_OPTIONS "-xarch=v9"
11856 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11857 #define AS_OPTIONS "-arch i386"
11858 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11859 #define AS_OPTIONS "--32"
11860 #else
11861 #define AS_OPTIONS ""
11862 #endif
11864 #if defined(TARGET_OSX)
11865 #define AS_NAME "clang"
11866 #elif defined(TARGET_WIN32_MSVC)
11867 #define AS_NAME "clang.exe"
11868 #else
11869 #define AS_NAME "as"
11870 #endif
11872 #ifdef TARGET_WIN32_MSVC
11873 #define AS_OBJECT_FILE_SUFFIX "obj"
11874 #else
11875 #define AS_OBJECT_FILE_SUFFIX "o"
11876 #endif
11878 #if defined(sparc)
11879 #define LD_NAME "ld"
11880 #define LD_OPTIONS "-shared -G"
11881 #elif defined(__ppc__) && defined(TARGET_MACH)
11882 #define LD_NAME "gcc"
11883 #define LD_OPTIONS "-dynamiclib"
11884 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
11885 #define LD_NAME "clang"
11886 #define LD_OPTIONS "--shared"
11887 #elif defined(TARGET_WIN32_MSVC)
11888 #define LD_NAME "link.exe"
11889 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
11890 #define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
11891 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
11892 #define LD_NAME "gcc"
11893 #define LD_OPTIONS "-shared"
11894 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11895 #define LD_NAME "clang"
11896 #define LD_OPTIONS "-m32 -dynamiclib"
11897 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11898 #define LD_OPTIONS "-m elf_i386"
11899 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
11900 #define LD_NAME "gcc"
11901 #define LD_OPTIONS "--shared"
11902 #elif defined(TARGET_POWERPC64)
11903 #define LD_OPTIONS "-m elf64ppc"
11904 #endif
11906 #ifndef LD_OPTIONS
11907 #define LD_OPTIONS ""
11908 #endif
11910 if (acfg->aot_opts.asm_only) {
11911 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
11912 if (acfg->aot_opts.static_link)
11913 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11914 if (acfg->llvm)
11915 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
11916 return 0;
11919 if (acfg->aot_opts.static_link) {
11920 if (acfg->aot_opts.outfile)
11921 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11922 else
11923 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
11924 } else {
11925 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
11928 #ifdef TARGET_OSX
11929 g_string_append (acfg->as_args, "-c -x assembler");
11930 #endif
11932 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11933 acfg->as_args ? acfg->as_args->str : "",
11934 wrap_path (objfile), wrap_path (acfg->tmpfname));
11935 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11936 if (execute_system (command) != 0) {
11937 g_free (command);
11938 g_free (objfile);
11939 return 1;
11942 if (acfg->llvm && !acfg->llvm_owriter) {
11943 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11944 acfg->as_args ? acfg->as_args->str : "",
11945 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
11946 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11947 if (execute_system (command) != 0) {
11948 g_free (command);
11949 g_free (objfile);
11950 return 1;
11954 g_free (command);
11956 if (acfg->aot_opts.static_link) {
11957 aot_printf (acfg, "Output file: '%s'.\n", objfile);
11958 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11959 g_free (objfile);
11960 return 0;
11963 if (acfg->aot_opts.outfile)
11964 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11965 else
11966 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
11968 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
11970 if (acfg->llvm) {
11971 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
11972 } else {
11973 llvm_ofile = g_strdup ("");
11976 /* replace the ; flags separators with spaces */
11977 g_strdelimit (ld_flags, ';', ' ');
11979 if (acfg->aot_opts.llvm_only)
11980 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
11982 #ifdef TARGET_WIN32_MSVC
11983 g_assert (tmp_outfile_name != NULL);
11984 g_assert (objfile != NULL);
11985 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:%s %s %s", tool_prefix, LD_NAME,
11986 acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, wrap_path (tmp_outfile_name), wrap_path (objfile), wrap_path (llvm_ofile));
11987 #elif defined(LD_NAME)
11988 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
11989 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11990 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11991 #else
11992 // Default (linux)
11993 if (acfg->aot_opts.tool_prefix) {
11994 /* Cross compiling */
11995 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
11996 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11997 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11998 } else {
11999 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
12000 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
12001 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
12003 if (acfg->aot_opts.llvm_only) {
12004 command = g_strdup_printf ("%s %s", acfg->aot_opts.clangxx, args);
12005 } else {
12006 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
12008 g_free (args);
12010 #endif
12011 aot_printf (acfg, "Executing the native linker: %s\n", command);
12012 if (execute_system (command) != 0) {
12013 g_free (tmp_outfile_name);
12014 g_free (outfile_name);
12015 g_free (command);
12016 g_free (objfile);
12017 g_free (ld_flags);
12018 return 1;
12021 g_free (command);
12023 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
12024 printf ("Stripping the binary: %s\n", com);
12025 execute_system (com);
12026 g_free (com);*/
12028 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
12030 * gas generates 'mapping symbols' each time code and data is mixed, which
12031 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
12033 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
12034 aot_printf (acfg, "Stripping the binary: %s\n", command);
12035 if (execute_system (command) != 0) {
12036 g_free (tmp_outfile_name);
12037 g_free (outfile_name);
12038 g_free (command);
12039 g_free (objfile);
12040 return 1;
12042 #endif
12044 if (0 != rename (tmp_outfile_name, outfile_name)) {
12045 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
12046 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
12047 unlink (outfile_name);
12048 rename (tmp_outfile_name, outfile_name);
12052 #if defined(TARGET_MACH)
12053 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
12054 aot_printf (acfg, "Executing dsymutil: %s\n", command);
12055 if (execute_system (command) != 0) {
12056 return 1;
12058 #endif
12060 if (!acfg->aot_opts.save_temps)
12061 unlink (objfile);
12063 g_free (tmp_outfile_name);
12064 g_free (outfile_name);
12065 g_free (objfile);
12067 if (acfg->aot_opts.save_temps)
12068 aot_printf (acfg, "Retained input file.\n");
12069 else
12070 unlink (acfg->tmpfname);
12072 return 0;
12075 static guint8
12076 profread_byte (FILE *infile)
12078 guint8 i;
12079 int res;
12081 res = fread (&i, 1, 1, infile);
12082 g_assert (res == 1);
12083 return i;
12086 static int
12087 profread_int (FILE *infile)
12089 int i, res;
12091 res = fread (&i, 4, 1, infile);
12092 g_assert (res == 1);
12093 return i;
12096 static char*
12097 profread_string (FILE *infile)
12099 int len, res;
12100 char *pbuf;
12102 len = profread_int (infile);
12103 pbuf = (char*)g_malloc (len + 1);
12104 res = fread (pbuf, 1, len, infile);
12105 g_assert (res == len);
12106 pbuf [len] = '\0';
12107 return pbuf;
12110 static void
12111 load_profile_file (MonoAotCompile *acfg, char *filename)
12113 FILE *infile;
12114 char buf [1024];
12115 int res, len, version;
12116 char magic [32];
12118 infile = fopen (filename, "rb");
12119 if (!infile) {
12120 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
12121 exit (1);
12124 printf ("Using profile data file '%s'\n", filename);
12126 sprintf (magic, AOT_PROFILER_MAGIC);
12127 len = strlen (magic);
12128 res = fread (buf, 1, len, infile);
12129 magic [len] = '\0';
12130 buf [len] = '\0';
12131 if ((res != len) || strcmp (buf, magic) != 0) {
12132 printf ("Profile file has wrong header: '%s'.\n", buf);
12133 fclose (infile);
12134 exit (1);
12136 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
12137 version = profread_int (infile);
12138 if (version != expected_version) {
12139 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
12140 fclose (infile);
12141 exit (1);
12144 ProfileData *data = g_new0 (ProfileData, 1);
12145 data->images = g_hash_table_new (NULL, NULL);
12146 data->classes = g_hash_table_new (NULL, NULL);
12147 data->ginsts = g_hash_table_new (NULL, NULL);
12148 data->methods = g_hash_table_new (NULL, NULL);
12150 while (TRUE) {
12151 int type = profread_byte (infile);
12152 int id = profread_int (infile);
12154 if (type == AOTPROF_RECORD_NONE)
12155 break;
12157 switch (type) {
12158 case AOTPROF_RECORD_IMAGE: {
12159 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
12160 idata->name = profread_string (infile);
12161 char *mvid = profread_string (infile);
12162 g_free (mvid);
12163 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
12164 break;
12166 case AOTPROF_RECORD_GINST: {
12167 int i;
12168 int len = profread_int (infile);
12170 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
12171 gdata->argc = len;
12172 gdata->argv = g_new0 (ClassProfileData*, len);
12174 for (i = 0; i < len; ++i) {
12175 int class_id = profread_int (infile);
12177 gdata->argv [i] = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
12178 g_assert (gdata->argv [i]);
12180 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
12181 break;
12183 case AOTPROF_RECORD_TYPE: {
12184 int type = profread_byte (infile);
12186 switch (type) {
12187 case MONO_TYPE_CLASS: {
12188 int image_id = profread_int (infile);
12189 int ginst_id = profread_int (infile);
12190 char *class_name = profread_string (infile);
12192 ImageProfileData *image = (ImageProfileData*)g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
12193 g_assert (image);
12195 char *p = strrchr (class_name, '.');
12196 g_assert (p);
12197 *p = '\0';
12199 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
12200 cdata->image = image;
12201 cdata->ns = g_strdup (class_name);
12202 cdata->name = g_strdup (p + 1);
12204 if (ginst_id != -1) {
12205 cdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
12206 g_assert (cdata->inst);
12208 g_free (class_name);
12210 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
12211 break;
12213 #if 0
12214 case MONO_TYPE_SZARRAY: {
12215 int elem_id = profread_int (infile);
12216 // FIXME:
12217 break;
12219 #endif
12220 default:
12221 g_assert_not_reached ();
12222 break;
12224 break;
12226 case AOTPROF_RECORD_METHOD: {
12227 int class_id = profread_int (infile);
12228 int ginst_id = profread_int (infile);
12229 int param_count = profread_int (infile);
12230 char *method_name = profread_string (infile);
12231 char *sig = profread_string (infile);
12233 ClassProfileData *klass = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
12234 g_assert (klass);
12236 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
12237 mdata->id = id;
12238 mdata->klass = klass;
12239 mdata->name = method_name;
12240 mdata->signature = sig;
12241 mdata->param_count = param_count;
12243 if (ginst_id != -1) {
12244 mdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
12245 g_assert (mdata->inst);
12247 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
12248 break;
12250 default:
12251 printf ("%d\n", type);
12252 g_assert_not_reached ();
12253 break;
12257 fclose (infile);
12258 acfg->profile_data = g_list_append (acfg->profile_data, data);
12261 static void
12262 resolve_class (ClassProfileData *cdata);
12264 static void
12265 resolve_ginst (GInstProfileData *inst_data)
12267 int i;
12269 if (inst_data->inst)
12270 return;
12272 for (i = 0; i < inst_data->argc; ++i) {
12273 resolve_class (inst_data->argv [i]);
12274 if (!inst_data->argv [i]->klass)
12275 return;
12277 MonoType **args = g_new0 (MonoType*, inst_data->argc);
12278 for (i = 0; i < inst_data->argc; ++i)
12279 args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
12281 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
12284 static void
12285 resolve_class (ClassProfileData *cdata)
12287 ERROR_DECL (error);
12288 MonoClass *klass;
12290 if (!cdata->image->image)
12291 return;
12293 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
12294 if (!klass) {
12295 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
12296 return;
12298 if (cdata->inst) {
12299 resolve_ginst (cdata->inst);
12300 if (!cdata->inst->inst)
12301 return;
12302 MonoGenericContext ctx;
12304 memset (&ctx, 0, sizeof (ctx));
12305 ctx.class_inst = cdata->inst->inst;
12306 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
12307 } else {
12308 cdata->klass = klass;
12313 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
12315 static void
12316 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data, MonoAssembly* current)
12318 GHashTableIter iter;
12319 gpointer key, value;
12320 int i;
12322 if (!data)
12323 return;
12325 /* Images */
12326 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
12327 g_hash_table_iter_init (&iter, data->images);
12328 while (g_hash_table_iter_next (&iter, &key, &value)) {
12329 ImageProfileData *idata = (ImageProfileData*)value;
12331 if (!strcmp (current->aname.name, idata->name)) {
12332 idata->image = current->image;
12333 break;
12336 for (i = 0; i < assemblies->len; ++i) {
12337 MonoAssembly *ass = (MonoAssembly*)g_ptr_array_index (assemblies, i);
12339 if (!strcmp (ass->aname.name, idata->name)) {
12340 idata->image = ass->image;
12341 break;
12345 g_ptr_array_free (assemblies, TRUE);
12347 /* Classes */
12348 g_hash_table_iter_init (&iter, data->classes);
12349 while (g_hash_table_iter_next (&iter, &key, &value)) {
12350 ClassProfileData *cdata = (ClassProfileData*)value;
12352 if (!cdata->image->image) {
12353 if (acfg->aot_opts.verbose)
12354 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
12355 continue;
12358 resolve_class (cdata);
12360 if (cdata->klass)
12361 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
12365 /* Methods */
12366 g_hash_table_iter_init (&iter, data->methods);
12367 while (g_hash_table_iter_next (&iter, &key, &value)) {
12368 MethodProfileData *mdata = (MethodProfileData*)value;
12369 MonoClass *klass;
12370 MonoMethod *m;
12371 gpointer miter;
12373 resolve_class (mdata->klass);
12374 klass = mdata->klass->klass;
12375 if (!klass) {
12376 if (acfg->aot_opts.verbose)
12377 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
12378 continue;
12380 miter = NULL;
12381 while ((m = mono_class_get_methods (klass, &miter))) {
12382 ERROR_DECL (error);
12384 if (strcmp (m->name, mdata->name))
12385 continue;
12386 MonoMethodSignature *sig = mono_method_signature_internal (m);
12387 if (!sig)
12388 continue;
12389 if (sig->param_count != mdata->param_count)
12390 continue;
12391 if (mdata->inst) {
12392 resolve_ginst (mdata->inst);
12393 if (!mdata->inst->inst)
12394 continue;
12395 MonoGenericContext ctx;
12397 memset (&ctx, 0, sizeof (ctx));
12398 ctx.method_inst = mdata->inst->inst;
12400 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
12401 if (!m)
12402 continue;
12403 sig = mono_method_signature_checked (m, error);
12404 if (!is_ok (error)) {
12405 mono_error_cleanup (error);
12406 continue;
12409 char *sig_str = mono_signature_full_name (sig);
12410 gboolean match = !strcmp (sig_str, mdata->signature);
12411 g_free (sig_str);
12412 if (!match)
12414 continue;
12415 //printf ("%s\n", mono_method_full_name (m, 1));
12416 mdata->method = m;
12417 break;
12419 if (!mdata->method) {
12420 if (acfg->aot_opts.verbose)
12421 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
12426 static gboolean
12427 inst_references_image (MonoGenericInst *inst, MonoImage *image)
12429 int i;
12431 for (i = 0; i < inst->type_argc; ++i) {
12432 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12433 if (m_class_get_image (k) == image)
12434 return TRUE;
12435 if (mono_class_is_ginst (k)) {
12436 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
12437 if (inst_references_image (kinst, image))
12438 return TRUE;
12441 return FALSE;
12444 static gboolean
12445 is_local_inst (MonoGenericInst *inst, MonoImage *image)
12447 int i;
12449 for (i = 0; i < inst->type_argc; ++i) {
12450 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12451 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
12452 return FALSE;
12454 return TRUE;
12457 static void
12458 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
12460 GHashTableIter iter;
12461 gpointer key, value;
12462 int count = 0;
12464 if (!data)
12465 return;
12467 if (acfg->aot_opts.profile_only) {
12468 /* Add methods referenced by the profile */
12469 g_hash_table_iter_init (&iter, data->methods);
12470 while (g_hash_table_iter_next (&iter, &key, &value)) {
12471 MethodProfileData *mdata = (MethodProfileData*)value;
12472 MonoMethod *m = mdata->method;
12474 if (!m)
12475 continue;
12476 if (m->is_inflated)
12477 continue;
12478 add_extra_method (acfg, m);
12479 g_hash_table_insert (acfg->profile_methods, m, m);
12480 count ++;
12485 * Add method instances 'related' to this assembly to the AOT image.
12487 g_hash_table_iter_init (&iter, data->methods);
12488 while (g_hash_table_iter_next (&iter, &key, &value)) {
12489 MethodProfileData *mdata = (MethodProfileData*)value;
12490 MonoMethod *m = mdata->method;
12491 MonoGenericContext *ctx;
12493 if (!m)
12494 continue;
12495 if (!m->is_inflated)
12496 continue;
12498 ctx = mono_method_get_context (m);
12499 /* For simplicity, add instances which reference the assembly we are compiling */
12500 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
12501 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
12502 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12503 //printf ("%s\n", mono_method_full_name (m, TRUE));
12504 add_extra_method (acfg, m);
12505 count ++;
12506 } else if (m_class_get_image (m->klass) == acfg->image &&
12507 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
12508 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
12509 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12510 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
12511 //printf ("%s\n", mono_method_full_name (m, TRUE));
12512 add_extra_method (acfg, m);
12513 count ++;
12516 * FIXME: We might skip some instances, for example:
12517 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
12518 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
12522 printf ("Added %d methods from profile.\n", count);
12525 static void
12526 init_got_info (GotInfo *info)
12528 int i;
12530 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12531 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12532 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12533 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12534 info->got_patches = g_ptr_array_new ();
12537 static MonoAotCompile*
12538 acfg_create (MonoAssembly *ass, guint32 opts)
12540 MonoImage *image = ass->image;
12541 MonoAotCompile *acfg;
12543 acfg = g_new0 (MonoAotCompile, 1);
12544 acfg->methods = g_ptr_array_new ();
12545 acfg->method_indexes = g_hash_table_new (NULL, NULL);
12546 acfg->method_depth = g_hash_table_new (NULL, NULL);
12547 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
12548 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12549 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
12550 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
12551 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12552 acfg->method_to_external_icall_symbol_name = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12553 acfg->image_hash = g_hash_table_new (NULL, NULL);
12554 acfg->image_table = g_ptr_array_new ();
12555 acfg->globals = g_ptr_array_new ();
12556 acfg->image = image;
12557 acfg->opts = opts;
12558 /* TODO: Write out set of SIMD instructions used, rather than just those available */
12559 #ifndef MONO_CROSS_COMPILE
12560 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
12561 #endif
12562 acfg->mempool = mono_mempool_new ();
12563 acfg->extra_methods = g_ptr_array_new ();
12564 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
12565 acfg->unwind_ops = g_ptr_array_new ();
12566 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
12567 acfg->method_order = g_ptr_array_new ();
12568 acfg->export_names = g_hash_table_new (NULL, NULL);
12569 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
12570 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
12571 acfg->ginst_blob_hash = g_hash_table_new (mono_metadata_generic_inst_hash, mono_metadata_generic_inst_equal);
12572 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
12573 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12574 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12575 acfg->profile_methods = g_hash_table_new (NULL, NULL);
12576 mono_os_mutex_init_recursive (&acfg->mutex);
12578 init_got_info (&acfg->got_info);
12579 init_got_info (&acfg->llvm_got_info);
12581 method_to_external_icall_symbol_name = acfg->method_to_external_icall_symbol_name;
12582 return acfg;
12585 static void
12586 got_info_free (GotInfo *info)
12588 int i;
12590 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12591 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
12592 g_free (info->patch_to_got_offset_by_type);
12593 g_hash_table_destroy (info->patch_to_got_offset);
12594 g_ptr_array_free (info->got_patches, TRUE);
12597 static void
12598 acfg_free (MonoAotCompile *acfg)
12600 int i;
12602 mono_img_writer_destroy (acfg->w);
12603 for (i = 0; i < acfg->nmethods; ++i)
12604 if (acfg->cfgs [i])
12605 mono_destroy_compile (acfg->cfgs [i]);
12607 g_free (acfg->cfgs);
12609 g_free (acfg->static_linking_symbol);
12610 g_free (acfg->got_symbol);
12611 g_free (acfg->plt_symbol);
12612 g_ptr_array_free (acfg->methods, TRUE);
12613 g_ptr_array_free (acfg->image_table, TRUE);
12614 g_ptr_array_free (acfg->globals, TRUE);
12615 g_ptr_array_free (acfg->unwind_ops, TRUE);
12616 g_hash_table_destroy (acfg->method_indexes);
12617 g_hash_table_destroy (acfg->method_depth);
12618 g_hash_table_destroy (acfg->plt_offset_to_entry);
12619 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12620 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
12621 g_free (acfg->patch_to_plt_entry);
12622 g_hash_table_destroy (acfg->method_to_cfg);
12623 g_hash_table_destroy (acfg->token_info_hash);
12624 g_hash_table_destroy (acfg->method_to_pinvoke_import);
12625 g_hash_table_destroy (acfg->method_to_external_icall_symbol_name);
12626 g_hash_table_destroy (acfg->image_hash);
12627 g_hash_table_destroy (acfg->unwind_info_offsets);
12628 g_hash_table_destroy (acfg->method_label_hash);
12629 g_hash_table_destroy (acfg->typespec_classes);
12630 g_hash_table_destroy (acfg->export_names);
12631 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
12632 g_hash_table_destroy (acfg->klass_blob_hash);
12633 g_hash_table_destroy (acfg->method_blob_hash);
12634 got_info_free (&acfg->got_info);
12635 got_info_free (&acfg->llvm_got_info);
12636 arch_free_unwind_info_section_cache (acfg);
12637 mono_mempool_destroy (acfg->mempool);
12639 method_to_external_icall_symbol_name = NULL;
12640 g_free (acfg);
12643 #define WRAPPER(e,n) n,
12644 static const char* const
12645 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
12646 #include "mono/metadata/wrapper-types.h"
12647 NULL
12650 static G_GNUC_UNUSED const char*
12651 get_wrapper_type_name (int type)
12653 return wrapper_type_names [type];
12656 //#define DUMP_PLT
12657 //#define DUMP_GOT
12659 static void aot_dump (MonoAotCompile *acfg)
12661 FILE *dumpfile;
12662 char * dumpname;
12664 JsonWriter writer;
12665 mono_json_writer_init (&writer);
12667 mono_json_writer_object_begin(&writer);
12669 // Methods
12670 mono_json_writer_indent (&writer);
12671 mono_json_writer_object_key(&writer, "methods");
12672 mono_json_writer_array_begin (&writer);
12674 int i;
12675 for (i = 0; i < acfg->nmethods; ++i) {
12676 MonoCompile *cfg;
12677 MonoMethod *method;
12678 MonoClass *klass;
12680 cfg = acfg->cfgs [i];
12681 if (ignore_cfg (cfg))
12682 continue;
12684 method = cfg->orig_method;
12686 mono_json_writer_indent (&writer);
12687 mono_json_writer_object_begin(&writer);
12689 mono_json_writer_indent (&writer);
12690 mono_json_writer_object_key(&writer, "name");
12691 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
12693 mono_json_writer_indent (&writer);
12694 mono_json_writer_object_key(&writer, "signature");
12695 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
12697 mono_json_writer_indent (&writer);
12698 mono_json_writer_object_key(&writer, "code_size");
12699 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
12701 klass = method->klass;
12703 mono_json_writer_indent (&writer);
12704 mono_json_writer_object_key(&writer, "class");
12705 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
12707 mono_json_writer_indent (&writer);
12708 mono_json_writer_object_key(&writer, "namespace");
12709 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
12711 mono_json_writer_indent (&writer);
12712 mono_json_writer_object_key(&writer, "wrapper_type");
12713 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
12715 mono_json_writer_indent_pop (&writer);
12716 mono_json_writer_indent (&writer);
12717 mono_json_writer_object_end (&writer);
12718 mono_json_writer_printf (&writer, ",\n");
12721 mono_json_writer_indent_pop (&writer);
12722 mono_json_writer_indent (&writer);
12723 mono_json_writer_array_end (&writer);
12724 mono_json_writer_printf (&writer, ",\n");
12726 // PLT entries
12727 #ifdef DUMP_PLT
12728 mono_json_writer_indent_push (&writer);
12729 mono_json_writer_indent (&writer);
12730 mono_json_writer_object_key(&writer, "plt");
12731 mono_json_writer_array_begin (&writer);
12733 for (i = 0; i < acfg->plt_offset; ++i) {
12734 MonoPltEntry *plt_entry = NULL;
12735 MonoJumpInfo *ji;
12737 if (i == 0)
12739 * The first plt entry is unused.
12741 continue;
12743 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
12744 ji = plt_entry->ji;
12746 mono_json_writer_indent (&writer);
12747 mono_json_writer_printf (&writer, "{ ");
12748 mono_json_writer_object_key(&writer, "symbol");
12749 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
12752 mono_json_writer_indent_pop (&writer);
12753 mono_json_writer_indent (&writer);
12754 mono_json_writer_array_end (&writer);
12755 mono_json_writer_printf (&writer, ",\n");
12756 #endif
12758 // GOT entries
12759 #ifdef DUMP_GOT
12760 mono_json_writer_indent_push (&writer);
12761 mono_json_writer_indent (&writer);
12762 mono_json_writer_object_key(&writer, "got");
12763 mono_json_writer_array_begin (&writer);
12765 mono_json_writer_indent_push (&writer);
12766 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
12767 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
12769 mono_json_writer_indent (&writer);
12770 mono_json_writer_printf (&writer, "{ ");
12771 mono_json_writer_object_key(&writer, "patch_name");
12772 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
12775 mono_json_writer_indent_pop (&writer);
12776 mono_json_writer_indent (&writer);
12777 mono_json_writer_array_end (&writer);
12778 mono_json_writer_printf (&writer, ",\n");
12779 #endif
12781 mono_json_writer_indent_pop (&writer);
12782 mono_json_writer_indent (&writer);
12783 mono_json_writer_object_end (&writer);
12785 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
12786 dumpfile = fopen (dumpname, "w+");
12787 g_free (dumpname);
12789 fprintf (dumpfile, "%s", writer.text->str);
12790 fclose (dumpfile);
12792 mono_json_writer_destroy (&writer);
12795 static const MonoJitICallId preinited_jit_icalls [] = {
12796 MONO_JIT_ICALL_mini_llvm_init_method,
12797 MONO_JIT_ICALL_mini_llvm_init_gshared_method_this,
12798 MONO_JIT_ICALL_mini_llvm_init_gshared_method_mrgctx,
12799 MONO_JIT_ICALL_mini_llvm_init_gshared_method_vtable,
12800 MONO_JIT_ICALL_mini_llvmonly_throw_nullref_exception,
12801 MONO_JIT_ICALL_mono_llvm_throw_corlib_exception,
12802 MONO_JIT_ICALL_mono_threads_state_poll,
12803 MONO_JIT_ICALL_mini_llvmonly_init_vtable_slot,
12804 MONO_JIT_ICALL_mono_helper_ldstr_mscorlib,
12805 MONO_JIT_ICALL_mono_fill_method_rgctx,
12806 MONO_JIT_ICALL_mono_fill_class_rgctx
12809 static void
12810 add_preinit_slot (MonoAotCompile *acfg, MonoJumpInfo *ji)
12812 if (!acfg->aot_opts.llvm_only)
12813 get_got_offset (acfg, FALSE, ji);
12814 get_got_offset (acfg, TRUE, ji);
12817 static void
12818 add_preinit_got_slots (MonoAotCompile *acfg)
12820 MonoJumpInfo *ji;
12821 int i;
12824 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
12825 * during method initialization etc.
12828 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12829 ji->type = MONO_PATCH_INFO_IMAGE;
12830 ji->data.image = acfg->image;
12831 add_preinit_slot (acfg, ji);
12833 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12834 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
12835 add_preinit_slot (acfg, ji);
12837 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12838 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
12839 add_preinit_slot (acfg, ji);
12841 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12842 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
12843 add_preinit_slot (acfg, ji);
12845 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12846 ji->type = MONO_PATCH_INFO_AOT_MODULE;
12847 add_preinit_slot (acfg, ji);
12849 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12850 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
12851 add_preinit_slot (acfg, ji);
12853 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12854 ji->type = MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG;
12855 add_preinit_slot (acfg, ji);
12857 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12858 ji->type = MONO_PATCH_INFO_GC_SAFE_POINT_FLAG;
12859 add_preinit_slot (acfg, ji);
12861 if (!acfg->aot_opts.llvm_only) {
12862 for (i = 0; i < TLS_KEY_NUM; i++) {
12863 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12864 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12865 ji->data.jit_icall_id = mono_get_tls_key_to_jit_icall_id (i);
12866 add_preinit_slot (acfg, ji);
12870 /* Called by native-to-managed wrappers on possibly unattached threads */
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_JIT_ICALL_mono_threads_attach_coop;
12874 add_preinit_slot (acfg, ji);
12876 for (i = 0; i < G_N_ELEMENTS (preinited_jit_icalls); ++i) {
12877 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12878 ji->type = MONO_PATCH_INFO_JIT_ICALL_ID;
12879 ji->data.jit_icall_id = preinited_jit_icalls [i];
12880 add_preinit_slot (acfg, ji);
12883 if (acfg->aot_opts.llvm_only)
12884 acfg->nshared_got_entries = acfg->llvm_got_offset;
12885 else
12886 acfg->nshared_got_entries = acfg->got_offset;
12887 g_assert (acfg->nshared_got_entries);
12890 static void
12891 mono_dedup_log_stats (MonoAotCompile *acfg)
12893 GHashTableIter iter;
12894 g_assert (acfg->dedup_stats);
12896 if (!acfg->dedup_emit_mode)
12897 return;
12899 // If dedup_emit_mode, acfg is the dummy dedup module that consolidates
12900 // deduped modules
12901 g_hash_table_iter_init (&iter, acfg->method_to_cfg);
12902 MonoCompile *dcfg = NULL;
12903 MonoMethod *method = NULL;
12905 size_t wrappers_size_saved = 0;
12906 size_t inflated_size_saved = 0;
12907 size_t copied_singles = 0;
12908 int wrappers_saved = 0;
12909 int instances_saved = 0;
12910 int copied = 0;
12912 while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
12913 gchar *dedup_name = mono_aot_get_mangled_method_name (method);
12914 guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
12916 if (count == 0)
12917 continue;
12919 if (acfg->dedup_emit_mode) {
12920 // Size *saved* is the size due to things not emitted.
12921 if (count < 2) {
12922 // Just moved, didn't save space / dedup
12923 copied ++;
12924 copied_singles += dcfg->code_len;
12925 } else if (method->wrapper_type != MONO_WRAPPER_NONE) {
12926 wrappers_saved ++;
12927 wrappers_size_saved += dcfg->code_len * (count - 1);
12928 } else {
12929 instances_saved ++;
12930 inflated_size_saved += dcfg->code_len * (count - 1);
12933 if (acfg->aot_opts.dedup) {
12934 if (method->wrapper_type != MONO_WRAPPER_NONE) {
12935 wrappers_saved ++;
12936 wrappers_size_saved += dcfg->code_len * count;
12937 } else {
12938 instances_saved ++;
12939 inflated_size_saved += dcfg->code_len * count;
12944 aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%d methods, %zu bytes\n", wrappers_saved, wrappers_size_saved);
12945 aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%d methods, %zu bytes\n", instances_saved, inflated_size_saved);
12946 if (acfg->dedup_emit_mode)
12947 aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%d methods, %zu bytes\n", copied, copied_singles);
12949 g_hash_table_destroy (acfg->dedup_stats);
12950 acfg->dedup_stats = NULL;
12953 // Flush the cache to tell future calls what to skip
12954 static void
12955 mono_flush_method_cache (MonoAotCompile *acfg)
12957 GHashTable *method_cache = acfg->dedup_cache;
12958 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12959 if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
12960 g_free (filename);
12961 return;
12964 acfg->dedup_cache = NULL;
12966 FILE *cache = fopen (filename, "w");
12968 if (!cache)
12969 g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
12971 GHashTableIter iter;
12972 gchar *name = NULL;
12973 g_hash_table_iter_init (&iter, method_cache);
12974 gboolean cont = TRUE;
12975 while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
12976 int res = fprintf (cache, "%s\n", name);
12977 cont = res >= 0;
12979 // FIXME: don't assert if error when flushing
12980 g_assert (cont);
12982 fclose (cache);
12983 g_free (filename);
12985 // The keys are all in the imageset, nothing to free
12986 // Values are just pointers to memory owned elsewhere, or sentinels
12987 g_hash_table_destroy (method_cache);
12990 // Read in what has been emitted by previous invocations,
12991 // what can be skipped
12992 static void
12993 mono_read_method_cache (MonoAotCompile *acfg)
12995 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12996 // Only do once, when dedup_cache is null
12997 if (acfg->dedup_cache)
12998 goto early_exit;
13000 if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
13001 g_assert (acfg->dedup_stats);
13003 // only in skip mode
13004 if (!acfg->aot_opts.dedup)
13005 goto early_exit;
13007 g_assert (acfg->dedup_cache);
13009 FILE *cache;
13010 cache = fopen (filename, "r");
13011 if (!cache)
13012 goto early_exit;
13014 // Since we do pointer comparisons, and it can't be allocated at
13015 // the address 0x1 due to alignment, we use this as a sentinel
13016 gpointer other_acfg_sentinel;
13017 other_acfg_sentinel = GINT_TO_POINTER (0x1);
13019 if (fseek (cache, 0L, SEEK_END))
13020 goto cleanup;
13022 size_t fileLength;
13023 fileLength = ftell (cache);
13024 g_assert (fileLength > 0);
13026 if (fseek (cache, 0L, SEEK_SET))
13027 goto cleanup;
13029 // Avoid thousands of new malloc entries
13030 // FIXME: allocate into imageset, so we don't need to free.
13031 // put the other mangled names there too.
13032 char *bulk;
13033 bulk = g_malloc0 (fileLength * sizeof (char));
13034 size_t offset;
13035 offset = 0;
13037 while (fgets (&bulk [offset], fileLength - offset, cache)) {
13038 // strip newline
13039 char *line = &bulk [offset];
13040 size_t len = strlen (line);
13041 if (len == 0)
13042 break;
13044 if (len >= 0 && line [len] == '\n')
13045 line [len] = '\0';
13046 offset += strlen (line) + 1;
13047 g_assert (fileLength >= offset);
13049 g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
13052 cleanup:
13053 fclose (cache);
13055 early_exit:
13056 g_free (filename);
13057 return;
13060 typedef struct {
13061 GHashTable *cache;
13062 GHashTable *stats;
13063 gboolean emit_inflated_methods;
13064 MonoAssembly *inflated_assembly;
13065 } MonoAotState;
13067 static MonoAotState *
13068 alloc_aot_state (void)
13070 MonoAotState *state = g_malloc (sizeof (MonoAotState));
13071 // FIXME: Should this own the memory?
13072 state->cache = g_hash_table_new (g_str_hash, g_str_equal);
13073 state->stats = g_hash_table_new (g_str_hash, g_str_equal);
13074 // Start in "collect mode"
13075 state->emit_inflated_methods = FALSE;
13076 state->inflated_assembly = NULL;
13077 return state;
13080 static void
13081 free_aot_state (MonoAotState *astate)
13083 g_hash_table_destroy (astate->cache);
13084 g_free (astate);
13087 static void
13088 mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
13090 GHashTableIter iter;
13091 gchar *name = NULL;
13092 MonoMethod *method = NULL;
13094 acfg->dedup_emit_mode = TRUE;
13096 g_hash_table_iter_init (&iter, astate->cache);
13097 while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
13098 add_method_full (acfg, method, TRUE, 0);
13100 return;
13103 static void
13104 mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
13106 if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
13107 return;
13109 if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
13110 // Thread the state through when making the inflate pass
13111 *astate = *global_aot_state;
13114 if (!*astate) {
13115 *astate = alloc_aot_state ();
13116 *global_aot_state = *astate;
13119 acfg->dedup_cache = (*astate)->cache;
13120 acfg->dedup_stats = (*astate)->stats;
13122 // fills out acfg->dedup_cache
13123 if (acfg->aot_opts.dedup)
13124 mono_read_method_cache (acfg);
13126 if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
13127 gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
13128 gchar *asm_file = NULL;
13130 // Get the last part of the path, the filename
13131 for (int i=0; asm_path [i] != NULL; i++)
13132 asm_file = asm_path [i];
13134 if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
13135 // Save
13136 *is_dedup_dummy = TRUE;
13137 (*astate)->inflated_assembly = ass;
13139 g_strfreev (asm_path);
13140 } else if ((*astate)->inflated_assembly) {
13141 *is_dedup_dummy = (ass == (*astate)->inflated_assembly);
13145 int
13146 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13148 // create assembly, loop and add extra_methods
13149 // in add_generic_instances , rip out what's in that for loop
13150 // and apply that to this aot_state inside of mono_compile_assembly
13151 MonoAotState *astate;
13152 astate = *(MonoAotState **)aot_state;
13153 g_assert (astate);
13155 // FIXME: allow suffixes?
13156 if (!astate->inflated_assembly) {
13157 const char* inflate = strstr (aot_options, "dedup-inflate");
13158 if (!inflate)
13159 return 0;
13160 else
13161 g_error ("Error: mono was not given an assembly with the provided inflate name\n");
13164 // Switch modes
13165 astate->emit_inflated_methods = TRUE;
13167 int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
13169 *aot_state = NULL;
13170 free_aot_state (astate);
13172 return res;
13175 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13176 static MonoMethodSignature * const * const interp_in_static_sigs [] = {
13177 &mono_icall_sig_bool_ptr_int32_ptrref,
13178 &mono_icall_sig_bool_ptr_ptrref,
13179 &mono_icall_sig_int32_int32_ptrref,
13180 &mono_icall_sig_int32_int32_ptr_ptrref,
13181 &mono_icall_sig_int32_ptr_int32_ptr,
13182 &mono_icall_sig_int32_ptr_int32_ptrref,
13183 &mono_icall_sig_int32_ptr_ptrref,
13184 &mono_icall_sig_object_object_ptr_ptr_ptr,
13185 &mono_icall_sig_object,
13186 &mono_icall_sig_ptr_int32_ptrref,
13187 &mono_icall_sig_ptr_ptr_int32_ptr_ptr_ptrref,
13188 &mono_icall_sig_ptr_ptr_int32_ptr_ptrref,
13189 &mono_icall_sig_ptr_ptr_int32_ptrref,
13190 &mono_icall_sig_ptr_ptr_ptr_int32_ptrref,
13191 &mono_icall_sig_ptr_ptr_ptr_ptrref_ptrref,
13192 &mono_icall_sig_ptr_ptr_ptr_ptr_ptrref,
13193 &mono_icall_sig_ptr_ptr_ptr_ptrref,
13194 &mono_icall_sig_ptr_ptr_ptrref,
13195 &mono_icall_sig_ptr_ptr_uint32_ptrref,
13196 &mono_icall_sig_ptr_uint32_ptrref,
13197 &mono_icall_sig_void_object_ptr_ptr_ptr,
13198 &mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref_ptr_ptrref,
13199 &mono_icall_sig_void_ptr_ptr_int32_ptr_ptrref,
13200 &mono_icall_sig_void_ptr_ptr_ptrref,
13201 &mono_icall_sig_void_ptr_ptrref,
13202 &mono_icall_sig_void_ptr,
13203 &mono_icall_sig_void_int32_ptrref,
13204 &mono_icall_sig_void_uint32_ptrref,
13205 &mono_icall_sig_void,
13207 #else
13208 // Common signatures for which we use interp in wrappers even in fullaot + trampolines mode
13209 // for increased performance
13210 static MonoMethodSignature *const * const interp_in_static_common_sigs [] = {
13211 &mono_icall_sig_void,
13212 &mono_icall_sig_ptr,
13213 &mono_icall_sig_void_ptr,
13214 &mono_icall_sig_ptr_ptr,
13215 &mono_icall_sig_void_ptr_ptr,
13216 &mono_icall_sig_ptr_ptr_ptr,
13217 &mono_icall_sig_void_ptr_ptr_ptr,
13218 &mono_icall_sig_ptr_ptr_ptr_ptr,
13219 &mono_icall_sig_void_ptr_ptr_ptr_ptr,
13220 &mono_icall_sig_ptr_ptr_ptr_ptr_ptr,
13221 &mono_icall_sig_void_ptr_ptr_ptr_ptr_ptr,
13222 &mono_icall_sig_ptr_ptr_ptr_ptr_ptr_ptr,
13223 &mono_icall_sig_void_ptr_ptr_ptr_ptr_ptr_ptr,
13224 &mono_icall_sig_ptr_ptr_ptr_ptr_ptr_ptr_ptr,
13226 #endif
13228 static void
13229 add_interp_in_wrapper_for_sig (MonoAotCompile *acfg, MonoMethodSignature *sig)
13231 MonoMethod *wrapper;
13233 sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
13234 sig->pinvoke = FALSE;
13235 wrapper = mini_get_interp_in_wrapper (sig);
13236 add_method (acfg, wrapper);
13240 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
13242 MonoImage *image = ass->image;
13243 int res;
13244 MonoAotCompile *acfg;
13245 char *p;
13246 TV_DECLARE (atv);
13247 TV_DECLARE (btv);
13249 acfg = acfg_create (ass, opts);
13251 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
13252 acfg->aot_opts.write_symbols = TRUE;
13253 acfg->aot_opts.ntrampolines = 4096;
13254 acfg->aot_opts.nrgctx_trampolines = 4096;
13255 acfg->aot_opts.nimt_trampolines = 512;
13256 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
13257 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
13258 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13259 acfg->aot_opts.nftnptr_arg_trampolines = 128;
13260 #endif
13261 acfg->aot_opts.nunbox_arbitrary_trampolines = 256;
13262 if (!acfg->aot_opts.llvm_path)
13263 acfg->aot_opts.llvm_path = g_strdup ("");
13264 acfg->aot_opts.temp_path = g_strdup ("");
13265 #ifdef MONOTOUCH
13266 acfg->aot_opts.use_trampolines_page = TRUE;
13267 #endif
13268 acfg->aot_opts.clangxx = g_strdup ("clang++");
13270 mono_aot_parse_options (aot_options, &acfg->aot_opts);
13272 // start dedup
13273 MonoAotState *astate = NULL;
13274 gboolean is_dedup_dummy = FALSE;
13275 mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
13277 // Process later
13278 if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
13279 return 0;
13281 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13282 acfg->dedup_collect_only = TRUE;
13283 // end dedup
13285 if (acfg->aot_opts.logfile) {
13286 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
13289 if (acfg->aot_opts.data_outfile) {
13290 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
13291 if (!acfg->data_outfile) {
13292 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
13293 return 1;
13295 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
13298 //acfg->aot_opts.print_skipped_methods = TRUE;
13300 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
13301 if (acfg->opts & MONO_OPT_GSHAREDVT) {
13302 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
13303 return 1;
13305 if (acfg->aot_opts.llvm_only) {
13306 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
13307 return 1;
13309 #else
13310 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13311 acfg->opts |= MONO_OPT_GSHAREDVT;
13312 #endif
13314 #if !defined(ENABLE_LLVM)
13315 if (acfg->aot_opts.llvm_only) {
13316 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
13317 return 1;
13319 #endif
13321 if (acfg->opts & MONO_OPT_GSHAREDVT)
13322 mono_set_generic_sharing_vt_supported (TRUE);
13324 if (!acfg->dedup_collect_only)
13325 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
13327 if (!acfg->aot_opts.deterministic)
13328 generate_aotid ((guint8*) &acfg->image->aotid);
13330 char *aotid = mono_guid_to_string (acfg->image->aotid);
13331 if (!acfg->dedup_collect_only)
13332 aot_printf (acfg, "AOTID %s\n", aotid);
13333 g_free (aotid);
13335 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
13336 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13337 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
13338 return 1;
13340 #endif
13342 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
13343 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
13344 return 1;
13347 if (acfg->aot_opts.static_link)
13348 acfg->aot_opts.asm_writer = TRUE;
13350 if (acfg->aot_opts.soft_debug) {
13351 mini_debug_options.mdb_optimizations = TRUE;
13352 mini_debug_options.gen_sdb_seq_points = TRUE;
13354 if (!mono_debug_enabled ()) {
13355 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
13356 return 1;
13358 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
13361 if (acfg->aot_opts.try_llvm)
13362 acfg->aot_opts.llvm = mini_llvm_init ();
13364 if (mono_use_llvm || acfg->aot_opts.llvm) {
13365 acfg->llvm = TRUE;
13366 acfg->aot_opts.asm_writer = TRUE;
13367 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
13369 if (acfg->aot_opts.soft_debug) {
13370 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
13371 return 1;
13374 mini_llvm_init ();
13376 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
13377 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
13378 return 1;
13382 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
13383 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
13384 acfg->is_full_aot = TRUE;
13387 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
13388 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_INTERP);
13389 acfg->is_full_aot = TRUE;
13392 if (mini_safepoints_enabled ())
13393 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
13395 // The methods in dedup-emit amodules must be available on runtime startup
13396 // Note: Only one such amodule can have this attribute
13397 if (astate && astate->emit_inflated_methods)
13398 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
13401 if (acfg->aot_opts.instances_logfile_path) {
13402 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
13403 if (!acfg->instances_logfile) {
13404 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
13405 return 1;
13409 if (acfg->aot_opts.profile_files) {
13410 GList *l;
13412 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
13413 load_profile_file (acfg, (char*)l->data);
13417 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13418 for (int method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index)
13419 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
13422 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
13423 #ifdef MONO_ARCH_GSHARED_SUPPORTED
13424 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
13425 #endif
13426 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
13427 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
13428 if (acfg->opts & MONO_OPT_GSHAREDVT)
13429 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
13430 #endif
13431 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
13432 acfg->num_trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = mono_aot_mode_is_interp (&acfg->aot_opts) ? acfg->aot_opts.nftnptr_arg_trampolines : 0;
13433 #endif
13434 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;
13436 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
13438 arch_init (acfg);
13440 if (mono_use_llvm || acfg->aot_opts.llvm) {
13442 * Emit all LLVM code into a separate assembly/object file and link with it
13443 * normally.
13445 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
13446 acfg->llvm_owriter = TRUE;
13447 } else if (acfg->aot_opts.llvm_outfile) {
13448 int len = strlen (acfg->aot_opts.llvm_outfile);
13450 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
13451 acfg->llvm_owriter = TRUE;
13455 if (acfg->llvm && acfg->thumb_mixed)
13456 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
13457 if (acfg->aot_opts.llvm_only)
13458 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
13460 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
13461 /* Get rid of characters which cannot occur in symbols */
13462 for (p = acfg->assembly_name_sym; *p; ++p) {
13463 if (!(isalnum (*p) || *p == '_'))
13464 *p = '_';
13467 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
13468 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
13469 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
13470 if (acfg->llvm) {
13471 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
13472 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
13475 acfg->method_index = 1;
13477 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13478 mono_set_partial_sharing_supported (TRUE);
13480 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13481 res = collect_methods (acfg);
13482 if (!res)
13483 return 1;
13486 // If we're emitting all of the inflated methods into a dummy
13487 // Assembly, then after extra_methods is set up, we're done
13488 // in this function.
13489 if (astate && astate->emit_inflated_methods)
13490 mono_add_deferred_extra_methods (acfg, astate);
13493 GList *l;
13495 for (l = acfg->profile_data; l; l = l->next)
13496 resolve_profile_data (acfg, (ProfileData*)l->data, ass);
13497 for (l = acfg->profile_data; l; l = l->next)
13498 add_profile_instances (acfg, (ProfileData*)l->data);
13501 acfg->cfgs_size = acfg->methods->len + 32;
13502 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
13504 /* PLT offset 0 is reserved for the PLT trampoline */
13505 acfg->plt_offset = 1;
13506 add_preinit_got_slots (acfg);
13508 #ifdef ENABLE_LLVM
13509 if (acfg->llvm) {
13510 llvm_acfg = acfg;
13511 LLVMModuleFlags flags = (LLVMModuleFlags)0;
13512 #ifdef EMIT_DWARF_INFO
13513 flags = LLVM_MODULE_FLAG_DWARF;
13514 #endif
13515 #ifdef EMIT_WIN32_CODEVIEW_INFO
13516 flags = LLVM_MODULE_FLAG_CODEVIEW;
13517 #endif
13518 if (acfg->aot_opts.static_link)
13519 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_STATIC);
13520 if (acfg->aot_opts.llvm_only)
13521 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_LLVM_ONLY);
13522 if (acfg->aot_opts.interp)
13523 flags = (LLVMModuleFlags)(flags | LLVM_MODULE_FLAG_INTERP);
13524 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, flags);
13526 add_lazy_init_wrappers (acfg);
13527 add_method (acfg, mono_marshal_get_llvm_func_wrapper (LLVM_FUNC_WRAPPER_GC_POLL));
13529 #endif
13531 if (mono_aot_mode_is_interp (&acfg->aot_opts) && mono_is_corlib_image (acfg->image->assembly->image)) {
13532 MonoMethod *wrapper = mini_get_interp_lmf_wrapper ("mono_interp_to_native_trampoline", (gpointer) mono_interp_to_native_trampoline);
13533 add_method (acfg, wrapper);
13535 wrapper = mini_get_interp_lmf_wrapper ("mono_interp_entry_from_trampoline", (gpointer) mono_interp_entry_from_trampoline);
13536 add_method (acfg, wrapper);
13538 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13539 for (int i = 0; i < G_N_ELEMENTS (interp_in_static_sigs); i++)
13540 add_interp_in_wrapper_for_sig (acfg, *interp_in_static_sigs [i]);
13541 #else
13542 for (int i = 0; i < G_N_ELEMENTS (interp_in_static_common_sigs); i++)
13543 add_interp_in_wrapper_for_sig (acfg, *interp_in_static_common_sigs [i]);
13544 #endif
13546 /* required for mixed mode */
13547 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
13548 add_gc_wrappers (acfg);
13550 for (int i = 0; i < MONO_JIT_ICALL_count; ++i)
13551 add_jit_icall_wrapper (acfg, mono_find_jit_icall_info ((MonoJitICallId)i));
13555 TV_GETTIME (atv);
13557 compile_methods (acfg);
13559 TV_GETTIME (btv);
13561 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
13563 dedup_skip_methods (acfg);
13565 if (acfg->aot_opts.dedup_include && !is_dedup_dummy)
13566 /* We only collected methods from this assembly */
13567 return 0;
13569 return emit_aot_image (acfg);
13572 static void
13573 print_stats (MonoAotCompile *acfg)
13575 int i;
13576 gint64 all_sizes;
13577 char llvm_stats_msg [256];
13579 if (acfg->llvm && !acfg->aot_opts.llvm_only)
13580 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
13581 else
13582 strcpy (llvm_stats_msg, "");
13584 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;
13586 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",
13587 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
13588 (int)acfg->stats.method_info_size, (int)(acfg->stats.method_info_size * 100 / all_sizes),
13589 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
13590 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
13591 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
13592 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,
13593 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
13594 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
13595 (int)(acfg->got_offset * sizeof (target_mgreg_t)),
13596 (int)acfg->stats.blob_size);
13597 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
13598 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
13599 llvm_stats_msg,
13600 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
13601 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
13602 if (acfg->stats.genericcount)
13603 aot_printf (acfg, "%d methods failed gsharing (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
13604 if (acfg->stats.abscount)
13605 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
13606 if (acfg->stats.lmfcount)
13607 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
13608 if (acfg->stats.ocount)
13609 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
13611 aot_printf (acfg, "GOT slot distribution:\n");
13612 int nslots = 0;
13613 int size = 0;
13614 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
13615 nslots += acfg->stats.got_slot_types [i];
13616 size += acfg->stats.got_slot_info_sizes [i];
13617 if (acfg->stats.got_slot_types [i])
13618 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]);
13620 aot_printf (acfg, "GOT SLOTS: %d, INFO SIZE: %d\n", nslots, size);
13622 aot_printf (acfg, "\nEncoding stats:\n");
13623 aot_printf (acfg, "\tMethod ref: %d (%dk)\n", acfg->stats.method_ref_count, acfg->stats.method_ref_size / 1024);
13624 aot_printf (acfg, "\tClass ref: %d (%dk)\n", acfg->stats.class_ref_count, acfg->stats.class_ref_size / 1024);
13625 aot_printf (acfg, "\tGinst: %d (%dk)\n", acfg->stats.ginst_count, acfg->stats.ginst_size / 1024);
13627 aot_printf (acfg, "\nMethod stats:\n");
13628 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
13629 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
13630 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
13631 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
13633 if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
13634 mono_dedup_log_stats (acfg);
13637 static void
13638 create_depfile (MonoAotCompile *acfg)
13640 FILE *depfile;
13642 // FIXME: Support other configurations
13643 g_assert (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only && acfg->aot_opts.llvm_outfile);
13645 depfile = fopen (acfg->aot_opts.depfile, "w");
13646 g_assert (depfile);
13648 int ntargets = 1;
13649 char **targets = g_new0 (char*, ntargets);
13650 targets [0] = acfg->aot_opts.llvm_outfile;
13651 for (int tindex = 0; tindex < ntargets; ++tindex) {
13652 fprintf (depfile, "%s: ", targets [tindex]);
13653 for (int i = 0; i < acfg->image_table->len; i++) {
13654 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
13655 fprintf (depfile, " %s", image->filename);
13657 fprintf (depfile, "\n");
13659 g_free (targets);
13660 fclose (depfile);
13663 static int
13664 emit_aot_image (MonoAotCompile *acfg)
13666 int i, res;
13667 TV_DECLARE (atv);
13668 TV_DECLARE (btv);
13670 TV_GETTIME (atv);
13672 #ifdef ENABLE_LLVM
13673 if (acfg->llvm) {
13674 if (acfg->aot_opts.asm_only) {
13675 if (acfg->aot_opts.outfile) {
13676 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13677 acfg->tmpbasename = g_strdup (acfg->tmpfname);
13678 } else {
13679 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
13680 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13682 g_assert (acfg->aot_opts.llvm_outfile);
13683 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13684 if (acfg->llvm_owriter)
13685 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
13686 else
13687 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13688 } else {
13689 gchar *temp_path;
13690 if (strcmp (acfg->aot_opts.temp_path, "") != 0) {
13691 temp_path = g_strdup (acfg->aot_opts.temp_path);
13692 } else {
13693 temp_path = g_mkdtemp (g_strdup ("mono_aot_XXXXXX"));
13694 g_assertf (temp_path, "mkdtemp failed, error = (%d) %s", errno, g_strerror (errno));
13695 acfg->temp_dir_to_delete = g_strdup (temp_path);
13698 acfg->tmpbasename = g_build_filename (temp_path, "temp", (const char*)NULL);
13699 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13700 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
13701 acfg->llvm_ofile = g_strdup_printf ("%s-llvm." AS_OBJECT_FILE_SUFFIX, acfg->tmpbasename);
13703 g_free (temp_path);
13706 #endif
13708 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
13709 if (acfg->aot_opts.outfile)
13710 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13711 else
13712 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
13713 acfg->fp = fopen (acfg->tmpfname, "w+");
13714 } else {
13715 if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
13716 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
13717 acfg->fp = fdopen (i, "w+");
13718 } else {
13719 acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", (const char*)NULL);
13720 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13721 acfg->fp = fopen (acfg->tmpfname, "w+");
13724 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
13725 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
13726 return 1;
13728 if (acfg->fp)
13729 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
13731 /* Compute symbols for methods */
13732 for (i = 0; i < acfg->nmethods; ++i) {
13733 if (acfg->cfgs [i]) {
13734 MonoCompile *cfg = acfg->cfgs [i];
13735 int method_index = get_method_index (acfg, cfg->orig_method);
13737 if (cfg->asm_symbol) {
13738 // Set by method emitter in backend
13739 if (acfg->llvm_label_prefix) {
13740 char *old_symbol = cfg->asm_symbol;
13741 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->asm_symbol);
13742 g_free (old_symbol);
13744 } else if (COMPILE_LLVM (cfg)) {
13745 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
13746 } else if (acfg->global_symbols || acfg->llvm) {
13747 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
13748 } else {
13749 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
13751 cfg->asm_debug_symbol = cfg->asm_symbol;
13755 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
13757 * CLANG supports GAS .file/.loc directives, so emit line number information this way
13759 acfg->gas_line_numbers = TRUE;
13762 #ifdef EMIT_DWARF_INFO
13763 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
13764 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
13765 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
13766 return 1;
13768 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
13770 #endif /* EMIT_DWARF_INFO */
13772 if (acfg->w)
13773 mono_img_writer_emit_start (acfg->w);
13775 if (acfg->dwarf)
13776 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
13778 if (acfg->aot_opts.dedup)
13779 mono_flush_method_cache (acfg);
13781 emit_code (acfg);
13783 emit_info (acfg);
13785 emit_extra_methods (acfg);
13787 emit_trampolines (acfg);
13789 emit_class_name_table (acfg);
13791 emit_got_info (acfg, FALSE);
13792 if (acfg->llvm)
13793 emit_got_info (acfg, TRUE);
13795 emit_exception_info (acfg);
13797 emit_unwind_info (acfg);
13799 emit_class_info (acfg);
13801 emit_plt (acfg);
13803 emit_image_table (acfg);
13805 emit_weak_field_indexes (acfg);
13807 emit_got (acfg);
13811 * The managed allocators are GC specific, so can't use an AOT image created by one GC
13812 * in another.
13814 const char *gc_name = mono_gc_get_gc_name ();
13815 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
13818 emit_blob (acfg);
13820 emit_objc_selectors (acfg);
13822 emit_globals (acfg);
13824 emit_file_info (acfg);
13826 if (acfg->dwarf) {
13827 emit_dwarf_info (acfg);
13828 mono_dwarf_writer_close (acfg->dwarf);
13829 } else {
13830 if (!acfg->aot_opts.nodebug)
13831 emit_codeview_info (acfg);
13834 emit_mem_end (acfg);
13836 if (acfg->need_pt_gnu_stack) {
13837 /* This is required so the .so doesn't have an executable stack */
13838 /* The bin writer already emits this */
13839 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
13842 if (acfg->aot_opts.data_outfile)
13843 fclose (acfg->data_outfile);
13845 #ifdef ENABLE_LLVM
13846 if (acfg->llvm) {
13847 gboolean res;
13849 res = emit_llvm_file (acfg);
13850 if (!res)
13851 return 1;
13853 #endif
13855 emit_library_info (acfg);
13857 TV_GETTIME (btv);
13859 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
13861 if (!acfg->aot_opts.stats)
13862 aot_printf (acfg, "Compiled: %d/%d\n", acfg->stats.ccount, acfg->stats.mcount);
13864 TV_GETTIME (atv);
13865 if (acfg->w) {
13866 res = mono_img_writer_emit_writeout (acfg->w);
13867 if (res != 0) {
13868 acfg_free (acfg);
13869 return res;
13871 res = compile_asm (acfg);
13872 if (res != 0) {
13873 acfg_free (acfg);
13874 return res;
13877 TV_GETTIME (btv);
13878 acfg->stats.link_time = TV_ELAPSED (atv, btv);
13880 if (acfg->aot_opts.stats)
13881 print_stats (acfg);
13883 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);
13885 if (acfg->aot_opts.depfile)
13886 create_depfile (acfg);
13888 if (acfg->aot_opts.dump_json)
13889 aot_dump (acfg);
13891 if (!acfg->aot_opts.save_temps && acfg->temp_dir_to_delete) {
13892 char *command = g_strdup_printf ("rm -r %s", acfg->temp_dir_to_delete);
13893 execute_system (command);
13894 g_free (command);
13897 acfg_free (acfg);
13899 return 0;
13902 #else
13904 /* AOT disabled */
13906 void*
13907 mono_aot_readonly_field_override (MonoClassField *field)
13909 return NULL;
13913 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
13915 return 0;
13918 gboolean
13919 mono_aot_is_shared_got_offset (int offset)
13921 return FALSE;
13925 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13927 g_assert_not_reached ();
13928 return 0;
13931 gboolean
13932 mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method)
13934 g_assert_not_reached ();
13935 return 0;
13938 #endif