[interp] Small fixes (#11667)
[mono-project.git] / mono / mini / aot-compiler.c
blob3413383ff403b0f279fa6f4af579d99edf710518
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 int nthreads;
212 int ntrampolines;
213 int nrgctx_trampolines;
214 int nimt_trampolines;
215 int ngsharedvt_arg_trampolines;
216 int nftnptr_arg_trampolines;
217 int nrgctx_fetch_trampolines;
218 int nunbox_arbitrary_trampolines;
219 gboolean print_skipped_methods;
220 gboolean stats;
221 gboolean verbose;
222 gboolean deterministic;
223 char *tool_prefix;
224 char *ld_flags;
225 char *mtriple;
226 char *llvm_path;
227 char *temp_path;
228 char *instances_logfile_path;
229 char *logfile;
230 char *llvm_opts;
231 char *llvm_llc;
232 gboolean dump_json;
233 gboolean profile_only;
234 gboolean no_opt;
235 char *clangxx;
236 } MonoAotOptions;
238 typedef enum {
239 METHOD_CAT_NORMAL,
240 METHOD_CAT_GSHAREDVT,
241 METHOD_CAT_INST,
242 METHOD_CAT_WRAPPER,
243 METHOD_CAT_NUM
244 } MethodCategory;
246 typedef struct MonoAotStats {
247 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
248 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
249 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
250 int got_slots, offsets_size;
251 int method_categories [METHOD_CAT_NUM];
252 int got_slot_types [MONO_PATCH_INFO_NUM];
253 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
254 int jit_time, gen_time, link_time;
255 } MonoAotStats;
257 typedef struct GotInfo {
258 GHashTable *patch_to_got_offset;
259 GHashTable **patch_to_got_offset_by_type;
260 GPtrArray *got_patches;
261 } GotInfo;
263 #ifdef EMIT_WIN32_UNWIND_INFO
264 typedef struct _UnwindInfoSectionCacheItem {
265 char *xdata_section_label;
266 PUNWIND_INFO unwind_info;
267 gboolean xdata_section_emitted;
268 } UnwindInfoSectionCacheItem;
269 #endif
271 typedef struct MonoAotCompile {
272 MonoImage *image;
273 GPtrArray *methods;
274 GHashTable *method_indexes;
275 GHashTable *method_depth;
276 MonoCompile **cfgs;
277 int cfgs_size;
278 GHashTable **patch_to_plt_entry;
279 GHashTable *plt_offset_to_entry;
280 //GHashTable *patch_to_got_offset;
281 //GHashTable **patch_to_got_offset_by_type;
282 //GPtrArray *got_patches;
283 GotInfo got_info, llvm_got_info;
284 GHashTable *image_hash;
285 GHashTable *method_to_cfg;
286 GHashTable *token_info_hash;
287 GHashTable *method_to_pinvoke_import;
288 GPtrArray *extra_methods;
289 GPtrArray *image_table;
290 GPtrArray *globals;
291 GPtrArray *method_order;
292 GHashTable *dedup_stats;
293 GHashTable *dedup_cache;
294 gboolean dedup_cache_changed;
295 GHashTable *export_names;
296 /* Maps MonoClass* -> blob offset */
297 GHashTable *klass_blob_hash;
298 /* Maps MonoMethod* -> blob offset */
299 GHashTable *method_blob_hash;
300 GHashTable *gsharedvt_in_signatures;
301 GHashTable *gsharedvt_out_signatures;
302 guint32 *plt_got_info_offsets;
303 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
304 /* Number of GOT entries reserved for trampolines */
305 guint32 num_trampoline_got_entries;
306 guint32 tramp_page_size;
308 guint32 table_offsets [MONO_AOT_TABLE_NUM];
309 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
310 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
311 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
312 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
314 MonoAotOptions aot_opts;
315 guint32 nmethods;
316 guint32 nextra_methods;
317 guint32 opts;
318 guint32 simd_opts;
319 MonoMemPool *mempool;
320 MonoAotStats stats;
321 int method_index;
322 char *static_linking_symbol;
323 mono_mutex_t mutex;
324 gboolean gas_line_numbers;
325 /* Whenever to emit an object file directly from llc */
326 gboolean llvm_owriter;
327 gboolean llvm_owriter_supported;
328 MonoImageWriter *w;
329 MonoDwarfWriter *dwarf;
330 FILE *fp;
331 char *tmpbasename;
332 char *tmpfname;
333 char *llvm_sfile;
334 char *llvm_ofile;
335 GSList *cie_program;
336 GHashTable *unwind_info_offsets;
337 GPtrArray *unwind_ops;
338 guint32 unwind_info_offset;
339 char *global_prefix;
340 char *got_symbol;
341 char *llvm_got_symbol;
342 char *plt_symbol;
343 char *llvm_eh_frame_symbol;
344 GHashTable *method_label_hash;
345 const char *temp_prefix;
346 const char *user_symbol_prefix;
347 const char *llvm_label_prefix;
348 const char *inst_directive;
349 int align_pad_value;
350 guint32 label_generator;
351 gboolean llvm;
352 gboolean has_jitted_code;
353 gboolean is_full_aot;
354 MonoAotFileFlags flags;
355 MonoDynamicStream blob;
356 gboolean blob_closed;
357 GHashTable *typespec_classes;
358 GString *llc_args;
359 GString *as_args;
360 char *assembly_name_sym;
361 GHashTable *plt_entry_debug_sym_cache;
362 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
363 GHashTable *ginst_hash;
364 GHashTable *dwarf_ln_filenames;
365 gboolean global_symbols;
366 int objc_selector_index, objc_selector_index_2;
367 GPtrArray *objc_selectors;
368 GHashTable *objc_selector_to_index;
369 GList *profile_data;
370 GHashTable *profile_methods;
371 #ifdef EMIT_WIN32_UNWIND_INFO
372 GList *unwind_info_section_cache;
373 #endif
374 FILE *logfile;
375 FILE *instances_logfile;
376 FILE *data_outfile;
377 int datafile_offset;
378 int gc_name_offset;
379 // In this mode, we are emitting dedupable methods that we encounter
380 gboolean dedup_emit_mode;
381 } MonoAotCompile;
383 typedef struct {
384 int plt_offset;
385 char *symbol, *llvm_symbol, *debug_sym;
386 MonoJumpInfo *ji;
387 gboolean jit_used, llvm_used;
388 } MonoPltEntry;
390 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
391 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
393 /* This points to the current acfg in LLVM mode */
394 static MonoAotCompile *llvm_acfg;
396 // This, instead of an array of pointers, to optimize away a pointer and a relocation per string.
397 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
398 #define MSGSTRFIELD1(line) str##line
399 static const struct msgstr_t {
400 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
401 #include "patch-info.h"
402 #undef PATCH_INFO
403 } opstr = {
404 #define PATCH_INFO(a,b) b,
405 #include "patch-info.h"
406 #undef PATCH_INFO
408 static const gint16 opidx [] = {
409 #define PATCH_INFO(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
410 #include "patch-info.h"
411 #undef PATCH_INFO
414 static G_GNUC_UNUSED const char*
415 get_patch_name (int info)
417 return (const char*)&opstr + opidx [info];
420 static void
421 mono_flush_method_cache (MonoAotCompile *acfg);
423 static void
424 mono_read_method_cache (MonoAotCompile *acfg);
426 static guint32
427 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
429 static char*
430 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
432 static void
433 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in);
435 static void
436 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
438 static inline gboolean
439 ignore_cfg (MonoCompile *cfg)
441 return !cfg || cfg->skip;
444 static void
445 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
447 FILE *output;
448 va_list args;
450 if (acfg->logfile)
451 output = acfg->logfile;
452 else
453 output = stdout;
455 va_start (args, format);
456 vfprintf (output, format, args);
457 va_end (args);
460 static void
461 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
463 FILE *output;
464 va_list args;
466 if (acfg->logfile)
467 output = acfg->logfile;
468 else
469 output = stderr;
471 va_start (args, format);
472 vfprintf (output, format, args);
473 va_end (args);
476 static void
477 report_loader_error (MonoAotCompile *acfg, MonoError *error, gboolean fatal, const char *format, ...)
479 FILE *output;
480 va_list args;
482 if (mono_error_ok (error))
483 return;
485 if (acfg->logfile)
486 output = acfg->logfile;
487 else
488 output = stderr;
490 va_start (args, format);
491 vfprintf (output, format, args);
492 va_end (args);
493 mono_error_cleanup (error);
495 if (acfg->is_full_aot && fatal) {
496 fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
497 exit (1);
501 /* Wrappers around the image writer functions */
503 #define MAX_SYMBOL_SIZE 256
505 static inline const char *
506 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
508 gsize needed_size = length;
510 g_assert (NULL != symbol);
511 g_assert (NULL != mangled_symbol);
512 g_assert (0 != length);
514 #if defined(TARGET_WIN32) && defined(TARGET_X86)
515 if (symbol && '_' != symbol [0]) {
516 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
517 } else {
518 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
520 #else
521 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
522 #endif
524 g_assert (0 <= needed_size && needed_size < length);
525 return mangled_symbol;
528 static inline char *
529 mangle_symbol_alloc (const char * symbol)
531 g_assert (NULL != symbol);
533 #if defined(TARGET_WIN32) && defined(TARGET_X86)
534 if (symbol && '_' != symbol [0]) {
535 return g_strdup_printf ("_%s", symbol);
537 else {
538 return g_strdup_printf ("%s", symbol);
540 #else
541 return g_strdup_printf ("%s", symbol);
542 #endif
545 static inline void
546 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
548 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
551 #if defined(TARGET_WIN32) && defined(TARGET_X86)
553 static inline void
554 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
556 const char * mangled_symbol_name = name;
557 char * mangled_symbol_name_alloc = NULL;
559 if (TRUE == func) {
560 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
561 mangled_symbol_name = mangled_symbol_name_alloc;
564 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
565 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
567 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
569 if (NULL != mangled_symbol_name_alloc) {
570 g_free (mangled_symbol_name_alloc);
574 #else
576 static inline void
577 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
579 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
582 #endif
584 static inline void
585 emit_label (MonoAotCompile *acfg, const char *name)
587 mono_img_writer_emit_label (acfg->w, name);
590 static inline void
591 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
593 mono_img_writer_emit_bytes (acfg->w, buf, size);
596 static inline void
597 emit_string (MonoAotCompile *acfg, const char *value)
599 mono_img_writer_emit_string (acfg->w, value);
602 static inline void
603 emit_line (MonoAotCompile *acfg)
605 mono_img_writer_emit_line (acfg->w);
608 static inline void
609 emit_alignment (MonoAotCompile *acfg, int size)
611 mono_img_writer_emit_alignment (acfg->w, size);
614 static inline void
615 emit_alignment_code (MonoAotCompile *acfg, int size)
617 if (acfg->align_pad_value)
618 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
619 else
620 mono_img_writer_emit_alignment (acfg->w, size);
623 static inline void
624 emit_padding (MonoAotCompile *acfg, int size)
626 int i;
627 guint8 buf [16];
629 if (acfg->align_pad_value) {
630 for (i = 0; i < 16; ++i)
631 buf [i] = acfg->align_pad_value;
632 } else {
633 memset (buf, 0, sizeof (buf));
636 for (i = 0; i < size; i += 16) {
637 if (size - i < 16)
638 emit_bytes (acfg, buf, size - i);
639 else
640 emit_bytes (acfg, buf, 16);
644 static inline void
645 emit_pointer (MonoAotCompile *acfg, const char *target)
647 mono_img_writer_emit_pointer (acfg->w, target);
650 static inline void
651 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
653 if (prefix [0] != '\0') {
654 char *s = g_strdup_printf ("%s%s", prefix, target);
655 mono_img_writer_emit_pointer (acfg->w, s);
656 g_free (s);
657 } else {
658 mono_img_writer_emit_pointer (acfg->w, target);
662 static inline void
663 emit_int16 (MonoAotCompile *acfg, int value)
665 mono_img_writer_emit_int16 (acfg->w, value);
668 static inline void
669 emit_int32 (MonoAotCompile *acfg, int value)
671 mono_img_writer_emit_int32 (acfg->w, value);
674 static inline void
675 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
677 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
680 static inline void
681 emit_zero_bytes (MonoAotCompile *acfg, int num)
683 mono_img_writer_emit_zero_bytes (acfg->w, num);
686 static inline void
687 emit_byte (MonoAotCompile *acfg, guint8 val)
689 mono_img_writer_emit_byte (acfg->w, val);
692 #if defined(TARGET_WIN32) && defined(TARGET_X86)
694 static G_GNUC_UNUSED void
695 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
697 const char * mangled_symbol_name = name;
698 char * mangled_symbol_name_alloc = NULL;
700 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
701 mangled_symbol_name = mangled_symbol_name_alloc;
703 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
704 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
706 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
708 if (NULL != mangled_symbol_name_alloc) {
709 g_free (mangled_symbol_name_alloc);
713 #else
715 static G_GNUC_UNUSED void
716 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
718 mono_img_writer_emit_global (acfg->w, name, func);
721 #endif
723 static inline gboolean
724 link_shared_library (MonoAotCompile *acfg)
726 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
729 static inline gboolean
730 add_to_global_symbol_table (MonoAotCompile *acfg)
732 #ifdef TARGET_WIN32_MSVC
733 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
734 #else
735 return acfg->aot_opts.no_dlsym;
736 #endif
739 static void
740 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
742 if (add_to_global_symbol_table (acfg))
743 g_ptr_array_add (acfg->globals, g_strdup (name));
745 if (acfg->aot_opts.no_dlsym) {
746 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
747 } else {
748 emit_global_inner (acfg, name, func);
752 static void
753 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
755 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
758 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
759 static void
760 emit_info_symbol (MonoAotCompile *acfg, const char *name, gboolean func)
762 char symbol [MAX_SYMBOL_SIZE];
764 if (acfg->llvm) {
765 emit_label (acfg, name);
766 /* LLVM generated code references this */
767 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
768 emit_label (acfg, symbol);
770 #ifndef TARGET_WIN32_MSVC
771 emit_global_inner (acfg, symbol, FALSE);
772 #else
773 emit_global_inner (acfg, symbol, func);
774 #endif
775 } else {
776 emit_label (acfg, name);
780 static void
781 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
783 if (acfg->llvm) {
784 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
785 return;
788 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
789 #ifdef TARGET_MACH
790 /* On apple, all symbols need to be aligned to avoid warnings from ld */
791 emit_alignment (acfg, 4);
792 #endif
793 mono_img_writer_emit_label (acfg->w, name);
794 mono_img_writer_emit_string (acfg->w, value);
797 static G_GNUC_UNUSED void
798 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
800 do {
801 guint8 b = value & 0x7f;
802 value >>= 7;
803 if (value != 0) /* more bytes to come */
804 b |= 0x80;
805 emit_byte (acfg, b);
806 } while (value);
809 static G_GNUC_UNUSED void
810 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
812 gboolean more = 1;
813 gboolean negative = (value < 0);
814 guint32 size = 64;
815 guint8 byte;
817 while (more) {
818 byte = value & 0x7f;
819 value >>= 7;
820 /* the following is unnecessary if the
821 * implementation of >>= uses an arithmetic rather
822 * than logical shift for a signed left operand
824 if (negative)
825 /* sign extend */
826 value |= - ((gint64)1 <<(size - 7));
827 /* sign bit of byte is second high order bit (0x40) */
828 if ((value == 0 && !(byte & 0x40)) ||
829 (value == -1 && (byte & 0x40)))
830 more = 0;
831 else
832 byte |= 0x80;
833 emit_byte (acfg, byte);
837 static G_GNUC_UNUSED void
838 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
840 guint8 *p = buf;
842 do {
843 guint8 b = value & 0x7f;
844 value >>= 7;
845 if (value != 0) /* more bytes to come */
846 b |= 0x80;
847 *p ++ = b;
848 } while (value);
850 *endbuf = p;
853 static G_GNUC_UNUSED void
854 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
856 gboolean more = 1;
857 gboolean negative = (value < 0);
858 guint32 size = 32;
859 guint8 byte;
860 guint8 *p = buf;
862 while (more) {
863 byte = value & 0x7f;
864 value >>= 7;
865 /* the following is unnecessary if the
866 * implementation of >>= uses an arithmetic rather
867 * than logical shift for a signed left operand
869 if (negative)
870 /* sign extend */
871 value |= - (1 <<(size - 7));
872 /* sign bit of byte is second high order bit (0x40) */
873 if ((value == 0 && !(byte & 0x40)) ||
874 (value == -1 && (byte & 0x40)))
875 more = 0;
876 else
877 byte |= 0x80;
878 *p ++= byte;
881 *endbuf = p;
884 static void
885 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
887 // FIXME: Big-endian
888 buf [0] = (val >> 0) & 0xff;
889 buf [1] = (val >> 8) & 0xff;
890 buf [2] = (val >> 16) & 0xff;
891 buf [3] = (val >> 24) & 0xff;
893 *endbuf = buf + 4;
896 static void
897 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
899 buf [0] = (val >> 0) & 0xff;
900 buf [1] = (val >> 8) & 0xff;
902 *endbuf = buf + 2;
905 static void
906 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
908 int len = strlen (s);
910 memcpy (buf, s, len + 1);
911 *endbuf = buf + len + 1;
914 static void
915 emit_unset_mode (MonoAotCompile *acfg)
917 mono_img_writer_emit_unset_mode (acfg->w);
920 static G_GNUC_UNUSED void
921 emit_set_thumb_mode (MonoAotCompile *acfg)
923 emit_unset_mode (acfg);
924 fprintf (acfg->fp, ".code 16\n");
927 static G_GNUC_UNUSED void
928 emit_set_arm_mode (MonoAotCompile *acfg)
930 emit_unset_mode (acfg);
931 fprintf (acfg->fp, ".code 32\n");
934 static inline void
935 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
937 #ifdef TARGET_ARM64
938 int i;
940 g_assert (size % 4 == 0);
941 emit_unset_mode (acfg);
942 for (i = 0; i < size; i += 4)
943 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
944 #else
945 emit_bytes (acfg, buf, size);
946 #endif
949 /* ARCHITECTURE SPECIFIC CODE */
951 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64) || defined (TARGET_RISCV)
952 #define EMIT_DWARF_INFO 1
953 #endif
955 #ifdef TARGET_WIN32_MSVC
956 #undef EMIT_DWARF_INFO
957 #define EMIT_WIN32_CODEVIEW_INFO
958 #endif
960 #ifdef EMIT_WIN32_UNWIND_INFO
961 static UnwindInfoSectionCacheItem *
962 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
964 static void
965 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg);
967 static void
968 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info);
970 static void
971 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops);
972 #endif
974 static void
975 arch_free_unwind_info_section_cache (MonoAotCompile *acfg)
977 #ifdef EMIT_WIN32_UNWIND_INFO
978 free_unwind_info_section_cache_win32 (acfg);
979 #endif
982 static void
983 arch_emit_unwind_info_sections (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
985 #ifdef EMIT_WIN32_UNWIND_INFO
986 gboolean own_unwind_ops = FALSE;
987 if (!unwind_ops) {
988 unwind_ops = mono_unwind_get_cie_program ();
989 own_unwind_ops = TRUE;
992 emit_unwind_info_sections_win32 (acfg, function_start, function_end, unwind_ops);
994 if (own_unwind_ops)
995 mono_free_unwind_info (unwind_ops);
996 #endif
999 #if defined(TARGET_ARM)
1000 #define AOT_FUNC_ALIGNMENT 4
1001 #else
1002 #define AOT_FUNC_ALIGNMENT 16
1003 #endif
1005 #if defined(TARGET_POWERPC64) && !defined(MONO_ARCH_ILP32)
1006 #define PPC_LD_OP "ld"
1007 #define PPC_LDX_OP "ldx"
1008 #else
1009 #define PPC_LD_OP "lwz"
1010 #define PPC_LDX_OP "lwzx"
1011 #endif
1013 #ifdef TARGET_X86_64_WIN32_MSVC
1014 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
1015 #elif TARGET_AMD64
1016 #define AOT_TARGET_STR "AMD64"
1017 #endif
1019 #ifdef TARGET_ARM
1020 #ifdef TARGET_MACH
1021 #define AOT_TARGET_STR "ARM (MACH)"
1022 #else
1023 #define AOT_TARGET_STR "ARM (!MACH)"
1024 #endif
1025 #endif
1027 #ifdef TARGET_ARM64
1028 #ifdef TARGET_MACH
1029 #define AOT_TARGET_STR "ARM64 (MACH)"
1030 #else
1031 #define AOT_TARGET_STR "ARM64 (!MACH)"
1032 #endif
1033 #endif
1035 #ifdef TARGET_POWERPC64
1036 #ifdef MONO_ARCH_ILP32
1037 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
1038 #else
1039 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
1040 #endif
1041 #else
1042 #ifdef TARGET_POWERPC
1043 #ifdef MONO_ARCH_ILP32
1044 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
1045 #else
1046 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
1047 #endif
1048 #endif
1049 #endif
1051 #ifdef TARGET_RISCV32
1052 #define AOT_TARGET_STR "RISCV32"
1053 #endif
1055 #ifdef TARGET_RISCV64
1056 #define AOT_TARGET_STR "RISCV64"
1057 #endif
1059 #ifdef TARGET_X86
1060 #ifdef TARGET_WIN32
1061 #define AOT_TARGET_STR "X86 (WIN32)"
1062 #else
1063 #define AOT_TARGET_STR "X86"
1064 #endif
1065 #endif
1067 #ifndef AOT_TARGET_STR
1068 #define AOT_TARGET_STR ""
1069 #endif
1071 static void
1072 arch_init (MonoAotCompile *acfg)
1074 acfg->llc_args = g_string_new ("");
1075 acfg->as_args = g_string_new ("");
1076 acfg->llvm_owriter_supported = TRUE;
1079 * The prefix LLVM likes to put in front of symbol names on darwin.
1080 * The mach-os specs require this for globals, but LLVM puts them in front of all
1081 * symbols. We need to handle this, since we need to refer to LLVM generated
1082 * symbols.
1084 acfg->llvm_label_prefix = "";
1085 acfg->user_symbol_prefix = "";
1087 #if defined(TARGET_X86)
1088 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
1089 #endif
1091 #if defined(TARGET_AMD64)
1092 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
1093 /* NOP */
1094 acfg->align_pad_value = 0x90;
1095 #endif
1097 #ifdef TARGET_ARM
1098 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
1099 g_string_append (acfg->llc_args, "-mattr=+v6");
1100 } else {
1101 g_string_append (acfg->llc_args, " -march=arm");
1102 #if defined(ARM_FPU_VFP_HARD)
1103 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
1104 g_string_append (acfg->as_args, " -mfpu=vfp3");
1105 #elif defined(ARM_FPU_VFP)
1106 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1107 g_string_append (acfg->as_args, " -mfpu=vfp3");
1108 #else
1109 #ifdef LLVM_API_VERSION > 100
1110 g_string_append (acfg->llc_args, " -mattr=+soft-float");
1111 #else
1112 g_string_append (acfg->llc_args, " -soft-float");
1113 #endif
1114 #endif
1116 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1117 acfg->thumb_mixed = TRUE;
1119 if (acfg->aot_opts.mtriple)
1120 mono_arch_set_target (acfg->aot_opts.mtriple);
1121 #endif
1123 #ifdef TARGET_ARM64
1124 g_string_append (acfg->llc_args, " -march=aarch64");
1125 acfg->inst_directive = ".inst";
1126 if (acfg->aot_opts.mtriple)
1127 mono_arch_set_target (acfg->aot_opts.mtriple);
1128 #endif
1130 #ifdef TARGET_MACH
1131 acfg->user_symbol_prefix = "_";
1132 acfg->llvm_label_prefix = "_";
1133 acfg->inst_directive = ".word";
1134 acfg->need_no_dead_strip = TRUE;
1135 acfg->aot_opts.gnu_asm = TRUE;
1136 #endif
1138 #if defined(__linux__) && !defined(TARGET_ARM)
1139 acfg->need_pt_gnu_stack = TRUE;
1140 #endif
1142 #ifdef TARGET_RISCV
1143 if (acfg->aot_opts.mtriple)
1144 mono_arch_set_target (acfg->aot_opts.mtriple);
1146 #ifdef TARGET_RISCV64
1148 g_string_append (acfg->as_args, " -march=rv64i ");
1149 #ifdef RISCV_FPABI_DOUBLE
1150 g_string_append (acfg->as_args, " -mabi=lp64d");
1151 #else
1152 g_string_append (acfg->as_args, " -mabi=lp64");
1153 #endif
1155 #else
1157 g_string_append (acfg->as_args, " -march=rv32i ");
1158 #ifdef RISCV_FPABI_DOUBLE
1159 g_string_append (acfg->as_args, " -mabi=ilp32d ");
1160 #else
1161 g_string_append (acfg->as_args, " -mabi=ilp32 ");
1162 #endif
1164 #endif
1166 #endif
1168 #ifdef MONOTOUCH
1169 acfg->global_symbols = TRUE;
1170 #endif
1172 #ifdef TARGET_ANDROID
1173 acfg->llvm_owriter_supported = FALSE;
1174 #endif
1177 #ifdef TARGET_ARM64
1180 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1181 static void
1182 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1184 int offset;
1186 g_assert (acfg->fp);
1187 emit_unset_mode (acfg);
1188 /* r16==ip0 */
1189 offset = (int)(got_slot * sizeof (target_mgreg_t));
1190 #ifdef TARGET_MACH
1191 /* clang's integrated assembler */
1192 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1193 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1194 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1195 #else
1196 /* Linux GAS */
1197 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1198 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1199 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1200 #endif
1203 static void
1204 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1206 int reg;
1208 g_assert (acfg->fp);
1209 emit_unset_mode (acfg);
1211 /* ldr rt, target */
1212 reg = arm_get_ldr_lit_reg (code);
1214 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1215 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1216 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1218 *code_size = 12;
1221 static void
1222 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1224 g_assert (acfg->fp);
1225 emit_unset_mode (acfg);
1226 if (ji && ji->relocation == MONO_R_ARM64_B) {
1227 fprintf (acfg->fp, "b %s\n", target);
1228 } else {
1229 if (ji)
1230 g_assert (ji->relocation == MONO_R_ARM64_BL);
1231 fprintf (acfg->fp, "bl %s\n", target);
1233 *call_size = 4;
1236 static void
1237 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1239 int reg;
1241 /* ldr rt, target */
1242 reg = arm_get_ldr_lit_reg (code);
1243 arm64_emit_load_got_slot (acfg, reg, got_slot);
1244 *code_size = 12;
1247 static void
1248 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1250 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (target_mgreg_t));
1251 fprintf (acfg->fp, "br x16\n");
1252 /* Used by mono_aot_get_plt_info_offset () */
1253 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1256 static void
1257 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1259 guint8 buf [256];
1260 guint8 *code;
1261 int imm;
1263 /* The common code */
1264 code = buf;
1265 imm = pagesize;
1266 /* The trampoline address is in IP0 */
1267 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1268 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1269 /* Compute the data slot address */
1270 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1271 /* Trampoline argument */
1272 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1273 /* Address */
1274 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1275 arm_brx (code, ARMREG_IP0);
1277 /* Emit it */
1278 emit_code_bytes (acfg, buf, code - buf);
1280 *size = code - buf;
1283 static void
1284 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1286 guint8 buf [256];
1287 guint8 *code;
1288 int i, count;
1290 count = (pagesize - common_tramp_size) / specific_tramp_size;
1291 for (i = 0; i < count; ++i) {
1292 code = buf;
1293 arm_adrx (code, ARMREG_IP0, code);
1294 /* Branch to the generic code */
1295 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1296 /* This has to be 2 pointers long */
1297 arm_nop (code);
1298 arm_nop (code);
1299 g_assert (code - buf == specific_tramp_size);
1300 emit_code_bytes (acfg, buf, code - buf);
1304 static void
1305 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1307 guint8 buf [128];
1308 guint8 *code;
1309 guint8 *labels [16];
1310 int common_tramp_size;
1311 int specific_tramp_size = 2 * 8;
1312 int imm, pagesize;
1313 char symbol [128];
1315 if (!acfg->aot_opts.use_trampolines_page)
1316 return;
1318 #ifdef TARGET_MACH
1319 /* Have to match the target pagesize */
1320 pagesize = 16384;
1321 #else
1322 pagesize = mono_pagesize ();
1323 #endif
1324 acfg->tramp_page_size = pagesize;
1326 /* The specific trampolines */
1327 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1328 emit_alignment (acfg, pagesize);
1329 emit_global (acfg, symbol, TRUE);
1330 emit_label (acfg, symbol);
1332 /* The common code */
1333 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1334 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1336 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1338 /* The rgctx trampolines */
1339 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1340 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1341 emit_alignment (acfg, pagesize);
1342 emit_global (acfg, symbol, TRUE);
1343 emit_label (acfg, symbol);
1345 /* The common code */
1346 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1347 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1349 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1351 /* The gsharedvt arg trampolines */
1352 /* These are the same as the specific trampolines */
1353 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1354 emit_alignment (acfg, pagesize);
1355 emit_global (acfg, symbol, TRUE);
1356 emit_label (acfg, symbol);
1358 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1359 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1361 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1363 /* Unbox arbitrary trampolines */
1364 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
1365 emit_alignment (acfg, pagesize);
1366 emit_global (acfg, symbol, TRUE);
1367 emit_label (acfg, symbol);
1369 code = buf;
1370 imm = pagesize;
1372 /* Unbox this arg */
1373 arm_addx_imm (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
1375 /* The trampoline address is in IP0 */
1376 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1377 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1378 /* Compute the data slot address */
1379 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1380 /* Address */
1381 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1382 arm_brx (code, ARMREG_IP0);
1384 /* Emit it */
1385 emit_code_bytes (acfg, buf, code - buf);
1387 common_tramp_size = code - buf;
1388 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = common_tramp_size;
1390 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1392 /* The IMT trampolines */
1393 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1394 emit_alignment (acfg, pagesize);
1395 emit_global (acfg, symbol, TRUE);
1396 emit_label (acfg, symbol);
1398 code = buf;
1399 imm = pagesize;
1400 /* The trampoline address is in IP0 */
1401 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1402 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1403 /* Compute the data slot address */
1404 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1405 /* Trampoline argument */
1406 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1408 /* Same as arch_emit_imt_trampoline () */
1409 labels [0] = code;
1410 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1411 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1412 labels [1] = code;
1413 arm_bcc (code, ARMCOND_EQ, 0);
1415 /* End-of-loop check */
1416 labels [2] = code;
1417 arm_cbzx (code, ARMREG_IP0, 0);
1419 /* Loop footer */
1420 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1421 arm_b (code, labels [0]);
1423 /* Match */
1424 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1425 /* Load vtable slot addr */
1426 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1427 /* Load vtable slot */
1428 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1429 arm_brx (code, ARMREG_IP0);
1431 /* No match */
1432 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1433 /* Load fail addr */
1434 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1435 arm_brx (code, ARMREG_IP0);
1437 emit_code_bytes (acfg, buf, code - buf);
1439 common_tramp_size = code - buf;
1440 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1442 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1445 static void
1446 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1448 /* Load argument from second GOT slot */
1449 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1450 /* Load generic trampoline address from first GOT slot */
1451 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1452 fprintf (acfg->fp, "br x16\n");
1453 *tramp_size = 7 * 4;
1456 static void
1457 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1459 emit_unset_mode (acfg);
1460 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
1461 fprintf (acfg->fp, "b %s\n", call_target);
1464 static void
1465 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1467 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1469 /* Load argument from first GOT slot */
1470 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1471 /* Load generic trampoline address from second GOT slot */
1472 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1473 fprintf (acfg->fp, "br x16\n");
1474 *tramp_size = 7 * 4;
1477 static void
1478 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1480 guint8 buf [128];
1481 guint8 *code, *labels [16];
1483 /* Load parameter from GOT slot into ip1 */
1484 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1486 code = buf;
1487 labels [0] = code;
1488 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1489 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1490 labels [1] = code;
1491 arm_bcc (code, ARMCOND_EQ, 0);
1493 /* End-of-loop check */
1494 labels [2] = code;
1495 arm_cbzx (code, ARMREG_IP0, 0);
1497 /* Loop footer */
1498 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1499 arm_b (code, labels [0]);
1501 /* Match */
1502 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1503 /* Load vtable slot addr */
1504 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1505 /* Load vtable slot */
1506 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1507 arm_brx (code, ARMREG_IP0);
1509 /* No match */
1510 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1511 /* Load fail addr */
1512 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1513 arm_brx (code, ARMREG_IP0);
1515 emit_code_bytes (acfg, buf, code - buf);
1517 *tramp_size = code - buf + (3 * 4);
1520 static void
1521 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1523 /* Similar to the specific trampolines, but the address is in the second slot */
1524 /* Load argument from first GOT slot */
1525 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1526 /* Load generic trampoline address from second GOT slot */
1527 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1528 fprintf (acfg->fp, "br x16\n");
1529 *tramp_size = 7 * 4;
1533 #endif
1535 #ifdef MONO_ARCH_AOT_SUPPORTED
1537 * arch_emit_direct_call:
1539 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1540 * calling code.
1542 static void
1543 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1545 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1546 /* Need to make sure this is exactly 5 bytes long */
1547 emit_unset_mode (acfg);
1548 fprintf (acfg->fp, "call %s\n", target);
1549 *call_size = 5;
1550 #elif defined(TARGET_ARM)
1551 emit_unset_mode (acfg);
1552 if (thumb)
1553 fprintf (acfg->fp, "blx %s\n", target);
1554 else
1555 fprintf (acfg->fp, "bl %s\n", target);
1556 *call_size = 4;
1557 #elif defined(TARGET_ARM64)
1558 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1559 #elif defined(TARGET_POWERPC)
1560 emit_unset_mode (acfg);
1561 fprintf (acfg->fp, "bl %s\n", target);
1562 *call_size = 4;
1563 #else
1564 g_assert_not_reached ();
1565 #endif
1567 #endif
1570 * PPC32 design:
1571 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1572 * the GOT pointer.
1573 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1574 * in in the 2. slot of every GOT, and require every method to place the GOT
1575 * address in r30, even when it doesn't access the GOT otherwise. This way,
1576 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1580 * PPC64 design:
1581 * PPC64 uses function descriptors which greatly complicate all code, since
1582 * these are used very inconsistently in the runtime. Some functions like
1583 * mono_compile_method () return ftn descriptors, while others like the
1584 * trampoline creation functions do not.
1585 * We assume that all GOT slots contain function descriptors, and create
1586 * descriptors in aot-runtime.c when needed.
1587 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1588 * from function descriptors, we could do the same, but it would require
1589 * rewriting all the ppc/aot code to handle function descriptors properly.
1590 * So instead, we use the same approach as on PPC32.
1591 * This is a horrible mess, but fixing it would probably lead to an even bigger
1592 * one.
1596 * X86 design:
1597 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1600 #ifdef MONO_ARCH_AOT_SUPPORTED
1602 * arch_emit_got_offset:
1604 * The memory pointed to by CODE should hold native code for computing the GOT
1605 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1606 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1608 static void
1609 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1611 #if defined(TARGET_POWERPC64)
1612 emit_unset_mode (acfg);
1614 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1615 * unsupported relocations. So we store the got address into the .Lgot_addr
1616 * symbol which is in the text segment, compute its address, and load it.
1618 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1619 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1620 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1621 fprintf (acfg->fp, "add 30, 30, 0\n");
1622 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1623 acfg->label_generator ++;
1624 *code_size = 16;
1625 #elif defined(TARGET_POWERPC)
1626 emit_unset_mode (acfg);
1627 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1628 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1629 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1630 acfg->label_generator ++;
1631 *code_size = 8;
1632 #else
1633 guint32 offset = mono_arch_get_patch_offset (code);
1634 emit_bytes (acfg, code, offset);
1635 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1637 *code_size = offset + 4;
1638 #endif
1642 * arch_emit_got_access:
1644 * The memory pointed to by CODE should hold native code for loading a GOT
1645 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1646 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1648 static void
1649 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1651 #ifdef TARGET_AMD64
1652 /* mov reg, got+offset(%rip) */
1653 if (acfg->llvm) {
1654 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1655 int dreg;
1656 int rex_r;
1658 /* Decode reg, see amd64_mov_reg_membase () */
1659 rex_r = code [0] & AMD64_REX_R;
1660 g_assert (code [0] == 0x49 + rex_r);
1661 g_assert (code [1] == 0x8b);
1662 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1664 emit_unset_mode (acfg);
1665 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
1666 *code_size = 7;
1667 } else {
1668 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1669 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t)) - 4));
1670 *code_size = mono_arch_get_patch_offset (code) + 4;
1672 #elif defined(TARGET_X86)
1673 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1674 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (target_mgreg_t))));
1675 *code_size = mono_arch_get_patch_offset (code) + 4;
1676 #elif defined(TARGET_ARM)
1677 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1678 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (target_mgreg_t))) - 12);
1679 *code_size = mono_arch_get_patch_offset (code) + 4;
1680 #elif defined(TARGET_ARM64)
1681 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1682 arm64_emit_got_access (acfg, code, got_slot, code_size);
1683 #elif defined(TARGET_POWERPC)
1685 guint8 buf [32];
1687 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1688 code = buf;
1689 ppc_load32 (code, ppc_r0, got_slot * sizeof (target_mgreg_t));
1690 g_assert (code - buf == 8);
1691 emit_bytes (acfg, buf, code - buf);
1692 *code_size = code - buf;
1694 #else
1695 g_assert_not_reached ();
1696 #endif
1699 #endif
1701 #ifdef MONO_ARCH_AOT_SUPPORTED
1703 * arch_emit_objc_selector_ref:
1705 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1707 static void
1708 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1710 #if defined(TARGET_ARM)
1711 char symbol1 [MAX_SYMBOL_SIZE];
1712 char symbol2 [MAX_SYMBOL_SIZE];
1713 int lindex = acfg->objc_selector_index_2 ++;
1715 /* Emit ldr.imm/b */
1716 emit_bytes (acfg, code, 8);
1718 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1719 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1721 emit_label (acfg, symbol1);
1722 mono_img_writer_emit_unset_mode (acfg->w);
1723 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1725 *code_size = 12;
1726 #elif defined(TARGET_ARM64)
1727 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1728 #else
1729 g_assert_not_reached ();
1730 #endif
1732 #endif
1735 * arch_emit_plt_entry:
1737 * Emit code for the PLT entry.
1738 * The plt entry should look like this:
1739 * <indirect jump to GOT_SYMBOL + OFFSET>
1740 * <INFO_OFFSET embedded into the instruction stream>
1742 static void
1743 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1745 #if defined(TARGET_X86)
1746 /* jmp *<offset>(%ebx) */
1747 emit_byte (acfg, 0xff);
1748 emit_byte (acfg, 0xa3);
1749 emit_int32 (acfg, offset);
1750 /* Used by mono_aot_get_plt_info_offset */
1751 emit_int32 (acfg, info_offset);
1752 #elif defined(TARGET_AMD64)
1753 emit_unset_mode (acfg);
1754 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1755 /* Used by mono_aot_get_plt_info_offset */
1756 emit_int32 (acfg, info_offset);
1757 acfg->stats.plt_size += 10;
1758 #elif defined(TARGET_ARM)
1759 guint8 buf [256];
1760 guint8 *code;
1762 code = buf;
1763 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1764 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1765 emit_bytes (acfg, buf, code - buf);
1766 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1767 /* Used by mono_aot_get_plt_info_offset */
1768 emit_int32 (acfg, info_offset);
1769 #elif defined(TARGET_ARM64)
1770 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1771 #elif defined(TARGET_POWERPC)
1772 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1773 emit_unset_mode (acfg);
1774 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1775 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1776 fprintf (acfg->fp, "add 11, 11, 30\n");
1777 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1778 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1779 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
1780 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1781 #endif
1782 fprintf (acfg->fp, "mtctr 11\n");
1783 fprintf (acfg->fp, "bctr\n");
1784 emit_int32 (acfg, info_offset);
1785 #else
1786 g_assert_not_reached ();
1787 #endif
1791 * arch_emit_llvm_plt_entry:
1793 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1794 * This is only needed on arm to handle thumb interop.
1796 static void
1797 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1799 #if defined(TARGET_ARM)
1800 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1801 /* The caller already transitioned to thumb */
1802 /* The code below should be 12 bytes long */
1803 /* clang has trouble encoding these instructions, so emit the binary */
1804 #if 0
1805 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1806 /* thumb can't encode ld pc, [pc, ip] */
1807 fprintf (acfg->fp, "add ip, pc, ip\n");
1808 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1809 fprintf (acfg->fp, "bx ip\n");
1810 #endif
1811 emit_set_thumb_mode (acfg);
1812 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1813 fprintf (acfg->fp, ".2byte 0x44fc\n");
1814 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1815 fprintf (acfg->fp, ".2byte 0x4760\n");
1816 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1817 emit_int32 (acfg, info_offset);
1818 emit_unset_mode (acfg);
1819 emit_set_arm_mode (acfg);
1820 #else
1821 g_assert_not_reached ();
1822 #endif
1825 /* Save unwind_info in the module and emit the offset to the information at symbol */
1826 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1828 guint32 uw_offset, encoded_len;
1829 guint8 *encoded;
1831 emit_section_change (acfg, RODATA_SECT, 0);
1832 emit_global (acfg, symbol, FALSE);
1833 emit_label (acfg, symbol);
1835 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1836 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1837 g_free (encoded);
1838 emit_int32 (acfg, uw_offset);
1842 * arch_emit_specific_trampoline_pages:
1844 * Emits a page full of trampolines: each trampoline uses its own address to
1845 * lookup both the generic trampoline code and the data argument.
1846 * This page can be remapped in process multiple times so we can get an
1847 * unlimited number of trampolines.
1848 * Specifically this implementation uses the following trick: two memory pages
1849 * are allocated, with the first containing the data and the second containing the trampolines.
1850 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1851 * implementation does all the lifting.
1852 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1853 * on the arm 32 bit system.
1855 static void
1856 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1858 #if defined(TARGET_ARM)
1859 guint8 buf [128];
1860 guint8 *code;
1861 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1862 int i;
1863 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1864 GSList *unwind_ops = NULL;
1865 #define COMMON_TRAMP_SIZE 16
1866 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1867 int imm8, rot_amount;
1868 char symbol [128];
1870 if (!acfg->aot_opts.use_trampolines_page)
1871 return;
1873 acfg->tramp_page_size = pagesize;
1875 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1876 emit_alignment (acfg, pagesize);
1877 emit_global (acfg, symbol, TRUE);
1878 emit_label (acfg, symbol);
1880 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1881 code = buf;
1882 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1883 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1884 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1885 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1886 ARM_NOP (code);
1887 g_assert (code - buf == COMMON_TRAMP_SIZE);
1889 /* Emit it */
1890 emit_bytes (acfg, buf, code - buf);
1892 for (i = 0; i < count; ++i) {
1893 code = buf;
1894 ARM_PUSH (code, 0x5fff);
1895 ARM_BL (code, 0);
1896 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1897 g_assert (code - buf == 8);
1898 emit_bytes (acfg, buf, code - buf);
1901 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1902 * the instruction pointer address, so the generic trampoline at the start of the page
1903 * subtracts 4096 to get to the data page and loads the values
1904 * We again fit the generic trampiline in 16 bytes.
1906 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1907 emit_global (acfg, symbol, TRUE);
1908 emit_label (acfg, symbol);
1909 code = buf;
1910 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1911 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1912 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1913 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1914 ARM_NOP (code);
1915 g_assert (code - buf == COMMON_TRAMP_SIZE);
1917 /* Emit it */
1918 emit_bytes (acfg, buf, code - buf);
1920 for (i = 0; i < count; ++i) {
1921 code = buf;
1922 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1923 ARM_B (code, 0);
1924 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1925 g_assert (code - buf == 8);
1926 emit_bytes (acfg, buf, code - buf);
1930 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1932 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1933 emit_global (acfg, symbol, TRUE);
1934 emit_label (acfg, symbol);
1935 code = buf;
1936 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1937 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1938 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1939 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1940 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1941 g_assert (code - buf == COMMON_TRAMP_SIZE);
1942 /* Emit it */
1943 emit_bytes (acfg, buf, code - buf);
1945 for (i = 0; i < count; ++i) {
1946 code = buf;
1947 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1948 ARM_B (code, 0);
1949 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1950 g_assert (code - buf == 8);
1951 emit_bytes (acfg, buf, code - buf);
1954 /* now the unbox arbitrary trampolines: each specific trampolines puts in the ip register
1955 * the instruction pointer address, so the generic trampoline at the start of the page
1956 * subtracts 4096 to get to the data page and loads the target addr.
1957 * We again fit the generic trampoline in 16 bytes.
1959 sprintf (symbol, "%sunbox_arbitrary_trampolines_page", acfg->user_symbol_prefix);
1960 emit_global (acfg, symbol, TRUE);
1961 emit_label (acfg, symbol);
1962 code = buf;
1964 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
1965 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1966 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1967 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1968 ARM_NOP (code);
1969 g_assert (code - buf == COMMON_TRAMP_SIZE);
1971 /* Emit it */
1972 emit_bytes (acfg, buf, code - buf);
1974 for (i = 0; i < count; ++i) {
1975 code = buf;
1976 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1977 ARM_B (code, 0);
1978 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1979 g_assert (code - buf == 8);
1980 emit_bytes (acfg, buf, code - buf);
1983 /* now the imt trampolines: each specific trampolines puts in the ip register
1984 * the instruction pointer address, so the generic trampoline at the start of the page
1985 * subtracts 4096 to get to the data page and loads the values
1987 #define IMT_TRAMP_SIZE 72
1988 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1989 emit_global (acfg, symbol, TRUE);
1990 emit_label (acfg, symbol);
1991 code = buf;
1992 /* Need at least two free registers, plus a slot for storing the pc */
1993 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
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_R0, ARMREG_IP, -8);
1999 /* The IMT method is in v5, r0 has the imt array address */
2001 loop_start = code;
2002 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2003 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2004 imt_found_check = code;
2005 ARM_B_COND (code, ARMCOND_EQ, 0);
2007 /* End-of-loop check */
2008 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2009 loop_end_check = code;
2010 ARM_B_COND (code, ARMCOND_EQ, 0);
2012 /* Loop footer */
2013 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2014 loop_branch_back = code;
2015 ARM_B (code, 0);
2016 arm_patch (loop_branch_back, loop_start);
2018 /* Match */
2019 arm_patch (imt_found_check, code);
2020 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2021 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2022 /* Save it to the third stack slot */
2023 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2024 /* Restore the registers and branch */
2025 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2027 /* No match */
2028 arm_patch (loop_end_check, code);
2029 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2030 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2031 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2032 ARM_NOP (code);
2034 /* Emit it */
2035 g_assert (code - buf == IMT_TRAMP_SIZE);
2036 emit_bytes (acfg, buf, code - buf);
2038 for (i = 0; i < count; ++i) {
2039 code = buf;
2040 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
2041 ARM_B (code, 0);
2042 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
2043 g_assert (code - buf == 8);
2044 emit_bytes (acfg, buf, code - buf);
2047 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
2048 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
2049 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
2050 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
2051 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_UNBOX_ARBITRARY] = 16;
2053 /* Unwind info for specifc trampolines */
2054 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
2055 /* We unwind to the original caller, from the stack, since lr is clobbered */
2056 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
2057 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
2058 save_unwind_info (acfg, symbol, unwind_ops);
2059 mono_free_unwind_info (unwind_ops);
2061 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
2062 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2063 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
2064 save_unwind_info (acfg, symbol, unwind_ops);
2065 mono_free_unwind_info (unwind_ops);
2067 /* Unwind info for rgctx trampolines */
2068 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
2069 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2070 save_unwind_info (acfg, symbol, unwind_ops);
2072 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
2073 save_unwind_info (acfg, symbol, unwind_ops);
2074 mono_free_unwind_info (unwind_ops);
2076 /* Unwind info for gsharedvt trampolines */
2077 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2078 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2079 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
2080 save_unwind_info (acfg, symbol, unwind_ops);
2081 mono_free_unwind_info (unwind_ops);
2083 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2084 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2085 save_unwind_info (acfg, symbol, unwind_ops);
2086 mono_free_unwind_info (unwind_ops);
2088 /* Unwind info for unbox arbitrary trampolines */
2089 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_gen_p", acfg->user_symbol_prefix);
2090 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2091 save_unwind_info (acfg, symbol, unwind_ops);
2093 sprintf (symbol, "%sunbox_arbitrary_trampolines_page_sp_p", acfg->user_symbol_prefix);
2094 save_unwind_info (acfg, symbol, unwind_ops);
2095 mono_free_unwind_info (unwind_ops);
2097 /* Unwind info for imt trampolines */
2098 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
2099 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2100 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
2101 save_unwind_info (acfg, symbol, unwind_ops);
2102 mono_free_unwind_info (unwind_ops);
2104 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
2105 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
2106 save_unwind_info (acfg, symbol, unwind_ops);
2107 mono_free_unwind_info (unwind_ops);
2108 #elif defined(TARGET_ARM64)
2109 arm64_emit_specific_trampoline_pages (acfg);
2110 #endif
2114 * arch_emit_specific_trampoline:
2116 * Emit code for a specific trampoline. OFFSET is the offset of the first of
2117 * two GOT slots which contain the generic trampoline address and the trampoline
2118 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
2120 static void
2121 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2124 * The trampolines created here are variations of the specific
2125 * trampolines created in mono_arch_create_specific_trampoline (). The
2126 * differences are:
2127 * - the generic trampoline address is taken from a got slot.
2128 * - the offset of the got slot where the trampoline argument is stored
2129 * is embedded in the instruction stream, and the generic trampoline
2130 * can load the argument by loading the offset, adding it to the
2131 * address of the trampoline to get the address of the got slot, and
2132 * loading the argument from there.
2133 * - all the trampolines should be of the same length.
2135 #if defined(TARGET_AMD64)
2136 /* This should be exactly 8 bytes long */
2137 *tramp_size = 8;
2138 /* call *<offset>(%rip) */
2139 if (acfg->llvm) {
2140 emit_unset_mode (acfg);
2141 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2142 emit_zero_bytes (acfg, 2);
2143 } else {
2144 emit_byte (acfg, '\x41');
2145 emit_byte (acfg, '\xff');
2146 emit_byte (acfg, '\x15');
2147 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2148 emit_zero_bytes (acfg, 1);
2150 #elif defined(TARGET_ARM)
2151 guint8 buf [128];
2152 guint8 *code;
2154 /* This should be exactly 20 bytes long */
2155 *tramp_size = 20;
2156 code = buf;
2157 ARM_PUSH (code, 0x5fff);
2158 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
2159 /* Load the value from the GOT */
2160 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2161 /* Branch to it */
2162 ARM_BLX_REG (code, ARMREG_R1);
2164 g_assert (code - buf == 16);
2166 /* Emit it */
2167 emit_bytes (acfg, buf, code - buf);
2169 * Only one offset is needed, since the second one would be equal to the
2170 * first one.
2172 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 4);
2173 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 8);
2174 #elif defined(TARGET_ARM64)
2175 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
2176 #elif defined(TARGET_POWERPC)
2177 guint8 buf [128];
2178 guint8 *code;
2180 *tramp_size = 4;
2181 code = buf;
2184 * PPC has no ip relative addressing, so we need to compute the address
2185 * of the mscorlib got. That is slow and complex, so instead, we store it
2186 * in the second got slot of every aot image. The caller already computed
2187 * the address of its got and placed it into r30.
2189 emit_unset_mode (acfg);
2190 /* Load mscorlib got address */
2191 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2192 /* Load generic trampoline address */
2193 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2194 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2195 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2196 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2197 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2198 #endif
2199 fprintf (acfg->fp, "mtctr 11\n");
2200 /* Load trampoline argument */
2201 /* On ppc, we pass it normally to the generic trampoline */
2202 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2203 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2204 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2205 /* Branch to generic trampoline */
2206 fprintf (acfg->fp, "bctr\n");
2208 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2209 *tramp_size = 10 * 4;
2210 #else
2211 *tramp_size = 9 * 4;
2212 #endif
2213 #elif defined(TARGET_X86)
2214 guint8 buf [128];
2215 guint8 *code;
2217 /* Similar to the PPC code above */
2219 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2221 code = buf;
2222 /* Load mscorlib got address */
2223 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2224 /* Push trampoline argument */
2225 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2226 /* Load generic trampoline address */
2227 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2228 /* Branch to generic trampoline */
2229 x86_jump_reg (code, X86_ECX);
2231 emit_bytes (acfg, buf, code - buf);
2233 *tramp_size = 17;
2234 g_assert (code - buf == *tramp_size);
2235 #else
2236 g_assert_not_reached ();
2237 #endif
2241 * arch_emit_unbox_trampoline:
2243 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2244 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2246 * See mono_aot_get_unbox_trampoline.
2248 static void
2249 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2251 #if defined(TARGET_AMD64)
2252 guint8 buf [32];
2253 guint8 *code;
2254 int this_reg;
2256 this_reg = mono_arch_get_this_arg_reg (NULL);
2257 code = buf;
2258 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2260 emit_bytes (acfg, buf, code - buf);
2261 /* jump <method> */
2262 if (acfg->llvm) {
2263 emit_unset_mode (acfg);
2264 fprintf (acfg->fp, "jmp %s\n", call_target);
2265 } else {
2266 emit_byte (acfg, '\xe9');
2267 emit_symbol_diff (acfg, call_target, ".", -4);
2269 #elif defined(TARGET_X86)
2270 guint8 buf [32];
2271 guint8 *code;
2272 int this_pos = 4;
2274 code = buf;
2276 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, MONO_ABI_SIZEOF (MonoObject));
2278 emit_bytes (acfg, buf, code - buf);
2280 /* jump <method> */
2281 emit_byte (acfg, '\xe9');
2282 emit_symbol_diff (acfg, call_target, ".", -4);
2283 #elif defined(TARGET_ARM)
2284 guint8 buf [128];
2285 guint8 *code;
2287 if (acfg->thumb_mixed && cfg->compile_llvm) {
2288 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)MONO_ABI_SIZEOF (MonoObject));
2289 fprintf (acfg->fp, "b %s\n", call_target);
2290 fprintf (acfg->fp, ".arm\n");
2291 fprintf (acfg->fp, ".align 2\n");
2292 return;
2295 code = buf;
2297 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2299 emit_bytes (acfg, buf, code - buf);
2300 /* jump to method */
2301 if (acfg->thumb_mixed && cfg->compile_llvm)
2302 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2303 else
2304 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2305 #elif defined(TARGET_ARM64)
2306 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2307 #elif defined(TARGET_POWERPC)
2308 int this_pos = 3;
2310 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)MONO_ABI_SIZEOF (MonoObject));
2311 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2312 #else
2313 g_assert_not_reached ();
2314 #endif
2318 * arch_emit_static_rgctx_trampoline:
2320 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2321 * two GOT slots which contain the rgctx argument, and the method to jump to.
2322 * TRAMP_SIZE is set to the size of the emitted trampoline.
2323 * These kinds of trampolines cannot be enumerated statically, since there could
2324 * be one trampoline per method instantiation, so we emit the same code for all
2325 * trampolines, and parameterize them using two GOT slots.
2327 static void
2328 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2330 #if defined(TARGET_AMD64)
2331 /* This should be exactly 13 bytes long */
2332 *tramp_size = 13;
2334 if (acfg->llvm) {
2335 emit_unset_mode (acfg);
2336 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (target_mgreg_t)));
2337 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (target_mgreg_t)));
2338 } else {
2339 /* mov <OFFSET>(%rip), %r10 */
2340 emit_byte (acfg, '\x4d');
2341 emit_byte (acfg, '\x8b');
2342 emit_byte (acfg, '\x15');
2343 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2345 /* jmp *<offset>(%rip) */
2346 emit_byte (acfg, '\xff');
2347 emit_byte (acfg, '\x25');
2348 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4);
2350 #elif defined(TARGET_ARM)
2351 guint8 buf [128];
2352 guint8 *code;
2354 /* This should be exactly 24 bytes long */
2355 *tramp_size = 24;
2356 code = buf;
2357 /* Load rgctx value */
2358 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2359 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2360 /* Load branch addr + branch */
2361 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2362 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2364 g_assert (code - buf == 16);
2366 /* Emit it */
2367 emit_bytes (acfg, buf, code - buf);
2368 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4 + 8);
2369 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) - 4 + 4);
2370 #elif defined(TARGET_ARM64)
2371 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2372 #elif defined(TARGET_POWERPC)
2373 guint8 buf [128];
2374 guint8 *code;
2376 *tramp_size = 4;
2377 code = buf;
2380 * PPC has no ip relative addressing, so we need to compute the address
2381 * of the mscorlib got. That is slow and complex, so instead, we store it
2382 * in the second got slot of every aot image. The caller already computed
2383 * the address of its got and placed it into r30.
2385 emit_unset_mode (acfg);
2386 /* Load mscorlib got address */
2387 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2388 /* Load rgctx */
2389 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (target_mgreg_t)));
2390 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (target_mgreg_t)));
2391 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2392 /* Load target address */
2393 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2394 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (target_mgreg_t)));
2395 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2396 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2397 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (target_mgreg_t));
2398 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2399 #endif
2400 fprintf (acfg->fp, "mtctr 11\n");
2401 /* Branch to the target address */
2402 fprintf (acfg->fp, "bctr\n");
2404 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2405 *tramp_size = 11 * 4;
2406 #else
2407 *tramp_size = 9 * 4;
2408 #endif
2410 #elif defined(TARGET_X86)
2411 guint8 buf [128];
2412 guint8 *code;
2414 /* Similar to the PPC code above */
2416 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2418 code = buf;
2419 /* Load mscorlib got address */
2420 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2421 /* Load arg */
2422 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2423 /* Branch to the target address */
2424 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2426 emit_bytes (acfg, buf, code - buf);
2428 *tramp_size = 15;
2429 g_assert (code - buf == *tramp_size);
2430 #else
2431 g_assert_not_reached ();
2432 #endif
2436 * arch_emit_imt_trampoline:
2438 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2439 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2440 * key is the IMT key, and ptr holds the address of a memory location holding
2441 * the address to branch to if the IMT arg matches the key. The array is
2442 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2443 * fail_tramp.
2444 * TRAMP_SIZE is set to the size of the emitted trampoline.
2446 static void
2447 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2449 #if defined(TARGET_AMD64)
2450 guint8 *buf, *code;
2451 guint8 *labels [16];
2452 guint8 mov_buf[3];
2453 guint8 *mov_buf_ptr = mov_buf;
2455 const int kSizeOfMove = 7;
2457 code = buf = (guint8 *)g_malloc (256);
2459 /* FIXME: Optimize this, i.e. use binary search etc. */
2460 /* Maybe move the body into a separate function (slower, but much smaller) */
2462 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2464 if (acfg->llvm) {
2465 emit_unset_mode (acfg);
2466 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));
2469 labels [0] = code;
2470 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2471 labels [1] = code;
2472 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2474 /* Check key */
2475 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (target_mgreg_t));
2476 labels [2] = code;
2477 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2479 /* Loop footer */
2480 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (target_mgreg_t));
2481 amd64_jump_code (code, labels [0]);
2483 /* Match */
2484 mono_amd64_patch (labels [2], code);
2485 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t), sizeof (target_mgreg_t));
2486 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2488 /* No match */
2489 mono_amd64_patch (labels [1], code);
2490 /* Load fail tramp */
2491 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (target_mgreg_t));
2492 /* Check if there is a fail tramp */
2493 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2494 labels [3] = code;
2495 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2496 /* Jump to fail tramp */
2497 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2499 /* Fail */
2500 mono_amd64_patch (labels [3], code);
2501 x86_breakpoint (code);
2503 if (!acfg->llvm) {
2504 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2505 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2506 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2507 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2508 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2509 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) - 4);
2511 emit_bytes (acfg, buf, code - buf);
2513 *tramp_size = code - buf + kSizeOfMove;
2515 g_free (buf);
2517 #elif defined(TARGET_X86)
2518 guint8 *buf, *code;
2519 guint8 *labels [16];
2521 code = buf = g_malloc (256);
2523 /* Allocate a temporary stack slot */
2524 x86_push_reg (code, X86_EAX);
2525 /* Save EAX */
2526 x86_push_reg (code, X86_EAX);
2528 /* Load mscorlib got address */
2529 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2530 /* Load arg */
2531 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (target_mgreg_t), 4);
2533 labels [0] = code;
2534 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2535 labels [1] = code;
2536 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2538 /* Check key */
2539 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2540 labels [2] = code;
2541 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2543 /* Loop footer */
2544 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (target_mgreg_t));
2545 x86_jump_code (code, labels [0]);
2547 /* Match */
2548 mono_x86_patch (labels [2], code);
2549 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2550 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2551 /* Save the target address to the temporary stack location */
2552 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2553 /* Restore EAX */
2554 x86_pop_reg (code, X86_EAX);
2555 /* Jump to the target address */
2556 x86_ret (code);
2558 /* No match */
2559 mono_x86_patch (labels [1], code);
2560 /* Load fail tramp */
2561 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (target_mgreg_t), 4);
2562 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2563 labels [3] = code;
2564 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2565 /* Jump to fail tramp */
2566 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2567 x86_pop_reg (code, X86_EAX);
2568 x86_ret (code);
2570 /* Fail */
2571 mono_x86_patch (labels [3], code);
2572 x86_breakpoint (code);
2574 emit_bytes (acfg, buf, code - buf);
2576 *tramp_size = code - buf;
2578 g_free (buf);
2580 #elif defined(TARGET_ARM)
2581 guint8 buf [128];
2582 guint8 *code, *code2, *labels [16];
2584 code = buf;
2586 /* The IMT method is in v5 */
2588 /* Need at least two free registers, plus a slot for storing the pc */
2589 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2590 labels [0] = code;
2591 /* Load the parameter from the GOT */
2592 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2593 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2595 labels [1] = code;
2596 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2597 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2598 labels [2] = code;
2599 ARM_B_COND (code, ARMCOND_EQ, 0);
2601 /* End-of-loop check */
2602 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2603 labels [3] = code;
2604 ARM_B_COND (code, ARMCOND_EQ, 0);
2606 /* Loop footer */
2607 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (target_mgreg_t) * 2);
2608 labels [4] = code;
2609 ARM_B (code, 0);
2610 arm_patch (labels [4], labels [1]);
2612 /* Match */
2613 arm_patch (labels [2], code);
2614 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2615 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2616 /* Save it to the third stack slot */
2617 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2618 /* Restore the registers and branch */
2619 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2621 /* No match */
2622 arm_patch (labels [3], code);
2623 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2624 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2625 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2627 /* Fixup offset */
2628 code2 = labels [0];
2629 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2631 emit_bytes (acfg, buf, code - buf);
2632 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (labels [0] + 8)) - 4);
2634 *tramp_size = code - buf + 4;
2635 #elif defined(TARGET_ARM64)
2636 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2637 #elif defined(TARGET_POWERPC)
2638 guint8 buf [128];
2639 guint8 *code, *labels [16];
2641 code = buf;
2643 /* Load the mscorlib got address */
2644 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r30);
2645 /* Load the parameter from the GOT */
2646 ppc_load (code, ppc_r0, offset * sizeof (target_mgreg_t));
2647 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2649 /* Load and check key */
2650 labels [1] = code;
2651 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2652 ppc_cmp (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2653 labels [2] = code;
2654 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2656 /* End-of-loop check */
2657 ppc_cmpi (code, 0, sizeof (target_mgreg_t) == 8 ? 1 : 0, ppc_r0, 0);
2658 labels [3] = code;
2659 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2661 /* Loop footer */
2662 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (target_mgreg_t));
2663 labels [4] = code;
2664 ppc_b (code, 0);
2665 mono_ppc_patch (labels [4], labels [1]);
2667 /* Match */
2668 mono_ppc_patch (labels [2], code);
2669 ppc_ldptr (code, ppc_r12, sizeof (target_mgreg_t), ppc_r12);
2670 /* r12 now contains the value of the vtable slot */
2671 /* this is not a function descriptor on ppc64 */
2672 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2673 ppc_mtctr (code, ppc_r12);
2674 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2676 /* Fail */
2677 mono_ppc_patch (labels [3], code);
2678 /* FIXME: */
2679 ppc_break (code);
2681 *tramp_size = code - buf;
2683 emit_bytes (acfg, buf, code - buf);
2684 #else
2685 g_assert_not_reached ();
2686 #endif
2690 #if defined (TARGET_AMD64)
2692 static void
2693 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2696 g_assert (acfg->fp);
2697 emit_unset_mode (acfg);
2699 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (target_mgreg_t))), mono_arch_regname (dreg));
2702 #endif
2706 * arch_emit_gsharedvt_arg_trampoline:
2708 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2709 * two GOT slots which contain the argument, and the code to jump to.
2710 * TRAMP_SIZE is set to the size of the emitted trampoline.
2711 * These kinds of trampolines cannot be enumerated statically, since there could
2712 * be one trampoline per method instantiation, so we emit the same code for all
2713 * trampolines, and parameterize them using two GOT slots.
2715 static void
2716 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2718 #if defined(TARGET_X86)
2719 guint8 buf [128];
2720 guint8 *code;
2722 /* Similar to the PPC code above */
2724 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2726 code = buf;
2727 /* Load mscorlib got address */
2728 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (target_mgreg_t), 4);
2729 /* Load arg */
2730 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (target_mgreg_t), 4);
2731 /* Branch to the target address */
2732 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (target_mgreg_t));
2734 emit_bytes (acfg, buf, code - buf);
2736 *tramp_size = 15;
2737 g_assert (code - buf == *tramp_size);
2738 #elif defined(TARGET_ARM)
2739 guint8 buf [128];
2740 guint8 *code;
2742 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2743 /* Similar to arch_emit_specific_trampoline () */
2744 *tramp_size = 24;
2745 code = buf;
2746 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2747 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2748 /* Load the arg value from the GOT */
2749 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2750 /* Load the addr from the GOT */
2751 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2752 /* Branch to it */
2753 ARM_BX (code, ARMREG_R1);
2755 g_assert (code - buf == 20);
2757 /* Emit it */
2758 emit_bytes (acfg, buf, code - buf);
2759 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4);
2760 #elif defined(TARGET_ARM64)
2761 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2762 #elif defined (TARGET_AMD64)
2764 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2765 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2766 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2767 fprintf (acfg->fp, "jmp *%%r11\n");
2769 *tramp_size = 0x11;
2770 #else
2771 g_assert_not_reached ();
2772 #endif
2775 static void
2776 arch_emit_ftnptr_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2778 #if defined(TARGET_ARM)
2779 guint8 buf [128];
2780 guint8 *code;
2782 *tramp_size = 32;
2783 code = buf;
2785 /* Load target address and push it on stack */
2786 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 16);
2787 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2788 ARM_PUSH (code, 1 << ARMREG_IP);
2789 /* Load argument in ARMREG_IP */
2790 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2791 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
2792 /* Branch */
2793 ARM_POP (code, 1 << ARMREG_PC);
2795 g_assert (code - buf == 24);
2797 /* Emit it */
2798 emit_bytes (acfg, buf, code - buf);
2799 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (target_mgreg_t)) + 12); // offset from ldr pc to addr
2800 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + 4); // offset from ldr pc to arg
2801 #else
2802 g_assert_not_reached ();
2803 #endif
2806 static void
2807 arch_emit_unbox_arbitrary_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2809 #if defined(TARGET_ARM64)
2810 emit_unset_mode (acfg);
2811 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(MONO_ABI_SIZEOF (MonoObject)));
2812 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
2813 fprintf (acfg->fp, "br x17\n");
2814 *tramp_size = 5 * 4;
2815 #elif defined (TARGET_AMD64)
2816 guint8 buf [32];
2817 guint8 *code;
2818 int this_reg;
2820 this_reg = mono_arch_get_this_arg_reg (NULL);
2821 code = buf;
2822 amd64_alu_reg_imm (code, X86_ADD, this_reg, MONO_ABI_SIZEOF (MonoObject));
2823 emit_bytes (acfg, buf, code - buf);
2825 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2826 fprintf (acfg->fp, "jmp *%%rax\n");
2828 *tramp_size = 13;
2829 #elif defined (TARGET_ARM)
2830 guint8 buf [32];
2831 guint8 *code, *label;
2833 code = buf;
2834 /* Unbox */
2835 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, MONO_ABI_SIZEOF (MonoObject));
2837 label = code;
2838 /* Calculate GOT slot */
2839 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
2840 /* Load target addr into PC*/
2841 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2843 g_assert (code - buf == 12);
2845 /* Emit it */
2846 emit_bytes (acfg, buf, code - buf);
2847 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (target_mgreg_t)) + (code - (label + 8)) - 4);
2848 *tramp_size = 4 * 4;
2849 #else
2850 g_error ("NOT IMPLEMENTED: needed for AOT<>interp mixed mode transition");
2851 #endif
2854 /* END OF ARCH SPECIFIC CODE */
2856 static guint32
2857 mono_get_field_token (MonoClassField *field)
2859 MonoClass *klass = field->parent;
2860 int i;
2862 int fcount = mono_class_get_field_count (klass);
2863 MonoClassField *klass_fields = m_class_get_fields (klass);
2864 for (i = 0; i < fcount; ++i) {
2865 if (field == &klass_fields [i])
2866 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2869 g_assert_not_reached ();
2870 return 0;
2873 static inline void
2874 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2876 guint8 *p = buf;
2878 //printf ("ENCODE: %d 0x%x.\n", value, value);
2881 * Same encoding as the one used in the metadata, extended to handle values
2882 * greater than 0x1fffffff.
2884 if ((value >= 0) && (value <= 127))
2885 *p++ = value;
2886 else if ((value >= 0) && (value <= 16383)) {
2887 p [0] = 0x80 | (value >> 8);
2888 p [1] = value & 0xff;
2889 p += 2;
2890 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2891 p [0] = (value >> 24) | 0xc0;
2892 p [1] = (value >> 16) & 0xff;
2893 p [2] = (value >> 8) & 0xff;
2894 p [3] = value & 0xff;
2895 p += 4;
2897 else {
2898 p [0] = 0xff;
2899 p [1] = (value >> 24) & 0xff;
2900 p [2] = (value >> 16) & 0xff;
2901 p [3] = (value >> 8) & 0xff;
2902 p [4] = value & 0xff;
2903 p += 5;
2905 if (endbuf)
2906 *endbuf = p;
2909 static void
2910 stream_init (MonoDynamicStream *sh)
2912 sh->index = 0;
2913 sh->alloc_size = 4096;
2914 sh->data = (char *)g_malloc (4096);
2916 /* So offsets are > 0 */
2917 sh->data [0] = 0;
2918 sh->index ++;
2921 static void
2922 make_room_in_stream (MonoDynamicStream *stream, int size)
2924 if (size <= stream->alloc_size)
2925 return;
2927 while (stream->alloc_size <= size) {
2928 if (stream->alloc_size < 4096)
2929 stream->alloc_size = 4096;
2930 else
2931 stream->alloc_size *= 2;
2934 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2937 static guint32
2938 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2940 guint32 idx;
2942 make_room_in_stream (stream, stream->index + len);
2943 memcpy (stream->data + stream->index, data, len);
2944 idx = stream->index;
2945 stream->index += len;
2946 return idx;
2950 * add_to_blob:
2952 * Add data to the binary blob inside the aot image. Returns the offset inside the
2953 * blob where the data was stored.
2955 static guint32
2956 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2958 g_assert (!acfg->blob_closed);
2960 if (acfg->blob.alloc_size == 0)
2961 stream_init (&acfg->blob);
2963 return add_stream_data (&acfg->blob, (char*)data, data_len);
2966 static guint32
2967 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2969 char buf [4] = {0};
2970 guint32 count;
2972 if (acfg->blob.alloc_size == 0)
2973 stream_init (&acfg->blob);
2975 count = acfg->blob.index % align;
2977 /* we assume the stream data will be aligned */
2978 if (count)
2979 add_stream_data (&acfg->blob, buf, 4 - count);
2981 return add_stream_data (&acfg->blob, (char*)data, data_len);
2984 /* Emit a table of data into the aot image */
2985 static void
2986 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2988 if (acfg->data_outfile) {
2989 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2990 fwrite (data,1, size, acfg->data_outfile);
2991 acfg->datafile_offset += size;
2992 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2993 int align = 8 - size % 8;
2994 acfg->datafile_offset += align;
2995 guint8 align_buf [16];
2996 memset (&align_buf, 0, sizeof (align_buf));
2997 fwrite (align_buf, align, 1, acfg->data_outfile);
2998 } else if (acfg->llvm) {
2999 mono_llvm_emit_aot_data (symbol, data, size);
3000 } else {
3001 emit_section_change (acfg, RODATA_SECT, 0);
3002 emit_alignment (acfg, 8);
3003 emit_label (acfg, symbol);
3004 emit_bytes (acfg, data, size);
3009 * emit_offset_table:
3011 * Emit a table of increasing offsets in a compact form using differential encoding.
3012 * There is an index entry for each GROUP_SIZE number of entries. The greater the
3013 * group size, the more compact the table becomes, but the slower it becomes to compute
3014 * a given entry. Returns the size of the table.
3016 static guint32
3017 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
3019 gint32 current_offset;
3020 int i, buf_size, ngroups, index_entry_size;
3021 guint8 *p, *buf;
3022 guint8 *data_p, *data_buf;
3023 guint32 *index_offsets;
3025 ngroups = (noffsets + (group_size - 1)) / group_size;
3027 index_offsets = g_new0 (guint32, ngroups);
3029 buf_size = noffsets * 4;
3030 p = buf = (guint8 *)g_malloc0 (buf_size);
3032 current_offset = 0;
3033 for (i = 0; i < noffsets; ++i) {
3034 //printf ("D: %d -> %d\n", i, offsets [i]);
3035 if ((i % group_size) == 0) {
3036 index_offsets [i / group_size] = p - buf;
3037 /* Emit the full value for these entries */
3038 encode_value (offsets [i], p, &p);
3039 } else {
3040 /* The offsets are allowed to be non-increasing */
3041 //g_assert (offsets [i] >= current_offset);
3042 encode_value (offsets [i] - current_offset, p, &p);
3044 current_offset = offsets [i];
3046 data_buf = buf;
3047 data_p = p;
3049 if (ngroups && index_offsets [ngroups - 1] < 65000)
3050 index_entry_size = 2;
3051 else
3052 index_entry_size = 4;
3054 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
3055 p = buf = (guint8 *)g_malloc0 (buf_size);
3057 /* Emit the header */
3058 encode_int (noffsets, p, &p);
3059 encode_int (group_size, p, &p);
3060 encode_int (ngroups, p, &p);
3061 encode_int (index_entry_size, p, &p);
3063 /* Emit the index */
3064 for (i = 0; i < ngroups; ++i) {
3065 if (index_entry_size == 2)
3066 encode_int16 (index_offsets [i], p, &p);
3067 else
3068 encode_int (index_offsets [i], p, &p);
3070 /* Emit the data */
3071 memcpy (p, data_buf, data_p - data_buf);
3072 p += data_p - data_buf;
3074 g_assert (p - buf <= buf_size);
3076 emit_aot_data (acfg, table, symbol, buf, p - buf);
3078 g_free (buf);
3079 g_free (data_buf);
3081 return (int)(p - buf);
3084 static guint32
3085 get_image_index (MonoAotCompile *cfg, MonoImage *image)
3087 guint32 index;
3089 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
3090 if (index)
3091 return index - 1;
3092 else {
3093 index = g_hash_table_size (cfg->image_hash);
3094 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
3095 g_ptr_array_add (cfg->image_table, image);
3096 return index;
3100 static guint32
3101 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
3103 int i;
3104 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
3106 /* FIXME: Search referenced images as well */
3107 if (!acfg->typespec_classes) {
3108 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
3109 for (i = 0; i < len; i++) {
3110 ERROR_DECL (error);
3111 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
3112 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, error);
3113 if (!is_ok (error)) {
3114 mono_error_cleanup (error);
3115 continue;
3117 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
3120 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
3123 static void
3124 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
3126 static void
3127 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
3129 static void
3130 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
3132 static void
3133 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
3135 static void
3136 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3138 guint8 *p = buf;
3141 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
3142 * information.
3145 if (mono_class_is_ginst (klass)) {
3146 guint32 token;
3147 g_assert (m_class_get_type_token (klass));
3149 /* Find a typespec for a class if possible */
3150 token = find_typespec_for_class (acfg, klass);
3151 if (token) {
3152 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
3153 encode_value (token, p, &p);
3154 } else {
3155 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
3156 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
3157 static int count = 0;
3158 guint8 *p1 = p;
3160 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
3161 encode_klass_ref (acfg, gclass, p, &p);
3162 encode_ginst (acfg, inst, p, &p);
3164 count += p - p1;
3166 } else if (m_class_get_type_token (klass)) {
3167 int iindex = get_image_index (acfg, m_class_get_image (klass));
3169 g_assert (mono_metadata_token_code (m_class_get_type_token (klass)) == MONO_TOKEN_TYPE_DEF);
3170 if (iindex == 0) {
3171 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
3172 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3173 } else {
3174 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
3175 encode_value (m_class_get_type_token (klass) - MONO_TOKEN_TYPE_DEF, p, &p);
3176 encode_value (get_image_index (acfg, m_class_get_image (klass)), p, &p);
3178 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3179 MonoGenericContainer *container = mono_type_get_generic_param_owner (m_class_get_byval_arg (klass));
3180 MonoGenericParam *par = m_class_get_byval_arg (klass)->data.generic_param;
3182 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
3184 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
3185 if (par->gshared_constraint) {
3186 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
3187 encode_type (acfg, par->gshared_constraint, p, &p);
3188 encode_klass_ref (acfg, mono_class_create_generic_parameter (gpar->parent), p, &p);
3189 } else {
3190 encode_value (m_class_get_byval_arg (klass)->type, p, &p);
3191 encode_value (mono_type_get_generic_param_num (m_class_get_byval_arg (klass)), p, &p);
3193 encode_value (container->is_anonymous ? 0 : 1, p, &p);
3195 if (!container->is_anonymous) {
3196 encode_value (container->is_method, p, &p);
3197 if (container->is_method)
3198 encode_method_ref (acfg, container->owner.method, p, &p);
3199 else
3200 encode_klass_ref (acfg, container->owner.klass, p, &p);
3203 } else if (m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR) {
3204 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
3205 encode_type (acfg, m_class_get_byval_arg (klass), p, &p);
3206 } else {
3207 /* Array class */
3208 g_assert (m_class_get_rank (klass) > 0);
3209 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
3210 encode_value (m_class_get_rank (klass), p, &p);
3211 encode_klass_ref (acfg, m_class_get_element_class (klass), p, &p);
3213 *endbuf = p;
3217 * encode_klass_ref:
3219 * Encode a reference to KLASS. We use our home-grown encoding instead of the
3220 * standard metadata encoding.
3222 static void
3223 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
3225 gboolean shared = FALSE;
3228 * The encoding of generic instances is large so emit them only once.
3230 if (mono_class_is_ginst (klass)) {
3231 guint32 token;
3232 g_assert (m_class_get_type_token (klass));
3234 /* Find a typespec for a class if possible */
3235 token = find_typespec_for_class (acfg, klass);
3236 if (!token)
3237 shared = TRUE;
3238 } else if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR)) {
3239 shared = TRUE;
3242 if (shared) {
3243 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
3244 guint8 *buf2, *p;
3246 if (!offset) {
3247 buf2 = (guint8 *)g_malloc (1024);
3248 p = buf2;
3250 encode_klass_ref_inner (acfg, klass, p, &p);
3251 g_assert (p - buf2 < 1024);
3253 offset = add_to_blob (acfg, buf2, p - buf2);
3254 g_free (buf2);
3256 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
3257 } else {
3258 offset --;
3261 p = buf;
3262 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
3263 encode_value (offset, p, &p);
3264 *endbuf = p;
3265 return;
3268 encode_klass_ref_inner (acfg, klass, buf, endbuf);
3271 static void
3272 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
3274 guint32 token = mono_get_field_token (field);
3275 guint8 *p = buf;
3277 encode_klass_ref (cfg, field->parent, p, &p);
3278 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
3279 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
3280 *endbuf = p;
3283 static void
3284 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3286 guint8 *p = buf;
3287 int i;
3289 encode_value (inst->type_argc, p, &p);
3290 for (i = 0; i < inst->type_argc; ++i)
3291 encode_klass_ref (acfg, mono_class_from_mono_type_internal (inst->type_argv [i]), p, &p);
3292 *endbuf = p;
3295 static void
3296 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3298 guint8 *p = buf;
3299 MonoGenericInst *inst;
3301 inst = context->class_inst;
3302 if (inst) {
3303 g_assert (inst->type_argc);
3304 encode_ginst (acfg, inst, p, &p);
3305 } else {
3306 encode_value (0, p, &p);
3308 inst = context->method_inst;
3309 if (inst) {
3310 g_assert (inst->type_argc);
3311 encode_ginst (acfg, inst, p, &p);
3312 } else {
3313 encode_value (0, p, &p);
3315 *endbuf = p;
3318 static void
3319 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3321 guint8 *p = buf;
3323 if (t->has_cmods) {
3324 MonoCustomModContainer *cm = mono_type_get_cmods (t);
3326 *p = MONO_TYPE_CMOD_REQD;
3327 ++p;
3329 encode_value (cm->count, p, &p);
3330 int iindex = get_image_index (acfg, cm->image);
3331 encode_value (iindex, p, &p);
3332 for (int i = 0; i < cm->count; ++i) {
3333 encode_value (cm->modifiers [i].required, p, &p);
3334 encode_value (cm->modifiers [i].token, p, &p);
3338 /* t->attrs can be ignored */
3339 //g_assert (t->attrs == 0);
3341 if (t->pinned) {
3342 *p = MONO_TYPE_PINNED;
3343 ++p;
3345 if (t->byref) {
3346 *p = MONO_TYPE_BYREF;
3347 ++p;
3350 *p = t->type;
3351 p ++;
3353 switch (t->type) {
3354 case MONO_TYPE_VOID:
3355 case MONO_TYPE_BOOLEAN:
3356 case MONO_TYPE_CHAR:
3357 case MONO_TYPE_I1:
3358 case MONO_TYPE_U1:
3359 case MONO_TYPE_I2:
3360 case MONO_TYPE_U2:
3361 case MONO_TYPE_I4:
3362 case MONO_TYPE_U4:
3363 case MONO_TYPE_I8:
3364 case MONO_TYPE_U8:
3365 case MONO_TYPE_R4:
3366 case MONO_TYPE_R8:
3367 case MONO_TYPE_I:
3368 case MONO_TYPE_U:
3369 case MONO_TYPE_STRING:
3370 case MONO_TYPE_OBJECT:
3371 case MONO_TYPE_TYPEDBYREF:
3372 break;
3373 case MONO_TYPE_VALUETYPE:
3374 case MONO_TYPE_CLASS:
3375 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3376 break;
3377 case MONO_TYPE_SZARRAY:
3378 encode_klass_ref (acfg, t->data.klass, p, &p);
3379 break;
3380 case MONO_TYPE_PTR:
3381 encode_type (acfg, t->data.type, p, &p);
3382 break;
3383 case MONO_TYPE_GENERICINST: {
3384 MonoClass *gclass = t->data.generic_class->container_class;
3385 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3387 encode_klass_ref (acfg, gclass, p, &p);
3388 encode_ginst (acfg, inst, p, &p);
3389 break;
3391 case MONO_TYPE_ARRAY: {
3392 MonoArrayType *array = t->data.array;
3393 int i;
3395 encode_klass_ref (acfg, array->eklass, p, &p);
3396 encode_value (array->rank, p, &p);
3397 encode_value (array->numsizes, p, &p);
3398 for (i = 0; i < array->numsizes; ++i)
3399 encode_value (array->sizes [i], p, &p);
3400 encode_value (array->numlobounds, p, &p);
3401 for (i = 0; i < array->numlobounds; ++i)
3402 encode_value (array->lobounds [i], p, &p);
3403 break;
3405 case MONO_TYPE_VAR:
3406 case MONO_TYPE_MVAR:
3407 encode_klass_ref (acfg, mono_class_from_mono_type_internal (t), p, &p);
3408 break;
3409 default:
3410 g_assert_not_reached ();
3413 *endbuf = p;
3416 static void
3417 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3419 guint8 *p = buf;
3420 guint32 flags = 0;
3421 int i;
3423 /* Similar to the metadata encoding */
3424 if (sig->generic_param_count)
3425 flags |= 0x10;
3426 if (sig->hasthis)
3427 flags |= 0x20;
3428 if (sig->explicit_this)
3429 flags |= 0x40;
3430 flags |= (sig->call_convention & 0x0F);
3432 *p = flags;
3433 ++p;
3434 if (sig->generic_param_count)
3435 encode_value (sig->generic_param_count, p, &p);
3436 encode_value (sig->param_count, p, &p);
3438 encode_type (acfg, sig->ret, p, &p);
3439 for (i = 0; i < sig->param_count; ++i) {
3440 if (sig->sentinelpos == i) {
3441 *p = MONO_TYPE_SENTINEL;
3442 ++p;
3444 encode_type (acfg, sig->params [i], p, &p);
3447 *endbuf = p;
3450 #define MAX_IMAGE_INDEX 250
3452 static void
3453 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3455 guint32 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3456 guint32 token = method->token;
3457 MonoJumpInfoToken *ji;
3458 guint8 *p = buf;
3461 * The encoding for most methods is as follows:
3462 * - image index encoded as a leb128
3463 * - token index encoded as a leb128
3464 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3465 * types of method encodings.
3468 /* Mark methods which can't use aot trampolines because they need the further
3469 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3471 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3472 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3473 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3475 if (method->wrapper_type) {
3476 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3478 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3480 encode_value (method->wrapper_type, p, &p);
3482 switch (method->wrapper_type) {
3483 case MONO_WRAPPER_REMOTING_INVOKE:
3484 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3485 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3486 MonoMethod *m;
3488 m = mono_marshal_method_from_wrapper (method);
3489 g_assert (m);
3490 encode_method_ref (acfg, m, p, &p);
3491 break;
3493 case MONO_WRAPPER_PROXY_ISINST:
3494 case MONO_WRAPPER_LDFLD:
3495 case MONO_WRAPPER_LDFLDA:
3496 case MONO_WRAPPER_STFLD: {
3497 g_assert (info);
3498 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3499 break;
3501 case MONO_WRAPPER_ALLOC: {
3502 /* The GC name is saved once in MonoAotFileInfo */
3503 g_assert (info->d.alloc.alloc_type != -1);
3504 encode_value (info->d.alloc.alloc_type, p, &p);
3505 break;
3507 case MONO_WRAPPER_WRITE_BARRIER: {
3508 g_assert (info);
3509 break;
3511 case MONO_WRAPPER_STELEMREF: {
3512 g_assert (info);
3513 encode_value (info->subtype, p, &p);
3514 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3515 encode_value (info->d.virtual_stelemref.kind, p, &p);
3516 break;
3518 case MONO_WRAPPER_UNKNOWN: {
3519 g_assert (info);
3520 encode_value (info->subtype, p, &p);
3521 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3522 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3523 encode_klass_ref (acfg, method->klass, p, &p);
3524 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3525 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3526 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3527 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3528 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
3529 encode_signature (acfg, info->d.interp_in.sig, p, &p);
3530 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3531 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3532 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3533 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3534 break;
3536 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3537 g_assert (info);
3538 encode_value (info->subtype, p, &p);
3539 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3540 MonoJitICallInfo *callinfo = NULL;
3541 callinfo = mono_find_jit_icall_by_addr (info->d.icall.func);
3542 g_assert (callinfo);
3543 strcpy ((char*)p, callinfo->name);
3544 p += strlen (callinfo->name) + 1;
3545 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3546 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3547 } else {
3548 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3549 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3551 break;
3553 case MONO_WRAPPER_SYNCHRONIZED: {
3554 MonoMethod *m;
3556 m = mono_marshal_method_from_wrapper (method);
3557 g_assert (m);
3558 g_assert (m != method);
3559 encode_method_ref (acfg, m, p, &p);
3560 break;
3562 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3563 g_assert (info);
3564 encode_value (info->subtype, p, &p);
3566 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3567 encode_value (info->d.element_addr.rank, p, &p);
3568 encode_value (info->d.element_addr.elem_size, p, &p);
3569 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3570 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3571 } else {
3572 g_assert_not_reached ();
3574 break;
3576 case MONO_WRAPPER_CASTCLASS: {
3577 g_assert (info);
3578 encode_value (info->subtype, p, &p);
3579 break;
3581 case MONO_WRAPPER_RUNTIME_INVOKE: {
3582 g_assert (info);
3583 encode_value (info->subtype, p, &p);
3584 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3585 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3586 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3587 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3588 break;
3590 case MONO_WRAPPER_DELEGATE_INVOKE:
3591 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3592 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3593 if (method->is_inflated) {
3594 /* These wrappers are identified by their class */
3595 encode_value (1, p, &p);
3596 encode_klass_ref (acfg, method->klass, p, &p);
3597 } else {
3598 MonoMethodSignature *sig = mono_method_signature_internal (method);
3599 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3601 encode_value (0, p, &p);
3602 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3603 encode_value (info ? info->subtype : 0, p, &p);
3604 encode_signature (acfg, sig, p, &p);
3606 break;
3608 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3609 g_assert (info);
3610 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3611 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3612 break;
3614 default:
3615 g_assert_not_reached ();
3617 } else if (mono_method_signature_internal (method)->is_inflated) {
3619 * This is a generic method, find the original token which referenced it and
3620 * encode that.
3621 * Obtain the token from information recorded by the JIT.
3623 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3624 if (ji) {
3625 image_index = get_image_index (acfg, ji->image);
3626 g_assert (image_index < MAX_IMAGE_INDEX);
3627 token = ji->token;
3629 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3630 encode_value (image_index, p, &p);
3631 encode_value (token, p, &p);
3632 } else {
3633 MonoMethod *declaring;
3634 MonoGenericContext *context = mono_method_get_context (method);
3636 g_assert (method->is_inflated);
3637 declaring = ((MonoMethodInflated*)method)->declaring;
3640 * This might be a non-generic method of a generic instance, which
3641 * doesn't have a token since the reference is generated by the JIT
3642 * like Nullable:Box/Unbox, or by generic sharing.
3644 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3645 /* Encode the klass */
3646 encode_klass_ref (acfg, method->klass, p, &p);
3647 /* Encode the method */
3648 image_index = get_image_index (acfg, m_class_get_image (method->klass));
3649 g_assert (image_index < MAX_IMAGE_INDEX);
3650 g_assert (declaring->token);
3651 token = declaring->token;
3652 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3653 encode_value (image_index, p, &p);
3654 encode_value (token, p, &p);
3655 encode_generic_context (acfg, context, p, &p);
3657 } else if (token == 0) {
3658 /* This might be a method of a constructed type like int[,].Set */
3659 /* Obtain the token from information recorded by the JIT */
3660 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3661 if (ji) {
3662 image_index = get_image_index (acfg, ji->image);
3663 g_assert (image_index < MAX_IMAGE_INDEX);
3664 token = ji->token;
3666 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3667 encode_value (image_index, p, &p);
3668 encode_value (token, p, &p);
3669 } else {
3670 /* Array methods */
3671 g_assert (m_class_get_rank (method->klass));
3673 /* Encode directly */
3674 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3675 encode_klass_ref (acfg, method->klass, p, &p);
3676 if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass))
3677 encode_value (0, p, &p);
3678 else if (!strcmp (method->name, ".ctor") && mono_method_signature_internal (method)->param_count == m_class_get_rank (method->klass) * 2)
3679 encode_value (1, p, &p);
3680 else if (!strcmp (method->name, "Get"))
3681 encode_value (2, p, &p);
3682 else if (!strcmp (method->name, "Address"))
3683 encode_value (3, p, &p);
3684 else if (!strcmp (method->name, "Set"))
3685 encode_value (4, p, &p);
3686 else
3687 g_assert_not_reached ();
3689 } else {
3690 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3692 if (image_index >= MONO_AOT_METHODREF_MIN) {
3693 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3694 encode_value (image_index, p, &p);
3695 encode_value (mono_metadata_token_index (token), p, &p);
3696 } else {
3697 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3700 *endbuf = p;
3703 static gint
3704 compare_patches (gconstpointer a, gconstpointer b)
3706 int i, j;
3708 i = (*(MonoJumpInfo**)a)->ip.i;
3709 j = (*(MonoJumpInfo**)b)->ip.i;
3711 if (i < j)
3712 return -1;
3713 else
3714 if (i > j)
3715 return 1;
3716 else
3717 return 0;
3720 static G_GNUC_UNUSED char*
3721 patch_to_string (MonoJumpInfo *patch_info)
3723 GString *str;
3725 str = g_string_new ("");
3727 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3729 switch (patch_info->type) {
3730 case MONO_PATCH_INFO_VTABLE:
3731 mono_type_get_desc (str, m_class_get_byval_arg (patch_info->data.klass), TRUE);
3732 break;
3733 default:
3734 break;
3736 g_string_append_printf (str, ")");
3737 return g_string_free (str, FALSE);
3741 * is_plt_patch:
3743 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3744 * PLT entry.
3746 static inline gboolean
3747 is_plt_patch (MonoJumpInfo *patch_info)
3749 switch (patch_info->type) {
3750 case MONO_PATCH_INFO_METHOD:
3751 case MONO_PATCH_INFO_INTERNAL_METHOD:
3752 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3753 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3754 case MONO_PATCH_INFO_RGCTX_FETCH:
3755 return TRUE;
3756 default:
3757 return FALSE;
3762 * get_plt_symbol:
3764 * Return the symbol identifying the plt entry PLT_OFFSET.
3766 static char*
3767 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3769 #ifdef TARGET_MACH
3771 * The Apple linker reorganizes object files, so it doesn't like branches to local
3772 * labels, since those have no relocations.
3774 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3775 #else
3776 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3777 #endif
3781 * get_plt_entry:
3783 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3785 static MonoPltEntry*
3786 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3788 MonoPltEntry *res;
3789 gboolean synchronized = FALSE;
3790 static int synchronized_symbol_idx;
3792 if (!is_plt_patch (patch_info))
3793 return NULL;
3795 if (!acfg->patch_to_plt_entry [patch_info->type])
3796 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3797 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3799 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3801 * Allocate a separate PLT slot for each such patch, since some plt
3802 * entries will refer to the method itself, and some will refer to the
3803 * wrapper.
3805 res = NULL;
3806 synchronized = TRUE;
3809 if (!res) {
3810 MonoJumpInfo *new_ji;
3812 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3814 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3815 res->plt_offset = acfg->plt_offset;
3816 res->ji = new_ji;
3817 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3818 if (acfg->aot_opts.write_symbols)
3819 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3820 if (synchronized) {
3821 /* Avoid duplicate symbols because we don't cache */
3822 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3823 if (res->debug_sym)
3824 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3825 synchronized_symbol_idx ++;
3828 if (res->debug_sym)
3829 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3830 else
3831 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3832 if (strstr (res->llvm_symbol, acfg->temp_prefix) == res->llvm_symbol) {
3833 /* The llvm symbol shouldn't be temporary, since the llvm generated object file references it */
3834 char *tmp = res->llvm_symbol;
3835 res->llvm_symbol = g_strdup (res->llvm_symbol + strlen (acfg->temp_prefix));
3836 g_free (tmp);
3839 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3841 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3843 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3844 //mono_print_ji (patch_info); printf ("\n");
3845 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3847 acfg->plt_offset ++;
3850 return res;
3853 static guint32
3854 lookup_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3856 guint32 got_offset;
3857 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3859 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3860 if (got_offset)
3861 return got_offset - 1;
3862 g_assert_not_reached ();
3866 * get_got_offset:
3868 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3869 * JI could be found if it exists, otherwise allocates a new one.
3871 static guint32
3872 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3874 guint32 got_offset;
3875 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3877 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3878 if (got_offset)
3879 return got_offset - 1;
3881 if (llvm) {
3882 got_offset = acfg->llvm_got_offset;
3883 acfg->llvm_got_offset ++;
3884 } else {
3885 got_offset = acfg->got_offset;
3886 acfg->got_offset ++;
3889 acfg->stats.got_slots ++;
3890 acfg->stats.got_slot_types [ji->type] ++;
3892 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3893 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3894 g_ptr_array_add (info->got_patches, ji);
3896 return got_offset;
3899 /* Add a method to the list of methods which need to be emitted */
3900 static void
3901 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3903 g_assert (method);
3904 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3905 g_ptr_array_add (acfg->methods, method);
3906 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3907 acfg->nmethods = acfg->methods->len + 1;
3910 if (method->wrapper_type || extra) {
3911 int token = mono_metadata_token_index (method->token) - 1;
3912 if (token < 0)
3913 acfg->nextra_methods++;
3914 g_ptr_array_add (acfg->extra_methods, method);
3918 static gboolean
3919 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3921 /* One instantiation with valuetypes is generated for each async method */
3922 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")))
3923 return TRUE;
3924 else
3925 return FALSE;
3928 static guint32
3929 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3931 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3933 g_assert (index);
3935 return index - 1;
3938 static int
3939 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3941 int index;
3943 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3944 if (index)
3945 return index - 1;
3947 index = acfg->method_index;
3948 add_method_with_index (acfg, method, index, extra);
3950 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3952 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3954 acfg->method_index ++;
3956 return index;
3959 static int
3960 add_method (MonoAotCompile *acfg, MonoMethod *method)
3962 return add_method_full (acfg, method, FALSE, 0);
3965 static void
3966 mono_dedup_cache_method (MonoAotCompile *acfg, MonoMethod *method)
3968 g_assert (acfg->dedup_stats);
3970 char *name = mono_aot_get_mangled_method_name (method);
3971 g_assert (name);
3973 // For stats
3974 char *stats_name = g_strdup (name);
3976 g_assert (acfg->dedup_cache);
3978 if (!g_hash_table_lookup (acfg->dedup_cache, name)) {
3979 // This AOTCompile owns this method
3980 // We do this to decide whether to write it to disk
3981 // during a dedup run (first phase, where we skip).
3983 // If never changed, then maybe can avoid a recompile
3984 // of the cache.
3986 // Files not read in during last phase.
3987 acfg->dedup_cache_changed = TRUE;
3989 // owns name
3990 g_hash_table_insert (acfg->dedup_cache, name, method);
3991 } else {
3992 // owns name
3993 g_free (name);
3996 guint count = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->dedup_stats, stats_name));
3997 count++;
3998 g_hash_table_insert (acfg->dedup_stats, stats_name, GUINT_TO_POINTER (count));
4001 static void
4002 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
4004 ERROR_DECL (error);
4005 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE)) {
4006 method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
4007 mono_error_assert_ok (error);
4009 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE)) {
4010 /* Use the gsharedvt version */
4011 method = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
4012 mono_error_assert_ok (error);
4015 if ((acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (method)) {
4016 mono_dedup_cache_method (acfg, method);
4018 if (!acfg->dedup_emit_mode)
4019 return;
4022 if (acfg->aot_opts.log_generics)
4023 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4025 add_method_full (acfg, method, TRUE, depth);
4028 static void
4029 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
4031 add_extra_method_with_depth (acfg, method, 0);
4034 static void
4035 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
4037 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
4038 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
4039 MonoMethod *wrapper;
4040 char *name;
4042 if (!callinfo->sig)
4043 return;
4045 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
4046 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
4047 g_free (name);
4049 add_method (acfg, wrapper);
4052 static MonoMethod*
4053 get_runtime_invoke_sig (MonoMethodSignature *sig)
4055 MonoMethodBuilder *mb;
4056 MonoMethod *m;
4058 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
4059 m = mono_mb_create_method (mb, sig, 16);
4060 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
4061 mono_mb_free (mb);
4062 return invoke;
4065 static MonoMethod*
4066 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
4068 return mono_marshal_get_runtime_invoke (method, virtual_);
4071 static gboolean
4072 can_marshal_struct (MonoClass *klass)
4074 MonoClassField *field;
4075 gboolean can_marshal = TRUE;
4076 gpointer iter = NULL;
4077 MonoMarshalType *info;
4078 int i;
4080 if (mono_class_is_auto_layout (klass))
4081 return FALSE;
4083 info = mono_marshal_load_type_info (klass);
4085 /* Only allow a few field types to avoid asserts in the marshalling code */
4086 while ((field = mono_class_get_fields_internal (klass, &iter))) {
4087 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
4088 continue;
4090 switch (field->type->type) {
4091 case MONO_TYPE_I4:
4092 case MONO_TYPE_U4:
4093 case MONO_TYPE_I1:
4094 case MONO_TYPE_U1:
4095 case MONO_TYPE_BOOLEAN:
4096 case MONO_TYPE_I2:
4097 case MONO_TYPE_U2:
4098 case MONO_TYPE_CHAR:
4099 case MONO_TYPE_I8:
4100 case MONO_TYPE_U8:
4101 case MONO_TYPE_I:
4102 case MONO_TYPE_U:
4103 case MONO_TYPE_PTR:
4104 case MONO_TYPE_R4:
4105 case MONO_TYPE_R8:
4106 case MONO_TYPE_STRING:
4107 break;
4108 case MONO_TYPE_VALUETYPE:
4109 if (!m_class_is_enumtype (mono_class_from_mono_type_internal (field->type)) && !can_marshal_struct (mono_class_from_mono_type_internal (field->type)))
4110 can_marshal = FALSE;
4111 break;
4112 case MONO_TYPE_SZARRAY: {
4113 gboolean has_mspec = FALSE;
4115 if (info) {
4116 for (i = 0; i < info->num_fields; ++i) {
4117 if (info->fields [i].field == field && info->fields [i].mspec)
4118 has_mspec = TRUE;
4121 if (!has_mspec)
4122 can_marshal = FALSE;
4123 break;
4125 default:
4126 can_marshal = FALSE;
4127 break;
4131 /* Special cases */
4132 /* Its hard to compute whenever these can be marshalled or not */
4133 if (!strcmp (m_class_get_name_space (klass), "System.Net.NetworkInformation.MacOsStructs") && strcmp (m_class_get_name (klass), "sockaddr_dl"))
4134 return TRUE;
4136 return can_marshal;
4139 static void
4140 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
4142 /* Create a vtype instantiation */
4143 MonoGenericContext shared_context;
4144 MonoType **args;
4145 MonoGenericInst *inst;
4146 MonoGenericContainer *container;
4147 MonoClass **constraints;
4148 int i;
4150 memset (ctx, 0, sizeof (MonoGenericContext));
4152 if (mono_class_is_gtd (method->klass)) {
4153 shared_context = mono_class_get_generic_container (method->klass)->context;
4154 inst = shared_context.class_inst;
4156 args = g_new0 (MonoType*, inst->type_argc);
4157 for (i = 0; i < inst->type_argc; ++i) {
4158 args [i] = mono_get_int_type ();
4160 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4162 if (method->is_generic) {
4163 container = mono_method_get_generic_container (method);
4164 g_assert (!container->is_anonymous && container->is_method);
4165 shared_context = container->context;
4166 inst = shared_context.method_inst;
4168 args = g_new0 (MonoType*, inst->type_argc);
4169 for (i = 0; i < container->type_argc; ++i) {
4170 MonoGenericParamInfo *info = mono_generic_param_info (&container->type_params [i]);
4171 gboolean ref_only = FALSE;
4173 if (info && info->constraints) {
4174 constraints = info->constraints;
4176 while (*constraints) {
4177 MonoClass *cklass = *constraints;
4178 if (!(cklass == mono_defaults.object_class || (m_class_get_image (cklass) == mono_defaults.corlib && !strcmp (m_class_get_name (cklass), "ValueType"))))
4179 /* Inflaring the method with our vtype would not be valid */
4180 ref_only = TRUE;
4181 constraints ++;
4185 if (ref_only)
4186 args [i] = mono_get_object_type ();
4187 else
4188 args [i] = mono_get_int_type ();
4190 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
4194 static void
4195 add_wrappers (MonoAotCompile *acfg)
4197 MonoMethod *method, *m;
4198 int i, j;
4199 MonoMethodSignature *sig, *csig;
4200 guint32 token;
4203 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
4204 * so there is only one wrapper of a given type, or inlining their contents into their
4205 * callers.
4207 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4208 ERROR_DECL (error);
4209 MonoMethod *method;
4210 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4211 gboolean skip = FALSE;
4213 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4214 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4216 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4217 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4218 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
4219 skip = TRUE;
4221 /* Skip methods which can not be handled by get_runtime_invoke () */
4222 sig = mono_method_signature_internal (method);
4223 if (!sig)
4224 continue;
4225 if ((sig->ret->type == MONO_TYPE_PTR) ||
4226 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
4227 skip = TRUE;
4228 if (mono_class_is_open_constructed_type (sig->ret))
4229 skip = TRUE;
4231 for (j = 0; j < sig->param_count; j++) {
4232 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
4233 skip = TRUE;
4234 if (mono_class_is_open_constructed_type (sig->params [j]))
4235 skip = TRUE;
4238 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4239 if (!mono_class_is_contextbound (method->klass)) {
4240 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
4241 gboolean has_nullable = FALSE;
4243 for (j = 0; j < sig->param_count; j++) {
4244 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (sig->params [j])))
4245 has_nullable = TRUE;
4248 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
4249 /* Supported by the dynamic runtime-invoke wrapper */
4250 skip = TRUE;
4252 if (info)
4253 mono_arch_dyn_call_free (info);
4255 #endif
4257 if (acfg->aot_opts.llvm_only)
4258 /* Supported by the gsharedvt based runtime-invoke wrapper */
4259 skip = TRUE;
4261 if (!skip) {
4262 //printf ("%s\n", mono_method_full_name (method, TRUE));
4263 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4267 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4268 int nallocators;
4270 /* Runtime invoke wrappers */
4272 MonoType *void_type = mono_get_void_type ();
4273 MonoType *string_type = m_class_get_byval_arg (mono_defaults.string_class);
4275 /* void runtime-invoke () [.cctor] */
4276 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4277 csig->ret = void_type;
4278 add_method (acfg, get_runtime_invoke_sig (csig));
4280 /* void runtime-invoke () [Finalize] */
4281 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4282 csig->hasthis = 1;
4283 csig->ret = void_type;
4284 add_method (acfg, get_runtime_invoke_sig (csig));
4286 /* void runtime-invoke (string) [exception ctor] */
4287 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4288 csig->hasthis = 1;
4289 csig->ret = void_type;
4290 csig->params [0] = string_type;
4291 add_method (acfg, get_runtime_invoke_sig (csig));
4293 /* void runtime-invoke (string, string) [exception ctor] */
4294 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4295 csig->hasthis = 1;
4296 csig->ret = void_type;
4297 csig->params [0] = string_type;
4298 csig->params [1] = string_type;
4299 add_method (acfg, get_runtime_invoke_sig (csig));
4301 /* string runtime-invoke () [Exception.ToString ()] */
4302 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4303 csig->hasthis = 1;
4304 csig->ret = string_type;
4305 add_method (acfg, get_runtime_invoke_sig (csig));
4307 /* void runtime-invoke (string, Exception) [exception ctor] */
4308 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4309 csig->hasthis = 1;
4310 csig->ret = void_type;
4311 csig->params [0] = string_type;
4312 csig->params [1] = m_class_get_byval_arg (mono_defaults.exception_class);
4313 add_method (acfg, get_runtime_invoke_sig (csig));
4315 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
4316 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4317 csig->hasthis = 1;
4318 csig->ret = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4319 csig->params [0] = string_type;
4320 csig->params [1] = m_class_get_byval_arg (mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"));
4321 csig->params [2] = m_class_get_byval_arg (mono_defaults.boolean_class);
4322 add_method (acfg, get_runtime_invoke_sig (csig));
4324 /* runtime-invoke used by finalizers */
4325 add_method (acfg, get_runtime_invoke (acfg, get_method_nofail (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
4327 /* This is used by mono_runtime_capture_context () */
4328 method = mono_get_context_capture_method ();
4329 if (method)
4330 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
4332 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
4333 if (!acfg->aot_opts.llvm_only)
4334 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
4335 #endif
4337 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
4338 if (acfg->aot_opts.llvm_only) {
4339 int variants;
4341 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
4342 for (variants = 0; variants < 4; ++variants) {
4343 for (i = 0; i < 40; ++i) {
4344 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
4345 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
4347 g_free (sig);
4352 /* stelemref */
4353 add_method (acfg, mono_marshal_get_stelemref ());
4355 /* Managed Allocators */
4356 nallocators = mono_gc_get_managed_allocator_types ();
4357 for (i = 0; i < nallocators; ++i) {
4358 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
4359 add_method (acfg, m);
4360 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
4361 add_method (acfg, m);
4362 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_PROFILER)))
4363 add_method (acfg, m);
4366 /* write barriers */
4367 if (mono_gc_is_moving ()) {
4368 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
4369 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
4372 /* Stelemref wrappers */
4374 MonoMethod **wrappers;
4375 int nwrappers;
4377 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
4378 for (i = 0; i < nwrappers; ++i)
4379 add_method (acfg, wrappers [i]);
4380 g_free (wrappers);
4383 /* castclass_with_check wrapper */
4384 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4385 /* isinst_with_check wrapper */
4386 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4388 /* JIT icall wrappers */
4389 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4390 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4394 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4395 * we use the original method instead at runtime.
4396 * Since full-aot doesn't support remoting, this is not a problem.
4398 #if 0
4399 /* remoting-invoke wrappers */
4400 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4401 ERROR_DECL (error);
4402 MonoMethodSignature *sig;
4404 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4405 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4406 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4408 sig = mono_method_signature_internal (method);
4410 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4411 m = mono_marshal_get_remoting_invoke_with_check (method);
4413 add_method (acfg, m);
4416 #endif
4418 /* delegate-invoke wrappers */
4419 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4420 ERROR_DECL (error);
4421 MonoClass *klass;
4422 MonoCustomAttrInfo *cattr;
4424 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4425 klass = mono_class_get_checked (acfg->image, token, error);
4427 if (!klass) {
4428 mono_error_cleanup (error);
4429 continue;
4432 if (!m_class_is_delegate (klass) || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4433 continue;
4435 if (!mono_class_is_gtd (klass)) {
4436 method = mono_get_delegate_invoke_internal (klass);
4438 m = mono_marshal_get_delegate_invoke (method, NULL);
4440 add_method (acfg, m);
4442 method = try_get_method_nofail (klass, "BeginInvoke", -1, 0);
4443 if (method)
4444 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4446 method = try_get_method_nofail (klass, "EndInvoke", -1, 0);
4447 if (method)
4448 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4450 cattr = mono_custom_attrs_from_class_checked (klass, error);
4451 if (!is_ok (error)) {
4452 mono_error_cleanup (error);
4453 continue;
4456 if (cattr) {
4457 int j;
4459 for (j = 0; j < cattr->num_attrs; ++j)
4460 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")))
4461 break;
4462 if (j < cattr->num_attrs) {
4463 MonoMethod *invoke;
4464 MonoMethod *wrapper;
4465 MonoMethod *del_invoke;
4467 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4468 invoke = mono_get_delegate_invoke_internal (klass);
4469 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4470 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4471 add_method (acfg, wrapper);
4472 add_method (acfg, del_invoke);
4475 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4476 ERROR_DECL (error);
4477 MonoGenericContext ctx;
4478 MonoMethod *inst, *gshared;
4481 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4483 /* Invoke */
4484 method = mono_get_delegate_invoke_internal (klass);
4485 create_gsharedvt_inst (acfg, method, &ctx);
4487 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4488 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4490 m = mono_marshal_get_delegate_invoke (inst, NULL);
4491 g_assert (m->is_inflated);
4493 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4494 mono_error_assert_ok (error);
4496 add_extra_method (acfg, gshared);
4498 /* begin-invoke */
4499 method = mono_get_delegate_begin_invoke_internal (klass);
4500 if (method) {
4501 create_gsharedvt_inst (acfg, method, &ctx);
4503 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4504 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4506 m = mono_marshal_get_delegate_begin_invoke (inst);
4507 g_assert (m->is_inflated);
4509 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4510 mono_error_assert_ok (error);
4512 add_extra_method (acfg, gshared);
4515 /* end-invoke */
4516 method = mono_get_delegate_end_invoke_internal (klass);
4517 if (method) {
4518 create_gsharedvt_inst (acfg, method, &ctx);
4520 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4521 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4523 m = mono_marshal_get_delegate_end_invoke (inst);
4524 g_assert (m->is_inflated);
4526 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4527 mono_error_assert_ok (error);
4529 add_extra_method (acfg, gshared);
4534 /* array access wrappers */
4535 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4536 ERROR_DECL (error);
4537 MonoClass *klass;
4539 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4540 klass = mono_class_get_checked (acfg->image, token, error);
4542 if (!klass) {
4543 mono_error_cleanup (error);
4544 continue;
4547 if (m_class_get_rank (klass) && MONO_TYPE_IS_PRIMITIVE (m_class_get_byval_arg (m_class_get_element_class (klass)))) {
4548 MonoMethod *m, *wrapper;
4550 /* Add runtime-invoke wrappers too */
4552 m = get_method_nofail (klass, "Get", -1, 0);
4553 g_assert (m);
4554 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4555 add_extra_method (acfg, wrapper);
4556 if (!acfg->aot_opts.llvm_only)
4557 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4559 m = get_method_nofail (klass, "Set", -1, 0);
4560 g_assert (m);
4561 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4562 add_extra_method (acfg, wrapper);
4563 if (!acfg->aot_opts.llvm_only)
4564 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4568 /* Synchronized wrappers */
4569 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4570 ERROR_DECL (error);
4571 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4572 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4573 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4575 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4576 if (method->is_generic) {
4577 // FIXME:
4578 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4579 ERROR_DECL (error);
4580 MonoGenericContext ctx;
4581 MonoMethod *inst, *gshared, *m;
4584 * Create a generic wrapper for a generic instance, and AOT that.
4586 create_gsharedvt_inst (acfg, method, &ctx);
4587 inst = mono_class_inflate_generic_method_checked (method, &ctx, error);
4588 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
4589 m = mono_marshal_get_synchronized_wrapper (inst);
4590 g_assert (m->is_inflated);
4591 gshared = mini_get_shared_method_full (m, SHARE_MODE_GSHAREDVT, error);
4592 mono_error_assert_ok (error);
4594 add_method (acfg, gshared);
4595 } else {
4596 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4601 /* pinvoke wrappers */
4602 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4603 ERROR_DECL (error);
4604 MonoMethod *method;
4605 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4607 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4608 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4610 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4611 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4612 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4615 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4616 if (acfg->aot_opts.llvm_only) {
4617 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4618 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (method), FALSE, TRUE, FALSE);
4623 /* native-to-managed wrappers */
4624 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4625 ERROR_DECL (error);
4626 MonoMethod *method;
4627 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4628 MonoCustomAttrInfo *cattr;
4629 int j;
4631 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
4632 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
4635 * Only generate native-to-managed wrappers for methods which have an
4636 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4637 * name to avoid defining a new assembly to contain it.
4639 cattr = mono_custom_attrs_from_method_checked (method, error);
4640 if (!is_ok (error)) {
4641 char *name = mono_method_get_full_name (method);
4642 report_loader_error (acfg, error, TRUE, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (error));
4643 g_free (name);
4646 if (cattr) {
4647 for (j = 0; j < cattr->num_attrs; ++j)
4648 if (cattr->attrs [j].ctor && !strcmp (m_class_get_name (cattr->attrs [j].ctor->klass), "MonoPInvokeCallbackAttribute"))
4649 break;
4650 if (j < cattr->num_attrs) {
4651 MonoCustomAttrEntry *e = &cattr->attrs [j];
4652 MonoMethodSignature *sig = mono_method_signature_internal (e->ctor);
4653 const char *p = (const char*)e->data;
4654 const char *named;
4655 int slen, num_named, named_type;
4656 char *n;
4657 MonoType *t;
4658 MonoClass *klass;
4659 char *export_name = NULL;
4660 MonoMethod *wrapper;
4662 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4663 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4664 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",
4665 mono_method_full_name (method, TRUE));
4666 exit (1);
4669 g_assert (sig->param_count == 1);
4670 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (m_class_get_name (mono_class_from_mono_type_internal (sig->params [0])), "Type"));
4673 * Decode the cattr manually since we can't create objects
4674 * during aot compilation.
4677 /* Skip prolog */
4678 p += 2;
4680 /* From load_cattr_value () in reflection.c */
4681 slen = mono_metadata_decode_value (p, &p);
4682 n = (char *)g_memdup (p, slen + 1);
4683 n [slen] = 0;
4684 t = mono_reflection_type_from_name_checked (n, acfg->image, error);
4685 g_assert (t);
4686 mono_error_assert_ok (error);
4687 g_free (n);
4689 klass = mono_class_from_mono_type_internal (t);
4690 g_assert (m_class_get_parent (klass) == mono_defaults.multicastdelegate_class);
4692 p += slen;
4694 num_named = read16 (p);
4695 p += 2;
4697 g_assert (num_named < 2);
4698 if (num_named == 1) {
4699 int name_len;
4700 char *name;
4702 /* parse ExportSymbol attribute */
4703 named = p;
4704 named_type = *named;
4705 named += 1;
4706 /* data_type = *named; */
4707 named += 1;
4709 name_len = mono_metadata_decode_blob_size (named, &named);
4710 name = (char *)g_malloc (name_len + 1);
4711 memcpy (name, named, name_len);
4712 name [name_len] = 0;
4713 named += name_len;
4715 g_assert (named_type == 0x54);
4716 g_assert (!strcmp (name, "ExportSymbol"));
4718 /* load_cattr_value (), string case */
4719 g_assert (*named != (char)0xff);
4720 slen = mono_metadata_decode_value (named, &named);
4721 export_name = (char *)g_malloc (slen + 1);
4722 memcpy (export_name, named, slen);
4723 export_name [slen] = 0;
4724 named += slen;
4727 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, error);
4728 mono_error_assert_ok (error);
4730 add_method (acfg, wrapper);
4731 if (export_name)
4732 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4734 g_free (cattr);
4737 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4738 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4739 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4743 /* StructureToPtr/PtrToStructure wrappers */
4744 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4745 ERROR_DECL (error);
4746 MonoClass *klass;
4748 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4749 klass = mono_class_get_checked (acfg->image, token, error);
4751 if (!klass) {
4752 mono_error_cleanup (error);
4753 continue;
4756 if (m_class_is_valuetype (klass) && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4757 !(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)))) {
4758 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4759 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4764 static gboolean
4765 has_type_vars (MonoClass *klass)
4767 if ((m_class_get_byval_arg (klass)->type == MONO_TYPE_VAR) || (m_class_get_byval_arg (klass)->type == MONO_TYPE_MVAR))
4768 return TRUE;
4769 if (m_class_get_rank (klass))
4770 return has_type_vars (m_class_get_element_class (klass));
4771 if (mono_class_is_ginst (klass)) {
4772 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4773 if (context->class_inst) {
4774 int i;
4776 for (i = 0; i < context->class_inst->type_argc; ++i)
4777 if (has_type_vars (mono_class_from_mono_type_internal (context->class_inst->type_argv [i])))
4778 return TRUE;
4781 if (mono_class_is_gtd (klass))
4782 return TRUE;
4783 return FALSE;
4786 static gboolean
4787 is_vt_inst (MonoGenericInst *inst)
4789 int i;
4791 for (i = 0; i < inst->type_argc; ++i) {
4792 MonoType *t = inst->type_argv [i];
4793 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4794 return TRUE;
4796 return FALSE;
4799 static gboolean
4800 method_has_type_vars (MonoMethod *method)
4802 if (has_type_vars (method->klass))
4803 return TRUE;
4805 if (method->is_inflated) {
4806 MonoGenericContext *context = mono_method_get_context (method);
4807 if (context->method_inst) {
4808 int i;
4810 for (i = 0; i < context->method_inst->type_argc; ++i)
4811 if (has_type_vars (mono_class_from_mono_type_internal (context->method_inst->type_argv [i])))
4812 return TRUE;
4815 return FALSE;
4818 static
4819 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4821 return opts->mode == MONO_AOT_MODE_FULL;
4824 static
4825 gboolean mono_aot_mode_is_interp (MonoAotOptions *opts)
4827 return opts->interp;
4830 static
4831 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4833 return opts->mode == MONO_AOT_MODE_HYBRID;
4836 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4838 static void
4839 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4841 /* This might lead to a huge code blowup so only do it if neccesary */
4842 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4843 return;
4845 add_generic_class_with_depth (acfg, klass, 0, ref);
4848 static gboolean
4849 check_type_depth (MonoType *t, int depth)
4851 int i;
4853 if (depth > 8)
4854 return TRUE;
4856 switch (t->type) {
4857 case MONO_TYPE_GENERICINST: {
4858 MonoGenericClass *gklass = t->data.generic_class;
4859 MonoGenericInst *ginst = gklass->context.class_inst;
4861 if (ginst) {
4862 for (i = 0; i < ginst->type_argc; ++i) {
4863 if (check_type_depth (ginst->type_argv [i], depth + 1))
4864 return TRUE;
4867 break;
4869 default:
4870 break;
4873 return FALSE;
4876 static void
4877 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4880 * add_generic_class:
4882 * Add all methods of a generic class.
4884 static void
4885 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4887 MonoMethod *method;
4888 MonoClassField *field;
4889 gpointer iter;
4890 gboolean use_gsharedvt = FALSE;
4892 if (!acfg->ginst_hash)
4893 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4895 mono_class_init (klass);
4897 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4898 return;
4900 if (has_type_vars (klass))
4901 return;
4903 if (!mono_class_is_ginst (klass) && !m_class_get_rank (klass))
4904 return;
4906 if (mono_class_has_failure (klass))
4907 return;
4909 if (!acfg->ginst_hash)
4910 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4912 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4913 return;
4915 if (check_type_depth (m_class_get_byval_arg (klass), 0))
4916 return;
4918 if (acfg->aot_opts.log_generics) {
4919 char *s = mono_type_full_name (m_class_get_byval_arg (klass));
4920 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", s, ref);
4921 g_free (s);
4924 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4927 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4928 * Enable this only for some classes since gsharedvt might not support all methods.
4930 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) &&
4931 (!strcmp (m_class_get_name (klass), "Dictionary`2") || !strcmp (m_class_get_name (klass), "List`1") || !strcmp (m_class_get_name (klass), "ReadOnlyCollection`1")))
4932 use_gsharedvt = TRUE;
4934 iter = NULL;
4935 while ((method = mono_class_get_methods (klass, &iter))) {
4936 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4938 * This is partial sharing, and we can't handle it yet
4940 continue;
4943 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4944 /* Already added */
4945 add_types_from_method_header (acfg, method);
4946 continue;
4949 if (method->is_generic)
4950 /* FIXME: */
4951 continue;
4954 * FIXME: Instances which are referenced by these methods are not added,
4955 * for example Array.Resize<int> for List<int>.Add ().
4957 add_extra_method_with_depth (acfg, method, depth + 1);
4960 iter = NULL;
4961 while ((field = mono_class_get_fields_internal (klass, &iter))) {
4962 if (field->type->type == MONO_TYPE_GENERICINST)
4963 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (field->type), depth + 1, "field");
4966 if (m_class_is_delegate (klass)) {
4967 method = mono_get_delegate_invoke_internal (klass);
4969 method = mono_marshal_get_delegate_invoke (method, NULL);
4971 if (acfg->aot_opts.log_generics)
4972 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4974 add_method (acfg, method);
4977 /* Add superclasses */
4978 if (m_class_get_parent (klass))
4979 add_generic_class_with_depth (acfg, m_class_get_parent (klass), depth, "parent");
4981 const char *klass_name = m_class_get_name (klass);
4982 const char *klass_name_space = m_class_get_name_space (klass);
4983 const gboolean in_corlib = m_class_get_image (klass) == mono_defaults.corlib;
4985 * For ICollection<T>, add instances of the helper methods
4986 * in Array, since a T[] could be cast to ICollection<T>.
4988 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") &&
4989 (!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"))) {
4990 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4991 MonoClass *array_class = mono_class_create_bounded_array (tclass, 1, FALSE);
4992 gpointer iter;
4993 char *name_prefix;
4995 if (!strcmp (klass_name, "IEnumerator`1"))
4996 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, "IEnumerable`1");
4997 else
4998 name_prefix = g_strdup_printf ("%s.%s", klass_name_space, klass_name);
5000 /* Add the T[]/InternalEnumerator class */
5001 if (!strcmp (klass_name, "IEnumerable`1") || !strcmp (klass_name, "IEnumerator`1")) {
5002 ERROR_DECL (error);
5003 MonoClass *nclass;
5005 iter = NULL;
5006 while ((nclass = mono_class_get_nested_types (m_class_get_parent (array_class), &iter))) {
5007 if (!strcmp (m_class_get_name (nclass), "InternalEnumerator`1"))
5008 break;
5010 g_assert (nclass);
5011 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), error);
5012 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5013 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
5016 iter = NULL;
5017 while ((method = mono_class_get_methods (array_class, &iter))) {
5018 if (!strncmp (method->name, name_prefix, strlen (name_prefix))) {
5019 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
5021 if (m->is_inflated && !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE))
5022 add_extra_method_with_depth (acfg, m, depth);
5026 g_free (name_prefix);
5029 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
5030 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5031 ERROR_DECL (error);
5032 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5033 MonoClass *icomparable, *gcomparer, *icomparable_inst;
5034 MonoGenericContext ctx;
5035 MonoType *args [16];
5037 memset (&ctx, 0, sizeof (ctx));
5039 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
5041 args [0] = m_class_get_byval_arg (tclass);
5042 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5044 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, error);
5045 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5047 if (mono_class_is_assignable_from_internal (icomparable_inst, tclass)) {
5048 MonoClass *gcomparer_inst;
5049 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
5050 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5051 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5053 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
5057 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
5058 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5059 ERROR_DECL (error);
5060 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5061 MonoClass *iface, *gcomparer, *iface_inst;
5062 MonoGenericContext ctx;
5063 MonoType *args [16];
5065 memset (&ctx, 0, sizeof (ctx));
5067 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
5068 g_assert (iface);
5069 args [0] = m_class_get_byval_arg (tclass);
5070 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5072 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, error);
5073 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5075 if (mono_class_is_assignable_from_internal (iface_inst, tclass)) {
5076 MonoClass *gcomparer_inst;
5077 ERROR_DECL (error);
5079 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
5080 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, error);
5081 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5082 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
5086 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
5087 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "EqualityComparer`1")) {
5088 MonoClass *enum_comparer;
5089 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5090 MonoGenericContext ctx;
5091 MonoType *args [16];
5093 if (m_class_is_enumtype (tclass)) {
5094 MonoClass *enum_comparer_inst;
5095 ERROR_DECL (error);
5097 memset (&ctx, 0, sizeof (ctx));
5098 args [0] = m_class_get_byval_arg (tclass);
5099 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5101 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5102 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, error);
5103 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5104 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
5108 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
5109 if (in_corlib && !strcmp (klass_name_space, "System.Collections.Generic") && !strcmp (klass_name, "Comparer`1")) {
5110 MonoClass *comparer;
5111 MonoClass *tclass = mono_class_from_mono_type_internal (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
5112 MonoGenericContext ctx;
5113 MonoType *args [16];
5115 if (m_class_is_enumtype (tclass)) {
5116 MonoClass *comparer_inst;
5117 ERROR_DECL (error);
5119 memset (&ctx, 0, sizeof (ctx));
5120 args [0] = m_class_get_byval_arg (tclass);
5121 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5123 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
5124 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, error);
5125 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5126 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
5131 static void
5132 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
5134 int i;
5135 MonoGenericContext ctx;
5136 MonoType *args [16];
5138 if (acfg->aot_opts.no_instances)
5139 return;
5141 memset (&ctx, 0, sizeof (ctx));
5143 for (i = 0; i < ninsts; ++i) {
5144 ERROR_DECL (error);
5145 MonoClass *generic_inst;
5146 args [0] = insts [i];
5147 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
5148 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, error);
5149 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5150 add_generic_class (acfg, generic_inst, force, "");
5154 static void
5155 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
5157 ERROR_DECL (error);
5158 MonoMethodHeader *header;
5159 MonoMethodSignature *sig;
5160 int j, depth;
5162 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5164 sig = mono_method_signature_checked (method, error);
5165 if (sig) {
5166 for (j = 0; j < sig->param_count; ++j)
5167 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
5168 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (sig->params [j]), depth + 1, "arg");
5169 } else {
5170 mono_error_cleanup (error);
5173 header = mono_method_get_header_checked (method, error);
5175 if (header) {
5176 for (j = 0; j < header->num_locals; ++j)
5177 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
5178 add_generic_class_with_depth (acfg, mono_class_from_mono_type_internal (header->locals [j]), depth + 1, "local");
5179 mono_metadata_free_mh (header);
5180 } else {
5181 mono_error_cleanup (error); /* FIXME report the error */
5187 * add_generic_instances:
5189 * Add instances referenced by the METHODSPEC/TYPESPEC table.
5191 static void
5192 add_generic_instances (MonoAotCompile *acfg)
5194 int i;
5195 guint32 token;
5196 MonoMethod *method;
5197 MonoGenericContext *context;
5199 if (acfg->aot_opts.no_instances)
5200 return;
5202 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
5203 ERROR_DECL (error);
5204 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
5205 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
5207 if (!method) {
5208 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (error));
5209 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
5210 mono_error_cleanup (error);
5211 continue;
5214 if (m_class_get_image (method->klass) != acfg->image)
5215 continue;
5217 context = mono_method_get_context (method);
5219 if (context && ((context->class_inst && context->class_inst->is_open)))
5220 continue;
5223 * For open methods, create an instantiation which can be passed to the JIT.
5224 * FIXME: Handle class_inst as well.
5226 if (context && context->method_inst && context->method_inst->is_open) {
5227 ERROR_DECL (error);
5228 MonoGenericContext shared_context;
5229 MonoGenericInst *inst;
5230 MonoType **type_argv;
5231 int i;
5232 MonoMethod *declaring_method;
5233 gboolean supported = TRUE;
5235 /* Check that the context doesn't contain open constructed types */
5236 if (context->class_inst) {
5237 inst = context->class_inst;
5238 for (i = 0; i < inst->type_argc; ++i) {
5239 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)
5240 continue;
5241 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5242 supported = FALSE;
5245 if (context->method_inst) {
5246 inst = context->method_inst;
5247 for (i = 0; i < inst->type_argc; ++i) {
5248 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)
5249 continue;
5250 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
5251 supported = FALSE;
5255 if (!supported)
5256 continue;
5258 memset (&shared_context, 0, sizeof (MonoGenericContext));
5260 inst = context->class_inst;
5261 if (inst) {
5262 type_argv = g_new0 (MonoType*, inst->type_argc);
5263 for (i = 0; i < inst->type_argc; ++i) {
5264 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)
5265 type_argv [i] = mono_get_object_type ();
5266 else
5267 type_argv [i] = inst->type_argv [i];
5270 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5271 g_free (type_argv);
5274 inst = context->method_inst;
5275 if (inst) {
5276 type_argv = g_new0 (MonoType*, inst->type_argc);
5277 for (i = 0; i < inst->type_argc; ++i) {
5278 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)
5279 type_argv [i] = mono_get_object_type ();
5280 else
5281 type_argv [i] = inst->type_argv [i];
5284 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
5285 g_free (type_argv);
5288 if (method->is_generic || mono_class_is_gtd (method->klass))
5289 declaring_method = method;
5290 else
5291 declaring_method = mono_method_get_declaring_generic_method (method);
5293 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, error);
5294 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5298 * If the method is fully sharable, it was already added in place of its
5299 * generic definition.
5301 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
5302 continue;
5305 * FIXME: Partially shared methods are not shared here, so we end up with
5306 * many identical methods.
5308 add_extra_method (acfg, method);
5311 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
5312 ERROR_DECL (error);
5313 MonoClass *klass;
5315 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
5317 klass = mono_class_get_checked (acfg->image, token, error);
5318 if (!klass || m_class_get_rank (klass)) {
5319 mono_error_cleanup (error);
5320 continue;
5323 add_generic_class (acfg, klass, FALSE, "typespec");
5326 /* Add types of args/locals */
5327 for (i = 0; i < acfg->methods->len; ++i) {
5328 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
5329 add_types_from_method_header (acfg, method);
5332 if (acfg->image == mono_defaults.corlib) {
5333 MonoClass *klass;
5334 MonoType *insts [256];
5335 int ninsts = 0;
5337 MonoType *byte_type = m_class_get_byval_arg (mono_defaults.byte_class);
5338 MonoType *sbyte_type = m_class_get_byval_arg (mono_defaults.sbyte_class);
5339 MonoType *int16_type = m_class_get_byval_arg (mono_defaults.int16_class);
5340 MonoType *uint16_type = m_class_get_byval_arg (mono_defaults.uint16_class);
5341 MonoType *int32_type = mono_get_int32_type ();
5342 MonoType *uint32_type = m_class_get_byval_arg (mono_defaults.uint32_class);
5343 MonoType *int64_type = m_class_get_byval_arg (mono_defaults.int64_class);
5344 MonoType *uint64_type = m_class_get_byval_arg (mono_defaults.uint64_class);
5345 MonoType *object_type = mono_get_object_type ();
5347 insts [ninsts ++] = byte_type;
5348 insts [ninsts ++] = sbyte_type;
5349 insts [ninsts ++] = int16_type;
5350 insts [ninsts ++] = uint16_type;
5351 insts [ninsts ++] = int32_type;
5352 insts [ninsts ++] = uint32_type;
5353 insts [ninsts ++] = int64_type;
5354 insts [ninsts ++] = uint64_type;
5355 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.single_class);
5356 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.double_class);
5357 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.char_class);
5358 insts [ninsts ++] = m_class_get_byval_arg (mono_defaults.boolean_class);
5360 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
5361 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
5362 if (klass)
5363 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5364 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
5365 if (klass)
5366 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5368 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
5370 MonoClass *enum_comparer;
5371 MonoType *insts [16];
5372 int ninsts;
5374 ninsts = 0;
5375 insts [ninsts ++] = int32_type;
5376 insts [ninsts ++] = uint32_type;
5377 insts [ninsts ++] = uint16_type;
5378 insts [ninsts ++] = byte_type;
5379 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
5380 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5382 ninsts = 0;
5383 insts [ninsts ++] = int16_type;
5384 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
5385 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5387 ninsts = 0;
5388 insts [ninsts ++] = sbyte_type;
5389 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
5390 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5392 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
5393 ninsts = 0;
5394 insts [ninsts ++] = int64_type;
5395 insts [ninsts ++] = uint64_type;
5396 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
5399 /* Add instances of the array generic interfaces for primitive types */
5400 /* This will add instances of the InternalArray_ helper methods in Array too */
5401 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
5402 if (klass)
5403 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5405 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
5406 if (klass)
5407 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5409 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
5410 if (klass)
5411 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5414 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5415 * used for all instances of GetGenericValueImpl by the AOT runtime.
5418 ERROR_DECL (error);
5419 MonoGenericContext ctx;
5420 MonoType *args [16];
5421 MonoMethod *get_method;
5422 MonoClass *array_klass = m_class_get_parent (mono_class_create_array (mono_defaults.object_class, 1));
5424 get_method = mono_class_get_method_from_name_checked (array_klass, "GetGenericValueImpl", 2, 0, error);
5425 mono_error_assert_ok (error);
5427 if (get_method) {
5428 memset (&ctx, 0, sizeof (ctx));
5429 args [0] = object_type;
5430 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5431 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, error), TRUE, TRUE));
5432 mono_error_assert_ok (error); /* FIXME don't swallow the error */
5436 /* Same for CompareExchange<T>/Exchange<T> */
5438 MonoGenericContext ctx;
5439 MonoType *args [16];
5440 MonoMethod *m;
5441 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5442 gpointer iter = NULL;
5444 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5445 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5446 ERROR_DECL (error);
5447 memset (&ctx, 0, sizeof (ctx));
5448 args [0] = object_type;
5449 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5450 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5451 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5456 /* Same for Volatile.Read/Write<T> */
5458 MonoGenericContext ctx;
5459 MonoType *args [16];
5460 MonoMethod *m;
5461 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5462 gpointer iter = NULL;
5464 if (volatile_klass) {
5465 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5466 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5467 ERROR_DECL (error);
5468 memset (&ctx, 0, sizeof (ctx));
5469 args [0] = object_type;
5470 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5471 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, error), TRUE, TRUE));
5472 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
5478 /* object[] accessor wrappers. */
5479 for (i = 1; i < 4; ++i) {
5480 MonoClass *obj_array_class = mono_class_create_array (mono_defaults.object_class, i);
5481 MonoMethod *m;
5483 m = get_method_nofail (obj_array_class, "Get", i, 0);
5484 g_assert (m);
5486 m = mono_marshal_get_array_accessor_wrapper (m);
5487 add_extra_method (acfg, m);
5489 m = get_method_nofail (obj_array_class, "Address", i, 0);
5490 g_assert (m);
5492 m = mono_marshal_get_array_accessor_wrapper (m);
5493 add_extra_method (acfg, m);
5495 m = get_method_nofail (obj_array_class, "Set", i + 1, 0);
5496 g_assert (m);
5498 m = mono_marshal_get_array_accessor_wrapper (m);
5499 add_extra_method (acfg, m);
5505 * is_direct_callable:
5507 * Return whenever the method identified by JI is directly callable without
5508 * going through the PLT.
5510 static gboolean
5511 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5513 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5514 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5515 if (callee_cfg) {
5516 gboolean direct_callable = TRUE;
5518 if (direct_callable && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include) && mono_aot_can_dedup (patch_info->data.method))
5519 direct_callable = FALSE;
5521 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5522 direct_callable = FALSE;
5523 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5524 // FIXME: Maybe call the wrapper directly ?
5525 direct_callable = FALSE;
5527 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5528 /* Disable this so all calls go through load_method (), see the
5529 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5530 * mono_debugger_agent_init ().
5532 direct_callable = FALSE;
5535 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5536 /* sgen does some initialization when the allocator method is created */
5537 direct_callable = FALSE;
5538 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5539 /* we don't know at compile time whether sgen is concurrent or not */
5540 direct_callable = FALSE;
5542 if (direct_callable)
5543 return TRUE;
5545 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5546 if (acfg->aot_opts.direct_pinvoke)
5547 return TRUE;
5548 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5549 if (acfg->aot_opts.direct_icalls)
5550 return TRUE;
5551 return FALSE;
5554 return FALSE;
5557 #ifdef MONO_ARCH_AOT_SUPPORTED
5558 static const char *
5559 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5561 MonoImage *image = m_class_get_image (method->klass);
5562 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5563 MonoTableInfo *tables = image->tables;
5564 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5565 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5566 guint32 im_cols [MONO_IMPLMAP_SIZE];
5567 char *import;
5569 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5570 if (import != NULL)
5571 return import;
5573 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5574 return NULL;
5576 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5578 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5579 return NULL;
5581 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5583 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5585 return import;
5587 #else
5588 static const char *
5589 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5591 return NULL;
5593 #endif
5595 static gint
5596 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5598 if (a->native_offset == b->native_offset)
5599 return a->il_offset - b->il_offset;
5600 else
5601 return a->native_offset - b->native_offset;
5605 * compute_line_numbers:
5607 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5608 * entry.
5610 static MonoDebugSourceLocation**
5611 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5613 MonoDebugMethodInfo *minfo;
5614 MonoDebugLineNumberEntry *ln_array;
5615 MonoDebugSourceLocation *loc;
5616 int i, prev_line, prev_il_offset;
5617 int *native_to_il_offset = NULL;
5618 MonoDebugSourceLocation **res;
5619 gboolean first;
5621 minfo = mono_debug_lookup_method (method);
5622 if (!minfo)
5623 return NULL;
5624 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5625 if (debug_info->code_size != code_size)
5626 return NULL;
5628 g_assert (code_size);
5630 /* Compute the native->IL offset mapping */
5632 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5633 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5635 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5637 native_to_il_offset = g_new0 (int, code_size + 1);
5639 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5640 int j;
5641 MonoDebugLineNumberEntry *lne = &ln_array [i];
5643 if (i == 0) {
5644 for (j = 0; j < lne->native_offset; ++j)
5645 native_to_il_offset [j] = -1;
5648 if (i < debug_info->num_line_numbers - 1) {
5649 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5651 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5652 native_to_il_offset [j] = lne->il_offset;
5653 } else {
5654 for (j = lne->native_offset; j < code_size; ++j)
5655 native_to_il_offset [j] = lne->il_offset;
5658 g_free (ln_array);
5660 /* Compute the native->line number mapping */
5661 res = g_new0 (MonoDebugSourceLocation*, code_size);
5662 prev_il_offset = -1;
5663 prev_line = -1;
5664 first = TRUE;
5665 for (i = 0; i < code_size; ++i) {
5666 int il_offset = native_to_il_offset [i];
5668 if (il_offset == -1 || il_offset == prev_il_offset)
5669 continue;
5670 prev_il_offset = il_offset;
5671 loc = mono_debug_method_lookup_location (minfo, il_offset);
5672 if (!(loc && loc->source_file))
5673 continue;
5674 if (loc->row == prev_line) {
5675 mono_debug_free_source_location (loc);
5676 continue;
5678 prev_line = loc->row;
5679 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5680 if (first)
5681 /* This will cover the prolog too */
5682 res [0] = loc;
5683 else
5684 res [i] = loc;
5685 first = FALSE;
5687 return res;
5690 static int
5691 get_file_index (MonoAotCompile *acfg, const char *source_file)
5693 int findex;
5695 // FIXME: Free these
5696 if (!acfg->dwarf_ln_filenames)
5697 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5698 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5699 if (!findex) {
5700 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5701 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5702 emit_unset_mode (acfg);
5703 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5705 return findex;
5708 #ifdef TARGET_ARM64
5709 #define INST_LEN 4
5710 #else
5711 #define INST_LEN 1
5712 #endif
5715 * emit_and_reloc_code:
5717 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5718 * is true, calls are made through the GOT too. This is used for emitting trampolines
5719 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5720 * since trampolines are needed to make PTL work.
5722 static void
5723 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5725 int i, pindex, start_index;
5726 GPtrArray *patches;
5727 MonoJumpInfo *patch_info;
5728 MonoDebugSourceLocation **locs = NULL;
5729 gboolean skip, prologue_end = FALSE;
5730 #ifdef MONO_ARCH_AOT_SUPPORTED
5731 gboolean direct_call, external_call;
5732 guint32 got_slot;
5733 const char *direct_call_target = 0;
5734 const char *direct_pinvoke;
5735 #endif
5737 if (acfg->gas_line_numbers && method && debug_info) {
5738 locs = compute_line_numbers (method, code_len, debug_info);
5739 if (!locs) {
5740 int findex = get_file_index (acfg, "<unknown>");
5741 emit_unset_mode (acfg);
5742 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5746 /* Collect and sort relocations */
5747 patches = g_ptr_array_new ();
5748 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5749 g_ptr_array_add (patches, patch_info);
5750 g_ptr_array_sort (patches, compare_patches);
5752 start_index = 0;
5753 for (i = 0; i < code_len; i += INST_LEN) {
5754 patch_info = NULL;
5755 for (pindex = start_index; pindex < patches->len; ++pindex) {
5756 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5757 if (patch_info->ip.i >= i)
5758 break;
5761 if (locs && locs [i]) {
5762 MonoDebugSourceLocation *loc = locs [i];
5763 int findex;
5764 const char *options;
5766 findex = get_file_index (acfg, loc->source_file);
5767 emit_unset_mode (acfg);
5768 if (!prologue_end)
5769 options = " prologue_end";
5770 else
5771 options = "";
5772 prologue_end = TRUE;
5773 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5774 mono_debug_free_source_location (loc);
5777 skip = FALSE;
5778 #ifdef MONO_ARCH_AOT_SUPPORTED
5779 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5780 start_index = pindex;
5782 switch (patch_info->type) {
5783 case MONO_PATCH_INFO_NONE:
5784 break;
5785 case MONO_PATCH_INFO_GOT_OFFSET: {
5786 int code_size;
5788 arch_emit_got_offset (acfg, code + i, &code_size);
5789 i += code_size - INST_LEN;
5790 skip = TRUE;
5791 patch_info->type = MONO_PATCH_INFO_NONE;
5792 break;
5794 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5795 int code_size, index;
5796 char *selector = (char *)patch_info->data.target;
5798 if (!acfg->objc_selector_to_index)
5799 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5800 if (!acfg->objc_selectors)
5801 acfg->objc_selectors = g_ptr_array_new ();
5802 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5803 if (index)
5804 index --;
5805 else {
5806 index = acfg->objc_selector_index;
5807 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5808 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5809 acfg->objc_selector_index ++;
5812 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5813 i += code_size - INST_LEN;
5814 skip = TRUE;
5815 patch_info->type = MONO_PATCH_INFO_NONE;
5816 break;
5818 default: {
5820 * If this patch is a call, try emitting a direct call instead of
5821 * through a PLT entry. This is possible if the called method is in
5822 * the same assembly and requires no initialization.
5824 direct_call = FALSE;
5825 external_call = FALSE;
5826 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (m_class_get_image (patch_info->data.method->klass) == acfg->image)) {
5827 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5828 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5830 // Don't compile inflated methods if we're doing dedup
5831 if (acfg->aot_opts.dedup && !mono_aot_can_dedup (patch_info->data.method)) {
5832 char *name = mono_aot_get_mangled_method_name (patch_info->data.method);
5833 mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT, "DIRECT CALL: %s by %s", name, method ? mono_method_full_name (method, TRUE) : "");
5834 g_free (name);
5836 direct_call = TRUE;
5837 direct_call_target = callee_cfg->asm_symbol;
5838 patch_info->type = MONO_PATCH_INFO_NONE;
5839 acfg->stats.direct_calls ++;
5843 acfg->stats.all_calls ++;
5844 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5845 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5846 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5847 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5848 else
5849 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5850 if (direct_pinvoke) {
5851 direct_call = TRUE;
5852 g_assert (strlen (direct_pinvoke) < 1000);
5853 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5856 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5857 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5858 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5859 /* Call to a C function implementing a jit icall */
5860 direct_call = TRUE;
5861 external_call = TRUE;
5862 g_assert (strlen (sym) < 1000);
5863 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5865 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5866 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5867 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5868 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5869 /* Call to a jit icall without a wrapper */
5870 direct_call = TRUE;
5871 external_call = TRUE;
5872 g_assert (strlen (sym) < 1000);
5873 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5877 if (direct_call) {
5878 patch_info->type = MONO_PATCH_INFO_NONE;
5879 acfg->stats.direct_calls ++;
5882 if (!got_only && !direct_call) {
5883 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5884 if (plt_entry) {
5885 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5886 direct_call = TRUE;
5887 direct_call_target = plt_entry->symbol;
5889 /* Nullify the patch */
5890 patch_info->type = MONO_PATCH_INFO_NONE;
5891 plt_entry->jit_used = TRUE;
5895 if (direct_call) {
5896 int call_size;
5898 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5899 i += call_size - INST_LEN;
5900 } else {
5901 int code_size;
5903 got_slot = get_got_offset (acfg, FALSE, patch_info);
5905 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5906 i += code_size - INST_LEN;
5908 skip = TRUE;
5912 #endif /* MONO_ARCH_AOT_SUPPORTED */
5914 if (!skip) {
5915 /* Find next patch */
5916 patch_info = NULL;
5917 for (pindex = start_index; pindex < patches->len; ++pindex) {
5918 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5919 if (patch_info->ip.i >= i)
5920 break;
5923 /* Try to emit multiple bytes at once */
5924 if (pindex < patches->len && patch_info->ip.i > i) {
5925 int limit;
5927 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5928 if (locs && locs [limit])
5929 break;
5932 emit_code_bytes (acfg, code + i, limit - i);
5933 i = limit - INST_LEN;
5934 } else {
5935 emit_code_bytes (acfg, code + i, INST_LEN);
5940 g_ptr_array_free (patches, TRUE);
5941 g_free (locs);
5945 * sanitize_symbol:
5947 * Return a modified version of S which only includes characters permissible in symbols.
5949 static char*
5950 sanitize_symbol (MonoAotCompile *acfg, char *s)
5952 gboolean process = FALSE;
5953 int i, len;
5954 GString *gs;
5955 char *res;
5957 if (!s)
5958 return s;
5960 len = strlen (s);
5961 for (i = 0; i < len; ++i)
5962 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5963 process = TRUE;
5964 if (!process)
5965 return s;
5967 gs = g_string_sized_new (len);
5968 for (i = 0; i < len; ++i) {
5969 guint8 c = s [i];
5970 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5971 g_string_append_c (gs, c);
5972 } else if (c > 0x7f) {
5973 /* multi-byte utf8 */
5974 g_string_append_printf (gs, "_0x%x", c);
5975 i ++;
5976 c = s [i];
5977 while (c >> 6 == 0x2) {
5978 g_string_append_printf (gs, "%x", c);
5979 i ++;
5980 c = s [i];
5982 g_string_append_printf (gs, "_");
5983 i --;
5984 } else {
5985 g_string_append_c (gs, '_');
5989 res = mono_mempool_strdup (acfg->mempool, gs->str);
5990 g_string_free (gs, TRUE);
5991 return res;
5994 static char*
5995 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5997 char *name1, *name2, *cached;
5998 int i, j, len, count;
5999 MonoMethod *cached_method;
6001 name1 = mono_method_full_name (method, TRUE);
6003 #ifdef TARGET_MACH
6004 // This is so that we don't accidentally create a local symbol (which starts with 'L')
6005 if ((!prefix || !*prefix) && name1 [0] == 'L')
6006 prefix = "_";
6007 #endif
6009 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6010 char adjustedPrefix [MAX_SYMBOL_SIZE];
6011 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
6012 #endif
6014 len = strlen (name1);
6015 name2 = (char *)malloc (strlen (prefix) + len + 16);
6016 memcpy (name2, prefix, strlen (prefix));
6017 j = strlen (prefix);
6018 for (i = 0; i < len; ++i) {
6019 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
6020 name2 [j ++] = '_';
6021 } else if (isalnum (name1 [i])) {
6022 name2 [j ++] = name1 [i];
6023 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
6024 i += 2;
6025 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
6026 name2 [j ++] = '_';
6027 i++;
6028 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
6029 } else
6030 name2 [j ++] = '_';
6032 name2 [j] = '\0';
6034 g_free (name1);
6036 count = 0;
6037 while (TRUE) {
6038 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
6039 if (!(cached_method && cached_method != method))
6040 break;
6041 sprintf (name2 + j, "_%d", count);
6042 count ++;
6045 cached = g_strdup (name2);
6046 g_hash_table_insert (cache, cached, method);
6048 return name2;
6051 static void
6052 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
6054 MonoMethod *method;
6055 int method_index;
6056 guint8 *code;
6057 char *debug_sym = NULL;
6058 char *symbol = NULL;
6059 int func_alignment = AOT_FUNC_ALIGNMENT;
6060 char *export_name;
6062 g_assert (!ignore_cfg (cfg));
6064 method = cfg->orig_method;
6065 code = cfg->native_code;
6067 method_index = get_method_index (acfg, method);
6068 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
6070 /* Make the labels local */
6071 emit_section_change (acfg, ".text", 0);
6072 emit_alignment_code (acfg, func_alignment);
6074 if (acfg->global_symbols && acfg->need_no_dead_strip)
6075 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
6077 emit_label (acfg, cfg->asm_symbol);
6079 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
6081 * Write a C style symbol for every method, this has two uses:
6082 * - it works on platforms where the dwarf debugging info is not
6083 * yet supported.
6084 * - it allows the setting of breakpoints of aot-ed methods.
6087 // Comment out to force dedup to link these symbols and forbid compiling
6088 // in duplicated code. This is an "assert when linking if broken" trick.
6089 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6090 /*debug_sym = mono_aot_get_mangled_method_name (method);*/
6091 /*else*/
6092 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
6094 cfg->asm_debug_symbol = g_strdup (debug_sym);
6096 if (acfg->need_no_dead_strip)
6097 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6099 // Comment out to force dedup to link these symbols and forbid compiling
6100 // in duplicated code. This is an "assert when linking if broken" trick.
6101 /*if (mono_aot_can_dedup (method) && (acfg->aot_opts.dedup || acfg->aot_opts.dedup_include))*/
6102 /*emit_global_inner (acfg, debug_sym, TRUE);*/
6103 /*else*/
6104 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
6106 emit_label (acfg, debug_sym);
6109 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
6110 if (export_name) {
6111 /* Emit a global symbol for the method */
6112 emit_global_inner (acfg, export_name, TRUE);
6113 emit_label (acfg, export_name);
6116 if (cfg->verbose_level > 0 && !ignore_cfg (cfg))
6117 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
6119 acfg->stats.code_size += cfg->code_len;
6121 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
6123 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 ()));
6125 emit_line (acfg);
6127 if (acfg->aot_opts.write_symbols) {
6128 if (debug_sym)
6129 emit_symbol_size (acfg, debug_sym, ".");
6130 else
6131 emit_symbol_size (acfg, cfg->asm_symbol, ".");
6132 g_free (debug_sym);
6135 emit_label (acfg, symbol);
6137 arch_emit_unwind_info_sections (acfg, cfg->asm_symbol, symbol, cfg->unwind_ops);
6139 g_free (symbol);
6143 * encode_patch:
6145 * Encode PATCH_INFO into its disk representation.
6147 static void
6148 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
6150 guint8 *p = buf;
6152 switch (patch_info->type) {
6153 case MONO_PATCH_INFO_NONE:
6154 break;
6155 case MONO_PATCH_INFO_IMAGE:
6156 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
6157 break;
6158 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
6159 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6160 case MONO_PATCH_INFO_GC_NURSERY_START:
6161 case MONO_PATCH_INFO_GC_NURSERY_BITS:
6162 break;
6163 case MONO_PATCH_INFO_CASTCLASS_CACHE:
6164 encode_value (patch_info->data.index, p, &p);
6165 break;
6166 case MONO_PATCH_INFO_METHOD_REL:
6167 encode_value ((gint)patch_info->data.offset, p, &p);
6168 break;
6169 case MONO_PATCH_INFO_SWITCH: {
6170 gpointer *table = (gpointer *)patch_info->data.table->table;
6171 int k;
6173 encode_value (patch_info->data.table->table_size, p, &p);
6174 for (k = 0; k < patch_info->data.table->table_size; k++)
6175 encode_value ((int)(gssize)table [k], p, &p);
6176 break;
6178 case MONO_PATCH_INFO_METHODCONST:
6179 case MONO_PATCH_INFO_METHOD:
6180 case MONO_PATCH_INFO_METHOD_JUMP:
6181 case MONO_PATCH_INFO_ICALL_ADDR:
6182 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
6183 case MONO_PATCH_INFO_METHOD_RGCTX:
6184 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
6185 encode_method_ref (acfg, patch_info->data.method, p, &p);
6186 break;
6187 case MONO_PATCH_INFO_AOT_JIT_INFO:
6188 case MONO_PATCH_INFO_GET_TLS_TRAMP:
6189 case MONO_PATCH_INFO_SET_TLS_TRAMP:
6190 encode_value (patch_info->data.index, p, &p);
6191 break;
6192 case MONO_PATCH_INFO_INTERNAL_METHOD:
6193 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6194 case MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL: {
6195 guint32 len = strlen (patch_info->data.name);
6197 encode_value (len, p, &p);
6199 memcpy (p, patch_info->data.name, len);
6200 p += len;
6201 *p++ = '\0';
6202 break;
6204 case MONO_PATCH_INFO_LDSTR: {
6205 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
6206 guint32 token = patch_info->data.token->token;
6207 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
6208 encode_value (image_index, p, &p);
6209 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
6210 break;
6212 case MONO_PATCH_INFO_RVA:
6213 case MONO_PATCH_INFO_DECLSEC:
6214 case MONO_PATCH_INFO_LDTOKEN:
6215 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
6216 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
6217 encode_value (patch_info->data.token->token, p, &p);
6218 encode_value (patch_info->data.token->has_context, p, &p);
6219 if (patch_info->data.token->has_context)
6220 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
6221 break;
6222 case MONO_PATCH_INFO_EXC_NAME: {
6223 MonoClass *ex_class;
6225 ex_class =
6226 mono_class_load_from_name (m_class_get_image (mono_defaults.exception_class),
6227 "System", (const char *)patch_info->data.target);
6228 encode_klass_ref (acfg, ex_class, p, &p);
6229 break;
6231 case MONO_PATCH_INFO_R4:
6232 encode_value (*((guint32 *)patch_info->data.target), p, &p);
6233 break;
6234 case MONO_PATCH_INFO_R8:
6235 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
6236 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
6237 break;
6238 case MONO_PATCH_INFO_VTABLE:
6239 case MONO_PATCH_INFO_CLASS:
6240 case MONO_PATCH_INFO_IID:
6241 case MONO_PATCH_INFO_ADJUSTED_IID:
6242 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
6243 break;
6244 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6245 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
6246 if (patch_info->data.del_tramp->method) {
6247 encode_value (1, p, &p);
6248 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
6249 } else {
6250 encode_value (0, p, &p);
6252 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
6253 break;
6254 case MONO_PATCH_INFO_FIELD:
6255 case MONO_PATCH_INFO_SFLDA:
6256 encode_field_info (acfg, patch_info->data.field, p, &p);
6257 break;
6258 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
6259 break;
6260 case MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT:
6261 case MONO_PATCH_INFO_PROFILER_CLAUSE_COUNT:
6262 break;
6263 case MONO_PATCH_INFO_RGCTX_FETCH:
6264 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
6265 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6266 guint32 offset;
6267 guint8 *buf2, *p2;
6270 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
6271 * reference the same method, so encode the method only once.
6273 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
6274 if (!offset) {
6275 buf2 = (guint8 *)g_malloc (1024);
6276 p2 = buf2;
6278 encode_method_ref (acfg, entry->method, p2, &p2);
6279 g_assert (p2 - buf2 < 1024);
6281 offset = add_to_blob (acfg, buf2, p2 - buf2);
6282 g_free (buf2);
6284 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
6285 } else {
6286 offset --;
6289 encode_value (offset, p, &p);
6290 g_assert ((int)entry->info_type < 256);
6291 g_assert (entry->data->type < 256);
6292 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
6293 encode_patch (acfg, entry->data, p, &p);
6294 break;
6296 case MONO_PATCH_INFO_SEQ_POINT_INFO:
6297 case MONO_PATCH_INFO_AOT_MODULE:
6298 break;
6299 case MONO_PATCH_INFO_SIGNATURE:
6300 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
6301 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
6302 break;
6303 case MONO_PATCH_INFO_GSHAREDVT_CALL:
6304 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
6305 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
6306 break;
6307 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
6308 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
6309 int i;
6311 encode_method_ref (acfg, info->method, p, &p);
6312 encode_value (info->num_entries, p, &p);
6313 for (i = 0; i < info->num_entries; ++i) {
6314 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
6316 encode_value (template_->info_type, p, &p);
6317 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
6318 case MONO_PATCH_INFO_CLASS:
6319 encode_klass_ref (acfg, mono_class_from_mono_type_internal ((MonoType *)template_->data), p, &p);
6320 break;
6321 case MONO_PATCH_INFO_FIELD:
6322 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
6323 break;
6324 default:
6325 g_assert_not_reached ();
6326 break;
6329 break;
6331 case MONO_PATCH_INFO_LDSTR_LIT: {
6332 const char *s = (const char *)patch_info->data.target;
6333 int len = strlen (s);
6335 encode_value (len, p, &p);
6336 memcpy (p, s, len + 1);
6337 p += len + 1;
6338 break;
6340 case MONO_PATCH_INFO_VIRT_METHOD:
6341 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
6342 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
6343 break;
6344 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
6345 break;
6346 default:
6347 g_warning ("unable to handle jump info %d", patch_info->type);
6348 g_assert_not_reached ();
6351 *endbuf = p;
6354 static void
6355 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, guint8 *buf, guint8 **endbuf)
6357 guint8 *p = buf;
6358 guint32 pindex, offset;
6359 MonoJumpInfo *patch_info;
6361 encode_value (n_patches, p, &p);
6363 for (pindex = 0; pindex < patches->len; ++pindex) {
6364 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6366 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
6367 /* Nothing to do */
6368 continue;
6369 /* This shouldn't allocate a new offset */
6370 offset = lookup_got_offset (acfg, llvm, patch_info);
6371 encode_value (offset, p, &p);
6374 *endbuf = p;
6377 static void
6378 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
6380 MonoMethod *method;
6381 int pindex, buf_size, n_patches;
6382 GPtrArray *patches;
6383 MonoJumpInfo *patch_info;
6384 guint32 method_index;
6385 guint8 *p, *buf;
6387 method = cfg->orig_method;
6389 method_index = get_method_index (acfg, method);
6391 /* Sort relocations */
6392 patches = g_ptr_array_new ();
6393 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
6394 g_ptr_array_add (patches, patch_info);
6395 g_ptr_array_sort (patches, compare_patches);
6397 /**********************/
6398 /* Encode method info */
6399 /**********************/
6401 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
6402 p = buf = (guint8 *)g_malloc (buf_size);
6404 if (mono_class_get_cctor (method->klass)) {
6405 encode_value (1, p, &p);
6406 encode_klass_ref (acfg, method->klass, p, &p);
6407 } else {
6408 /* Not needed when loading the method */
6409 encode_value (0, p, &p);
6412 g_assert (!(cfg->opt & MONO_OPT_SHARED));
6414 n_patches = 0;
6415 for (pindex = 0; pindex < patches->len; ++pindex) {
6416 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
6418 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
6419 (patch_info->type == MONO_PATCH_INFO_NONE)) {
6420 patch_info->type = MONO_PATCH_INFO_NONE;
6421 /* Nothing to do */
6422 continue;
6425 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
6426 /* Stored in a GOT slot initialized at module load time */
6427 patch_info->type = MONO_PATCH_INFO_NONE;
6428 continue;
6431 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
6432 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
6433 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
6434 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
6435 /* Stored in a GOT slot initialized at module load time */
6436 patch_info->type = MONO_PATCH_INFO_NONE;
6437 continue;
6440 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
6441 /* Calls are made through the PLT */
6442 patch_info->type = MONO_PATCH_INFO_NONE;
6443 continue;
6446 n_patches ++;
6449 if (n_patches)
6450 g_assert (cfg->has_got_slots);
6452 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, p, &p);
6454 g_ptr_array_free (patches, TRUE);
6456 acfg->stats.info_size += p - buf;
6458 g_assert (p - buf < buf_size);
6460 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6461 g_free (buf);
6464 static guint32
6465 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6467 guint32 cache_index;
6468 guint32 offset;
6470 /* Reuse the unwind module to canonize and store unwind info entries */
6471 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6473 /* Use +/- 1 to distinguish 0s from missing entries */
6474 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6475 if (offset)
6476 return offset - 1;
6477 else {
6478 guint8 buf [16];
6479 guint8 *p;
6482 * It would be easier to use assembler symbols, but the caller needs an
6483 * offset now.
6485 offset = acfg->unwind_info_offset;
6486 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6487 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6489 p = buf;
6490 encode_value (encoded_len, p, &p);
6492 acfg->unwind_info_offset += encoded_len + (p - buf);
6493 return offset;
6497 static void
6498 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6500 int i, k, buf_size;
6501 guint32 debug_info_size, seq_points_size;
6502 guint8 *code;
6503 MonoMethodHeader *header;
6504 guint8 *p, *buf, *debug_info;
6505 MonoJitInfo *jinfo = cfg->jit_info;
6506 guint32 flags;
6507 gboolean use_unwind_ops = FALSE;
6508 MonoSeqPointInfo *seq_points;
6510 code = cfg->native_code;
6511 header = cfg->header;
6513 if (!acfg->aot_opts.nodebug) {
6514 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6515 } else {
6516 debug_info = NULL;
6517 debug_info_size = 0;
6520 seq_points = cfg->seq_point_info;
6521 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6523 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6524 if (jinfo->has_try_block_holes) {
6525 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6526 buf_size += table->num_holes * 16;
6529 p = buf = (guint8 *)g_malloc (buf_size);
6531 use_unwind_ops = cfg->unwind_ops != NULL;
6533 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);
6535 encode_value (flags, p, &p);
6537 if (use_unwind_ops) {
6538 guint32 encoded_len;
6539 guint8 *encoded;
6540 guint32 unwind_desc;
6542 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6544 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6545 encode_value (unwind_desc, p, &p);
6547 g_free (encoded);
6548 } else {
6549 encode_value (jinfo->unwind_info, p, &p);
6552 /*Encode the number of holes before the number of clauses to make decoding easier*/
6553 if (jinfo->has_try_block_holes) {
6554 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6555 encode_value (table->num_holes, p, &p);
6558 if (jinfo->has_arch_eh_info) {
6560 * In AOT mode, the code length is calculated from the address of the previous method,
6561 * which could include alignment padding, so calculating the start of the epilog as
6562 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6564 encode_value (jinfo->code_size, p, &p);
6567 /* Exception table */
6568 if (cfg->compile_llvm) {
6570 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6571 * since the information is only available to llc. Instead, we let llc save the data
6572 * into the LSDA, and read it from there at runtime.
6574 /* The assembly might be CIL stripped so emit the data ourselves */
6575 if (header->num_clauses)
6576 encode_value (header->num_clauses, p, &p);
6578 for (k = 0; k < header->num_clauses; ++k) {
6579 MonoExceptionClause *clause;
6581 clause = &header->clauses [k];
6583 encode_value (clause->flags, p, &p);
6584 if (!(clause->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6585 if (clause->data.catch_class) {
6586 guint8 *buf2, *p2;
6587 int len;
6589 buf2 = (guint8 *)g_malloc (4096);
6590 p2 = buf2;
6591 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6592 len = p2 - buf2;
6593 g_assert (len < 4096);
6594 encode_value (len, p, &p);
6595 memcpy (p, buf2, len);
6596 p += p2 - buf2;
6597 g_free (buf2);
6598 } else {
6599 encode_value (0, p, &p);
6603 /* Emit the IL ranges too, since they might not be available at runtime */
6604 encode_value (clause->try_offset, p, &p);
6605 encode_value (clause->try_len, p, &p);
6606 encode_value (clause->handler_offset, p, &p);
6607 encode_value (clause->handler_len, p, &p);
6609 /* Emit a list of nesting clauses */
6610 for (i = 0; i < header->num_clauses; ++i) {
6611 gint32 cindex1 = k;
6612 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6613 gint32 cindex2 = i;
6614 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6616 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6617 encode_value (i, p, &p);
6619 encode_value (-1, p, &p);
6621 } else {
6622 if (jinfo->num_clauses)
6623 encode_value (jinfo->num_clauses, p, &p);
6625 for (k = 0; k < jinfo->num_clauses; ++k) {
6626 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6628 encode_value (ei->flags, p, &p);
6629 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6630 /* Not used for catch clauses */
6631 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6632 encode_value (ei->exvar_offset, p, &p);
6633 #else
6634 encode_value (ei->exvar_offset, p, &p);
6635 #endif
6637 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6638 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6639 else {
6640 if (ei->data.catch_class) {
6641 guint8 *buf2, *p2;
6642 int len;
6644 buf2 = (guint8 *)g_malloc (4096);
6645 p2 = buf2;
6646 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6647 len = p2 - buf2;
6648 g_assert (len < 4096);
6649 encode_value (len, p, &p);
6650 memcpy (p, buf2, len);
6651 p += p2 - buf2;
6652 g_free (buf2);
6653 } else {
6654 encode_value (0, p, &p);
6658 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6659 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6660 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6664 if (jinfo->has_try_block_holes) {
6665 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6666 for (i = 0; i < table->num_holes; ++i) {
6667 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6668 encode_value (hole->clause, p, &p);
6669 encode_value (hole->length, p, &p);
6670 encode_value (hole->offset, p, &p);
6674 if (jinfo->has_arch_eh_info) {
6675 MonoArchEHJitInfo *eh_info;
6677 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6678 encode_value (eh_info->stack_size, p, &p);
6679 encode_value (eh_info->epilog_size, p, &p);
6682 if (jinfo->has_generic_jit_info) {
6683 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6684 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6685 guint8 *buf2, *p2;
6686 int len;
6688 encode_value (gi->nlocs, p, &p);
6689 if (gi->nlocs) {
6690 for (i = 0; i < gi->nlocs; ++i) {
6691 MonoDwarfLocListEntry *entry = &gi->locations [i];
6693 encode_value (entry->is_reg ? 1 : 0, p, &p);
6694 encode_value (entry->reg, p, &p);
6695 if (!entry->is_reg)
6696 encode_value (entry->offset, p, &p);
6697 if (i == 0)
6698 g_assert (entry->from == 0);
6699 else
6700 encode_value (entry->from, p, &p);
6701 encode_value (entry->to, p, &p);
6703 } else {
6704 if (!cfg->compile_llvm) {
6705 encode_value (gi->has_this ? 1 : 0, p, &p);
6706 encode_value (gi->this_reg, p, &p);
6707 encode_value (gi->this_offset, p, &p);
6712 * Need to encode jinfo->method too, since it is not equal to 'method'
6713 * when using generic sharing.
6715 buf2 = (guint8 *)g_malloc (4096);
6716 p2 = buf2;
6717 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6718 len = p2 - buf2;
6719 g_assert (len < 4096);
6720 encode_value (len, p, &p);
6721 memcpy (p, buf2, len);
6722 p += p2 - buf2;
6723 g_free (buf2);
6725 if (gsctx && gsctx->is_gsharedvt) {
6726 encode_value (1, p, &p);
6727 } else {
6728 encode_value (0, p, &p);
6732 if (seq_points_size)
6733 p += mono_seq_point_info_write (seq_points, p);
6735 g_assert (debug_info_size < buf_size);
6737 encode_value (debug_info_size, p, &p);
6738 if (debug_info_size) {
6739 memcpy (p, debug_info, debug_info_size);
6740 p += debug_info_size;
6741 g_free (debug_info);
6744 /* GC Map */
6745 if (cfg->gc_map) {
6746 encode_value (cfg->gc_map_size, p, &p);
6747 /* The GC map requires 4 bytes of alignment */
6748 while ((gsize)p % 4)
6749 p ++;
6750 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6751 p += cfg->gc_map_size;
6754 acfg->stats.ex_info_size += p - buf;
6756 g_assert (p - buf < buf_size);
6758 /* Emit info */
6759 /* The GC Map requires 4 byte alignment */
6760 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6761 g_free (buf);
6764 static guint32
6765 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6767 ERROR_DECL (error);
6768 MonoClass *klass = mono_class_get_checked (acfg->image, token, error);
6769 guint8 *p, *buf;
6770 int i, buf_size, res;
6771 gboolean no_special_static, cant_encode;
6772 gpointer iter = NULL;
6774 if (!klass) {
6775 mono_error_cleanup (error);
6777 buf_size = 16;
6779 p = buf = (guint8 *)g_malloc (buf_size);
6781 /* Mark as unusable */
6782 encode_value (-1, p, &p);
6784 res = add_to_blob (acfg, buf, p - buf);
6785 g_free (buf);
6787 return res;
6790 buf_size = 10240 + (m_class_get_vtable_size (klass) * 16);
6791 p = buf = (guint8 *)g_malloc (buf_size);
6793 g_assert (klass);
6795 mono_class_init (klass);
6797 mono_class_get_nested_types (klass, &iter);
6798 g_assert (m_class_is_nested_classes_inited (klass));
6800 mono_class_setup_vtable (klass);
6803 * Emit all the information which is required for creating vtables so
6804 * the runtime does not need to create the MonoMethod structures which
6805 * take up a lot of space.
6808 no_special_static = !mono_class_has_special_static_fields (klass);
6810 /* Check whenever we have enough info to encode the vtable */
6811 cant_encode = FALSE;
6812 MonoMethod **klass_vtable = m_class_get_vtable (klass);
6813 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
6814 MonoMethod *cm = klass_vtable [i];
6816 if (cm && mono_method_signature_internal (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6817 cant_encode = TRUE;
6820 mono_class_has_finalizer (klass);
6821 if (mono_class_has_failure (klass))
6822 cant_encode = TRUE;
6824 if (mono_class_is_gtd (klass) || cant_encode) {
6825 encode_value (-1, p, &p);
6826 } else {
6827 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6828 encode_value (m_class_get_vtable_size (klass), p, &p);
6829 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);
6830 if (m_class_has_cctor (klass))
6831 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6832 if (m_class_has_finalize (klass))
6833 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6835 encode_value (m_class_get_instance_size (klass), p, &p);
6836 encode_value (mono_class_data_size (klass), p, &p);
6837 encode_value (m_class_get_packing_size (klass), p, &p);
6838 encode_value (m_class_get_min_align (klass), p, &p);
6840 for (i = 0; i < m_class_get_vtable_size (klass); ++i) {
6841 MonoMethod *cm = klass_vtable [i];
6843 if (cm)
6844 encode_method_ref (acfg, cm, p, &p);
6845 else
6846 encode_value (0, p, &p);
6850 acfg->stats.class_info_size += p - buf;
6852 g_assert (p - buf < buf_size);
6853 res = add_to_blob (acfg, buf, p - buf);
6854 g_free (buf);
6856 return res;
6859 static char*
6860 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6862 char *debug_sym = NULL;
6863 char *prefix;
6865 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6866 /* Need to add a prefix to create unique symbols */
6867 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6868 } else {
6869 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6870 prefix = mangle_symbol_alloc ("plt_");
6871 #else
6872 prefix = g_strdup ("plt_");
6873 #endif
6876 switch (ji->type) {
6877 case MONO_PATCH_INFO_METHOD:
6878 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6879 break;
6880 case MONO_PATCH_INFO_INTERNAL_METHOD:
6881 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6882 break;
6883 case MONO_PATCH_INFO_RGCTX_FETCH:
6884 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6885 break;
6886 case MONO_PATCH_INFO_ICALL_ADDR:
6887 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6888 char *s = get_debug_sym (ji->data.method, "", cache);
6890 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6891 g_free (s);
6892 break;
6894 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6895 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6896 break;
6897 default:
6898 break;
6901 g_free (prefix);
6903 return sanitize_symbol (acfg, debug_sym);
6907 * Calls made from AOTed code are routed through a table of jumps similar to the
6908 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6909 * control to the AOT runtime through a trampoline.
6911 static void
6912 emit_plt (MonoAotCompile *acfg)
6914 int i;
6916 if (acfg->aot_opts.llvm_only) {
6917 g_assert (acfg->plt_offset == 1);
6918 return;
6921 emit_line (acfg);
6923 emit_section_change (acfg, ".text", 0);
6924 emit_alignment_code (acfg, 16);
6925 emit_info_symbol (acfg, "plt", TRUE);
6926 emit_label (acfg, acfg->plt_symbol);
6928 for (i = 0; i < acfg->plt_offset; ++i) {
6929 char *debug_sym = NULL;
6930 MonoPltEntry *plt_entry = NULL;
6932 if (i == 0)
6934 * The first plt entry is unused.
6936 continue;
6938 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6940 debug_sym = plt_entry->debug_sym;
6942 if (acfg->thumb_mixed && !plt_entry->jit_used)
6943 /* Emit only a thumb version */
6944 continue;
6946 /* Skip plt entries not actually called */
6947 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6948 continue;
6950 if (acfg->llvm && !acfg->thumb_mixed) {
6951 emit_label (acfg, plt_entry->llvm_symbol);
6952 if (acfg->llvm) {
6953 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6954 #if defined(TARGET_MACH)
6955 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6956 #endif
6960 if (debug_sym) {
6961 if (acfg->need_no_dead_strip) {
6962 emit_unset_mode (acfg);
6963 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6965 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6966 emit_label (acfg, debug_sym);
6969 emit_label (acfg, plt_entry->symbol);
6971 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (target_mgreg_t), acfg->plt_got_info_offsets [i]);
6973 if (debug_sym)
6974 emit_symbol_size (acfg, debug_sym, ".");
6977 if (acfg->thumb_mixed) {
6978 /* Make sure the ARM symbols don't alias the thumb ones */
6979 emit_zero_bytes (acfg, 16);
6982 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6983 * code.
6985 for (i = 0; i < acfg->plt_offset; ++i) {
6986 char *debug_sym = NULL;
6987 MonoPltEntry *plt_entry = NULL;
6989 if (i == 0)
6990 continue;
6992 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6994 /* Skip plt entries not actually called by LLVM code */
6995 if (!plt_entry->llvm_used)
6996 continue;
6998 if (acfg->aot_opts.write_symbols) {
6999 if (plt_entry->debug_sym)
7000 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
7003 if (debug_sym) {
7004 #if defined(TARGET_MACH)
7005 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
7006 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
7007 #endif
7008 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
7009 emit_label (acfg, debug_sym);
7011 fprintf (acfg->fp, "\n.thumb_func\n");
7013 emit_label (acfg, plt_entry->llvm_symbol);
7015 if (acfg->llvm)
7016 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
7018 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]);
7020 if (debug_sym) {
7021 emit_symbol_size (acfg, debug_sym, ".");
7022 g_free (debug_sym);
7027 emit_symbol_size (acfg, acfg->plt_symbol, ".");
7029 emit_info_symbol (acfg, "plt_end", TRUE);
7031 arch_emit_unwind_info_sections (acfg, "plt", "plt_end", NULL);
7035 * emit_trampoline_full:
7037 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
7038 * create_jit_info_for_trampoline ().
7040 static G_GNUC_UNUSED void
7041 emit_trampoline_full (MonoAotCompile *acfg, MonoTrampInfo *info, gboolean emit_tinfo)
7043 char start_symbol [MAX_SYMBOL_SIZE];
7044 char end_symbol [MAX_SYMBOL_SIZE];
7045 char symbol [MAX_SYMBOL_SIZE];
7046 guint32 buf_size, info_offset;
7047 MonoJumpInfo *patch_info;
7048 guint8 *buf, *p;
7049 GPtrArray *patches;
7050 char *name;
7051 guint8 *code;
7052 guint32 code_size;
7053 MonoJumpInfo *ji;
7054 GSList *unwind_ops;
7056 g_assert (info);
7058 name = info->name;
7059 code = info->code;
7060 code_size = info->code_size;
7061 ji = info->ji;
7062 unwind_ops = info->unwind_ops;
7064 /* Emit code */
7066 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
7068 emit_section_change (acfg, ".text", 0);
7069 emit_global (acfg, start_symbol, TRUE);
7070 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7071 emit_label (acfg, start_symbol);
7073 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
7074 emit_label (acfg, symbol);
7077 * The code should access everything through the GOT, so we pass
7078 * TRUE here.
7080 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
7082 emit_symbol_size (acfg, start_symbol, ".");
7084 if (emit_tinfo) {
7085 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
7086 emit_label (acfg, end_symbol);
7089 /* Emit info */
7091 /* Sort relocations */
7092 patches = g_ptr_array_new ();
7093 for (patch_info = ji; patch_info; patch_info = patch_info->next)
7094 if (patch_info->type != MONO_PATCH_INFO_NONE)
7095 g_ptr_array_add (patches, patch_info);
7096 g_ptr_array_sort (patches, compare_patches);
7098 buf_size = patches->len * 128 + 128;
7099 buf = (guint8 *)g_malloc (buf_size);
7100 p = buf;
7102 encode_patch_list (acfg, patches, patches->len, FALSE, p, &p);
7103 g_assert (p - buf < buf_size);
7104 g_ptr_array_free (patches, TRUE);
7106 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
7108 info_offset = add_to_blob (acfg, buf, p - buf);
7110 emit_section_change (acfg, RODATA_SECT, 0);
7111 emit_global (acfg, symbol, FALSE);
7112 emit_label (acfg, symbol);
7114 emit_int32 (acfg, info_offset);
7116 if (emit_tinfo) {
7117 guint8 *encoded;
7118 guint32 encoded_len;
7119 guint32 uw_offset;
7122 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
7124 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
7125 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
7126 g_free (encoded);
7128 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
7129 emit_int32 (acfg, uw_offset);
7132 /* Emit debug info */
7133 if (unwind_ops) {
7134 char symbol2 [MAX_SYMBOL_SIZE];
7136 sprintf (symbol, "%s", name);
7137 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
7139 arch_emit_unwind_info_sections (acfg, start_symbol, end_symbol, unwind_ops);
7141 if (acfg->dwarf)
7142 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
7145 g_free (buf);
7148 static G_GNUC_UNUSED void
7149 emit_trampoline (MonoAotCompile *acfg, MonoTrampInfo *info)
7151 emit_trampoline_full (acfg, info, TRUE);
7154 static void
7155 emit_trampolines (MonoAotCompile *acfg)
7157 char symbol [MAX_SYMBOL_SIZE];
7158 char end_symbol [MAX_SYMBOL_SIZE];
7159 int i, tramp_got_offset;
7160 int ntype;
7161 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7162 int tramp_type;
7163 #endif
7165 if ((!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only) && !mono_aot_mode_is_interp (&acfg->aot_opts))
7166 return;
7168 g_assert (acfg->image->assembly);
7170 /* Currently, we emit most trampolines into the mscorlib AOT image. */
7171 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
7172 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7173 MonoTrampInfo *info;
7176 * Emit the generic trampolines.
7178 * We could save some code by treating the generic trampolines as a wrapper
7179 * method, but that approach has its own complexities, so we choose the simpler
7180 * method.
7182 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
7183 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
7184 #ifdef DISABLE_REMOTING
7185 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
7186 continue;
7187 #endif
7188 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
7189 emit_trampoline (acfg, info);
7190 mono_tramp_info_free (info);
7193 /* Emit the exception related code pieces */
7194 mono_arch_get_restore_context (&info, TRUE);
7195 emit_trampoline (acfg, info);
7196 mono_tramp_info_free (info);
7198 mono_arch_get_call_filter (&info, TRUE);
7199 emit_trampoline (acfg, info);
7200 mono_tramp_info_free (info);
7202 mono_arch_get_throw_exception (&info, TRUE);
7203 emit_trampoline (acfg, info);
7204 mono_tramp_info_free (info);
7206 mono_arch_get_rethrow_exception (&info, TRUE);
7207 emit_trampoline (acfg, info);
7208 mono_tramp_info_free (info);
7210 mono_arch_get_rethrow_preserve_exception (&info, TRUE);
7211 emit_trampoline (acfg, info);
7212 mono_tramp_info_free (info);
7214 mono_arch_get_throw_corlib_exception (&info, TRUE);
7215 emit_trampoline (acfg, info);
7216 mono_tramp_info_free (info);
7218 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
7219 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
7220 emit_trampoline (acfg, info);
7221 mono_tramp_info_free (info);
7223 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
7224 emit_trampoline (acfg, info);
7225 mono_tramp_info_free (info);
7226 #endif
7228 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
7229 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
7230 if (info) {
7231 emit_trampoline_full (acfg, info, TRUE);
7233 /* Create a separate out trampoline for more information in stack traces */
7234 info->name = g_strdup ("gsharedvt_out_trampoline");
7235 emit_trampoline_full (acfg, info, TRUE);
7236 mono_tramp_info_free (info);
7238 #endif
7240 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
7242 GSList *l = mono_arch_get_trampolines (TRUE);
7244 while (l) {
7245 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7247 emit_trampoline (acfg, info);
7248 l = l->next;
7251 #endif
7253 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
7254 int offset;
7256 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
7257 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7258 emit_trampoline (acfg, info);
7259 mono_tramp_info_free (info);
7261 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
7262 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
7263 emit_trampoline (acfg, info);
7264 mono_tramp_info_free (info);
7267 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
7268 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
7269 emit_trampoline (acfg, info);
7270 mono_tramp_info_free (info);
7271 #endif
7274 GSList *l;
7276 /* delegate_invoke_impl trampolines */
7277 l = mono_arch_get_delegate_invoke_impls ();
7278 while (l) {
7279 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
7281 emit_trampoline (acfg, info);
7282 l = l->next;
7286 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
7287 mono_arch_get_interp_to_native_trampoline (&info);
7288 emit_trampoline (acfg, info);
7289 #ifdef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
7290 mono_arch_get_native_to_interp_trampoline (&info);
7291 emit_trampoline (acfg, info);
7292 #endif
7295 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
7297 /* Emit trampolines which are numerous */
7300 * These include the following:
7301 * - specific trampolines
7302 * - static rgctx invoke trampolines
7303 * - imt trampolines
7304 * These trampolines have the same code, they are parameterized by GOT
7305 * slots.
7306 * They are defined in this file, in the arch_... routines instead of
7307 * in tramp-<ARCH>.c, since it is easier to do it this way.
7311 * When running in aot-only mode, we can't create specific trampolines at
7312 * runtime, so we create a few, and save them in the AOT file.
7313 * Normal trampolines embed their argument as a literal inside the
7314 * trampoline code, we can't do that here, so instead we embed an offset
7315 * which needs to be added to the trampoline address to get the address of
7316 * the GOT slot which contains the argument value.
7317 * The generated trampolines jump to the generic trampolines using another
7318 * GOT slot, which will be setup by the AOT loader to point to the
7319 * generic trampoline code of the given type.
7323 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
7324 * each class).
7327 emit_section_change (acfg, ".text", 0);
7329 tramp_got_offset = acfg->got_offset;
7331 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
7332 switch (ntype) {
7333 case MONO_AOT_TRAMP_SPECIFIC:
7334 sprintf (symbol, "specific_trampolines");
7335 break;
7336 case MONO_AOT_TRAMP_STATIC_RGCTX:
7337 sprintf (symbol, "static_rgctx_trampolines");
7338 break;
7339 case MONO_AOT_TRAMP_IMT:
7340 sprintf (symbol, "imt_trampolines");
7341 break;
7342 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7343 sprintf (symbol, "gsharedvt_arg_trampolines");
7344 break;
7345 case MONO_AOT_TRAMP_FTNPTR_ARG:
7346 sprintf (symbol, "ftnptr_arg_trampolines");
7347 break;
7348 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7349 sprintf (symbol, "unbox_arbitrary_trampolines");
7350 break;
7351 default:
7352 g_assert_not_reached ();
7355 sprintf (end_symbol, "%s_e", symbol);
7357 if (acfg->aot_opts.write_symbols)
7358 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
7360 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
7361 emit_info_symbol (acfg, symbol, TRUE);
7363 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
7365 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
7366 int tramp_size = 0;
7368 switch (ntype) {
7369 case MONO_AOT_TRAMP_SPECIFIC:
7370 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
7371 tramp_got_offset += 2;
7372 break;
7373 case MONO_AOT_TRAMP_STATIC_RGCTX:
7374 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
7375 tramp_got_offset += 2;
7376 break;
7377 case MONO_AOT_TRAMP_IMT:
7378 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
7379 tramp_got_offset += 1;
7380 break;
7381 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
7382 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7383 tramp_got_offset += 2;
7384 break;
7385 case MONO_AOT_TRAMP_FTNPTR_ARG:
7386 arch_emit_ftnptr_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
7387 tramp_got_offset += 2;
7388 break;
7389 case MONO_AOT_TRAMP_UNBOX_ARBITRARY:
7390 arch_emit_unbox_arbitrary_trampoline (acfg, tramp_got_offset, &tramp_size);
7391 tramp_got_offset += 1;
7392 break;
7393 default:
7394 g_assert_not_reached ();
7396 if (!acfg->trampoline_size [ntype]) {
7397 g_assert (tramp_size);
7398 acfg->trampoline_size [ntype] = tramp_size;
7402 emit_label (acfg, end_symbol);
7403 emit_int32 (acfg, 0);
7406 arch_emit_specific_trampoline_pages (acfg);
7408 /* Reserve some entries at the end of the GOT for our use */
7409 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
7412 acfg->got_offset += acfg->num_trampoline_got_entries;
7415 static gboolean
7416 str_begins_with (const char *str1, const char *str2)
7418 int len = strlen (str2);
7419 return strncmp (str1, str2, len) == 0;
7422 void*
7423 mono_aot_readonly_field_override (MonoClassField *field)
7425 ReadOnlyValue *rdv;
7426 for (rdv = readonly_values; rdv; rdv = rdv->next) {
7427 char *p = rdv->name;
7428 int len;
7429 len = strlen (m_class_get_name_space (field->parent));
7430 if (strncmp (p, m_class_get_name_space (field->parent), len))
7431 continue;
7432 p += len;
7433 if (*p++ != '.')
7434 continue;
7435 len = strlen (m_class_get_name (field->parent));
7436 if (strncmp (p, m_class_get_name (field->parent), len))
7437 continue;
7438 p += len;
7439 if (*p++ != '.')
7440 continue;
7441 if (strcmp (p, field->name))
7442 continue;
7443 switch (rdv->type) {
7444 case MONO_TYPE_I1:
7445 return &rdv->value.i1;
7446 case MONO_TYPE_I2:
7447 return &rdv->value.i2;
7448 case MONO_TYPE_I4:
7449 return &rdv->value.i4;
7450 default:
7451 break;
7454 return NULL;
7457 static void
7458 add_readonly_value (MonoAotOptions *opts, const char *val)
7460 ReadOnlyValue *rdv;
7461 const char *fval;
7462 const char *tval;
7463 /* the format of val is:
7464 * namespace.typename.fieldname=type/value
7465 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
7467 fval = strrchr (val, '/');
7468 if (!fval) {
7469 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
7470 exit (1);
7472 tval = strrchr (val, '=');
7473 if (!tval) {
7474 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
7475 exit (1);
7477 rdv = g_new0 (ReadOnlyValue, 1);
7478 rdv->name = (char *)g_malloc0 (tval - val + 1);
7479 memcpy (rdv->name, val, tval - val);
7480 tval++;
7481 fval++;
7482 if (strncmp (tval, "i1", 2) == 0) {
7483 rdv->value.i1 = atoi (fval);
7484 rdv->type = MONO_TYPE_I1;
7485 } else if (strncmp (tval, "i2", 2) == 0) {
7486 rdv->value.i2 = atoi (fval);
7487 rdv->type = MONO_TYPE_I2;
7488 } else if (strncmp (tval, "i4", 2) == 0) {
7489 rdv->value.i4 = atoi (fval);
7490 rdv->type = MONO_TYPE_I4;
7491 } else {
7492 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7493 exit (1);
7495 rdv->next = readonly_values;
7496 readonly_values = rdv;
7499 static gchar *
7500 clean_path (gchar * path)
7502 if (!path)
7503 return NULL;
7505 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7506 return path;
7508 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7509 g_free (path);
7511 return clean;
7514 static const gchar *
7515 wrap_path (const gchar * path)
7517 int len;
7518 if (!path)
7519 return NULL;
7521 // If the string contains no spaces, just return the original string.
7522 if (strstr (path, " ") == NULL)
7523 return path;
7525 // If the string is already wrapped in quotes, return it.
7526 len = strlen (path);
7527 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7528 return path;
7530 // If the string contains spaces, then wrap it in quotes.
7531 gchar *clean = g_strdup_printf ("\"%s\"", path);
7533 return clean;
7536 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7537 static void
7538 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7540 ptrdiff_t len = end-start;
7541 if (len > 0)
7542 g_ptr_array_add (args, g_strndup (start, len));
7545 static GPtrArray *
7546 mono_aot_split_options (const char *aot_options)
7548 enum MonoAotOptionState {
7549 MONO_AOT_OPTION_STATE_DEFAULT,
7550 MONO_AOT_OPTION_STATE_STRING,
7551 MONO_AOT_OPTION_STATE_ESCAPE,
7554 GPtrArray *args = g_ptr_array_new ();
7555 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7556 gchar const *opt_start = aot_options;
7557 gboolean end_of_string = FALSE;
7558 gchar cur;
7560 g_return_val_if_fail (aot_options != NULL, NULL);
7562 while ((cur = *aot_options) != '\0') {
7563 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7564 goto next;
7566 switch (cur) {
7567 case '"':
7568 // If we find a quote, then if we're in the default case then
7569 // it means we've found the start of a string, if not then it
7570 // means we've found the end of the string and should switch
7571 // back to the default case.
7572 switch (state) {
7573 case MONO_AOT_OPTION_STATE_DEFAULT:
7574 state = MONO_AOT_OPTION_STATE_STRING;
7575 break;
7576 case MONO_AOT_OPTION_STATE_STRING:
7577 state = MONO_AOT_OPTION_STATE_DEFAULT;
7578 break;
7579 case MONO_AOT_OPTION_STATE_ESCAPE:
7580 g_assert_not_reached ();
7581 break;
7583 break;
7584 case '\\':
7585 // If we've found an escaping operator, then this means we
7586 // should not process the next character if inside a string.
7587 if (state == MONO_AOT_OPTION_STATE_STRING)
7588 state = MONO_AOT_OPTION_STATE_ESCAPE;
7589 break;
7590 case ',':
7591 // If we're in the default state then this means we've found
7592 // an option, store it for later processing.
7593 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7594 goto new_opt;
7595 break;
7598 next:
7599 aot_options++;
7600 restart:
7601 // If the next character is end of string, then process the last option.
7602 if (*(aot_options) == '\0') {
7603 end_of_string = TRUE;
7604 goto new_opt;
7606 continue;
7608 new_opt:
7609 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7610 opt_start = ++aot_options;
7611 if (end_of_string)
7612 break;
7613 goto restart; // Check for null and continue loop
7616 return args;
7619 static void
7620 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7622 GPtrArray* args;
7624 args = mono_aot_split_options (aot_options ? aot_options : "");
7625 for (int i = 0; i < args->len; ++i) {
7626 const char *arg = (const char *)g_ptr_array_index (args, i);
7628 if (str_begins_with (arg, "outfile=")) {
7629 opts->outfile = g_strdup (arg + strlen ("outfile="));
7630 } else if (str_begins_with (arg, "llvm-outfile=")) {
7631 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7632 } else if (str_begins_with (arg, "temp-path=")) {
7633 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7634 } else if (str_begins_with (arg, "save-temps")) {
7635 opts->save_temps = TRUE;
7636 } else if (str_begins_with (arg, "keep-temps")) {
7637 opts->save_temps = TRUE;
7638 } else if (str_begins_with (arg, "write-symbols")) {
7639 opts->write_symbols = TRUE;
7640 } else if (str_begins_with (arg, "no-write-symbols")) {
7641 opts->write_symbols = FALSE;
7642 // Intentionally undocumented -- one-off experiment
7643 } else if (str_begins_with (arg, "metadata-only")) {
7644 opts->metadata_only = TRUE;
7645 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7646 opts->bind_to_runtime_version = TRUE;
7647 } else if (str_begins_with (arg, "full")) {
7648 opts->mode = MONO_AOT_MODE_FULL;
7649 } else if (str_begins_with (arg, "hybrid")) {
7650 opts->mode = MONO_AOT_MODE_HYBRID;
7651 } else if (str_begins_with (arg, "interp")) {
7652 opts->interp = TRUE;
7653 } else if (str_begins_with (arg, "threads=")) {
7654 opts->nthreads = atoi (arg + strlen ("threads="));
7655 } else if (str_begins_with (arg, "static")) {
7656 opts->static_link = TRUE;
7657 opts->no_dlsym = TRUE;
7658 } else if (str_begins_with (arg, "asmonly")) {
7659 opts->asm_only = TRUE;
7660 } else if (str_begins_with (arg, "asmwriter")) {
7661 opts->asm_writer = TRUE;
7662 } else if (str_begins_with (arg, "nodebug")) {
7663 opts->nodebug = TRUE;
7664 } else if (str_begins_with (arg, "dwarfdebug")) {
7665 opts->dwarf_debug = TRUE;
7666 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7667 } else if (str_begins_with (arg, "nopagetrampolines")) {
7668 opts->use_trampolines_page = FALSE;
7669 } else if (str_begins_with (arg, "ntrampolines=")) {
7670 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7671 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7672 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7673 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7674 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7675 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7676 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7677 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7678 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7679 } else if (str_begins_with (arg, "nftnptr-arg-trampolines=")) {
7680 opts->nftnptr_arg_trampolines = atoi (arg + strlen ("nftnptr-arg-trampolines="));
7681 } else if (str_begins_with (arg, "nunbox-arbitrary-trampolines=")) {
7682 opts->nunbox_arbitrary_trampolines = atoi (arg + strlen ("unbox-arbitrary-trampolines="));
7683 } else if (str_begins_with (arg, "tool-prefix=")) {
7684 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7685 } else if (str_begins_with (arg, "ld-flags=")) {
7686 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7687 } else if (str_begins_with (arg, "soft-debug")) {
7688 opts->soft_debug = TRUE;
7689 // Intentionally undocumented x2-- deprecated
7690 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7691 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7692 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7693 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7694 } else if (str_begins_with (arg, "msym-dir=")) {
7695 mini_debug_options.no_seq_points_compact_data = FALSE;
7696 opts->gen_msym_dir = TRUE;
7697 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7698 } else if (str_begins_with (arg, "direct-pinvoke")) {
7699 opts->direct_pinvoke = TRUE;
7700 } else if (str_begins_with (arg, "direct-icalls")) {
7701 opts->direct_icalls = TRUE;
7702 } else if (str_begins_with (arg, "no-direct-calls")) {
7703 opts->no_direct_calls = TRUE;
7704 } else if (str_begins_with (arg, "print-skipped")) {
7705 opts->print_skipped_methods = TRUE;
7706 } else if (str_begins_with (arg, "stats")) {
7707 opts->stats = TRUE;
7708 // Intentionally undocumented-- has no known function other than to debug the compiler
7709 } else if (str_begins_with (arg, "no-instances")) {
7710 opts->no_instances = TRUE;
7711 // Intentionally undocumented x4-- Used for internal debugging of compiler
7712 } else if (str_begins_with (arg, "log-generics")) {
7713 opts->log_generics = TRUE;
7714 } else if (str_begins_with (arg, "log-instances=")) {
7715 opts->log_instances = TRUE;
7716 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7717 } else if (str_begins_with (arg, "log-instances")) {
7718 opts->log_instances = TRUE;
7719 } else if (str_begins_with (arg, "internal-logfile=")) {
7720 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7721 } else if (str_begins_with (arg, "dedup-skip")) {
7722 opts->dedup = TRUE;
7723 } else if (str_begins_with (arg, "dedup-include=")) {
7724 opts->dedup_include = g_strdup (arg + strlen ("dedup-include="));
7725 } else if (str_begins_with (arg, "mtriple=")) {
7726 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7727 } else if (str_begins_with (arg, "llvm-path=")) {
7728 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7729 } else if (!strcmp (arg, "try-llvm")) {
7730 // If we can load LLVM, use it
7731 // Note: if you call this function from anywhere but mono_compile_assembly,
7732 // this will only set the try_llvm attribute and not do the probing / set the
7733 // attribute.
7734 opts->try_llvm = TRUE;
7735 } else if (!strcmp (arg, "llvm")) {
7736 opts->llvm = TRUE;
7737 } else if (str_begins_with (arg, "readonly-value=")) {
7738 add_readonly_value (opts, arg + strlen ("readonly-value="));
7739 } else if (str_begins_with (arg, "info")) {
7740 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7741 exit (0);
7742 // Intentionally undocumented: Used for precise stack maps, which are not available yet
7743 } else if (str_begins_with (arg, "gc-maps")) {
7744 mini_gc_enable_gc_maps_for_aot ();
7745 // Intentionally undocumented: Used for internal debugging
7746 } else if (str_begins_with (arg, "dump")) {
7747 opts->dump_json = TRUE;
7748 } else if (str_begins_with (arg, "llvmonly")) {
7749 opts->mode = MONO_AOT_MODE_FULL;
7750 opts->llvm = TRUE;
7751 opts->llvm_only = TRUE;
7752 } else if (str_begins_with (arg, "data-outfile=")) {
7753 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7754 } else if (str_begins_with (arg, "profile=")) {
7755 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7756 } else if (!strcmp (arg, "profile-only")) {
7757 opts->profile_only = TRUE;
7758 } else if (!strcmp (arg, "verbose")) {
7759 opts->verbose = TRUE;
7760 } else if (str_begins_with (arg, "llvmopts=")){
7761 opts->llvm_opts = g_strdup (arg + strlen ("llvmopts="));
7762 } else if (str_begins_with (arg, "llvmllc=")){
7763 opts->llvm_llc = g_strdup (arg + strlen ("llvmllc="));
7764 } else if (!strcmp (arg, "deterministic")) {
7765 opts->deterministic = TRUE;
7766 } else if (!strcmp (arg, "no-opt")) {
7767 opts->no_opt = TRUE;
7768 } else if (str_begins_with (arg, "clangxx=")) {
7769 opts->clangxx = g_strdup (arg + strlen ("clangxx="));;
7770 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7771 printf ("Supported options for --aot:\n");
7772 printf (" asmonly\n");
7773 printf (" bind-to-runtime-version\n");
7774 printf (" bitcode\n");
7775 printf (" data-outfile=\n");
7776 printf (" direct-icalls\n");
7777 printf (" direct-pinvoke\n");
7778 printf (" dwarfdebug\n");
7779 printf (" full\n");
7780 printf (" hybrid\n");
7781 printf (" info\n");
7782 printf (" keep-temps\n");
7783 printf (" llvm\n");
7784 printf (" llvmonly\n");
7785 printf (" llvm-outfile=\n");
7786 printf (" llvm-path=\n");
7787 printf (" msym-dir=\n");
7788 printf (" mtriple\n");
7789 printf (" nimt-trampolines=\n");
7790 printf (" nodebug\n");
7791 printf (" no-direct-calls\n");
7792 printf (" no-write-symbols\n");
7793 printf (" nrgctx-trampolines=\n");
7794 printf (" nrgctx-fetch-trampolines=\n");
7795 printf (" ngsharedvt-trampolines=\n");
7796 printf (" nftnptr-arg-trampolines=\n");
7797 printf (" nunbox-arbitrary-trampolines=\n");
7798 printf (" ntrampolines=\n");
7799 printf (" outfile=\n");
7800 printf (" profile=\n");
7801 printf (" profile-only\n");
7802 printf (" print-skipped-methods\n");
7803 printf (" readonly-value=\n");
7804 printf (" save-temps\n");
7805 printf (" soft-debug\n");
7806 printf (" static\n");
7807 printf (" stats\n");
7808 printf (" temp-path=\n");
7809 printf (" tool-prefix=\n");
7810 printf (" threads=\n");
7811 printf (" write-symbols\n");
7812 printf (" verbose\n");
7813 printf (" no-opt\n");
7814 printf (" llvmopts=\n");
7815 printf (" llvmllc=\n");
7816 printf (" clangxx=\n");
7817 printf (" help/?\n");
7818 exit (0);
7819 } else {
7820 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7821 exit (1);
7824 g_free ((gpointer) arg);
7827 if (opts->use_trampolines_page) {
7828 opts->ntrampolines = 0;
7829 opts->nrgctx_trampolines = 0;
7830 opts->nimt_trampolines = 0;
7831 opts->ngsharedvt_arg_trampolines = 0;
7832 opts->nftnptr_arg_trampolines = 0;
7833 opts->nunbox_arbitrary_trampolines = 0;
7836 g_ptr_array_free (args, /*free_seg=*/TRUE);
7839 static void
7840 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7842 MonoMethod *method = (MonoMethod*)key;
7843 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7844 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7845 MonoJumpInfoToken *new_ji;
7847 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7848 new_ji->image = ji->image;
7849 new_ji->token = ji->token;
7850 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7853 static gboolean
7854 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7856 if (m_class_get_type_token (klass))
7857 return TRUE;
7858 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))
7859 return TRUE;
7860 if (m_class_get_rank (klass))
7861 return can_encode_class (acfg, m_class_get_element_class (klass));
7862 return FALSE;
7865 static gboolean
7866 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7868 if (method->wrapper_type) {
7869 switch (method->wrapper_type) {
7870 case MONO_WRAPPER_NONE:
7871 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7872 case MONO_WRAPPER_XDOMAIN_INVOKE:
7873 case MONO_WRAPPER_STFLD:
7874 case MONO_WRAPPER_LDFLD:
7875 case MONO_WRAPPER_LDFLDA:
7876 case MONO_WRAPPER_STELEMREF:
7877 case MONO_WRAPPER_PROXY_ISINST:
7878 case MONO_WRAPPER_ALLOC:
7879 case MONO_WRAPPER_REMOTING_INVOKE:
7880 case MONO_WRAPPER_UNKNOWN:
7881 case MONO_WRAPPER_WRITE_BARRIER:
7882 case MONO_WRAPPER_DELEGATE_INVOKE:
7883 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7884 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7885 case MONO_WRAPPER_SYNCHRONIZED:
7886 case MONO_WRAPPER_MANAGED_TO_NATIVE:
7887 break;
7888 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7889 case MONO_WRAPPER_CASTCLASS: {
7890 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7892 if (info)
7893 return TRUE;
7894 else
7895 return FALSE;
7896 break;
7898 default:
7899 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7900 return FALSE;
7902 } else {
7903 if (!method->token) {
7904 /* The method is part of a constructed type like Int[,].Set (). */
7905 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7906 if (m_class_get_rank (method->klass))
7907 return TRUE;
7908 return FALSE;
7912 return TRUE;
7915 static gboolean
7916 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7918 switch (patch_info->type) {
7919 case MONO_PATCH_INFO_METHOD:
7920 case MONO_PATCH_INFO_METHODCONST:
7921 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7922 MonoMethod *method = patch_info->data.method;
7924 return can_encode_method (acfg, method);
7926 case MONO_PATCH_INFO_VTABLE:
7927 case MONO_PATCH_INFO_CLASS:
7928 case MONO_PATCH_INFO_IID:
7929 case MONO_PATCH_INFO_ADJUSTED_IID:
7930 if (!can_encode_class (acfg, patch_info->data.klass)) {
7931 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
7932 return FALSE;
7934 break;
7935 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7936 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7937 //printf ("Skip: %s\n", mono_type_full_name (m_class_get_byval_arg (patch_info->data.klass)));
7938 return FALSE;
7940 break;
7942 case MONO_PATCH_INFO_RGCTX_FETCH:
7943 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7944 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7946 if (!can_encode_method (acfg, entry->method))
7947 return FALSE;
7948 if (!can_encode_patch (acfg, entry->data))
7949 return FALSE;
7950 break;
7952 default:
7953 break;
7956 return TRUE;
7959 static gboolean
7960 is_concrete_type (MonoType *t)
7962 MonoClass *klass;
7963 int i;
7965 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7966 return FALSE;
7967 if (t->type == MONO_TYPE_GENERICINST) {
7968 MonoGenericContext *orig_ctx;
7969 MonoGenericInst *inst;
7970 MonoType *arg;
7972 if (!MONO_TYPE_ISSTRUCT (t))
7973 return TRUE;
7974 klass = mono_class_from_mono_type_internal (t);
7975 orig_ctx = &mono_class_get_generic_class (klass)->context;
7977 inst = orig_ctx->class_inst;
7978 if (inst) {
7979 for (i = 0; i < inst->type_argc; ++i) {
7980 arg = mini_get_underlying_type (inst->type_argv [i]);
7981 if (!is_concrete_type (arg))
7982 return FALSE;
7985 inst = orig_ctx->method_inst;
7986 if (inst) {
7987 for (i = 0; i < inst->type_argc; ++i) {
7988 arg = mini_get_underlying_type (inst->type_argv [i]);
7989 if (!is_concrete_type (arg))
7990 return FALSE;
7994 return TRUE;
7997 /* LOCKING: Assumes the loader lock is held */
7998 static void
7999 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out, gboolean interp_in)
8001 MonoMethod *wrapper;
8002 gboolean concrete = TRUE;
8003 gboolean add_in = gsharedvt_in;
8004 gboolean add_out = gsharedvt_out;
8006 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
8007 add_in = FALSE;
8008 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
8009 add_out = FALSE;
8011 if (!add_in && !add_out)
8012 return;
8014 if (mini_is_gsharedvt_variable_signature (sig))
8015 return;
8017 if (add_in)
8018 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
8019 if (add_out)
8020 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
8022 if (sig->has_type_parameters) {
8023 /* For signatures created during generic sharing, convert them to a concrete signature if possible */
8024 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
8025 int i;
8027 //printf ("%s\n", mono_signature_full_name (sig));
8029 if (sig->ret->byref)
8030 copy->ret = m_class_get_this_arg (mono_defaults.int_class);
8031 else
8032 copy->ret = mini_get_underlying_type (sig->ret);
8033 if (!is_concrete_type (copy->ret))
8034 concrete = FALSE;
8035 for (i = 0; i < sig->param_count; ++i) {
8036 if (sig->params [i]->byref) {
8037 MonoType *t = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->params [i]));
8038 t = mini_get_underlying_type (t);
8039 copy->params [i] = m_class_get_this_arg (mono_class_from_mono_type_internal (t));
8040 } else {
8041 copy->params [i] = mini_get_underlying_type (sig->params [i]);
8043 if (!is_concrete_type (copy->params [i]))
8044 concrete = FALSE;
8046 copy->has_type_parameters = 0;
8047 if (!concrete)
8048 return;
8049 sig = copy;
8052 //printf ("%s\n", mono_signature_full_name (sig));
8054 if (gsharedvt_in) {
8055 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
8056 add_extra_method (acfg, wrapper);
8058 if (gsharedvt_out) {
8059 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
8060 add_extra_method (acfg, wrapper);
8062 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
8063 if (interp_in) {
8064 wrapper = mini_get_interp_in_wrapper (sig);
8065 add_extra_method (acfg, wrapper);
8066 //printf ("X: %s\n", mono_method_full_name (wrapper, 1));
8068 #endif
8072 * compile_method:
8074 * AOT compile a given method.
8075 * This function might be called by multiple threads, so it must be thread-safe.
8077 static void
8078 compile_method (MonoAotCompile *acfg, MonoMethod *method)
8080 MonoCompile *cfg;
8081 MonoJumpInfo *patch_info;
8082 gboolean skip;
8083 int index, depth;
8084 MonoMethod *wrapped;
8085 GTimer *jit_timer;
8086 JitFlags flags;
8088 if (acfg->aot_opts.metadata_only)
8089 return;
8091 mono_acfg_lock (acfg);
8092 index = get_method_index (acfg, method);
8093 mono_acfg_unlock (acfg);
8095 /* fixme: maybe we can also precompile wrapper methods */
8096 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8097 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8098 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
8099 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
8100 return;
8103 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
8104 return;
8106 wrapped = mono_marshal_method_from_wrapper (method);
8107 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
8108 // FIXME: The wrapper should be generic too, but it is not
8109 return;
8111 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
8112 return;
8114 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
8115 return;
8117 if (method->is_generic || mono_class_is_gtd (method->klass))
8118 /* generic method which has no ref instantiation */
8119 return;
8121 mono_atomic_inc_i32 (&acfg->stats.mcount);
8123 #if 0
8124 if (method->is_generic || mono_class_is_gtd (method->klass)) {
8125 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8126 return;
8128 #endif
8130 //acfg->aot_opts.print_skipped_methods = TRUE;
8133 * Since these methods are the only ones which are compiled with
8134 * AOT support, and they are not used by runtime startup/shutdown code,
8135 * the runtime will not see AOT methods during AOT compilation,so it
8136 * does not need to support them by creating a fake GOT etc.
8138 flags = JIT_FLAG_AOT;
8139 if (mono_aot_mode_is_full (&acfg->aot_opts))
8140 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
8141 if (acfg->llvm)
8142 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
8143 if (acfg->aot_opts.llvm_only)
8144 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
8145 if (acfg->aot_opts.no_direct_calls)
8146 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
8147 if (acfg->aot_opts.direct_pinvoke)
8148 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
8150 jit_timer = mono_time_track_start ();
8151 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
8152 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
8154 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
8155 if (acfg->aot_opts.print_skipped_methods)
8156 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
8157 mono_atomic_inc_i32 (&acfg->stats.genericcount);
8158 return;
8160 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
8161 /* Some instances cannot be JITted due to constraints etc. */
8162 if (!method->is_inflated)
8163 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));
8164 /* Let the exception happen at runtime */
8165 return;
8168 if (cfg->disable_aot) {
8169 if (acfg->aot_opts.print_skipped_methods)
8170 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
8171 mono_atomic_inc_i32 (&acfg->stats.ocount);
8172 return;
8174 cfg->method_index = index;
8176 /* Nullify patches which need no aot processing */
8177 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8178 switch (patch_info->type) {
8179 case MONO_PATCH_INFO_LABEL:
8180 case MONO_PATCH_INFO_BB:
8181 patch_info->type = MONO_PATCH_INFO_NONE;
8182 break;
8183 default:
8184 break;
8188 /* Collect method->token associations from the cfg */
8189 mono_acfg_lock (acfg);
8190 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
8191 mono_acfg_unlock (acfg);
8192 g_hash_table_destroy (cfg->token_info_hash);
8193 cfg->token_info_hash = NULL;
8196 * Check for absolute addresses.
8198 skip = FALSE;
8199 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8200 switch (patch_info->type) {
8201 case MONO_PATCH_INFO_ABS:
8202 /* unable to handle this */
8203 skip = TRUE;
8204 break;
8205 default:
8206 break;
8210 if (skip) {
8211 if (acfg->aot_opts.print_skipped_methods)
8212 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
8213 mono_atomic_inc_i32 (&acfg->stats.abscount);
8214 return;
8217 /* Lock for the rest of the code */
8218 mono_acfg_lock (acfg);
8220 if (cfg->gsharedvt)
8221 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
8222 else if (cfg->gshared)
8223 acfg->stats.method_categories [METHOD_CAT_INST] ++;
8224 else if (cfg->method->wrapper_type)
8225 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
8226 else
8227 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
8230 * Check for methods/klasses we can't encode.
8232 skip = FALSE;
8233 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8234 if (!can_encode_patch (acfg, patch_info))
8235 skip = TRUE;
8238 if (skip) {
8239 if (acfg->aot_opts.print_skipped_methods)
8240 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
8241 acfg->stats.ocount++;
8242 mono_acfg_unlock (acfg);
8243 return;
8246 if (!cfg->compile_llvm)
8247 acfg->has_jitted_code = TRUE;
8249 if (method->is_inflated && acfg->aot_opts.log_instances) {
8250 if (acfg->instances_logfile)
8251 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8252 else
8253 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
8256 /* Adds generic instances referenced by this method */
8258 * The depth is used to avoid infinite loops when generic virtual recursion is
8259 * encountered.
8261 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
8262 if (!acfg->aot_opts.no_instances && depth < 32 && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8263 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8264 switch (patch_info->type) {
8265 case MONO_PATCH_INFO_RGCTX_FETCH:
8266 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
8267 case MONO_PATCH_INFO_METHOD:
8268 case MONO_PATCH_INFO_METHOD_RGCTX: {
8269 MonoMethod *m = NULL;
8271 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
8272 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
8274 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
8275 m = e->data->data.method;
8276 } else {
8277 m = patch_info->data.method;
8280 if (!m)
8281 break;
8282 if (m->is_inflated && (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))) {
8283 if (!(mono_class_generic_sharing_enabled (m->klass) &&
8284 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
8285 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
8286 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8287 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
8288 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
8289 } else {
8290 add_extra_method_with_depth (acfg, m, depth + 1);
8291 add_types_from_method_header (acfg, m);
8294 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
8296 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
8297 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
8299 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
8300 add_extra_method_with_depth (acfg, m, depth + 1);
8302 break;
8304 case MONO_PATCH_INFO_VTABLE: {
8305 MonoClass *klass = patch_info->data.klass;
8307 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
8308 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
8309 break;
8311 case MONO_PATCH_INFO_SFLDA: {
8312 MonoClass *klass = patch_info->data.field->parent;
8314 /* The .cctor needs to run at runtime. */
8315 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))
8316 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
8317 break;
8319 default:
8320 break;
8325 /* Determine whenever the method has GOT slots */
8326 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8327 switch (patch_info->type) {
8328 case MONO_PATCH_INFO_GOT_OFFSET:
8329 case MONO_PATCH_INFO_NONE:
8330 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
8331 case MONO_PATCH_INFO_GC_NURSERY_START:
8332 case MONO_PATCH_INFO_GC_NURSERY_BITS:
8333 break;
8334 case MONO_PATCH_INFO_IMAGE:
8335 /* The assembly is stored in GOT slot 0 */
8336 if (patch_info->data.image != acfg->image)
8337 cfg->has_got_slots = TRUE;
8338 break;
8339 default:
8340 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
8341 cfg->has_got_slots = TRUE;
8342 break;
8346 if (!cfg->has_got_slots)
8347 mono_atomic_inc_i32 (&acfg->stats.methods_without_got_slots);
8349 /* Add gsharedvt wrappers for signatures used by the method */
8350 if (acfg->aot_opts.llvm_only) {
8351 GSList *l;
8353 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8354 /* These only need out wrappers */
8355 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, FALSE);
8357 for (l = cfg->signatures; l; l = l->next) {
8358 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
8360 /* These only need in wrappers */
8361 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE, FALSE);
8363 } else if (mono_aot_mode_is_full (&acfg->aot_opts) && mono_aot_mode_is_interp (&acfg->aot_opts)) {
8364 /* The interpreter uses these wrappers to call aot-ed code */
8365 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8366 add_gsharedvt_wrappers (acfg, mono_method_signature_internal (cfg->method), FALSE, TRUE, TRUE);
8370 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
8372 /* Make a copy of the patch info which is in the mempool */
8374 MonoJumpInfo *patches = NULL, *patches_end = NULL;
8376 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8377 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
8379 if (!patches)
8380 patches = new_patch_info;
8381 else
8382 patches_end->next = new_patch_info;
8383 patches_end = new_patch_info;
8385 cfg->patch_info = patches;
8387 /* Make a copy of the unwind info */
8389 GSList *l, *unwind_ops;
8390 MonoUnwindOp *op;
8392 unwind_ops = NULL;
8393 for (l = cfg->unwind_ops; l; l = l->next) {
8394 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
8395 memcpy (op, l->data, sizeof (MonoUnwindOp));
8396 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
8398 cfg->unwind_ops = g_slist_reverse (unwind_ops);
8400 /* Make a copy of the argument/local info */
8402 ERROR_DECL (error);
8403 MonoInst **args, **locals;
8404 MonoMethodSignature *sig;
8405 MonoMethodHeader *header;
8406 int i;
8408 sig = mono_method_signature_internal (method);
8409 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
8410 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
8411 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8412 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
8414 cfg->args = args;
8416 header = mono_method_get_header_checked (method, error);
8417 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8418 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
8419 for (i = 0; i < header->num_locals; ++i) {
8420 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
8421 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
8423 mono_metadata_free_mh (header);
8424 cfg->locals = locals;
8427 /* Free some fields used by cfg to conserve memory */
8428 mono_empty_compile (cfg);
8430 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
8432 while (index >= acfg->cfgs_size) {
8433 MonoCompile **new_cfgs;
8434 int new_size;
8436 new_size = acfg->cfgs_size * 2;
8437 new_cfgs = g_new0 (MonoCompile*, new_size);
8438 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
8439 g_free (acfg->cfgs);
8440 acfg->cfgs = new_cfgs;
8441 acfg->cfgs_size = new_size;
8443 acfg->cfgs [index] = cfg;
8445 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
8447 /* Update global stats while holding a lock. */
8448 mono_update_jit_stats (cfg);
8451 if (cfg->orig_method->wrapper_type)
8452 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
8455 mono_acfg_unlock (acfg);
8457 mono_atomic_inc_i32 (&acfg->stats.ccount);
8460 static mono_thread_start_return_t WINAPI
8461 compile_thread_main (gpointer user_data)
8463 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
8464 GPtrArray *methods = ((GPtrArray **)user_data) [1];
8465 int i;
8467 ERROR_DECL (error);
8468 MonoInternalThread *internal = mono_thread_internal_current ();
8469 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", error);
8470 mono_error_assert_ok (error);
8471 mono_thread_set_name_internal (internal, str, TRUE, FALSE, error);
8472 mono_error_assert_ok (error);
8474 for (i = 0; i < methods->len; ++i)
8475 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
8477 return 0;
8480 /* Used by the LLVM backend */
8481 guint32
8482 mono_aot_get_got_offset (MonoJumpInfo *ji)
8484 return get_got_offset (llvm_acfg, TRUE, ji);
8488 * mono_aot_is_shared_got_offset:
8490 * Return whenever OFFSET refers to a GOT slot which is preinitialized
8491 * when the AOT image is loaded.
8493 gboolean
8494 mono_aot_is_shared_got_offset (int offset)
8496 return offset < llvm_acfg->nshared_got_entries;
8499 char*
8500 mono_aot_get_method_name (MonoCompile *cfg)
8502 if (llvm_acfg->aot_opts.static_link)
8503 /* Include the assembly name too to avoid duplicate symbol errors */
8504 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
8505 else
8506 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
8509 static gboolean
8510 append_mangled_type (GString *s, MonoType *t)
8512 if (t->byref)
8513 g_string_append_printf (s, "b");
8514 switch (t->type) {
8515 case MONO_TYPE_VOID:
8516 g_string_append_printf (s, "void_");
8517 break;
8518 case MONO_TYPE_I1:
8519 g_string_append_printf (s, "i1");
8520 break;
8521 case MONO_TYPE_U1:
8522 g_string_append_printf (s, "u1");
8523 break;
8524 case MONO_TYPE_I2:
8525 g_string_append_printf (s, "i2");
8526 break;
8527 case MONO_TYPE_U2:
8528 g_string_append_printf (s, "u2");
8529 break;
8530 case MONO_TYPE_I4:
8531 g_string_append_printf (s, "i4");
8532 break;
8533 case MONO_TYPE_U4:
8534 g_string_append_printf (s, "u4");
8535 break;
8536 case MONO_TYPE_I8:
8537 g_string_append_printf (s, "i8");
8538 break;
8539 case MONO_TYPE_U8:
8540 g_string_append_printf (s, "u8");
8541 break;
8542 case MONO_TYPE_I:
8543 g_string_append_printf (s, "ii");
8544 break;
8545 case MONO_TYPE_U:
8546 g_string_append_printf (s, "ui");
8547 break;
8548 case MONO_TYPE_R4:
8549 g_string_append_printf (s, "fl");
8550 break;
8551 case MONO_TYPE_R8:
8552 g_string_append_printf (s, "do");
8553 break;
8554 default: {
8555 char *fullname = mono_type_full_name (t);
8556 GString *temp;
8557 char *temps;
8558 int i, len;
8561 * Have to create a mangled name which is:
8562 * - a valid symbol
8563 * - unique
8565 temp = g_string_new ("");
8566 len = strlen (fullname);
8567 for (i = 0; i < len; ++i) {
8568 char c = fullname [i];
8569 if (isalnum (c)) {
8570 g_string_append_c (temp, c);
8571 } else if (c == '_') {
8572 g_string_append_c (temp, '_');
8573 g_string_append_c (temp, '_');
8574 } else {
8575 g_string_append_c (temp, '_');
8576 g_string_append_printf (temp, "%x", (int)c);
8579 temps = g_string_free (temp, FALSE);
8580 /* Include the length to avoid different length type names aliasing each other */
8581 g_string_append_printf (s, "cl%x_%s_", (int)strlen (temps), temps);
8582 g_free (temps);
8585 if (t->attrs)
8586 g_string_append_printf (s, "_attrs_%d", t->attrs);
8587 return TRUE;
8590 static gboolean
8591 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8593 int i;
8594 gboolean supported;
8596 supported = append_mangled_type (s, sig->ret);
8597 if (!supported)
8598 return FALSE;
8599 if (sig->hasthis)
8600 g_string_append_printf (s, "this_");
8601 if (sig->pinvoke)
8602 g_string_append_printf (s, "pinvoke_");
8603 for (i = 0; i < sig->param_count; ++i) {
8604 supported = append_mangled_type (s, sig->params [i]);
8605 if (!supported)
8606 return FALSE;
8609 return TRUE;
8612 static void
8613 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8615 const char *label;
8617 switch (wrapper_type) {
8618 case MONO_WRAPPER_REMOTING_INVOKE:
8619 label = "remoting_invoke";
8620 break;
8621 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8622 label = "remoting_invoke_check";
8623 break;
8624 case MONO_WRAPPER_XDOMAIN_INVOKE:
8625 label = "remoting_invoke_xdomain";
8626 break;
8627 case MONO_WRAPPER_PROXY_ISINST:
8628 label = "proxy_isinst";
8629 break;
8630 case MONO_WRAPPER_LDFLD:
8631 label = "ldfld";
8632 break;
8633 case MONO_WRAPPER_LDFLDA:
8634 label = "ldflda";
8635 break;
8636 case MONO_WRAPPER_STFLD:
8637 label = "stfld";
8638 break;
8639 case MONO_WRAPPER_ALLOC:
8640 label = "alloc";
8641 break;
8642 case MONO_WRAPPER_WRITE_BARRIER:
8643 label = "write_barrier";
8644 break;
8645 case MONO_WRAPPER_STELEMREF:
8646 label = "stelemref";
8647 break;
8648 case MONO_WRAPPER_UNKNOWN:
8649 label = "unknown";
8650 break;
8651 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8652 label = "man2native";
8653 break;
8654 case MONO_WRAPPER_SYNCHRONIZED:
8655 label = "synch";
8656 break;
8657 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8658 label = "man2man";
8659 break;
8660 case MONO_WRAPPER_CASTCLASS:
8661 label = "castclass";
8662 break;
8663 case MONO_WRAPPER_RUNTIME_INVOKE:
8664 label = "run_invoke";
8665 break;
8666 case MONO_WRAPPER_DELEGATE_INVOKE:
8667 label = "del_inv";
8668 break;
8669 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8670 label = "del_beg_inv";
8671 break;
8672 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8673 label = "del_end_inv";
8674 break;
8675 case MONO_WRAPPER_NATIVE_TO_MANAGED:
8676 label = "native2man";
8677 break;
8678 default:
8679 g_assert_not_reached ();
8682 g_string_append_printf (s, "%s_", label);
8685 static void
8686 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
8688 const char *label;
8690 switch (subtype)
8692 case WRAPPER_SUBTYPE_NONE:
8693 return;
8694 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8695 label = "elem_addr";
8696 break;
8697 case WRAPPER_SUBTYPE_STRING_CTOR:
8698 label = "str_ctor";
8699 break;
8700 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8701 label = "virt_stelem";
8702 break;
8703 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8704 label = "fast_mon_enter";
8705 break;
8706 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8707 label = "fast_mon_enter_4";
8708 break;
8709 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8710 label = "fast_monitor_exit";
8711 break;
8712 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8713 label = "ptr2struct";
8714 break;
8715 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8716 label = "struct2ptr";
8717 break;
8718 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8719 label = "castclass_w_cache";
8720 break;
8721 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8722 label = "isinst_w_cache";
8723 break;
8724 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8725 label = "run_inv_norm";
8726 break;
8727 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8728 label = "run_inv_dyn";
8729 break;
8730 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8731 label = "run_inv_dir";
8732 break;
8733 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8734 label = "run_inv_vir";
8735 break;
8736 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8737 label = "icall";
8738 break;
8739 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8740 label = "native_func_aot";
8741 break;
8742 case WRAPPER_SUBTYPE_PINVOKE:
8743 label = "pinvoke";
8744 break;
8745 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8746 label = "synch_inner";
8747 break;
8748 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8749 label = "gshared_in";
8750 break;
8751 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8752 label = "gshared_out";
8753 break;
8754 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8755 label = "array_acc";
8756 break;
8757 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8758 label = "generic_arry_help";
8759 break;
8760 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8761 label = "del_inv_virt";
8762 break;
8763 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8764 label = "del_inv_bound";
8765 break;
8766 case WRAPPER_SUBTYPE_INTERP_IN:
8767 label = "interp_in";
8768 break;
8769 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8770 label = "gsharedvt_in_sig";
8771 break;
8772 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8773 label = "gsharedvt_out_sig";
8774 break;
8775 default:
8776 g_assert_not_reached ();
8779 g_string_append_printf (s, "%s_", label);
8782 static char *
8783 sanitize_mangled_string (const char *input)
8785 GString *s = g_string_new ("");
8787 for (int i=0; input [i] != '\0'; i++) {
8788 char c = input [i];
8789 switch (c) {
8790 case '.':
8791 g_string_append (s, "_dot_");
8792 break;
8793 case ' ':
8794 g_string_append (s, "_");
8795 break;
8796 case '`':
8797 g_string_append (s, "_bt_");
8798 break;
8799 case '<':
8800 g_string_append (s, "_le_");
8801 break;
8802 case '>':
8803 g_string_append (s, "_gt_");
8804 break;
8805 case '/':
8806 g_string_append (s, "_sl_");
8807 break;
8808 case '[':
8809 g_string_append (s, "_lbrack_");
8810 break;
8811 case ']':
8812 g_string_append (s, "_rbrack_");
8813 break;
8814 case '(':
8815 g_string_append (s, "_lparen_");
8816 break;
8817 case '-':
8818 g_string_append (s, "_dash_");
8819 break;
8820 case ')':
8821 g_string_append (s, "_rparen_");
8822 break;
8823 case ',':
8824 g_string_append (s, "_comma_");
8825 break;
8826 case ':':
8827 g_string_append (s, "_colon_");
8828 break;
8829 default:
8830 g_string_append_c (s, c);
8834 return g_string_free (s, FALSE);
8837 static gboolean
8838 append_mangled_klass (GString *s, MonoClass *klass)
8840 char *klass_desc = mono_class_full_name (klass);
8841 g_string_append_printf (s, "_%s_%s_", m_class_get_name_space (klass), klass_desc);
8842 g_free (klass_desc);
8844 // Success
8845 return TRUE;
8848 static gboolean
8849 append_mangled_method (GString *s, MonoMethod *method);
8851 static gboolean
8852 append_mangled_wrapper (GString *s, MonoMethod *method)
8854 gboolean success = TRUE;
8855 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8856 g_string_append_printf (s, "wrapper_");
8857 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
8859 append_mangled_wrapper_type (s, method->wrapper_type);
8861 switch (method->wrapper_type) {
8862 case MONO_WRAPPER_REMOTING_INVOKE:
8863 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8864 case MONO_WRAPPER_XDOMAIN_INVOKE: {
8865 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8866 g_assert (m);
8867 success = success && append_mangled_method (s, m);
8868 break;
8870 case MONO_WRAPPER_PROXY_ISINST:
8871 case MONO_WRAPPER_LDFLD:
8872 case MONO_WRAPPER_LDFLDA:
8873 case MONO_WRAPPER_STFLD: {
8874 g_assert (info);
8875 success = success && append_mangled_klass (s, info->d.proxy.klass);
8876 break;
8878 case MONO_WRAPPER_ALLOC: {
8879 /* The GC name is saved once in MonoAotFileInfo */
8880 g_assert (info->d.alloc.alloc_type != -1);
8881 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8882 // SlowAlloc, etc
8883 g_string_append_printf (s, "%s_", method->name);
8884 break;
8886 case MONO_WRAPPER_WRITE_BARRIER: {
8887 g_string_append_printf (s, "%s_", method->name);
8888 break;
8890 case MONO_WRAPPER_STELEMREF: {
8891 append_mangled_wrapper_subtype (s, info->subtype);
8892 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8893 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8894 break;
8896 case MONO_WRAPPER_UNKNOWN: {
8897 append_mangled_wrapper_subtype (s, info->subtype);
8898 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8899 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8900 success = success && append_mangled_klass (s, method->klass);
8901 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8902 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8903 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8904 success = success && append_mangled_method (s, info->d.array_accessor.method);
8905 else if (info->subtype == WRAPPER_SUBTYPE_INTERP_IN)
8906 append_mangled_signature (s, info->d.interp_in.sig);
8907 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
8908 append_mangled_signature (s, info->d.gsharedvt.sig);
8909 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8910 append_mangled_signature (s, info->d.gsharedvt.sig);
8911 break;
8913 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8914 append_mangled_wrapper_subtype (s, info->subtype);
8915 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8916 g_string_append_printf (s, "%s", method->name);
8917 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8918 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8919 } else {
8920 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8921 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8923 break;
8925 case MONO_WRAPPER_SYNCHRONIZED: {
8926 MonoMethod *m;
8928 m = mono_marshal_method_from_wrapper (method);
8929 g_assert (m);
8930 g_assert (m != method);
8931 success = success && append_mangled_method (s, m);
8932 break;
8934 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8935 append_mangled_wrapper_subtype (s, info->subtype);
8937 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8938 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8939 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8940 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8941 success = success && append_mangled_method (s, info->d.string_ctor.method);
8942 } else if (info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
8943 success = success && append_mangled_method (s, info->d.generic_array_helper.method);
8944 } else {
8945 success = FALSE;
8947 break;
8949 case MONO_WRAPPER_CASTCLASS: {
8950 append_mangled_wrapper_subtype (s, info->subtype);
8951 break;
8953 case MONO_WRAPPER_RUNTIME_INVOKE: {
8954 append_mangled_wrapper_subtype (s, info->subtype);
8955 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
8956 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
8957 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
8958 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
8959 break;
8961 case MONO_WRAPPER_DELEGATE_INVOKE:
8962 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8963 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
8964 if (method->is_inflated) {
8965 /* These wrappers are identified by their class */
8966 g_string_append_printf (s, "i_");
8967 success = success && append_mangled_klass (s, method->klass);
8968 } else {
8969 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8971 g_string_append_printf (s, "u_");
8972 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8973 append_mangled_wrapper_subtype (s, info->subtype);
8974 g_string_append_printf (s, "u_sigstart");
8976 break;
8978 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
8979 g_assert (info);
8980 success = success && append_mangled_method (s, info->d.native_to_managed.method);
8981 success = success && append_mangled_klass (s, method->klass);
8982 break;
8984 default:
8985 g_assert_not_reached ();
8987 return success && append_mangled_signature (s, mono_method_signature_internal (method));
8990 static void
8991 append_mangled_ginst (GString *str, MonoGenericInst *ginst)
8993 int i;
8995 for (i = 0; i < ginst->type_argc; ++i) {
8996 if (i > 0)
8997 g_string_append (str, ", ");
8998 MonoType *type = ginst->type_argv [i];
8999 switch (type->type) {
9000 case MONO_TYPE_VAR:
9001 case MONO_TYPE_MVAR: {
9002 MonoType *constraint = NULL;
9003 if (type->data.generic_param)
9004 constraint = type->data.generic_param->gshared_constraint;
9005 if (constraint) {
9006 g_assert (constraint->type != MONO_TYPE_VAR && constraint->type != MONO_TYPE_MVAR);
9007 g_string_append (str, "gshared:");
9008 mono_type_get_desc (str, constraint, TRUE);
9009 break;
9011 // Else falls through to common case
9013 default:
9014 mono_type_get_desc (str, type, TRUE);
9019 static void
9020 append_mangled_context (GString *str, MonoGenericContext *context)
9022 GString *res = g_string_new ("");
9024 g_string_append_printf (res, "gens_");
9025 g_string_append (res, "00");
9027 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
9028 good = good || (context->method_inst && context->method_inst->type_argc > 0);
9029 g_assert (good);
9031 if (context->class_inst)
9032 append_mangled_ginst (res, context->class_inst);
9033 if (context->method_inst) {
9034 if (context->class_inst)
9035 g_string_append (res, "11");
9036 append_mangled_ginst (res, context->method_inst);
9038 g_string_append_printf (str, "gens_%s", res->str);
9039 g_free (res);
9042 static gboolean
9043 append_mangled_method (GString *s, MonoMethod *method)
9045 if (method->wrapper_type)
9046 return append_mangled_wrapper (s, method);
9048 if (method->is_inflated) {
9049 g_string_append_printf (s, "inflated_");
9050 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
9051 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
9053 append_mangled_context (s, &imethod->context);
9054 g_string_append_printf (s, "_declared_by_");
9055 append_mangled_method (s, imethod->declaring);
9056 } else if (method->is_generic) {
9057 g_string_append_printf (s, "%s_", m_class_get_image (method->klass)->assembly->aname.name);
9059 g_string_append_printf (s, "generic_");
9060 append_mangled_klass (s, method->klass);
9061 g_string_append_printf (s, "_%s_", method->name);
9063 MonoGenericContainer *container = mono_method_get_generic_container (method);
9064 g_string_append_printf (s, "_");
9065 append_mangled_context (s, &container->context);
9067 return append_mangled_signature (s, mono_method_signature_internal (method));
9068 } else {
9069 g_string_append_printf (s, "_");
9070 append_mangled_klass (s, method->klass);
9071 g_string_append_printf (s, "_%s_", method->name);
9072 if (!append_mangled_signature (s, mono_method_signature_internal (method))) {
9073 g_string_free (s, TRUE);
9074 return FALSE;
9078 return TRUE;
9082 * mono_aot_get_mangled_method_name:
9084 * Return a unique mangled name for METHOD, or NULL.
9086 char*
9087 mono_aot_get_mangled_method_name (MonoMethod *method)
9089 // FIXME: use static cache (mempool?)
9090 // We call this a *lot*
9092 GString *s = g_string_new ("aot_");
9093 if (!append_mangled_method (s, method)) {
9094 g_string_free (s, TRUE);
9095 return NULL;
9096 } else {
9097 char *out = g_string_free (s, FALSE);
9098 // Scrub method and class names
9099 char *cleaned = sanitize_mangled_string (out);
9100 g_free (out);
9101 return cleaned;
9105 gboolean
9106 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
9108 return is_direct_callable (llvm_acfg, NULL, patch_info);
9111 void
9112 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
9114 MonoPltEntry *plt_entry;
9116 plt_entry = get_plt_entry (llvm_acfg, patch_info);
9117 plt_entry->llvm_used = FALSE;
9120 char*
9121 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
9123 const char *sym = NULL;
9125 if (llvm_acfg->aot_opts.direct_icalls) {
9126 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9127 /* Call to a C function implementing a jit icall */
9128 sym = mono_lookup_jit_icall_symbol ((const char *)data);
9129 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9130 MonoMethod *method = (MonoMethod *)data;
9131 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9132 sym = mono_lookup_icall_symbol (method);
9133 else if (llvm_acfg->aot_opts.direct_pinvoke)
9134 sym = get_pinvoke_import (llvm_acfg, method);
9135 } else if (type == MONO_PATCH_INFO_INTERNAL_METHOD) {
9136 MonoJitICallInfo *info = mono_find_jit_icall_by_name ((const char*)data);
9137 const char *name = mono_lookup_jit_icall_symbol ((const char*)data);
9138 if (name && llvm_acfg->aot_opts.direct_icalls && info->func == info->wrapper)
9139 sym = name;
9141 if (sym)
9142 return g_strdup (sym);
9144 return NULL;
9147 char*
9148 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
9150 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
9151 MonoPltEntry *plt_entry;
9152 const char *sym = NULL;
9154 ji->type = type;
9155 ji->data.target = data;
9157 if (!can_encode_patch (llvm_acfg, ji))
9158 return NULL;
9160 if (llvm_acfg->aot_opts.direct_icalls) {
9161 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
9162 /* Call to a C function implementing a jit icall */
9163 sym = mono_lookup_jit_icall_symbol ((const char *)data);
9164 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
9165 MonoMethod *method = (MonoMethod *)data;
9166 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
9167 sym = mono_lookup_icall_symbol (method);
9169 if (sym)
9170 return g_strdup (sym);
9173 plt_entry = get_plt_entry (llvm_acfg, ji);
9174 plt_entry->llvm_used = TRUE;
9176 #if defined(TARGET_MACH)
9177 return g_strdup (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
9178 #else
9179 return g_strdup (plt_entry->llvm_symbol);
9180 #endif
9184 mono_aot_get_method_index (MonoMethod *method)
9186 g_assert (llvm_acfg);
9187 return get_method_index (llvm_acfg, method);
9190 MonoJumpInfo*
9191 mono_aot_patch_info_dup (MonoJumpInfo* ji)
9193 MonoJumpInfo *res;
9195 mono_acfg_lock (llvm_acfg);
9196 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
9197 mono_acfg_unlock (llvm_acfg);
9199 return res;
9202 static int
9203 execute_system (const char * command)
9205 int status = 0;
9207 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) && defined(HOST_WIN32)
9208 // We need an extra set of quotes around the whole command to properly handle commands
9209 // with spaces since internally the command is called through "cmd /c.
9210 char * quoted_command = g_strdup_printf ("\"%s\"", command);
9212 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
9213 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
9214 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
9215 status = _wsystem (wstr);
9216 g_free (wstr);
9218 g_free (quoted_command);
9219 #elif defined (HAVE_SYSTEM)
9220 status = system (command);
9221 #else
9222 g_assert_not_reached ();
9223 #endif
9225 return status;
9228 #ifdef ENABLE_LLVM
9231 * emit_llvm_file:
9233 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
9234 * tools.
9236 static gboolean
9237 emit_llvm_file (MonoAotCompile *acfg)
9239 char *command, *opts, *tempbc, *optbc, *output_fname;
9241 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
9242 if (acfg->aot_opts.no_opt)
9243 tempbc = g_strdup (acfg->aot_opts.llvm_outfile);
9244 else
9245 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9246 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
9247 } else {
9248 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
9249 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
9252 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
9254 if (acfg->aot_opts.no_opt)
9255 return TRUE;
9257 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
9258 * a lot of time, and doesn't seem to save much space.
9259 * The following optimizations cannot be enabled:
9260 * - 'tailcallelim'
9261 * - 'jump-threading' changes our blockaddress references to int constants.
9262 * - 'basiccg' fails because it contains:
9263 * if (CS && !isa<IntrinsicInst>(II)) {
9264 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
9265 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
9266 * The opt list below was produced by taking the output of:
9267 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
9268 * then removing tailcallelim + the global opts.
9269 * strip-dead-prototypes deletes unused intrinsics definitions.
9271 /* The dse pass is disabled because of #13734 and #17616 */
9273 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
9274 * // If we have no DataLayout information around, then the size of the store
9275 * // is inferrable from the pointee type. If they are the same type, then
9276 * // we know that the store is safe.
9277 * if (AA.getDataLayout() == 0 &&
9278 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
9279 * return OverwriteComplete;
9280 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
9282 if (acfg->aot_opts.llvm_only) {
9283 // FIXME: This doesn't work yet
9284 opts = g_strdup ("");
9285 } else {
9286 #if LLVM_API_VERSION > 100
9287 opts = g_strdup ("-O2 -disable-tail-calls");
9288 #else
9289 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -inline-cost -inline -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -adce -simplifycfg -instcombine -strip-dead-prototypes -domtree -verify");
9290 #endif
9291 if (acfg->aot_opts.llvm_opts) {
9292 opts = g_strdup_printf ("%s %s", opts, acfg->aot_opts.llvm_opts);
9296 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
9297 aot_printf (acfg, "Executing opt: %s\n", command);
9298 if (execute_system (command) != 0)
9299 return FALSE;
9300 g_free (opts);
9302 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
9303 /* Nothing else to do */
9304 return TRUE;
9306 if (acfg->aot_opts.llvm_only) {
9307 /* Use the stock clang from xcode */
9308 // FIXME: arch
9309 command = g_strdup_printf ("%s -fexceptions -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.clangxx, acfg->llvm_ofile, acfg->tmpbasename);
9311 aot_printf (acfg, "Executing clang: %s\n", command);
9312 if (execute_system (command) != 0)
9313 return FALSE;
9314 return TRUE;
9317 if (!acfg->llc_args)
9318 acfg->llc_args = g_string_new ("");
9320 /* Verbose asm slows down llc greatly */
9321 g_string_append (acfg->llc_args, " -asm-verbose=false");
9323 if (acfg->aot_opts.mtriple)
9324 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
9326 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
9328 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
9330 #if LLVM_API_VERSION > 100
9331 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
9332 #endif
9334 #if LLVM_API_VERSION > 500 && (defined(TARGET_AMD64) || defined(TARGET_X86))
9335 /* This generates stack adjustments in the middle of functions breaking unwind info */
9336 g_string_append_printf (acfg->llc_args, " -no-x86-call-frame-opt");
9337 #endif
9339 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS)
9340 /* ios requires PIC code now */
9341 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9342 #else
9343 if (llvm_acfg->aot_opts.static_link)
9344 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
9345 else
9346 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
9347 #endif
9349 if (acfg->llvm_owriter) {
9350 /* Emit an object file directly */
9351 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
9352 g_string_append_printf (acfg->llc_args, " -filetype=obj");
9353 } else {
9354 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
9357 if (acfg->aot_opts.llvm_llc) {
9358 g_string_append_printf (acfg->llc_args, " %s", acfg->aot_opts.llvm_llc);
9361 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
9362 g_free (output_fname);
9364 aot_printf (acfg, "Executing llc: %s\n", command);
9366 if (execute_system (command) != 0)
9367 return FALSE;
9368 return TRUE;
9370 #endif
9372 static void
9373 emit_code (MonoAotCompile *acfg)
9375 int oindex, i, prev_index;
9376 gboolean saved_unbox_info = FALSE; // See mono_aot_get_unbox_trampoline.
9377 char symbol [MAX_SYMBOL_SIZE];
9379 if (acfg->aot_opts.llvm_only)
9380 return;
9382 #if defined(TARGET_POWERPC64)
9383 sprintf (symbol, ".Lgot_addr");
9384 emit_section_change (acfg, ".text", 0);
9385 emit_alignment (acfg, 8);
9386 emit_label (acfg, symbol);
9387 emit_pointer (acfg, acfg->got_symbol);
9388 #endif
9391 * This global symbol is used to compute the address of each method using the
9392 * code_offsets array. It is also used to compute the memory ranges occupied by
9393 * AOT code, so it must be equal to the address of the first emitted method.
9395 emit_section_change (acfg, ".text", 0);
9396 emit_alignment_code (acfg, 8);
9397 emit_info_symbol (acfg, "jit_code_start", TRUE);
9400 * Emit some padding so the local symbol for the first method doesn't have the
9401 * same address as 'methods'.
9403 emit_padding (acfg, 16);
9405 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9406 MonoCompile *cfg;
9407 MonoMethod *method;
9409 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9411 cfg = acfg->cfgs [i];
9413 if (!cfg)
9414 continue;
9416 method = cfg->orig_method;
9418 gboolean dedup_collect = acfg->aot_opts.dedup || (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode);
9419 gboolean dedupable = mono_aot_can_dedup (method);
9421 // cfg->skip is vital for LLVM to work, can't just continue in this loop
9422 if (dedupable && strcmp (method->name, "wbarrier_conc") && dedup_collect) {
9423 mono_dedup_cache_method (acfg, method);
9425 // Don't compile inflated methods if we're in first phase of
9426 // dedup
9428 // In second phase, we emit methods that
9429 // are dedupable. We also emit later methods
9430 // which are referenced by them and added later.
9431 // For this reason, when in the dedup_include mode,
9432 // we never set skip.
9433 if (acfg->aot_opts.dedup)
9434 cfg->skip = TRUE;
9437 // Don't compile anything in this mode
9438 if (acfg->aot_opts.dedup_include && !acfg->dedup_emit_mode)
9439 cfg->skip = TRUE;
9441 // Compile everything in this mode
9442 if (acfg->aot_opts.dedup_include && acfg->dedup_emit_mode)
9443 cfg->skip = FALSE;
9445 /*if (dedup_collect) {*/
9446 /*char *name = mono_aot_get_mangled_method_name (method);*/
9448 /*if (ignore_cfg (cfg))*/
9449 /*aot_printf (acfg, "Dedup Skipping %s\n", acfg->image->name, name);*/
9450 /*else*/
9451 /*aot_printf (acfg, "Dedup Keeping %s\n", acfg->image->name, name);*/
9453 /*g_free (name);*/
9454 /*}*/
9456 if (ignore_cfg (cfg))
9457 continue;
9459 /* Emit unbox trampoline */
9460 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9461 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
9463 emit_section_change (acfg, ".text", 0);
9465 if (acfg->thumb_mixed && cfg->compile_llvm) {
9466 emit_set_thumb_mode (acfg);
9467 fprintf (acfg->fp, "\n.thumb_func\n");
9470 emit_label (acfg, symbol);
9472 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
9474 if (acfg->thumb_mixed && cfg->compile_llvm)
9475 emit_set_arm_mode (acfg);
9477 if (!saved_unbox_info) {
9478 char user_symbol [128];
9479 GSList *unwind_ops;
9480 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
9482 emit_label (acfg, "ut_end");
9484 unwind_ops = mono_unwind_get_cie_program ();
9485 save_unwind_info (acfg, user_symbol, unwind_ops);
9486 mono_free_unwind_info (unwind_ops);
9488 /* Save the unbox trampoline size */
9489 #ifdef TARGET_AMD64
9490 // LLVM unbox trampolines vary in size, 6 or 9 bytes,
9491 // due to the last instruction being 2 or 5 bytes.
9492 // There is no need to describe interior bytes of instructions
9493 // however, so state the size as if the last instruction is size 1.
9494 emit_int32 (acfg, 5);
9495 #else
9496 emit_symbol_diff (acfg, "ut_end", symbol, 0);
9497 #endif
9498 saved_unbox_info = TRUE;
9502 if (cfg->compile_llvm) {
9503 acfg->stats.llvm_count ++;
9504 } else {
9505 emit_method_code (acfg, cfg);
9509 emit_section_change (acfg, ".text", 0);
9510 emit_alignment_code (acfg, 8);
9511 emit_info_symbol (acfg, "jit_code_end", TRUE);
9513 /* To distinguish it from the next symbol */
9514 emit_padding (acfg, 4);
9517 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
9518 * from optimizing them away, since it doesn't see that code_offsets references them.
9519 * JITted methods don't need this since they are referenced using assembler local
9520 * symbols.
9521 * FIXME: This is why write-symbols doesn't work on OSX ?
9523 if (acfg->llvm && acfg->need_no_dead_strip) {
9524 fprintf (acfg->fp, "\n");
9525 for (i = 0; i < acfg->nmethods; ++i) {
9526 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
9527 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
9532 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
9533 * This is PIE code, and the linker can update it if needed.
9536 sprintf (symbol, "method_addresses");
9537 emit_section_change (acfg, ".text", 1);
9538 emit_alignment_code (acfg, 8);
9539 emit_info_symbol (acfg, symbol, TRUE);
9540 if (acfg->aot_opts.write_symbols)
9541 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
9542 emit_unset_mode (acfg);
9543 if (acfg->need_no_dead_strip)
9544 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
9546 for (i = 0; i < acfg->nmethods; ++i) {
9547 #ifdef MONO_ARCH_AOT_SUPPORTED
9548 int call_size;
9550 if (!ignore_cfg (acfg->cfgs [i])) {
9551 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
9552 } else {
9553 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
9555 #endif
9558 sprintf (symbol, "method_addresses_end");
9559 emit_label (acfg, symbol);
9560 emit_line (acfg);
9562 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
9563 sprintf (symbol, "unbox_trampolines");
9564 emit_section_change (acfg, RODATA_SECT, 0);
9565 emit_alignment (acfg, 8);
9566 emit_info_symbol (acfg, symbol, FALSE);
9568 prev_index = -1;
9569 for (i = 0; i < acfg->nmethods; ++i) {
9570 MonoCompile *cfg;
9571 MonoMethod *method;
9572 int index;
9574 cfg = acfg->cfgs [i];
9575 if (ignore_cfg (cfg))
9576 continue;
9578 method = cfg->orig_method;
9580 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9581 index = get_method_index (acfg, method);
9583 emit_int32 (acfg, index);
9584 /* Make sure the table is sorted by index */
9585 g_assert (index > prev_index);
9586 prev_index = index;
9589 sprintf (symbol, "unbox_trampolines_end");
9590 emit_info_symbol (acfg, symbol, FALSE);
9591 emit_int32 (acfg, 0);
9593 /* Emit a separate table with the trampoline addresses/offsets */
9594 sprintf (symbol, "unbox_trampoline_addresses");
9595 emit_section_change (acfg, ".text", 0);
9596 emit_alignment_code (acfg, 8);
9597 emit_info_symbol (acfg, symbol, TRUE);
9599 for (i = 0; i < acfg->nmethods; ++i) {
9600 MonoCompile *cfg;
9601 MonoMethod *method;
9602 int index;
9604 cfg = acfg->cfgs [i];
9605 if (ignore_cfg (cfg))
9606 continue;
9608 method = cfg->orig_method;
9610 if (mono_aot_mode_is_full (&acfg->aot_opts) && m_class_is_valuetype (cfg->orig_method->klass)) {
9611 #ifdef MONO_ARCH_AOT_SUPPORTED
9612 int call_size;
9614 index = get_method_index (acfg, method);
9615 sprintf (symbol, "ut_%d", index);
9617 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
9618 #endif
9621 emit_int32 (acfg, 0);
9624 static void
9625 emit_info (MonoAotCompile *acfg)
9627 int oindex, i;
9628 gint32 *offsets;
9630 offsets = g_new0 (gint32, acfg->nmethods);
9632 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
9633 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9635 if (acfg->cfgs [i]) {
9636 emit_method_info (acfg, acfg->cfgs [i]);
9637 offsets [i] = acfg->cfgs [i]->method_info_offset;
9638 } else {
9639 offsets [i] = 0;
9643 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9645 g_free (offsets);
9648 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
9650 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
9651 #define mix(a,b,c) { \
9652 a -= c; a ^= rot(c, 4); c += b; \
9653 b -= a; b ^= rot(a, 6); a += c; \
9654 c -= b; c ^= rot(b, 8); b += a; \
9655 a -= c; a ^= rot(c,16); c += b; \
9656 b -= a; b ^= rot(a,19); a += c; \
9657 c -= b; c ^= rot(b, 4); b += a; \
9659 #define mono_final(a,b,c) { \
9660 c ^= b; c -= rot(b,14); \
9661 a ^= c; a -= rot(c,11); \
9662 b ^= a; b -= rot(a,25); \
9663 c ^= b; c -= rot(b,16); \
9664 a ^= c; a -= rot(c,4); \
9665 b ^= a; b -= rot(a,14); \
9666 c ^= b; c -= rot(b,24); \
9669 static guint
9670 mono_aot_type_hash (MonoType *t1)
9672 guint hash = t1->type;
9674 hash |= t1->byref << 6; /* do not collide with t1->type values */
9675 switch (t1->type) {
9676 case MONO_TYPE_VALUETYPE:
9677 case MONO_TYPE_CLASS:
9678 case MONO_TYPE_SZARRAY:
9679 /* check if the distribution is good enough */
9680 return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (t1->data.klass));
9681 case MONO_TYPE_PTR:
9682 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9683 case MONO_TYPE_ARRAY:
9684 return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass));
9685 case MONO_TYPE_GENERICINST:
9686 return ((hash << 5) - hash) ^ 0;
9687 default:
9688 return hash;
9693 * mono_aot_method_hash:
9695 * Return a hash code for methods which only depends on metadata.
9697 guint32
9698 mono_aot_method_hash (MonoMethod *method)
9700 MonoMethodSignature *sig;
9701 MonoClass *klass;
9702 int i, hindex;
9703 int hashes_count;
9704 guint32 *hashes_start, *hashes;
9705 guint32 a, b, c;
9706 MonoGenericInst *class_ginst = NULL;
9707 MonoGenericInst *ginst = NULL;
9709 /* Similar to the hash in mono_method_get_imt_slot () */
9711 sig = mono_method_signature_internal (method);
9713 if (mono_class_is_ginst (method->klass))
9714 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9715 if (method->is_inflated)
9716 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9718 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9719 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9720 hashes = hashes_start;
9722 /* Some wrappers are assigned to random classes */
9723 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9724 klass = method->klass;
9725 else
9726 klass = mono_defaults.object_class;
9728 if (!method->wrapper_type) {
9729 char *full_name;
9731 if (mono_class_is_ginst (klass))
9732 full_name = mono_type_full_name (m_class_get_byval_arg (mono_class_get_generic_class (klass)->container_class));
9733 else
9734 full_name = mono_type_full_name (m_class_get_byval_arg (klass));
9736 hashes [0] = mono_metadata_str_hash (full_name);
9737 hashes [1] = 0;
9738 g_free (full_name);
9739 } else {
9740 hashes [0] = mono_metadata_str_hash (m_class_get_name (klass));
9741 hashes [1] = mono_metadata_str_hash (m_class_get_name_space (klass));
9743 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9744 /* The method name includes a stringified pointer */
9745 hashes [2] = 0;
9746 else
9747 hashes [2] = mono_metadata_str_hash (method->name);
9748 hashes [3] = method->wrapper_type;
9749 hashes [4] = mono_aot_type_hash (sig->ret);
9750 hindex = 5;
9751 for (i = 0; i < sig->param_count; i++) {
9752 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9754 if (class_ginst) {
9755 for (i = 0; i < class_ginst->type_argc; ++i)
9756 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9758 if (ginst) {
9759 for (i = 0; i < ginst->type_argc; ++i)
9760 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9762 g_assert (hindex == hashes_count);
9764 /* Setup internal state */
9765 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9767 /* Handle most of the hashes */
9768 while (hashes_count > 3) {
9769 a += hashes [0];
9770 b += hashes [1];
9771 c += hashes [2];
9772 mix (a,b,c);
9773 hashes_count -= 3;
9774 hashes += 3;
9777 /* Handle the last 3 hashes (all the case statements fall through) */
9778 switch (hashes_count) {
9779 case 3 : c += hashes [2];
9780 case 2 : b += hashes [1];
9781 case 1 : a += hashes [0];
9782 mono_final (a,b,c);
9783 case 0: /* nothing left to add */
9784 break;
9787 g_free (hashes_start);
9789 return c;
9791 #undef rot
9792 #undef mix
9793 #undef mono_final
9796 * mono_aot_get_array_helper_from_wrapper;
9798 * Get the helper method in Array called by an array wrapper method.
9800 MonoMethod*
9801 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9803 MonoMethod *m;
9804 const char *prefix;
9805 MonoGenericContext ctx;
9806 MonoType *args [16];
9807 char *mname, *iname, *s, *s2, *helper_name = NULL;
9809 prefix = "System.Collections.Generic";
9810 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9811 s2 = strstr (s, "`1.");
9812 g_assert (s2);
9813 s2 [0] = '\0';
9814 iname = s;
9815 mname = s2 + 3;
9817 //printf ("X: %s %s\n", iname, mname);
9819 if (!strcmp (iname, "IList"))
9820 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9821 else
9822 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9823 m = get_method_nofail (mono_defaults.array_class, helper_name, mono_method_signature_internal (method)->param_count, 0);
9824 g_assert (m);
9825 g_free (helper_name);
9826 g_free (s);
9828 if (m->is_generic) {
9829 ERROR_DECL (error);
9830 memset (&ctx, 0, sizeof (ctx));
9831 args [0] = m_class_get_byval_arg (m_class_get_element_class (method->klass));
9832 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9833 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
9834 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
9837 return m;
9840 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9842 typedef struct HashEntry {
9843 guint32 key, value, index;
9844 struct HashEntry *next;
9845 } HashEntry;
9848 * emit_extra_methods:
9850 * Emit methods which are not in the METHOD table, like wrappers.
9852 static void
9853 emit_extra_methods (MonoAotCompile *acfg)
9855 int i, table_size, buf_size;
9856 guint8 *p, *buf;
9857 guint32 *info_offsets;
9858 guint32 hash;
9859 GPtrArray *table;
9860 HashEntry *entry, *new_entry;
9861 int nmethods, max_chain_length;
9862 int *chain_lengths;
9864 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9866 /* Emit method info */
9867 nmethods = 0;
9868 for (i = 0; i < acfg->extra_methods->len; ++i) {
9869 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9870 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9872 if (ignore_cfg (cfg))
9873 continue;
9875 buf_size = 10240;
9876 p = buf = (guint8 *)g_malloc (buf_size);
9878 nmethods ++;
9880 method = cfg->method_to_register;
9882 encode_method_ref (acfg, method, p, &p);
9884 g_assert ((p - buf) < buf_size);
9886 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9887 g_free (buf);
9891 * Construct a chained hash table for mapping indexes in extra_method_info to
9892 * method indexes.
9894 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9895 table = g_ptr_array_sized_new (table_size);
9896 for (i = 0; i < table_size; ++i)
9897 g_ptr_array_add (table, NULL);
9898 chain_lengths = g_new0 (int, table_size);
9899 max_chain_length = 0;
9900 for (i = 0; i < acfg->extra_methods->len; ++i) {
9901 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9902 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9903 guint32 key, value;
9905 if (ignore_cfg (cfg))
9906 continue;
9908 key = info_offsets [i];
9909 value = get_method_index (acfg, method);
9911 hash = mono_aot_method_hash (method) % table_size;
9912 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9914 chain_lengths [hash] ++;
9915 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9917 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9918 new_entry->key = key;
9919 new_entry->value = value;
9921 entry = (HashEntry *)g_ptr_array_index (table, hash);
9922 if (entry == NULL) {
9923 new_entry->index = hash;
9924 g_ptr_array_index (table, hash) = new_entry;
9925 } else {
9926 while (entry->next)
9927 entry = entry->next;
9929 entry->next = new_entry;
9930 new_entry->index = table->len;
9931 g_ptr_array_add (table, new_entry);
9934 g_free (chain_lengths);
9936 //printf ("MAX: %d\n", max_chain_length);
9938 buf_size = table->len * 12 + 4;
9939 p = buf = (guint8 *)g_malloc (buf_size);
9940 encode_int (table_size, p, &p);
9942 for (i = 0; i < table->len; ++i) {
9943 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9945 if (entry == NULL) {
9946 encode_int (0, p, &p);
9947 encode_int (0, p, &p);
9948 encode_int (0, p, &p);
9949 } else {
9950 //g_assert (entry->key > 0);
9951 encode_int (entry->key, p, &p);
9952 encode_int (entry->value, p, &p);
9953 if (entry->next)
9954 encode_int (entry->next->index, p, &p);
9955 else
9956 encode_int (0, p, &p);
9959 g_assert (p - buf <= buf_size);
9961 /* Emit the table */
9962 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9964 g_free (buf);
9967 * Emit a table reverse mapping method indexes to their index in extra_method_info.
9968 * This is used by mono_aot_find_jit_info ().
9970 buf_size = acfg->extra_methods->len * 8 + 4;
9971 p = buf = (guint8 *)g_malloc (buf_size);
9972 encode_int (acfg->extra_methods->len, p, &p);
9973 for (i = 0; i < acfg->extra_methods->len; ++i) {
9974 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9976 encode_int (get_method_index (acfg, method), p, &p);
9977 encode_int (info_offsets [i], p, &p);
9979 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9981 g_free (buf);
9982 g_free (info_offsets);
9983 g_ptr_array_free (table, TRUE);
9986 static void
9987 generate_aotid (guint8* aotid)
9989 gpointer rand_handle;
9990 ERROR_DECL (error);
9992 mono_rand_open ();
9993 rand_handle = mono_rand_init (NULL, 0);
9995 mono_rand_try_get_bytes (&rand_handle, aotid, 16, error);
9996 mono_error_assert_ok (error);
9998 mono_rand_close (rand_handle);
10001 static void
10002 emit_exception_info (MonoAotCompile *acfg)
10004 int i;
10005 gint32 *offsets;
10006 SeqPointData sp_data;
10007 gboolean seq_points_to_file = FALSE;
10009 offsets = g_new0 (gint32, acfg->nmethods);
10010 for (i = 0; i < acfg->nmethods; ++i) {
10011 if (acfg->cfgs [i]) {
10012 MonoCompile *cfg = acfg->cfgs [i];
10014 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
10015 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
10016 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
10017 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
10018 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
10020 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
10021 offsets [i] = cfg->ex_info_offset;
10023 if (method_seq_points_to_file) {
10024 if (!seq_points_to_file) {
10025 mono_seq_point_data_init (&sp_data, acfg->nmethods);
10026 seq_points_to_file = TRUE;
10028 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
10030 } else {
10031 offsets [i] = 0;
10035 if (seq_points_to_file) {
10036 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
10037 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
10038 char *image_basename = g_path_get_basename (acfg->image->name);
10039 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
10040 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
10042 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
10043 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
10044 exit (1);
10047 mono_seq_point_data_write (&sp_data, aot_file_path);
10048 mono_seq_point_data_free (&sp_data);
10050 g_free (aotid);
10051 g_free (dir);
10052 g_free (image_basename);
10053 g_free (aot_file);
10054 g_free (aot_file_path);
10057 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
10058 g_free (offsets);
10061 static void
10062 emit_unwind_info (MonoAotCompile *acfg)
10064 int i;
10065 char symbol [128];
10067 if (acfg->aot_opts.llvm_only) {
10068 g_assert (acfg->unwind_ops->len == 0);
10069 return;
10073 * The unwind info contains a lot of duplicates so we emit each unique
10074 * entry once, and only store the offset from the start of the table in the
10075 * exception info.
10078 sprintf (symbol, "unwind_info");
10079 emit_section_change (acfg, RODATA_SECT, 1);
10080 emit_alignment (acfg, 8);
10081 emit_info_symbol (acfg, symbol, TRUE);
10083 for (i = 0; i < acfg->unwind_ops->len; ++i) {
10084 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
10085 guint8 *unwind_info;
10086 guint32 unwind_info_len;
10087 guint8 buf [16];
10088 guint8 *p;
10090 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
10092 p = buf;
10093 encode_value (unwind_info_len, p, &p);
10094 emit_bytes (acfg, buf, p - buf);
10095 emit_bytes (acfg, unwind_info, unwind_info_len);
10097 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
10101 static void
10102 emit_class_info (MonoAotCompile *acfg)
10104 int i;
10105 gint32 *offsets;
10107 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
10108 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
10109 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
10111 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);
10112 g_free (offsets);
10115 typedef struct ClassNameTableEntry {
10116 guint32 token, index;
10117 struct ClassNameTableEntry *next;
10118 } ClassNameTableEntry;
10120 static void
10121 emit_class_name_table (MonoAotCompile *acfg)
10123 int i, table_size, buf_size;
10124 guint32 token, hash;
10125 MonoClass *klass;
10126 GPtrArray *table;
10127 char *full_name;
10128 guint8 *buf, *p;
10129 ClassNameTableEntry *entry, *new_entry;
10132 * Construct a chained hash table for mapping class names to typedef tokens.
10134 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
10135 table = g_ptr_array_sized_new (table_size);
10136 for (i = 0; i < table_size; ++i)
10137 g_ptr_array_add (table, NULL);
10138 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
10139 ERROR_DECL (error);
10140 token = MONO_TOKEN_TYPE_DEF | (i + 1);
10141 klass = mono_class_get_checked (acfg->image, token, error);
10142 if (!klass) {
10143 mono_error_cleanup (error);
10144 continue;
10146 full_name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
10147 hash = mono_metadata_str_hash (full_name) % table_size;
10148 g_free (full_name);
10150 /* FIXME: Allocate from the mempool */
10151 new_entry = g_new0 (ClassNameTableEntry, 1);
10152 new_entry->token = token;
10154 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
10155 if (entry == NULL) {
10156 new_entry->index = hash;
10157 g_ptr_array_index (table, hash) = new_entry;
10158 } else {
10159 while (entry->next)
10160 entry = entry->next;
10162 entry->next = new_entry;
10163 new_entry->index = table->len;
10164 g_ptr_array_add (table, new_entry);
10168 /* Emit the table */
10169 buf_size = table->len * 4 + 4;
10170 p = buf = (guint8 *)g_malloc0 (buf_size);
10172 /* FIXME: Optimize memory usage */
10173 g_assert (table_size < 65000);
10174 encode_int16 (table_size, p, &p);
10175 g_assert (table->len < 65000);
10176 for (i = 0; i < table->len; ++i) {
10177 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
10179 if (entry == NULL) {
10180 encode_int16 (0, p, &p);
10181 encode_int16 (0, p, &p);
10182 } else {
10183 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
10184 if (entry->next)
10185 encode_int16 (entry->next->index, p, &p);
10186 else
10187 encode_int16 (0, p, &p);
10189 g_free (entry);
10191 g_assert (p - buf <= buf_size);
10192 g_ptr_array_free (table, TRUE);
10194 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
10196 g_free (buf);
10199 static void
10200 emit_image_table (MonoAotCompile *acfg)
10202 int i, buf_size;
10203 guint8 *buf, *p;
10206 * The image table is small but referenced in a lot of places.
10207 * So we emit it at once, and reference its elements by an index.
10209 buf_size = acfg->image_table->len * 28 + 4;
10210 for (i = 0; i < acfg->image_table->len; i++) {
10211 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10212 MonoAssemblyName *aname = &image->assembly->aname;
10214 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
10217 buf = p = (guint8 *)g_malloc0 (buf_size);
10218 encode_int (acfg->image_table->len, p, &p);
10219 for (i = 0; i < acfg->image_table->len; i++) {
10220 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
10221 MonoAssemblyName *aname = &image->assembly->aname;
10223 /* FIXME: Support multi-module assemblies */
10224 g_assert (image->assembly->image == image);
10226 encode_string (image->assembly_name, p, &p);
10227 encode_string (image->guid, p, &p);
10228 encode_string (aname->culture ? aname->culture : "", p, &p);
10229 encode_string ((const char*)aname->public_key_token, p, &p);
10231 while (GPOINTER_TO_UINT (p) % 8 != 0)
10232 p ++;
10234 encode_int (aname->flags, p, &p);
10235 encode_int (aname->major, p, &p);
10236 encode_int (aname->minor, p, &p);
10237 encode_int (aname->build, p, &p);
10238 encode_int (aname->revision, p, &p);
10240 g_assert (p - buf <= buf_size);
10242 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
10244 g_free (buf);
10247 static void
10248 emit_weak_field_indexes (MonoAotCompile *acfg)
10250 GHashTable *indexes;
10251 GHashTableIter iter;
10252 gpointer key, value;
10253 int buf_size;
10254 guint8 *buf, *p;
10256 /* Emit a table of weak field indexes, since computing these at runtime is expensive */
10257 mono_assembly_init_weak_fields (acfg->image);
10258 indexes = acfg->image->weak_field_indexes;
10259 g_assert (indexes);
10261 buf_size = (g_hash_table_size (indexes) + 1) * 4;
10262 buf = p = (guint8 *)g_malloc0 (buf_size);
10264 encode_int (g_hash_table_size (indexes), p, &p);
10265 g_hash_table_iter_init (&iter, indexes);
10266 while (g_hash_table_iter_next (&iter, &key, &value)) {
10267 guint32 index = GPOINTER_TO_UINT (key);
10268 encode_int (index, p, &p);
10270 g_assert (p - buf <= buf_size);
10272 emit_aot_data (acfg, MONO_AOT_TABLE_WEAK_FIELD_INDEXES, "weak_field_indexes", buf, p - buf);
10274 g_free (buf);
10277 static void
10278 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
10280 int i, first_plt_got_patch = 0, buf_size;
10281 guint8 *p, *buf;
10282 guint32 *got_info_offsets;
10283 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
10285 /* Add the patches needed by the PLT to the GOT */
10286 if (!llvm) {
10287 acfg->plt_got_offset_base = acfg->got_offset;
10288 first_plt_got_patch = info->got_patches->len;
10289 for (i = 1; i < acfg->plt_offset; ++i) {
10290 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10292 g_ptr_array_add (info->got_patches, plt_entry->ji);
10294 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
10297 acfg->got_offset += acfg->plt_offset;
10301 * FIXME:
10302 * - optimize offsets table.
10303 * - reduce number of exported symbols.
10304 * - emit info for a klass only once.
10305 * - determine when a method uses a GOT slot which is guaranteed to be already
10306 * initialized.
10307 * - clean up and document the code.
10308 * - use String.Empty in class libs.
10311 /* Encode info required to decode shared GOT entries */
10312 buf_size = info->got_patches->len * 128;
10313 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
10314 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
10315 if (!llvm) {
10316 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
10317 /* Unused */
10318 if (acfg->plt_offset)
10319 acfg->plt_got_info_offsets [0] = 0;
10321 for (i = 0; i < info->got_patches->len; ++i) {
10322 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
10323 guint8 *p2;
10325 p = buf;
10327 encode_value (ji->type, p, &p);
10328 p2 = p;
10329 encode_patch (acfg, ji, p, &p);
10330 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
10331 g_assert (p - buf <= buf_size);
10332 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
10334 if (!llvm && i >= first_plt_got_patch)
10335 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
10336 acfg->stats.got_info_size += p - buf;
10339 /* Emit got_info_offsets table */
10341 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
10342 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);
10345 static void
10346 emit_got (MonoAotCompile *acfg)
10348 char symbol [MAX_SYMBOL_SIZE];
10350 if (acfg->aot_opts.llvm_only)
10351 return;
10353 /* Don't make GOT global so accesses to it don't need relocations */
10354 sprintf (symbol, "%s", acfg->got_symbol);
10356 #ifdef TARGET_MACH
10357 emit_unset_mode (acfg);
10358 fprintf (acfg->fp, ".section __DATA, __bss\n");
10359 emit_alignment (acfg, 8);
10360 if (acfg->llvm)
10361 emit_info_symbol (acfg, "jit_got", FALSE);
10362 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10363 #else
10364 emit_section_change (acfg, ".bss", 0);
10365 emit_alignment (acfg, 8);
10366 if (acfg->aot_opts.write_symbols)
10367 emit_local_symbol (acfg, symbol, "got_end", FALSE);
10368 emit_label (acfg, symbol);
10369 if (acfg->llvm)
10370 emit_info_symbol (acfg, "jit_got", FALSE);
10371 if (acfg->got_offset > 0)
10372 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (target_mgreg_t)));
10373 #endif
10375 sprintf (symbol, "got_end");
10376 emit_label (acfg, symbol);
10379 typedef struct GlobalsTableEntry {
10380 guint32 value, index;
10381 struct GlobalsTableEntry *next;
10382 } GlobalsTableEntry;
10384 #ifdef TARGET_WIN32_MSVC
10385 #define DLL_ENTRY_POINT "DllMain"
10387 static void
10388 emit_library_info (MonoAotCompile *acfg)
10390 // Only include for shared libraries linked directly from generated object.
10391 if (link_shared_library (acfg)) {
10392 char *name = NULL;
10393 char symbol [MAX_SYMBOL_SIZE];
10395 // Ask linker to export all global symbols.
10396 emit_section_change (acfg, ".drectve", 0);
10397 for (guint i = 0; i < acfg->globals->len; ++i) {
10398 name = (char *)g_ptr_array_index (acfg->globals, i);
10399 g_assert (name != NULL);
10400 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
10401 emit_string (acfg, symbol);
10404 // Emit DLLMain function, needed by MSVC linker for DLL's.
10405 // NOTE, DllMain should not go into exports above.
10406 emit_section_change (acfg, ".text", 0);
10407 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
10408 emit_label (acfg, DLL_ENTRY_POINT);
10410 // Simple implementation of DLLMain, just returning TRUE.
10411 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
10412 fprintf (acfg->fp, "movl $1, %%eax\n");
10413 fprintf (acfg->fp, "ret\n");
10415 // Inform linker about our dll entry function.
10416 emit_section_change (acfg, ".drectve", 0);
10417 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
10418 return;
10422 #else
10424 static inline void
10425 emit_library_info (MonoAotCompile *acfg)
10427 return;
10429 #endif
10431 static void
10432 emit_globals (MonoAotCompile *acfg)
10434 int i, table_size;
10435 guint32 hash;
10436 GPtrArray *table;
10437 char symbol [1024];
10438 GlobalsTableEntry *entry, *new_entry;
10440 if (!acfg->aot_opts.static_link)
10441 return;
10443 if (acfg->aot_opts.llvm_only) {
10444 g_assert (acfg->globals->len == 0);
10445 return;
10449 * When static linking, we emit a table containing our globals.
10453 * Construct a chained hash table for mapping global names to their index in
10454 * the globals table.
10456 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
10457 table = g_ptr_array_sized_new (table_size);
10458 for (i = 0; i < table_size; ++i)
10459 g_ptr_array_add (table, NULL);
10460 for (i = 0; i < acfg->globals->len; ++i) {
10461 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10463 hash = mono_metadata_str_hash (name) % table_size;
10465 /* FIXME: Allocate from the mempool */
10466 new_entry = g_new0 (GlobalsTableEntry, 1);
10467 new_entry->value = i;
10469 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
10470 if (entry == NULL) {
10471 new_entry->index = hash;
10472 g_ptr_array_index (table, hash) = new_entry;
10473 } else {
10474 while (entry->next)
10475 entry = entry->next;
10477 entry->next = new_entry;
10478 new_entry->index = table->len;
10479 g_ptr_array_add (table, new_entry);
10483 /* Emit the table */
10484 sprintf (symbol, ".Lglobals_hash");
10485 emit_section_change (acfg, RODATA_SECT, 0);
10486 emit_alignment (acfg, 8);
10487 emit_label (acfg, symbol);
10489 /* FIXME: Optimize memory usage */
10490 g_assert (table_size < 65000);
10491 emit_int16 (acfg, table_size);
10492 for (i = 0; i < table->len; ++i) {
10493 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
10495 if (entry == NULL) {
10496 emit_int16 (acfg, 0);
10497 emit_int16 (acfg, 0);
10498 } else {
10499 emit_int16 (acfg, entry->value + 1);
10500 if (entry->next)
10501 emit_int16 (acfg, entry->next->index);
10502 else
10503 emit_int16 (acfg, 0);
10507 /* Emit the names */
10508 for (i = 0; i < acfg->globals->len; ++i) {
10509 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10511 sprintf (symbol, "name_%d", i);
10512 emit_section_change (acfg, RODATA_SECT, 1);
10513 #ifdef TARGET_MACH
10514 emit_alignment (acfg, 4);
10515 #endif
10516 emit_label (acfg, symbol);
10517 emit_string (acfg, name);
10520 /* Emit the globals table */
10521 sprintf (symbol, "globals");
10522 emit_section_change (acfg, ".data", 0);
10523 /* This is not a global, since it is accessed by the init function */
10524 emit_alignment (acfg, 8);
10525 emit_info_symbol (acfg, symbol, FALSE);
10527 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
10528 emit_pointer (acfg, symbol);
10530 for (i = 0; i < acfg->globals->len; ++i) {
10531 char *name = (char *)g_ptr_array_index (acfg->globals, i);
10533 sprintf (symbol, "name_%d", i);
10534 emit_pointer (acfg, symbol);
10536 g_assert (strlen (name) < sizeof (symbol));
10537 sprintf (symbol, "%s", name);
10538 emit_pointer (acfg, symbol);
10540 /* Null terminate the table */
10541 emit_int32 (acfg, 0);
10542 emit_int32 (acfg, 0);
10545 static void
10546 emit_mem_end (MonoAotCompile *acfg)
10548 char symbol [128];
10550 if (acfg->aot_opts.llvm_only)
10551 return;
10553 sprintf (symbol, "mem_end");
10554 emit_section_change (acfg, ".text", 1);
10555 emit_alignment_code (acfg, 8);
10556 emit_label (acfg, symbol);
10559 static void
10560 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10562 int i;
10564 info->version = MONO_AOT_FILE_VERSION;
10565 info->plt_got_offset_base = acfg->plt_got_offset_base;
10566 info->got_size = acfg->got_offset * sizeof (target_mgreg_t);
10567 info->plt_size = acfg->plt_offset;
10568 info->nmethods = acfg->nmethods;
10569 info->nextra_methods = acfg->nextra_methods;
10570 info->flags = acfg->flags;
10571 info->opts = acfg->opts;
10572 info->simd_opts = acfg->simd_opts;
10573 info->gc_name_index = acfg->gc_name_offset;
10574 info->datafile_size = acfg->datafile_offset;
10575 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10576 info->table_offsets [i] = acfg->table_offsets [i];
10577 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10578 info->num_trampolines [i] = acfg->num_trampolines [i];
10579 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10580 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
10581 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10582 info->trampoline_size [i] = acfg->trampoline_size [i];
10583 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
10585 int card_table_shift_bits = 0;
10586 target_mgreg_t card_table_mask = 0;
10588 mono_gc_get_target_card_table (&card_table_shift_bits, &card_table_mask);
10591 * Sanity checking variables used to make sure the host and target
10592 * environment matches when cross compiling.
10594 info->double_align = MONO_ABI_ALIGNOF (double);
10595 info->long_align = MONO_ABI_ALIGNOF (gint64);
10596 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
10597 info->card_table_shift_bits = card_table_shift_bits;
10598 info->card_table_mask = card_table_mask;
10600 info->tramp_page_size = acfg->tramp_page_size;
10601 info->nshared_got_entries = acfg->nshared_got_entries;
10602 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10603 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
10605 memcpy(&info->aotid, acfg->image->aotid, 16);
10608 static void
10609 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
10611 char symbol [MAX_SYMBOL_SIZE];
10612 int i, sindex;
10613 const char **symbols;
10615 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10616 sindex = 0;
10617 symbols [sindex ++] = acfg->got_symbol;
10618 if (acfg->llvm) {
10619 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
10620 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
10621 } else {
10622 symbols [sindex ++] = NULL;
10623 symbols [sindex ++] = NULL;
10625 /* llvm_get_method */
10626 symbols [sindex ++] = NULL;
10627 /* llvm_get_unbox_tramp */
10628 symbols [sindex ++] = NULL;
10629 if (!acfg->aot_opts.llvm_only) {
10630 symbols [sindex ++] = "jit_code_start";
10631 symbols [sindex ++] = "jit_code_end";
10632 symbols [sindex ++] = "method_addresses";
10633 } else {
10634 symbols [sindex ++] = NULL;
10635 symbols [sindex ++] = NULL;
10636 symbols [sindex ++] = NULL;
10639 if (acfg->data_outfile) {
10640 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10641 symbols [sindex ++] = NULL;
10642 } else {
10643 symbols [sindex ++] = "blob";
10644 symbols [sindex ++] = "class_name_table";
10645 symbols [sindex ++] = "class_info_offsets";
10646 symbols [sindex ++] = "method_info_offsets";
10647 symbols [sindex ++] = "ex_info_offsets";
10648 symbols [sindex ++] = "extra_method_info_offsets";
10649 symbols [sindex ++] = "extra_method_table";
10650 symbols [sindex ++] = "got_info_offsets";
10651 if (acfg->llvm)
10652 symbols [sindex ++] = "llvm_got_info_offsets";
10653 else
10654 symbols [sindex ++] = NULL;
10655 symbols [sindex ++] = "image_table";
10656 symbols [sindex ++] = "weak_field_indexes";
10659 symbols [sindex ++] = "mem_end";
10660 symbols [sindex ++] = "assembly_guid";
10661 symbols [sindex ++] = "runtime_version";
10662 if (acfg->num_trampoline_got_entries) {
10663 symbols [sindex ++] = "specific_trampolines";
10664 symbols [sindex ++] = "static_rgctx_trampolines";
10665 symbols [sindex ++] = "imt_trampolines";
10666 symbols [sindex ++] = "gsharedvt_arg_trampolines";
10667 symbols [sindex ++] = "ftnptr_arg_trampolines";
10668 symbols [sindex ++] = "unbox_arbitrary_trampolines";
10669 } else {
10670 symbols [sindex ++] = NULL;
10671 symbols [sindex ++] = NULL;
10672 symbols [sindex ++] = NULL;
10673 symbols [sindex ++] = NULL;
10674 symbols [sindex ++] = NULL;
10675 symbols [sindex ++] = NULL;
10677 if (acfg->aot_opts.static_link) {
10678 symbols [sindex ++] = "globals";
10679 } else {
10680 symbols [sindex ++] = NULL;
10682 symbols [sindex ++] = "assembly_name";
10683 symbols [sindex ++] = "plt";
10684 symbols [sindex ++] = "plt_end";
10685 symbols [sindex ++] = "unwind_info";
10686 if (!acfg->aot_opts.llvm_only) {
10687 symbols [sindex ++] = "unbox_trampolines";
10688 symbols [sindex ++] = "unbox_trampolines_end";
10689 symbols [sindex ++] = "unbox_trampoline_addresses";
10690 } else {
10691 symbols [sindex ++] = NULL;
10692 symbols [sindex ++] = NULL;
10693 symbols [sindex ++] = NULL;
10696 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10698 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
10699 emit_section_change (acfg, ".data", 0);
10700 emit_alignment (acfg, 8);
10701 emit_label (acfg, symbol);
10702 if (!acfg->aot_opts.static_link)
10703 emit_global (acfg, symbol, FALSE);
10705 /* The data emitted here must match MonoAotFileInfo. */
10707 emit_int32 (acfg, info->version);
10708 emit_int32 (acfg, info->dummy);
10711 * We emit pointers to our data structures instead of emitting global symbols which
10712 * point to them, to reduce the number of globals, and because using globals leads to
10713 * various problems (i.e. arm/thumb).
10715 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10716 emit_pointer (acfg, symbols [i]);
10718 emit_int32 (acfg, info->plt_got_offset_base);
10719 emit_int32 (acfg, info->got_size);
10720 emit_int32 (acfg, info->plt_size);
10721 emit_int32 (acfg, info->nmethods);
10722 emit_int32 (acfg, info->nextra_methods);
10723 emit_int32 (acfg, info->flags);
10724 emit_int32 (acfg, info->opts);
10725 emit_int32 (acfg, info->simd_opts);
10726 emit_int32 (acfg, info->gc_name_index);
10727 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10728 emit_int32 (acfg, info->double_align);
10729 emit_int32 (acfg, info->long_align);
10730 emit_int32 (acfg, info->generic_tramp_num);
10731 emit_int32 (acfg, info->card_table_shift_bits);
10732 emit_int32 (acfg, info->card_table_mask);
10733 emit_int32 (acfg, info->tramp_page_size);
10734 emit_int32 (acfg, info->nshared_got_entries);
10735 emit_int32 (acfg, info->datafile_size);
10737 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10738 emit_int32 (acfg, info->table_offsets [i]);
10739 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10740 emit_int32 (acfg, info->num_trampolines [i]);
10741 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10742 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10743 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10744 emit_int32 (acfg, info->trampoline_size [i]);
10745 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10746 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10748 emit_bytes (acfg, info->aotid, 16);
10750 if (acfg->aot_opts.static_link) {
10751 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10752 emit_alignment (acfg, sizeof (target_mgreg_t));
10753 emit_label (acfg, acfg->static_linking_symbol);
10754 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10759 * Emit a structure containing all the information not stored elsewhere.
10761 static void
10762 emit_file_info (MonoAotCompile *acfg)
10764 char *build_info;
10765 MonoAotFileInfo *info;
10767 if (acfg->aot_opts.bind_to_runtime_version) {
10768 build_info = mono_get_runtime_build_info ();
10769 emit_string_symbol (acfg, "runtime_version", build_info);
10770 g_free (build_info);
10771 } else {
10772 emit_string_symbol (acfg, "runtime_version", "");
10775 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10777 /* Emit a string holding the assembly name */
10778 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10780 info = g_new0 (MonoAotFileInfo, 1);
10781 init_aot_file_info (acfg, info);
10783 if (acfg->aot_opts.static_link) {
10784 char symbol [MAX_SYMBOL_SIZE];
10785 char *p;
10788 * Emit a global symbol which can be passed by an embedding app to
10789 * mono_aot_register_module (). The symbol points to a pointer to the the file info
10790 * structure.
10792 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10794 /* Get rid of characters which cannot occur in symbols */
10795 p = symbol;
10796 for (p = symbol; *p; ++p) {
10797 if (!(isalnum (*p) || *p == '_'))
10798 *p = '_';
10800 acfg->static_linking_symbol = g_strdup (symbol);
10803 if (acfg->llvm)
10804 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10805 else
10806 emit_aot_file_info (acfg, info);
10809 static void
10810 emit_blob (MonoAotCompile *acfg)
10812 acfg->blob_closed = TRUE;
10814 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10817 static void
10818 emit_objc_selectors (MonoAotCompile *acfg)
10820 int i;
10821 char symbol [128];
10823 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10824 return;
10827 * From
10828 * cat > foo.m << EOF
10829 * void *ret ()
10831 * return @selector(print:);
10833 * EOF
10836 mono_img_writer_emit_unset_mode (acfg->w);
10837 g_assert (acfg->fp);
10838 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10839 fprintf (acfg->fp, ".align 3\n");
10840 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10841 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10842 emit_label (acfg, symbol);
10843 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10844 emit_pointer (acfg, symbol);
10847 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
10848 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10849 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10850 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10853 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10854 fprintf (acfg->fp, ".align 3\n");
10855 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10856 fprintf (acfg->fp, ".long 0\n");
10857 fprintf (acfg->fp, ".long 16\n");
10860 static void
10861 emit_dwarf_info (MonoAotCompile *acfg)
10863 #ifdef EMIT_DWARF_INFO
10864 int i;
10865 char symbol2 [128];
10867 /* DIEs for methods */
10868 for (i = 0; i < acfg->nmethods; ++i) {
10869 MonoCompile *cfg = acfg->cfgs [i];
10871 if (ignore_cfg (cfg))
10872 continue;
10874 // FIXME: LLVM doesn't define .Lme_...
10875 if (cfg->compile_llvm)
10876 continue;
10878 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10880 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 ()));
10882 #endif
10885 #ifdef EMIT_WIN32_CODEVIEW_INFO
10886 typedef struct _CodeViewSubSectionData
10888 gchar *start_section;
10889 gchar *end_section;
10890 gchar *start_section_record;
10891 gchar *end_section_record;
10892 int section_type;
10893 int section_record_type;
10894 int section_id;
10895 } CodeViewSubsectionData;
10897 typedef struct _CodeViewCompilerVersion
10899 gint major;
10900 gint minor;
10901 gint revision;
10902 gint patch;
10903 } CodeViewCompilerVersion;
10905 #define CODEVIEW_SUBSECTION_SYMBOL_TYPE 0xF1
10906 #define CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE 0x113c
10907 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE 0x1147
10908 #define CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE 0x114F
10909 #define CODEVIEW_CSHARP_LANGUAGE_TYPE 0x0A
10910 #define CODEVIEW_CPU_TYPE 0x0
10911 #define CODEVIEW_MAGIC_HEADER 0x4
10913 static void
10914 codeview_clear_subsection_data (CodeViewSubsectionData *section_data)
10916 g_free (section_data->start_section);
10917 g_free (section_data->end_section);
10918 g_free (section_data->start_section_record);
10919 g_free (section_data->end_section_record);
10921 memset (section_data, 0, sizeof (CodeViewSubsectionData));
10924 static void
10925 codeview_parse_compiler_version (gchar *version, CodeViewCompilerVersion *data)
10927 gint values[4] = { 0 };
10928 gint *value = values;
10930 while (*version && (value < values + G_N_ELEMENTS (values))) {
10931 if (isdigit (*version)) {
10932 *value *= 10;
10933 *value += *version - '0';
10935 else if (*version == '.') {
10936 value++;
10939 version++;
10942 data->major = values[0];
10943 data->minor = values[1];
10944 data->revision = values[2];
10945 data->patch = values[3];
10948 static void
10949 emit_codeview_start_subsection (MonoAotCompile *acfg, int section_id, int section_type, int section_record_type, CodeViewSubsectionData *section_data)
10951 // Starting a new subsection, clear old data.
10952 codeview_clear_subsection_data (section_data);
10954 // Keep subsection data.
10955 section_data->section_id = section_id;
10956 section_data->section_type = section_type;
10957 section_data->section_record_type = section_record_type;
10959 // Allocate all labels used in subsection.
10960 section_data->start_section = g_strdup_printf ("%scvs_%d", acfg->temp_prefix, section_data->section_id);
10961 section_data->end_section = g_strdup_printf ("%scvse_%d", acfg->temp_prefix, section_data->section_id);
10962 section_data->start_section_record = g_strdup_printf ("%scvsr_%d", acfg->temp_prefix, section_data->section_id);
10963 section_data->end_section_record = g_strdup_printf ("%scvsre_%d", acfg->temp_prefix, section_data->section_id);
10965 // Subsection type, function symbol.
10966 emit_int32 (acfg, section_data->section_type);
10968 // Subsection size.
10969 emit_symbol_diff (acfg, section_data->end_section, section_data->start_section, 0);
10970 emit_label (acfg, section_data->start_section);
10972 // Subsection record size.
10973 fprintf (acfg->fp, "\t.word %s - %s\n", section_data->end_section_record, section_data->start_section_record);
10974 emit_label (acfg, section_data->start_section_record);
10976 // Subsection record type.
10977 emit_int16 (acfg, section_record_type);
10980 static void
10981 emit_codeview_end_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
10983 g_assert (section_data->start_section);
10984 g_assert (section_data->end_section);
10985 g_assert (section_data->start_section_record);
10986 g_assert (section_data->end_section_record);
10988 emit_label (acfg, section_data->end_section_record);
10990 if (section_data->section_record_type == CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE) {
10991 // Emit record length.
10992 emit_int16 (acfg, 2);
10994 // Emit specific record type end.
10995 emit_int16 (acfg, CODEVIEW_SUBSECTION_RECORD_FUNCTION_END_TYPE);
10998 emit_label (acfg, section_data->end_section);
11000 // Next subsection needs to be 4 byte aligned.
11001 emit_alignment (acfg, 4);
11003 *section_id = section_data->section_id + 1;
11004 codeview_clear_subsection_data (section_data);
11007 inline static void
11008 emit_codeview_start_symbol_subsection (MonoAotCompile *acfg, int section_id, int section_record_type, CodeViewSubsectionData *section_data)
11010 emit_codeview_start_subsection (acfg, section_id, CODEVIEW_SUBSECTION_SYMBOL_TYPE, section_record_type, section_data);
11013 inline static void
11014 emit_codeview_end_symbol_subsection (MonoAotCompile *acfg, CodeViewSubsectionData *section_data, int *section_id)
11016 emit_codeview_end_subsection (acfg, section_data, section_id);
11019 static void
11020 emit_codeview_compiler_info (MonoAotCompile *acfg, int *section_id)
11022 CodeViewSubsectionData section_data = { 0 };
11023 CodeViewCompilerVersion compiler_version = { 0 };
11025 // Start new compiler record subsection.
11026 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_COMPILER_TYPE, &section_data);
11028 emit_int32 (acfg, CODEVIEW_CSHARP_LANGUAGE_TYPE);
11029 emit_int16 (acfg, CODEVIEW_CPU_TYPE);
11031 // Get compiler version information.
11032 codeview_parse_compiler_version (VERSION, &compiler_version);
11034 // Compiler frontend version, 4 digits.
11035 emit_int16 (acfg, compiler_version.major);
11036 emit_int16 (acfg, compiler_version.minor);
11037 emit_int16 (acfg, compiler_version.revision);
11038 emit_int16 (acfg, compiler_version.patch);
11040 // Compiler backend version, 4 digits (currently same as frontend).
11041 emit_int16 (acfg, compiler_version.major);
11042 emit_int16 (acfg, compiler_version.minor);
11043 emit_int16 (acfg, compiler_version.revision);
11044 emit_int16 (acfg, compiler_version.patch);
11046 // Compiler string.
11047 emit_string (acfg, "Mono AOT compiler");
11049 // Done with section.
11050 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11053 static void
11054 emit_codeview_function_info (MonoAotCompile *acfg, MonoMethod *method, int *section_id, gchar *symbol, gchar *symbol_start, gchar *symbol_end)
11056 CodeViewSubsectionData section_data = { 0 };
11057 gchar *full_method_name = NULL;
11059 // Start new function record subsection.
11060 emit_codeview_start_symbol_subsection (acfg, *section_id, CODEVIEW_SUBSECTION_RECORD_FUNCTION_START_TYPE, &section_data);
11062 // Emit 3 int 0 byte padding, currently not used.
11063 emit_zero_bytes (acfg, sizeof (int) * 3);
11065 // Emit size of function.
11066 emit_symbol_diff (acfg, symbol_end, symbol_start, 0);
11068 // Emit 3 int 0 byte padding, currently not used.
11069 emit_zero_bytes (acfg, sizeof (int) * 3);
11071 // Emit reallocation info.
11072 fprintf (acfg->fp, "\t.secrel32 %s\n", symbol);
11073 fprintf (acfg->fp, "\t.secidx %s\n", symbol);
11075 // Emit flag, currently not used.
11076 emit_zero_bytes (acfg, 1);
11078 // Emit function name, exclude signature since it should be described by own metadata.
11079 full_method_name = mono_method_full_name (method, FALSE);
11080 emit_string (acfg, full_method_name ? full_method_name : "");
11081 g_free (full_method_name);
11083 // Done with section.
11084 emit_codeview_end_symbol_subsection (acfg, &section_data, section_id);
11087 static void
11088 emit_codeview_info (MonoAotCompile *acfg)
11090 int i;
11091 int section_id = 0;
11092 gchar symbol_buffer[MAX_SYMBOL_SIZE];
11094 // Emit codeview debug info section
11095 emit_section_change (acfg, ".debug$S", 0);
11097 // Emit magic header.
11098 emit_int32 (acfg, CODEVIEW_MAGIC_HEADER);
11100 emit_codeview_compiler_info (acfg, &section_id);
11102 for (i = 0; i < acfg->nmethods; ++i) {
11103 MonoCompile *cfg = acfg->cfgs[i];
11105 if (!cfg || COMPILE_LLVM (cfg))
11106 continue;
11108 int ret = g_snprintf (symbol_buffer, G_N_ELEMENTS (symbol_buffer), "%sme_%x", acfg->temp_prefix, i);
11109 if (ret > 0 && ret < G_N_ELEMENTS (symbol_buffer))
11110 emit_codeview_function_info (acfg, cfg->method, &section_id, cfg->asm_debug_symbol, cfg->asm_symbol, symbol_buffer);
11113 #else
11114 static void
11115 emit_codeview_info (MonoAotCompile *acfg)
11118 #endif /* EMIT_WIN32_CODEVIEW_INFO */
11120 #ifdef EMIT_WIN32_UNWIND_INFO
11121 static UnwindInfoSectionCacheItem *
11122 get_cached_unwind_info_section_item_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11124 UnwindInfoSectionCacheItem *item = NULL;
11126 if (!acfg->unwind_info_section_cache)
11127 acfg->unwind_info_section_cache = g_list_alloc ();
11129 PUNWIND_INFO unwind_info = mono_arch_unwindinfo_alloc_unwind_info (unwind_ops);
11131 // Search for unwind info in cache.
11132 GList *list = acfg->unwind_info_section_cache;
11133 int list_size = 0;
11134 while (list && list->data) {
11135 item = (UnwindInfoSectionCacheItem*)list->data;
11136 if (!memcmp (unwind_info, item->unwind_info, sizeof (UNWIND_INFO))) {
11137 // Cache hit, return cached item.
11138 return item;
11140 list = list->next;
11141 list_size++;
11144 // Add to cache.
11145 if (acfg->unwind_info_section_cache) {
11146 item = g_new0 (UnwindInfoSectionCacheItem, 1);
11147 if (item) {
11148 // Format .xdata section label for function, used to get unwind info address RVA.
11149 // Since the unwind info is similar for most functions, the symbol will be reused.
11150 item->xdata_section_label = g_strdup_printf ("%sunwind_%d", acfg->temp_prefix, list_size);
11152 // Cache unwind info data, used when checking cache for matching unwind info. NOTE, cache takes
11153 //over ownership of unwind info.
11154 item->unwind_info = unwind_info;
11156 // Needs to be emitted once.
11157 item->xdata_section_emitted = FALSE;
11159 // Prepend to beginning of list to speed up inserts.
11160 acfg->unwind_info_section_cache = g_list_prepend (acfg->unwind_info_section_cache, (gpointer)item);
11164 return item;
11167 static void
11168 free_unwind_info_section_cache_win32 (MonoAotCompile *acfg)
11170 GList *list = acfg->unwind_info_section_cache;
11172 while (list) {
11173 UnwindInfoSectionCacheItem *item = (UnwindInfoSectionCacheItem *)list->data;
11174 if (item) {
11175 g_free (item->xdata_section_label);
11176 mono_arch_unwindinfo_free_unwind_info (item->unwind_info);
11178 g_free (item);
11179 list->data = NULL;
11182 list = list->next;
11185 g_list_free (acfg->unwind_info_section_cache);
11186 acfg->unwind_info_section_cache = NULL;
11189 static void
11190 emit_unwind_info_data_win32 (MonoAotCompile *acfg, PUNWIND_INFO unwind_info)
11192 // Emit the unwind info struct.
11193 emit_bytes (acfg, (guint8*)unwind_info, sizeof (UNWIND_INFO) - (sizeof (UNWIND_CODE) * MONO_MAX_UNWIND_CODES));
11195 // Emit all unwind codes encoded in unwind info struct.
11196 PUNWIND_CODE current_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES - unwind_info->CountOfCodes];
11197 PUNWIND_CODE last_unwind_node = &unwind_info->UnwindCode[MONO_MAX_UNWIND_CODES];
11199 while (current_unwind_node < last_unwind_node) {
11200 guint8 node_count = 0;
11201 switch (current_unwind_node->UnwindOp) {
11202 case UWOP_PUSH_NONVOL:
11203 case UWOP_ALLOC_SMALL:
11204 case UWOP_SET_FPREG:
11205 case UWOP_PUSH_MACHFRAME:
11206 node_count = 1;
11207 break;
11208 case UWOP_SAVE_NONVOL:
11209 case UWOP_SAVE_XMM128:
11210 node_count = 2;
11211 break;
11212 case UWOP_SAVE_NONVOL_FAR:
11213 case UWOP_SAVE_XMM128_FAR:
11214 node_count = 3;
11215 break;
11216 case UWOP_ALLOC_LARGE:
11217 if (current_unwind_node->OpInfo == 0)
11218 node_count = 2;
11219 else
11220 node_count = 3;
11221 break;
11222 default:
11223 g_assert (!"Unknown unwind opcode.");
11226 while (node_count > 0) {
11227 g_assert (current_unwind_node < last_unwind_node);
11229 //Emit current node.
11230 emit_bytes (acfg, (guint8*)current_unwind_node, sizeof (UNWIND_CODE));
11232 node_count--;
11233 current_unwind_node++;
11238 // Emit unwind info sections for each function. Unwind info on Windows x64 is emitted into two different sections.
11239 // .pdata includes the serialized DWORD aligned RVA's of function start, end and address of serialized
11240 // UNWIND_INFO struct emitted into .xdata, see https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx.
11241 // .xdata section includes DWORD aligned serialized version of UNWIND_INFO struct, https://msdn.microsoft.com/en-us/library/ddssxxy8.aspx.
11242 static void
11243 emit_unwind_info_sections_win32 (MonoAotCompile *acfg, const char *function_start, const char *function_end, GSList *unwind_ops)
11245 char *pdata_section_label = NULL;
11247 int temp_prefix_len = (acfg->temp_prefix != NULL) ? strlen (acfg->temp_prefix) : 0;
11248 if (strncmp (function_start, acfg->temp_prefix, temp_prefix_len)) {
11249 temp_prefix_len = 0;
11252 // Format .pdata section label for function.
11253 pdata_section_label = g_strdup_printf ("%spdata_%s", acfg->temp_prefix, function_start + temp_prefix_len);
11255 UnwindInfoSectionCacheItem *cache_item = get_cached_unwind_info_section_item_win32 (acfg, function_start, function_end, unwind_ops);
11256 g_assert (cache_item && cache_item->xdata_section_label && cache_item->unwind_info);
11258 // Emit .pdata section.
11259 emit_section_change (acfg, ".pdata", 0);
11260 emit_alignment (acfg, sizeof (DWORD));
11261 emit_label (acfg, pdata_section_label);
11263 // Emit function start address RVA.
11264 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_start);
11266 // Emit function end address RVA.
11267 fprintf (acfg->fp, "\t.long %s@IMGREL\n", function_end);
11269 // Emit unwind info address RVA.
11270 fprintf (acfg->fp, "\t.long %s@IMGREL\n", cache_item->xdata_section_label);
11272 if (!cache_item->xdata_section_emitted) {
11273 // Emit .xdata section.
11274 emit_section_change (acfg, ".xdata", 0);
11275 emit_alignment (acfg, sizeof (DWORD));
11276 emit_label (acfg, cache_item->xdata_section_label);
11278 // Emit unwind info into .xdata section.
11279 emit_unwind_info_data_win32 (acfg, cache_item->unwind_info);
11280 cache_item->xdata_section_emitted = TRUE;
11283 g_free (pdata_section_label);
11285 #endif
11287 static gboolean
11288 should_emit_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
11290 #ifdef TARGET_WASM
11291 if (acfg->image == mono_get_corlib () && !strcmp (m_class_get_name (method->klass), "Vector`1"))
11292 /* The SIMD fallback code in Vector<T> is very large, and not likely to be used */
11293 return FALSE;
11294 #endif
11295 return TRUE;
11298 static gboolean
11299 collect_methods (MonoAotCompile *acfg)
11301 int mindex, i;
11302 MonoImage *image = acfg->image;
11304 /* Collect methods */
11305 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
11306 ERROR_DECL (error);
11307 MonoMethod *method;
11308 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
11310 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11312 if (!method) {
11313 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (error));
11314 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
11315 mono_error_cleanup (error);
11316 return FALSE;
11319 /* Load all methods eagerly to skip the slower lazy loading code */
11320 mono_class_setup_methods (method->klass);
11322 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
11323 /* Compile the wrapper instead */
11324 /* We do this here instead of add_wrappers () because it is easy to do it here */
11325 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
11326 method = wrapper;
11329 /* FIXME: Some mscorlib methods don't have debug info */
11331 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
11332 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
11333 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
11334 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
11335 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
11336 if (!mono_debug_lookup_method (method)) {
11337 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
11338 exit (1);
11344 if (method->is_generic || mono_class_is_gtd (method->klass)) {
11345 /* Compile the ref shared version instead */
11346 MonoMethod *shared_method = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
11347 if (!shared_method) {
11348 /* Fails ref constraints */
11349 /* Keep the original method, compile_method () will skip it */
11350 } else {
11351 method = shared_method;
11355 /* Since we add the normal methods first, their index will be equal to their zero based token index */
11356 add_method_with_index (acfg, method, i, FALSE);
11357 acfg->method_index ++;
11360 /* gsharedvt methods */
11361 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
11362 ERROR_DECL (error);
11363 MonoMethod *method;
11364 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
11366 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
11367 continue;
11369 method = mono_get_method_checked (acfg->image, token, NULL, NULL, error);
11370 report_loader_error (acfg, error, TRUE, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (error));
11372 if ((method->is_generic || mono_class_is_gtd (method->klass)) && should_emit_gsharedvt_method (acfg, method)) {
11373 MonoMethod *gshared;
11375 gshared = mini_get_shared_method_full (method, SHARE_MODE_GSHAREDVT, error);
11376 mono_error_assert_ok (error);
11378 add_extra_method (acfg, gshared);
11382 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11383 add_generic_instances (acfg);
11385 if (mono_aot_mode_is_full (&acfg->aot_opts))
11386 add_wrappers (acfg);
11387 return TRUE;
11390 static void
11391 compile_methods (MonoAotCompile *acfg)
11393 int i, methods_len;
11395 if (acfg->aot_opts.nthreads > 0) {
11396 GPtrArray *frag;
11397 int len, j;
11398 GPtrArray *threads;
11399 MonoThreadHandle *thread_handle;
11400 gpointer *user_data;
11401 MonoMethod **methods;
11403 methods_len = acfg->methods->len;
11405 len = acfg->methods->len / acfg->aot_opts.nthreads;
11406 g_assert (len > 0);
11408 * Partition the list of methods into fragments, and hand it to threads to
11409 * process.
11411 threads = g_ptr_array_new ();
11412 /* Make a copy since acfg->methods is modified by compile_method () */
11413 methods = g_new0 (MonoMethod*, methods_len);
11414 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
11415 for (i = 0; i < methods_len; ++i)
11416 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
11417 i = 0;
11418 while (i < methods_len) {
11419 ERROR_DECL (error);
11420 MonoInternalThread *thread;
11422 frag = g_ptr_array_new ();
11423 for (j = 0; j < len; ++j) {
11424 if (i < methods_len) {
11425 g_ptr_array_add (frag, methods [i]);
11426 i ++;
11430 user_data = g_new0 (gpointer, 3);
11431 user_data [0] = acfg;
11432 user_data [1] = frag;
11434 thread = mono_thread_create_internal (mono_domain_get (), (gpointer)compile_thread_main, user_data, MONO_THREAD_CREATE_FLAGS_NONE, error);
11435 mono_error_assert_ok (error);
11437 thread_handle = mono_threads_open_thread_handle (thread->handle);
11438 g_ptr_array_add (threads, thread_handle);
11440 g_free (methods);
11442 for (i = 0; i < threads->len; ++i) {
11443 mono_thread_info_wait_one_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
11444 mono_threads_close_thread_handle ((MonoThreadHandle*)g_ptr_array_index (threads, i));
11446 } else {
11447 methods_len = 0;
11450 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
11451 for (i = methods_len; i < acfg->methods->len; ++i) {
11452 /* This can add new methods to acfg->methods */
11453 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
11456 #ifdef ENABLE_LLVM
11457 if (acfg->llvm)
11458 mono_llvm_fixup_aot_module ();
11459 #endif
11462 static int
11463 compile_asm (MonoAotCompile *acfg)
11465 char *command, *objfile;
11466 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
11467 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
11468 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
11470 #ifdef TARGET_WIN32_MSVC
11471 #define AS_OPTIONS "-c -x assembler"
11472 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
11473 #define AS_OPTIONS "--64"
11474 #elif defined(TARGET_POWERPC64)
11475 #define AS_OPTIONS "-a64 -mppc64"
11476 #elif defined(sparc) && TARGET_SIZEOF_VOID_P == 8
11477 #define AS_OPTIONS "-xarch=v9"
11478 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11479 #define AS_OPTIONS "-arch i386"
11480 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11481 #define AS_OPTIONS "--32"
11482 #else
11483 #define AS_OPTIONS ""
11484 #endif
11486 #if defined(TARGET_OSX)
11487 #define AS_NAME "clang"
11488 #elif defined(TARGET_WIN32_MSVC)
11489 #define AS_NAME "clang.exe"
11490 #else
11491 #define AS_NAME "as"
11492 #endif
11494 #ifdef TARGET_WIN32_MSVC
11495 #define AS_OBJECT_FILE_SUFFIX "obj"
11496 #else
11497 #define AS_OBJECT_FILE_SUFFIX "o"
11498 #endif
11500 #if defined(sparc)
11501 #define LD_NAME "ld"
11502 #define LD_OPTIONS "-shared -G"
11503 #elif defined(__ppc__) && defined(TARGET_MACH)
11504 #define LD_NAME "gcc"
11505 #define LD_OPTIONS "-dynamiclib"
11506 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
11507 #define LD_NAME "clang"
11508 #define LD_OPTIONS "--shared"
11509 #elif defined(TARGET_WIN32_MSVC)
11510 #define LD_NAME "link.exe"
11511 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO /INCREMENTAL:NO"
11512 #define LD_DEBUG_OPTIONS LD_OPTIONS " /DEBUG"
11513 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
11514 #define LD_NAME "gcc"
11515 #define LD_OPTIONS "-shared"
11516 #elif defined(TARGET_X86) && defined(TARGET_MACH)
11517 #define LD_NAME "clang"
11518 #define LD_OPTIONS "-m32 -dynamiclib"
11519 #elif defined(TARGET_X86) && !defined(TARGET_MACH)
11520 #define LD_OPTIONS "-m elf_i386"
11521 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
11522 #define LD_NAME "gcc"
11523 #define LD_OPTIONS "--shared"
11524 #elif defined(TARGET_POWERPC64)
11525 #define LD_OPTIONS "-m elf64ppc"
11526 #endif
11528 #ifndef LD_OPTIONS
11529 #define LD_OPTIONS ""
11530 #endif
11532 if (acfg->aot_opts.asm_only) {
11533 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
11534 if (acfg->aot_opts.static_link)
11535 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11536 if (acfg->llvm)
11537 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
11538 return 0;
11541 if (acfg->aot_opts.static_link) {
11542 if (acfg->aot_opts.outfile)
11543 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11544 else
11545 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
11546 } else {
11547 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
11550 #ifdef TARGET_OSX
11551 g_string_append (acfg->as_args, "-c -x assembler");
11552 #endif
11554 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11555 acfg->as_args ? acfg->as_args->str : "",
11556 wrap_path (objfile), wrap_path (acfg->tmpfname));
11557 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11558 if (execute_system (command) != 0) {
11559 g_free (command);
11560 g_free (objfile);
11561 return 1;
11564 if (acfg->llvm && !acfg->llvm_owriter) {
11565 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
11566 acfg->as_args ? acfg->as_args->str : "",
11567 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
11568 aot_printf (acfg, "Executing the native assembler: %s\n", command);
11569 if (execute_system (command) != 0) {
11570 g_free (command);
11571 g_free (objfile);
11572 return 1;
11576 g_free (command);
11578 if (acfg->aot_opts.static_link) {
11579 aot_printf (acfg, "Output file: '%s'.\n", objfile);
11580 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
11581 g_free (objfile);
11582 return 0;
11585 if (acfg->aot_opts.outfile)
11586 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11587 else
11588 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
11590 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
11592 if (acfg->llvm) {
11593 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
11594 } else {
11595 llvm_ofile = g_strdup ("");
11598 /* replace the ; flags separators with spaces */
11599 g_strdelimit (ld_flags, ';', ' ');
11601 if (acfg->aot_opts.llvm_only)
11602 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
11604 #ifdef TARGET_WIN32_MSVC
11605 g_assert (tmp_outfile_name != NULL);
11606 g_assert (objfile != NULL);
11607 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:%s %s %s", tool_prefix, LD_NAME,
11608 acfg->aot_opts.nodebug ? LD_OPTIONS : LD_DEBUG_OPTIONS, ld_flags, wrap_path (tmp_outfile_name), wrap_path (objfile), wrap_path (llvm_ofile));
11609 #elif defined(LD_NAME)
11610 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
11611 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11612 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11613 #else
11614 // Default (linux)
11615 if (acfg->aot_opts.tool_prefix) {
11616 /* Cross compiling */
11617 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
11618 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11619 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11620 } else {
11621 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
11622 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
11623 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
11625 if (acfg->aot_opts.llvm_only) {
11626 command = g_strdup_printf ("%s %s", acfg->aot_opts.clangxx, args);
11627 } else {
11628 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
11630 g_free (args);
11632 #endif
11633 aot_printf (acfg, "Executing the native linker: %s\n", command);
11634 if (execute_system (command) != 0) {
11635 g_free (tmp_outfile_name);
11636 g_free (outfile_name);
11637 g_free (command);
11638 g_free (objfile);
11639 g_free (ld_flags);
11640 return 1;
11643 g_free (command);
11645 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
11646 printf ("Stripping the binary: %s\n", com);
11647 execute_system (com);
11648 g_free (com);*/
11650 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
11652 * gas generates 'mapping symbols' each time code and data is mixed, which
11653 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
11655 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
11656 aot_printf (acfg, "Stripping the binary: %s\n", command);
11657 if (execute_system (command) != 0) {
11658 g_free (tmp_outfile_name);
11659 g_free (outfile_name);
11660 g_free (command);
11661 g_free (objfile);
11662 return 1;
11664 #endif
11666 if (0 != rename (tmp_outfile_name, outfile_name)) {
11667 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
11668 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
11669 unlink (outfile_name);
11670 rename (tmp_outfile_name, outfile_name);
11674 #if defined(TARGET_MACH)
11675 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
11676 aot_printf (acfg, "Executing dsymutil: %s\n", command);
11677 if (execute_system (command) != 0) {
11678 return 1;
11680 #endif
11682 if (!acfg->aot_opts.save_temps)
11683 unlink (objfile);
11685 g_free (tmp_outfile_name);
11686 g_free (outfile_name);
11687 g_free (objfile);
11689 if (acfg->aot_opts.save_temps)
11690 aot_printf (acfg, "Retained input file.\n");
11691 else
11692 unlink (acfg->tmpfname);
11694 return 0;
11697 static guint8
11698 profread_byte (FILE *infile)
11700 guint8 i;
11701 int res;
11703 res = fread (&i, 1, 1, infile);
11704 g_assert (res == 1);
11705 return i;
11708 static int
11709 profread_int (FILE *infile)
11711 int i, res;
11713 res = fread (&i, 4, 1, infile);
11714 g_assert (res == 1);
11715 return i;
11718 static char*
11719 profread_string (FILE *infile)
11721 int len, res;
11722 char *pbuf;
11724 len = profread_int (infile);
11725 pbuf = (char*)g_malloc (len + 1);
11726 res = fread (pbuf, 1, len, infile);
11727 g_assert (res == len);
11728 pbuf [len] = '\0';
11729 return pbuf;
11732 static void
11733 load_profile_file (MonoAotCompile *acfg, char *filename)
11735 FILE *infile;
11736 char buf [1024];
11737 int res, len, version;
11738 char magic [32];
11740 infile = fopen (filename, "r");
11741 if (!infile) {
11742 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
11743 exit (1);
11746 printf ("Using profile data file '%s'\n", filename);
11748 sprintf (magic, AOT_PROFILER_MAGIC);
11749 len = strlen (magic);
11750 res = fread (buf, 1, len, infile);
11751 magic [len] = '\0';
11752 buf [len] = '\0';
11753 if ((res != len) || strcmp (buf, magic) != 0) {
11754 printf ("Profile file has wrong header: '%s'.\n", buf);
11755 fclose (infile);
11756 exit (1);
11758 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
11759 version = profread_int (infile);
11760 if (version != expected_version) {
11761 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
11762 fclose (infile);
11763 exit (1);
11766 ProfileData *data = g_new0 (ProfileData, 1);
11767 data->images = g_hash_table_new (NULL, NULL);
11768 data->classes = g_hash_table_new (NULL, NULL);
11769 data->ginsts = g_hash_table_new (NULL, NULL);
11770 data->methods = g_hash_table_new (NULL, NULL);
11772 while (TRUE) {
11773 int type = profread_byte (infile);
11774 int id = profread_int (infile);
11776 if (type == AOTPROF_RECORD_NONE)
11777 break;
11779 switch (type) {
11780 case AOTPROF_RECORD_IMAGE: {
11781 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
11782 idata->name = profread_string (infile);
11783 char *mvid = profread_string (infile);
11784 g_free (mvid);
11785 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
11786 break;
11788 case AOTPROF_RECORD_GINST: {
11789 int i;
11790 int len = profread_int (infile);
11792 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
11793 gdata->argc = len;
11794 gdata->argv = g_new0 (ClassProfileData*, len);
11796 for (i = 0; i < len; ++i) {
11797 int class_id = profread_int (infile);
11799 gdata->argv [i] = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
11800 g_assert (gdata->argv [i]);
11802 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
11803 break;
11805 case AOTPROF_RECORD_TYPE: {
11806 int type = profread_byte (infile);
11808 switch (type) {
11809 case MONO_TYPE_CLASS: {
11810 int image_id = profread_int (infile);
11811 int ginst_id = profread_int (infile);
11812 char *class_name = profread_string (infile);
11814 ImageProfileData *image = (ImageProfileData*)g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
11815 g_assert (image);
11817 char *p = strrchr (class_name, '.');
11818 g_assert (p);
11819 *p = '\0';
11821 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
11822 cdata->image = image;
11823 cdata->ns = g_strdup (class_name);
11824 cdata->name = g_strdup (p + 1);
11826 if (ginst_id != -1) {
11827 cdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
11828 g_assert (cdata->inst);
11830 g_free (class_name);
11832 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
11833 break;
11835 #if 0
11836 case MONO_TYPE_SZARRAY: {
11837 int elem_id = profread_int (infile);
11838 // FIXME:
11839 break;
11841 #endif
11842 default:
11843 g_assert_not_reached ();
11844 break;
11846 break;
11848 case AOTPROF_RECORD_METHOD: {
11849 int class_id = profread_int (infile);
11850 int ginst_id = profread_int (infile);
11851 int param_count = profread_int (infile);
11852 char *method_name = profread_string (infile);
11853 char *sig = profread_string (infile);
11855 ClassProfileData *klass = (ClassProfileData*)g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
11856 g_assert (klass);
11858 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
11859 mdata->id = id;
11860 mdata->klass = klass;
11861 mdata->name = method_name;
11862 mdata->signature = sig;
11863 mdata->param_count = param_count;
11865 if (ginst_id != -1) {
11866 mdata->inst = (GInstProfileData*)g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
11867 g_assert (mdata->inst);
11869 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
11870 break;
11872 default:
11873 printf ("%d\n", type);
11874 g_assert_not_reached ();
11875 break;
11879 fclose (infile);
11880 acfg->profile_data = g_list_append (acfg->profile_data, data);
11883 static void
11884 resolve_class (ClassProfileData *cdata);
11886 static void
11887 resolve_ginst (GInstProfileData *inst_data)
11889 int i;
11891 if (inst_data->inst)
11892 return;
11894 for (i = 0; i < inst_data->argc; ++i) {
11895 resolve_class (inst_data->argv [i]);
11896 if (!inst_data->argv [i]->klass)
11897 return;
11899 MonoType **args = g_new0 (MonoType*, inst_data->argc);
11900 for (i = 0; i < inst_data->argc; ++i)
11901 args [i] = m_class_get_byval_arg (inst_data->argv [i]->klass);
11903 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
11906 static void
11907 resolve_class (ClassProfileData *cdata)
11909 ERROR_DECL (error);
11910 MonoClass *klass;
11912 if (!cdata->image->image)
11913 return;
11915 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, error);
11916 if (!klass) {
11917 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
11918 return;
11920 if (cdata->inst) {
11921 resolve_ginst (cdata->inst);
11922 if (!cdata->inst->inst)
11923 return;
11924 MonoGenericContext ctx;
11926 memset (&ctx, 0, sizeof (ctx));
11927 ctx.class_inst = cdata->inst->inst;
11928 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, error);
11929 } else {
11930 cdata->klass = klass;
11935 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
11937 static void
11938 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
11940 GHashTableIter iter;
11941 gpointer key, value;
11942 int i;
11944 if (!data)
11945 return;
11947 /* Images */
11948 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
11949 g_hash_table_iter_init (&iter, data->images);
11950 while (g_hash_table_iter_next (&iter, &key, &value)) {
11951 ImageProfileData *idata = (ImageProfileData*)value;
11953 for (i = 0; i < assemblies->len; ++i) {
11954 MonoAssembly *ass = (MonoAssembly*)g_ptr_array_index (assemblies, i);
11956 if (!strcmp (ass->aname.name, idata->name)) {
11957 idata->image = ass->image;
11958 break;
11962 g_ptr_array_free (assemblies, TRUE);
11964 /* Classes */
11965 g_hash_table_iter_init (&iter, data->classes);
11966 while (g_hash_table_iter_next (&iter, &key, &value)) {
11967 ClassProfileData *cdata = (ClassProfileData*)value;
11969 if (!cdata->image->image) {
11970 if (acfg->aot_opts.verbose)
11971 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
11972 continue;
11975 resolve_class (cdata);
11977 if (cdata->klass)
11978 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
11982 /* Methods */
11983 g_hash_table_iter_init (&iter, data->methods);
11984 while (g_hash_table_iter_next (&iter, &key, &value)) {
11985 MethodProfileData *mdata = (MethodProfileData*)value;
11986 MonoClass *klass;
11987 MonoMethod *m;
11988 gpointer miter;
11990 resolve_class (mdata->klass);
11991 klass = mdata->klass->klass;
11992 if (!klass) {
11993 if (acfg->aot_opts.verbose)
11994 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
11995 continue;
11997 miter = NULL;
11998 while ((m = mono_class_get_methods (klass, &miter))) {
11999 ERROR_DECL (error);
12001 if (strcmp (m->name, mdata->name))
12002 continue;
12003 MonoMethodSignature *sig = mono_method_signature_internal (m);
12004 if (!sig)
12005 continue;
12006 if (sig->param_count != mdata->param_count)
12007 continue;
12008 if (mdata->inst) {
12009 resolve_ginst (mdata->inst);
12010 if (!mdata->inst->inst)
12011 continue;
12012 MonoGenericContext ctx;
12014 memset (&ctx, 0, sizeof (ctx));
12015 ctx.method_inst = mdata->inst->inst;
12017 m = mono_class_inflate_generic_method_checked (m, &ctx, error);
12018 if (!m)
12019 continue;
12020 sig = mono_method_signature_checked (m, error);
12021 if (!is_ok (error)) {
12022 mono_error_cleanup (error);
12023 continue;
12026 char *sig_str = mono_signature_full_name (sig);
12027 gboolean match = !strcmp (sig_str, mdata->signature);
12028 g_free (sig_str);
12029 if (!match)
12031 continue;
12032 //printf ("%s\n", mono_method_full_name (m, 1));
12033 mdata->method = m;
12034 break;
12036 if (!mdata->method) {
12037 if (acfg->aot_opts.verbose)
12038 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
12043 static gboolean
12044 inst_references_image (MonoGenericInst *inst, MonoImage *image)
12046 int i;
12048 for (i = 0; i < inst->type_argc; ++i) {
12049 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12050 if (m_class_get_image (k) == image)
12051 return TRUE;
12052 if (mono_class_is_ginst (k)) {
12053 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
12054 if (inst_references_image (kinst, image))
12055 return TRUE;
12058 return FALSE;
12061 static gboolean
12062 is_local_inst (MonoGenericInst *inst, MonoImage *image)
12064 int i;
12066 for (i = 0; i < inst->type_argc; ++i) {
12067 MonoClass *k = mono_class_from_mono_type_internal (inst->type_argv [i]);
12068 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && m_class_get_image (k) != image)
12069 return FALSE;
12071 return TRUE;
12074 static void
12075 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
12077 GHashTableIter iter;
12078 gpointer key, value;
12079 int count = 0;
12081 if (!data)
12082 return;
12084 if (acfg->aot_opts.profile_only) {
12085 /* Add methods referenced by the profile */
12086 g_hash_table_iter_init (&iter, data->methods);
12087 while (g_hash_table_iter_next (&iter, &key, &value)) {
12088 MethodProfileData *mdata = (MethodProfileData*)value;
12089 MonoMethod *m = mdata->method;
12091 if (!m)
12092 continue;
12093 if (m->is_inflated)
12094 continue;
12095 add_extra_method (acfg, m);
12096 g_hash_table_insert (acfg->profile_methods, m, m);
12097 count ++;
12102 * Add method instances 'related' to this assembly to the AOT image.
12104 g_hash_table_iter_init (&iter, data->methods);
12105 while (g_hash_table_iter_next (&iter, &key, &value)) {
12106 MethodProfileData *mdata = (MethodProfileData*)value;
12107 MonoMethod *m = mdata->method;
12108 MonoGenericContext *ctx;
12110 if (!m)
12111 continue;
12112 if (!m->is_inflated)
12113 continue;
12115 ctx = mono_method_get_context (m);
12116 /* For simplicity, add instances which reference the assembly we are compiling */
12117 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
12118 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
12119 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12120 //printf ("%s\n", mono_method_full_name (m, TRUE));
12121 add_extra_method (acfg, m);
12122 count ++;
12123 } else if (m_class_get_image (m->klass) == acfg->image &&
12124 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
12125 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
12126 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
12127 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
12128 //printf ("%s\n", mono_method_full_name (m, TRUE));
12129 add_extra_method (acfg, m);
12130 count ++;
12133 * FIXME: We might skip some instances, for example:
12134 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
12135 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
12139 printf ("Added %d methods from profile.\n", count);
12142 static void
12143 init_got_info (GotInfo *info)
12145 int i;
12147 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12148 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12149 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12150 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
12151 info->got_patches = g_ptr_array_new ();
12154 static MonoAotCompile*
12155 acfg_create (MonoAssembly *ass, guint32 opts)
12157 MonoImage *image = ass->image;
12158 MonoAotCompile *acfg;
12160 acfg = g_new0 (MonoAotCompile, 1);
12161 acfg->methods = g_ptr_array_new ();
12162 acfg->method_indexes = g_hash_table_new (NULL, NULL);
12163 acfg->method_depth = g_hash_table_new (NULL, NULL);
12164 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
12165 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
12166 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
12167 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
12168 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
12169 acfg->image_hash = g_hash_table_new (NULL, NULL);
12170 acfg->image_table = g_ptr_array_new ();
12171 acfg->globals = g_ptr_array_new ();
12172 acfg->image = image;
12173 acfg->opts = opts;
12174 /* TODO: Write out set of SIMD instructions used, rather than just those available */
12175 #ifndef MONO_CROSS_COMPILE
12176 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
12177 #endif
12178 acfg->mempool = mono_mempool_new ();
12179 acfg->extra_methods = g_ptr_array_new ();
12180 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
12181 acfg->unwind_ops = g_ptr_array_new ();
12182 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
12183 acfg->method_order = g_ptr_array_new ();
12184 acfg->export_names = g_hash_table_new (NULL, NULL);
12185 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
12186 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
12187 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
12188 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12189 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
12190 acfg->profile_methods = g_hash_table_new (NULL, NULL);
12191 mono_os_mutex_init_recursive (&acfg->mutex);
12193 init_got_info (&acfg->got_info);
12194 init_got_info (&acfg->llvm_got_info);
12196 return acfg;
12199 static void
12200 got_info_free (GotInfo *info)
12202 int i;
12204 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12205 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
12206 g_free (info->patch_to_got_offset_by_type);
12207 g_hash_table_destroy (info->patch_to_got_offset);
12208 g_ptr_array_free (info->got_patches, TRUE);
12211 static void
12212 acfg_free (MonoAotCompile *acfg)
12214 int i;
12216 mono_img_writer_destroy (acfg->w);
12217 for (i = 0; i < acfg->nmethods; ++i)
12218 if (acfg->cfgs [i])
12219 mono_destroy_compile (acfg->cfgs [i]);
12221 g_free (acfg->cfgs);
12223 g_free (acfg->static_linking_symbol);
12224 g_free (acfg->got_symbol);
12225 g_free (acfg->plt_symbol);
12226 g_ptr_array_free (acfg->methods, TRUE);
12227 g_ptr_array_free (acfg->image_table, TRUE);
12228 g_ptr_array_free (acfg->globals, TRUE);
12229 g_ptr_array_free (acfg->unwind_ops, TRUE);
12230 g_hash_table_destroy (acfg->method_indexes);
12231 g_hash_table_destroy (acfg->method_depth);
12232 g_hash_table_destroy (acfg->plt_offset_to_entry);
12233 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
12234 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
12235 g_free (acfg->patch_to_plt_entry);
12236 g_hash_table_destroy (acfg->method_to_cfg);
12237 g_hash_table_destroy (acfg->token_info_hash);
12238 g_hash_table_destroy (acfg->method_to_pinvoke_import);
12239 g_hash_table_destroy (acfg->image_hash);
12240 g_hash_table_destroy (acfg->unwind_info_offsets);
12241 g_hash_table_destroy (acfg->method_label_hash);
12242 g_hash_table_destroy (acfg->typespec_classes);
12243 g_hash_table_destroy (acfg->export_names);
12244 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
12245 g_hash_table_destroy (acfg->klass_blob_hash);
12246 g_hash_table_destroy (acfg->method_blob_hash);
12247 got_info_free (&acfg->got_info);
12248 got_info_free (&acfg->llvm_got_info);
12249 arch_free_unwind_info_section_cache (acfg);
12250 mono_mempool_destroy (acfg->mempool);
12251 g_free (acfg);
12254 #define WRAPPER(e,n) n,
12255 static const char* const
12256 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
12257 #include "mono/metadata/wrapper-types.h"
12258 NULL
12261 static G_GNUC_UNUSED const char*
12262 get_wrapper_type_name (int type)
12264 return wrapper_type_names [type];
12267 //#define DUMP_PLT
12268 //#define DUMP_GOT
12270 static void aot_dump (MonoAotCompile *acfg)
12272 FILE *dumpfile;
12273 char * dumpname;
12275 JsonWriter writer;
12276 mono_json_writer_init (&writer);
12278 mono_json_writer_object_begin(&writer);
12280 // Methods
12281 mono_json_writer_indent (&writer);
12282 mono_json_writer_object_key(&writer, "methods");
12283 mono_json_writer_array_begin (&writer);
12285 int i;
12286 for (i = 0; i < acfg->nmethods; ++i) {
12287 MonoCompile *cfg;
12288 MonoMethod *method;
12289 MonoClass *klass;
12291 cfg = acfg->cfgs [i];
12292 if (ignore_cfg (cfg))
12293 continue;
12295 method = cfg->orig_method;
12297 mono_json_writer_indent (&writer);
12298 mono_json_writer_object_begin(&writer);
12300 mono_json_writer_indent (&writer);
12301 mono_json_writer_object_key(&writer, "name");
12302 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
12304 mono_json_writer_indent (&writer);
12305 mono_json_writer_object_key(&writer, "signature");
12306 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
12308 mono_json_writer_indent (&writer);
12309 mono_json_writer_object_key(&writer, "code_size");
12310 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
12312 klass = method->klass;
12314 mono_json_writer_indent (&writer);
12315 mono_json_writer_object_key(&writer, "class");
12316 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name (klass));
12318 mono_json_writer_indent (&writer);
12319 mono_json_writer_object_key(&writer, "namespace");
12320 mono_json_writer_printf (&writer, "\"%s\",\n", m_class_get_name_space (klass));
12322 mono_json_writer_indent (&writer);
12323 mono_json_writer_object_key(&writer, "wrapper_type");
12324 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
12326 mono_json_writer_indent_pop (&writer);
12327 mono_json_writer_indent (&writer);
12328 mono_json_writer_object_end (&writer);
12329 mono_json_writer_printf (&writer, ",\n");
12332 mono_json_writer_indent_pop (&writer);
12333 mono_json_writer_indent (&writer);
12334 mono_json_writer_array_end (&writer);
12335 mono_json_writer_printf (&writer, ",\n");
12337 // PLT entries
12338 #ifdef DUMP_PLT
12339 mono_json_writer_indent_push (&writer);
12340 mono_json_writer_indent (&writer);
12341 mono_json_writer_object_key(&writer, "plt");
12342 mono_json_writer_array_begin (&writer);
12344 for (i = 0; i < acfg->plt_offset; ++i) {
12345 MonoPltEntry *plt_entry = NULL;
12346 MonoJumpInfo *ji;
12348 if (i == 0)
12350 * The first plt entry is unused.
12352 continue;
12354 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
12355 ji = plt_entry->ji;
12357 mono_json_writer_indent (&writer);
12358 mono_json_writer_printf (&writer, "{ ");
12359 mono_json_writer_object_key(&writer, "symbol");
12360 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
12363 mono_json_writer_indent_pop (&writer);
12364 mono_json_writer_indent (&writer);
12365 mono_json_writer_array_end (&writer);
12366 mono_json_writer_printf (&writer, ",\n");
12367 #endif
12369 // GOT entries
12370 #ifdef DUMP_GOT
12371 mono_json_writer_indent_push (&writer);
12372 mono_json_writer_indent (&writer);
12373 mono_json_writer_object_key(&writer, "got");
12374 mono_json_writer_array_begin (&writer);
12376 mono_json_writer_indent_push (&writer);
12377 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
12378 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
12380 mono_json_writer_indent (&writer);
12381 mono_json_writer_printf (&writer, "{ ");
12382 mono_json_writer_object_key(&writer, "patch_name");
12383 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
12386 mono_json_writer_indent_pop (&writer);
12387 mono_json_writer_indent (&writer);
12388 mono_json_writer_array_end (&writer);
12389 mono_json_writer_printf (&writer, ",\n");
12390 #endif
12392 mono_json_writer_indent_pop (&writer);
12393 mono_json_writer_indent (&writer);
12394 mono_json_writer_object_end (&writer);
12396 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
12397 dumpfile = fopen (dumpname, "w+");
12398 g_free (dumpname);
12400 fprintf (dumpfile, "%s", writer.text->str);
12401 fclose (dumpfile);
12403 mono_json_writer_destroy (&writer);
12406 static const char *preinited_jit_icalls[] = {
12407 "mono_aot_init_llvm_method",
12408 "mono_aot_init_gshared_method_this",
12409 "mono_aot_init_gshared_method_mrgctx",
12410 "mono_aot_init_gshared_method_vtable",
12411 "mono_llvm_throw_corlib_exception",
12412 "mono_init_vtable_slot",
12413 "mono_helper_ldstr_mscorlib"
12416 static void
12417 add_preinit_got_slots (MonoAotCompile *acfg)
12419 MonoJumpInfo *ji;
12420 int i;
12423 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
12424 * during method initialization etc.
12427 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12428 ji->type = MONO_PATCH_INFO_IMAGE;
12429 ji->data.image = acfg->image;
12430 get_got_offset (acfg, FALSE, ji);
12431 get_got_offset (acfg, TRUE, ji);
12433 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12434 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
12435 get_got_offset (acfg, FALSE, ji);
12436 get_got_offset (acfg, TRUE, ji);
12438 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12439 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
12440 get_got_offset (acfg, FALSE, ji);
12441 get_got_offset (acfg, TRUE, ji);
12443 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12444 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
12445 get_got_offset (acfg, FALSE, ji);
12446 get_got_offset (acfg, TRUE, ji);
12448 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12449 ji->type = MONO_PATCH_INFO_AOT_MODULE;
12450 get_got_offset (acfg, FALSE, ji);
12451 get_got_offset (acfg, TRUE, ji);
12453 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12454 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
12455 get_got_offset (acfg, FALSE, ji);
12456 get_got_offset (acfg, TRUE, ji);
12458 for (i = 0; i < TLS_KEY_NUM; i++) {
12459 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12460 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
12461 ji->data.index = i;
12462 get_got_offset (acfg, FALSE, ji);
12463 get_got_offset (acfg, TRUE, ji);
12465 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12466 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
12467 ji->data.index = i;
12468 get_got_offset (acfg, FALSE, ji);
12469 get_got_offset (acfg, TRUE, ji);
12472 /* Called by native-to-managed wrappers on possibly unattached threads */
12473 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
12474 ji->type = MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL;
12475 ji->data.name = "mono_threads_attach_coop";
12476 get_got_offset (acfg, FALSE, ji);
12477 get_got_offset (acfg, TRUE, ji);
12479 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
12480 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
12481 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
12482 ji->data.name = preinited_jit_icalls [i];
12483 get_got_offset (acfg, FALSE, ji);
12484 get_got_offset (acfg, TRUE, ji);
12487 acfg->nshared_got_entries = acfg->got_offset;
12490 static void
12491 mono_dedup_log_stats (MonoAotCompile *acfg)
12493 GHashTableIter iter;
12494 g_assert (acfg->dedup_stats);
12496 // If dedup_emit_mode, acfg is the dummy dedup module that consolidates
12497 // deduped modules
12498 g_hash_table_iter_init (&iter, acfg->method_to_cfg);
12499 MonoCompile *dcfg = NULL;
12500 MonoMethod *method = NULL;
12502 size_t wrappers_size_saved = 0;
12503 size_t inflated_size_saved = 0;
12504 size_t copied_singles = 0;
12506 while (g_hash_table_iter_next (&iter, (gpointer *) &method, (gpointer *)&dcfg)) {
12507 gchar *dedup_name = mono_aot_get_mangled_method_name (method);
12508 guint count = GPOINTER_TO_UINT(g_hash_table_lookup (acfg->dedup_stats, dedup_name));
12510 if (count == 0)
12511 continue;
12513 if (acfg->dedup_emit_mode) {
12514 // Size *saved* is the size due to things not emitted.
12515 if (count < 2) {
12516 // Just moved, didn't save space / dedup
12517 copied_singles += dcfg->code_len;
12518 } else if (method->wrapper_type != MONO_WRAPPER_NONE) {
12519 wrappers_size_saved += dcfg->code_len * (count - 1);
12520 } else {
12521 inflated_size_saved += dcfg->code_len * (count - 1);
12524 if (acfg->aot_opts.dedup) {
12525 if (method->wrapper_type != MONO_WRAPPER_NONE) {
12526 wrappers_size_saved += dcfg->code_len * count;
12527 } else {
12528 inflated_size_saved += dcfg->code_len * count;
12533 aot_printf (acfg, "Dedup Pass: Size Saved From Deduped Wrappers:\t%zu bytes\n", wrappers_size_saved);
12534 aot_printf (acfg, "Dedup Pass: Size Saved From Inflated Methods:\t%zu bytes\n", inflated_size_saved);
12535 if (acfg->dedup_emit_mode)
12536 aot_printf (acfg, "Dedup Pass: Size of Moved But Not Deduped (only 1 copy) Methods:\t%zu bytes\n", copied_singles);
12538 g_hash_table_destroy (acfg->dedup_stats);
12539 acfg->dedup_stats = NULL;
12542 // Flush the cache to tell future calls what to skip
12543 static void
12544 mono_flush_method_cache (MonoAotCompile *acfg)
12546 GHashTable *method_cache = acfg->dedup_cache;
12547 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12548 if (!acfg->dedup_cache_changed || !acfg->aot_opts.dedup) {
12549 g_free (filename);
12550 return;
12553 acfg->dedup_cache = NULL;
12555 FILE *cache = fopen (filename, "w");
12557 if (!cache)
12558 g_error ("Could not create cache at %s because of error: %s\n", filename, strerror (errno));
12560 GHashTableIter iter;
12561 gchar *name = NULL;
12562 g_hash_table_iter_init (&iter, method_cache);
12563 gboolean cont = TRUE;
12564 while (cont && g_hash_table_iter_next (&iter, (gpointer *) &name, NULL)) {
12565 int res = fprintf (cache, "%s\n", name);
12566 cont = res >= 0;
12568 // FIXME: don't assert if error when flushing
12569 g_assert (cont);
12571 fclose (cache);
12572 g_free (filename);
12574 // The keys are all in the imageset, nothing to free
12575 // Values are just pointers to memory owned elsewhere, or sentinels
12576 g_hash_table_destroy (method_cache);
12579 // Read in what has been emitted by previous invocations,
12580 // what can be skipped
12581 static void
12582 mono_read_method_cache (MonoAotCompile *acfg)
12584 char *filename = g_strdup_printf ("%s.dedup", acfg->image->name);
12585 // Only do once, when dedup_cache is null
12586 if (acfg->dedup_cache)
12587 goto early_exit;
12589 if (acfg->aot_opts.dedup_include || acfg->aot_opts.dedup)
12590 g_assert (acfg->dedup_stats);
12592 // only in skip mode
12593 if (!acfg->aot_opts.dedup)
12594 goto early_exit;
12596 g_assert (acfg->dedup_cache);
12598 FILE *cache;
12599 cache = fopen (filename, "r");
12600 if (!cache)
12601 goto early_exit;
12603 // Since we do pointer comparisons, and it can't be allocated at
12604 // the address 0x1 due to alignment, we use this as a sentinel
12605 gpointer other_acfg_sentinel;
12606 other_acfg_sentinel = GINT_TO_POINTER (0x1);
12608 if (fseek (cache, 0L, SEEK_END))
12609 goto cleanup;
12611 size_t fileLength;
12612 fileLength = ftell (cache);
12613 g_assert (fileLength > 0);
12615 if (fseek (cache, 0L, SEEK_SET))
12616 goto cleanup;
12618 // Avoid thousands of new malloc entries
12619 // FIXME: allocate into imageset, so we don't need to free.
12620 // put the other mangled names there too.
12621 char *bulk;
12622 bulk = g_malloc0 (fileLength * sizeof (char));
12623 size_t offset;
12624 offset = 0;
12626 while (fgets (&bulk [offset], fileLength - offset, cache)) {
12627 // strip newline
12628 char *line = &bulk [offset];
12629 size_t len = strlen (line);
12630 if (len == 0)
12631 break;
12633 if (len >= 0 && line [len] == '\n')
12634 line [len] = '\0';
12635 offset += strlen (line) + 1;
12636 g_assert (fileLength >= offset);
12638 g_hash_table_insert (acfg->dedup_cache, line, other_acfg_sentinel);
12641 cleanup:
12642 fclose (cache);
12644 early_exit:
12645 g_free (filename);
12646 return;
12649 typedef struct {
12650 GHashTable *cache;
12651 GHashTable *stats;
12652 gboolean emit_inflated_methods;
12653 MonoAssembly *inflated_assembly;
12654 } MonoAotState;
12656 static MonoAotState *
12657 alloc_aot_state (void)
12659 MonoAotState *state = g_malloc (sizeof (MonoAotState));
12660 // FIXME: Should this own the memory?
12661 state->cache = g_hash_table_new (g_str_hash, g_str_equal);
12662 state->stats = g_hash_table_new (g_str_hash, g_str_equal);
12663 // Start in "collect mode"
12664 state->emit_inflated_methods = FALSE;
12665 state->inflated_assembly = NULL;
12666 return state;
12669 static void
12670 free_aot_state (MonoAotState *astate)
12672 g_hash_table_destroy (astate->cache);
12673 g_free (astate);
12676 static void
12677 mono_add_deferred_extra_methods (MonoAotCompile *acfg, MonoAotState *astate)
12679 GHashTableIter iter;
12680 gchar *name = NULL;
12681 MonoMethod *method = NULL;
12683 acfg->dedup_emit_mode = TRUE;
12685 g_hash_table_iter_init (&iter, astate->cache);
12686 while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &method)) {
12687 add_method_full (acfg, method, TRUE, 0);
12689 return;
12692 static void
12693 mono_setup_dedup_state (MonoAotCompile *acfg, MonoAotState **global_aot_state, MonoAssembly *ass, MonoAotState **astate, gboolean *is_dedup_dummy)
12695 if (!acfg->aot_opts.dedup_include && !acfg->aot_opts.dedup)
12696 return;
12698 if (global_aot_state && *global_aot_state && acfg->aot_opts.dedup_include) {
12699 // Thread the state through when making the inflate pass
12700 *astate = *global_aot_state;
12703 if (!*astate) {
12704 *astate = alloc_aot_state ();
12705 *global_aot_state = *astate;
12708 acfg->dedup_cache = (*astate)->cache;
12709 acfg->dedup_stats = (*astate)->stats;
12711 // fills out acfg->dedup_cache
12712 if (acfg->aot_opts.dedup)
12713 mono_read_method_cache (acfg);
12715 if (!(*astate)->inflated_assembly && acfg->aot_opts.dedup_include) {
12716 gchar **asm_path = g_strsplit (ass->image->name, G_DIR_SEPARATOR_S, 0);
12717 gchar *asm_file = NULL;
12719 // Get the last part of the path, the filename
12720 for (int i=0; asm_path [i] != NULL; i++)
12721 asm_file = asm_path [i];
12723 if (!strcmp (acfg->aot_opts.dedup_include, asm_file)) {
12724 // Save
12725 *is_dedup_dummy = TRUE;
12726 (*astate)->inflated_assembly = ass;
12728 g_strfreev (asm_path);
12729 } else if ((*astate)->inflated_assembly) {
12730 *is_dedup_dummy = (ass == (*astate)->inflated_assembly);
12734 int
12735 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
12737 // create assembly, loop and add extra_methods
12738 // in add_generic_instances , rip out what's in that for loop
12739 // and apply that to this aot_state inside of mono_compile_assembly
12740 MonoAotState *astate;
12741 astate = *(MonoAotState **)aot_state;
12742 g_assert (astate);
12744 // FIXME: allow suffixes?
12745 if (!astate->inflated_assembly) {
12746 const char* inflate = strstr (aot_options, "dedup-inflate");
12747 if (!inflate)
12748 return 0;
12749 else
12750 g_error ("Error: mono was not given an assembly with the provided inflate name\n");
12753 // Switch modes
12754 astate->emit_inflated_methods = TRUE;
12756 int res = mono_compile_assembly (astate->inflated_assembly, opts, aot_options, aot_state);
12758 *aot_state = NULL;
12759 free_aot_state (astate);
12761 return res;
12764 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
12765 static const char* interp_in_static_sigs[] = {
12766 "bool ptr int32 ptr&",
12767 "bool ptr ptr&",
12768 "int32 int32 ptr&",
12769 "int32 int32 ptr ptr&",
12770 "int32 ptr int32 ptr",
12771 "int32 ptr int32 ptr&",
12772 "int32 ptr ptr&",
12773 "object object ptr ptr ptr",
12774 "object",
12775 "ptr int32 ptr&",
12776 "ptr ptr int32 ptr ptr ptr&",
12777 "ptr ptr int32 ptr ptr&",
12778 "ptr ptr int32 ptr&",
12779 "ptr ptr ptr int32 ptr&",
12780 "ptr ptr ptr ptr& ptr&",
12781 "ptr ptr ptr ptr ptr&",
12782 "ptr ptr ptr ptr&",
12783 "ptr ptr ptr&",
12784 "ptr ptr uint32 ptr&",
12785 "ptr uint32 ptr&",
12786 "void object ptr ptr ptr",
12787 "void ptr ptr int32 ptr ptr& ptr ptr&",
12788 "void ptr ptr int32 ptr ptr&",
12789 "void ptr ptr ptr&",
12790 "void ptr ptr&",
12791 "void ptr",
12792 "void int32 ptr&",
12793 "void uint32 ptr&",
12794 "void"
12796 #endif
12799 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **global_aot_state)
12801 MonoImage *image = ass->image;
12802 int i, res;
12803 gint64 all_sizes;
12804 MonoAotCompile *acfg;
12805 char llvm_stats_msg [256], *p;
12806 TV_DECLARE (atv);
12807 TV_DECLARE (btv);
12809 acfg = acfg_create (ass, opts);
12811 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
12812 acfg->aot_opts.write_symbols = TRUE;
12813 acfg->aot_opts.ntrampolines = 4096;
12814 acfg->aot_opts.nrgctx_trampolines = 4096;
12815 acfg->aot_opts.nimt_trampolines = 512;
12816 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
12817 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
12818 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
12819 acfg->aot_opts.nftnptr_arg_trampolines = 128;
12820 #endif
12821 acfg->aot_opts.nunbox_arbitrary_trampolines = 256;
12822 acfg->aot_opts.llvm_path = g_strdup ("");
12823 acfg->aot_opts.temp_path = g_strdup ("");
12824 #ifdef MONOTOUCH
12825 acfg->aot_opts.use_trampolines_page = TRUE;
12826 #endif
12827 acfg->aot_opts.clangxx = g_strdup ("clang++");
12829 mono_aot_parse_options (aot_options, &acfg->aot_opts);
12831 // start dedup
12832 MonoAotState *astate = NULL;
12833 gboolean is_dedup_dummy = FALSE;
12834 mono_setup_dedup_state (acfg, (MonoAotState **) global_aot_state, ass, &astate, &is_dedup_dummy);
12836 // Process later
12837 if (is_dedup_dummy && astate && !astate->emit_inflated_methods)
12838 return 0;
12840 // end dedup
12842 if (acfg->aot_opts.logfile) {
12843 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
12846 if (acfg->aot_opts.data_outfile) {
12847 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
12848 if (!acfg->data_outfile) {
12849 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
12850 return 1;
12852 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
12855 //acfg->aot_opts.print_skipped_methods = TRUE;
12857 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
12858 if (acfg->opts & MONO_OPT_GSHAREDVT) {
12859 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
12860 return 1;
12862 if (acfg->aot_opts.llvm_only) {
12863 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
12864 return 1;
12866 #else
12867 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
12868 acfg->opts |= MONO_OPT_GSHAREDVT;
12869 #endif
12871 #if !defined(ENABLE_LLVM)
12872 if (acfg->aot_opts.llvm_only) {
12873 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
12874 return 1;
12876 #endif
12878 if (acfg->opts & MONO_OPT_GSHAREDVT)
12879 mono_set_generic_sharing_vt_supported (TRUE);
12881 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
12883 if (!acfg->aot_opts.deterministic)
12884 generate_aotid ((guint8*) &acfg->image->aotid);
12886 char *aotid = mono_guid_to_string (acfg->image->aotid);
12887 aot_printf (acfg, "AOTID %s\n", aotid);
12888 g_free (aotid);
12890 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
12891 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
12892 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
12893 return 1;
12895 #endif
12897 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
12898 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
12899 return 1;
12902 if (acfg->aot_opts.static_link)
12903 acfg->aot_opts.asm_writer = TRUE;
12905 if (acfg->aot_opts.soft_debug) {
12906 MonoDebugOptions *opt = mini_get_debug_options ();
12908 opt->mdb_optimizations = TRUE;
12909 opt->gen_sdb_seq_points = TRUE;
12911 if (!mono_debug_enabled ()) {
12912 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
12913 return 1;
12915 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
12918 if (acfg->aot_opts.try_llvm)
12919 acfg->aot_opts.llvm = mini_llvm_init ();
12921 if (mono_use_llvm || acfg->aot_opts.llvm) {
12922 acfg->llvm = TRUE;
12923 acfg->aot_opts.asm_writer = TRUE;
12924 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
12926 if (acfg->aot_opts.soft_debug) {
12927 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
12928 return 1;
12931 mini_llvm_init ();
12933 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
12934 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
12935 return 1;
12939 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
12940 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
12941 acfg->is_full_aot = TRUE;
12944 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
12945 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_INTERP);
12946 acfg->is_full_aot = TRUE;
12949 if (mono_threads_are_safepoints_enabled ())
12950 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
12952 // The methods in dedup-emit amodules must be available on runtime startup
12953 // Note: Only one such amodule can have this attribute
12954 if (astate && astate->emit_inflated_methods)
12955 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_EAGER_LOAD);
12958 if (acfg->aot_opts.instances_logfile_path) {
12959 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
12960 if (!acfg->instances_logfile) {
12961 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
12962 return 1;
12966 if (acfg->aot_opts.profile_files) {
12967 GList *l;
12969 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
12970 load_profile_file (acfg, (char*)l->data);
12974 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
12975 for (int method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index)
12976 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
12979 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
12980 #ifdef MONO_ARCH_GSHARED_SUPPORTED
12981 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
12982 #endif
12983 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
12984 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
12985 if (acfg->opts & MONO_OPT_GSHAREDVT)
12986 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
12987 #endif
12988 #ifdef MONO_ARCH_HAVE_FTNPTR_ARG_TRAMPOLINE
12989 acfg->num_trampolines [MONO_AOT_TRAMP_FTNPTR_ARG] = mono_aot_mode_is_interp (&acfg->aot_opts) ? acfg->aot_opts.nftnptr_arg_trampolines : 0;
12990 #endif
12991 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;
12993 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
12995 arch_init (acfg);
12997 if (mono_use_llvm || acfg->aot_opts.llvm) {
12999 * Emit all LLVM code into a separate assembly/object file and link with it
13000 * normally.
13002 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
13003 acfg->llvm_owriter = TRUE;
13004 } else if (acfg->aot_opts.llvm_outfile) {
13005 int len = strlen (acfg->aot_opts.llvm_outfile);
13007 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
13008 acfg->llvm_owriter = TRUE;
13012 if (acfg->llvm && acfg->thumb_mixed)
13013 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
13014 if (acfg->aot_opts.llvm_only)
13015 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
13017 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
13018 /* Get rid of characters which cannot occur in symbols */
13019 for (p = acfg->assembly_name_sym; *p; ++p) {
13020 if (!(isalnum (*p) || *p == '_'))
13021 *p = '_';
13024 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
13025 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
13026 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
13027 if (acfg->llvm) {
13028 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
13029 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
13032 acfg->method_index = 1;
13034 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
13035 mono_set_partial_sharing_supported (TRUE);
13037 if (!(mono_aot_mode_is_interp (&acfg->aot_opts) && !mono_aot_mode_is_full (&acfg->aot_opts))) {
13038 res = collect_methods (acfg);
13039 if (!res)
13040 return 1;
13043 // If we're emitting all of the inflated methods into a dummy
13044 // Assembly, then after extra_methods is set up, we're done
13045 // in this function.
13046 if (astate && astate->emit_inflated_methods)
13047 mono_add_deferred_extra_methods (acfg, astate);
13050 GList *l;
13052 for (l = acfg->profile_data; l; l = l->next)
13053 resolve_profile_data (acfg, (ProfileData*)l->data);
13054 for (l = acfg->profile_data; l; l = l->next)
13055 add_profile_instances (acfg, (ProfileData*)l->data);
13058 acfg->cfgs_size = acfg->methods->len + 32;
13059 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
13061 /* PLT offset 0 is reserved for the PLT trampoline */
13062 acfg->plt_offset = 1;
13063 add_preinit_got_slots (acfg);
13065 #ifdef ENABLE_LLVM
13066 if (acfg->llvm) {
13067 llvm_acfg = acfg;
13068 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, acfg->nshared_got_entries, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
13070 #endif
13072 if (mono_aot_mode_is_interp (&acfg->aot_opts)) {
13073 MonoMethod *wrapper = mini_get_interp_lmf_wrapper ();
13074 add_method (acfg, wrapper);
13076 #ifndef MONO_ARCH_HAVE_INTERP_ENTRY_TRAMPOLINE
13077 for (int i = 0; i < sizeof (interp_in_static_sigs) / sizeof (const char *); i++) {
13078 MonoMethodSignature *sig = mono_create_icall_signature (interp_in_static_sigs [i]);
13079 sig = mono_metadata_signature_dup_full (mono_get_corlib (), sig);
13080 sig->pinvoke = FALSE;
13081 wrapper = mini_get_interp_in_wrapper (sig);
13082 add_method (acfg, wrapper);
13084 #endif
13087 TV_GETTIME (atv);
13089 compile_methods (acfg);
13091 TV_GETTIME (btv);
13093 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
13095 TV_GETTIME (atv);
13097 #ifdef ENABLE_LLVM
13098 if (acfg->llvm) {
13099 if (acfg->aot_opts.asm_only) {
13100 if (acfg->aot_opts.outfile) {
13101 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13102 acfg->tmpbasename = g_strdup (acfg->tmpfname);
13103 } else {
13104 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
13105 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13107 g_assert (acfg->aot_opts.llvm_outfile);
13108 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13109 if (acfg->llvm_owriter)
13110 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
13111 else
13112 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
13113 } else {
13114 gchar *temp_path;
13115 if (strcmp (acfg->aot_opts.temp_path, "") != 0) {
13116 temp_path = g_strdup (acfg->aot_opts.temp_path);
13117 } else {
13118 temp_path = g_mkdtemp (g_strdup ("mono_aot_XXXXXX"));
13119 g_assertf (temp_path, "mkdtemp failed, error = (%d) %s", errno, g_strerror (errno));
13122 acfg->tmpbasename = g_build_filename (temp_path, "temp", NULL);
13123 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13124 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
13125 acfg->llvm_ofile = g_strdup_printf ("%s-llvm." AS_OBJECT_FILE_SUFFIX, acfg->tmpbasename);
13127 g_free (temp_path);
13130 #endif
13132 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
13133 if (acfg->aot_opts.outfile)
13134 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
13135 else
13136 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
13137 acfg->fp = fopen (acfg->tmpfname, "w+");
13138 } else {
13139 if (strcmp (acfg->aot_opts.temp_path, "") == 0) {
13140 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
13141 acfg->fp = fdopen (i, "w+");
13142 } else {
13143 acfg->tmpbasename = g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
13144 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
13145 acfg->fp = fopen (acfg->tmpfname, "w+");
13148 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
13149 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
13150 return 1;
13152 if (acfg->fp)
13153 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
13155 /* Compute symbols for methods */
13156 for (i = 0; i < acfg->nmethods; ++i) {
13157 if (acfg->cfgs [i]) {
13158 MonoCompile *cfg = acfg->cfgs [i];
13159 int method_index = get_method_index (acfg, cfg->orig_method);
13161 if (COMPILE_LLVM (cfg))
13162 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
13163 else if (acfg->global_symbols || acfg->llvm)
13164 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
13165 else
13166 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
13167 cfg->asm_debug_symbol = cfg->asm_symbol;
13171 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
13173 * CLANG supports GAS .file/.loc directives, so emit line number information this way
13175 acfg->gas_line_numbers = TRUE;
13178 #ifdef EMIT_DWARF_INFO
13179 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
13180 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
13181 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
13182 return 1;
13184 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
13186 #endif /* EMIT_DWARF_INFO */
13188 if (acfg->w)
13189 mono_img_writer_emit_start (acfg->w);
13191 if (acfg->dwarf)
13192 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
13194 emit_code (acfg);
13195 if (acfg->aot_opts.dedup)
13196 mono_flush_method_cache (acfg);
13197 if (acfg->aot_opts.dedup || acfg->dedup_emit_mode)
13198 mono_dedup_log_stats (acfg);
13200 emit_info (acfg);
13202 emit_extra_methods (acfg);
13204 if (acfg->aot_opts.dedup_include && !is_dedup_dummy) {
13205 fclose (acfg->fp);
13206 return 0;
13209 emit_trampolines (acfg);
13211 emit_class_name_table (acfg);
13213 emit_got_info (acfg, FALSE);
13214 if (acfg->llvm)
13215 emit_got_info (acfg, TRUE);
13217 emit_exception_info (acfg);
13219 emit_unwind_info (acfg);
13221 emit_class_info (acfg);
13223 emit_plt (acfg);
13225 emit_image_table (acfg);
13227 emit_weak_field_indexes (acfg);
13229 emit_got (acfg);
13233 * The managed allocators are GC specific, so can't use an AOT image created by one GC
13234 * in another.
13236 const char *gc_name = mono_gc_get_gc_name ();
13237 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
13240 emit_blob (acfg);
13242 emit_objc_selectors (acfg);
13244 emit_globals (acfg);
13246 emit_file_info (acfg);
13248 if (acfg->dwarf) {
13249 emit_dwarf_info (acfg);
13250 mono_dwarf_writer_close (acfg->dwarf);
13251 } else {
13252 if (!acfg->aot_opts.nodebug)
13253 emit_codeview_info (acfg);
13256 emit_mem_end (acfg);
13258 if (acfg->need_pt_gnu_stack) {
13259 /* This is required so the .so doesn't have an executable stack */
13260 /* The bin writer already emits this */
13261 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
13264 if (acfg->aot_opts.data_outfile)
13265 fclose (acfg->data_outfile);
13267 #ifdef ENABLE_LLVM
13268 if (acfg->llvm) {
13269 gboolean res;
13271 res = emit_llvm_file (acfg);
13272 if (!res)
13273 return 1;
13275 #endif
13277 emit_library_info (acfg);
13279 TV_GETTIME (btv);
13281 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
13283 if (acfg->llvm)
13284 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
13285 else
13286 strcpy (llvm_stats_msg, "");
13288 all_sizes = acfg->stats.code_size + acfg->stats.info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
13290 aot_printf (acfg, "Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d\n",
13291 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
13292 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
13293 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
13294 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
13295 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
13296 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,
13297 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
13298 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
13299 (int)(acfg->got_offset * sizeof (target_mgreg_t)));
13300 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
13301 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
13302 llvm_stats_msg,
13303 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
13304 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
13305 if (acfg->stats.genericcount)
13306 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
13307 if (acfg->stats.abscount)
13308 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
13309 if (acfg->stats.lmfcount)
13310 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
13311 if (acfg->stats.ocount)
13312 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
13314 TV_GETTIME (atv);
13315 if (acfg->w) {
13316 res = mono_img_writer_emit_writeout (acfg->w);
13317 if (res != 0) {
13318 acfg_free (acfg);
13319 return res;
13321 res = compile_asm (acfg);
13322 if (res != 0) {
13323 acfg_free (acfg);
13324 return res;
13327 TV_GETTIME (btv);
13328 acfg->stats.link_time = TV_ELAPSED (atv, btv);
13330 if (acfg->aot_opts.stats) {
13331 int i;
13333 aot_printf (acfg, "GOT slot distribution:\n");
13334 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
13335 if (acfg->stats.got_slot_types [i])
13336 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]);
13337 aot_printf (acfg, "\nMethod stats:\n");
13338 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
13339 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
13340 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
13341 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
13344 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);
13346 if (acfg->aot_opts.dump_json)
13347 aot_dump (acfg);
13349 acfg_free (acfg);
13351 return 0;
13354 #else
13356 /* AOT disabled */
13358 void*
13359 mono_aot_readonly_field_override (MonoClassField *field)
13361 return NULL;
13365 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state)
13367 return 0;
13370 gboolean
13371 mono_aot_is_shared_got_offset (int offset)
13373 return FALSE;
13377 mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state)
13379 g_assert_not_reached ();
13380 return 0;
13383 #endif