Merge pull request #3734 from kumpera/monoclass_reorg
[mono-project.git] / mono / mini / aot-compiler.c
blobbf043ec27a41175a5b881d4d7f6d47c1be9d19c3
1 /*
2 * aot-compiler.c: mono Ahead of Time compiler
4 * Author:
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
11 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14 #include "config.h"
15 #include <sys/types.h>
16 #ifdef HAVE_UNISTD_H
17 #include <unistd.h>
18 #endif
19 #ifdef HAVE_STDINT_H
20 #include <stdint.h>
21 #endif
22 #include <fcntl.h>
23 #include <ctype.h>
24 #include <string.h>
25 #ifndef HOST_WIN32
26 #include <sys/time.h>
27 #else
28 #include <winsock2.h>
29 #include <windows.h>
30 #endif
32 #include <errno.h>
33 #include <sys/stat.h>
35 #include <mono/metadata/abi-details.h>
36 #include <mono/metadata/tabledefs.h>
37 #include <mono/metadata/class.h>
38 #include <mono/metadata/object.h>
39 #include <mono/metadata/tokentype.h>
40 #include <mono/metadata/appdomain.h>
41 #include <mono/metadata/debug-helpers.h>
42 #include <mono/metadata/assembly.h>
43 #include <mono/metadata/metadata-internals.h>
44 #include <mono/metadata/reflection-internals.h>
45 #include <mono/metadata/marshal.h>
46 #include <mono/metadata/gc-internals.h>
47 #include <mono/metadata/mempool-internals.h>
48 #include <mono/metadata/mono-endian.h>
49 #include <mono/metadata/threads-types.h>
50 #include <mono/utils/mono-logger-internals.h>
51 #include <mono/utils/mono-compiler.h>
52 #include <mono/utils/mono-time.h>
53 #include <mono/utils/mono-mmap.h>
54 #include <mono/utils/mono-rand.h>
55 #include <mono/utils/json.h>
56 #include <mono/utils/mono-threads-coop.h>
58 #include "aot-compiler.h"
59 #include "seq-points.h"
60 #include "image-writer.h"
61 #include "dwarfwriter.h"
62 #include "mini-gc.h"
63 #include "mini-llvm.h"
65 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
67 #if defined(__linux__) || defined(__native_client_codegen__)
68 #define RODATA_SECT ".rodata"
69 #elif defined(TARGET_MACH)
70 #define RODATA_SECT ".section __TEXT, __const"
71 #else
72 #define RODATA_SECT ".text"
73 #endif
75 #define TV_DECLARE(name) gint64 name
76 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
77 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
79 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
80 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
81 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
83 /* predefined values for static readonly fields without needed to run the .cctor */
84 typedef struct _ReadOnlyValue ReadOnlyValue;
85 struct _ReadOnlyValue {
86 ReadOnlyValue *next;
87 char *name;
88 int type; /* to be used later for typechecking to prevent user errors */
89 union {
90 guint8 i1;
91 guint16 i2;
92 guint32 i4;
93 guint64 i8;
94 gpointer ptr;
95 } value;
97 static ReadOnlyValue *readonly_values;
99 typedef struct MonoAotOptions {
100 char *outfile;
101 char *llvm_outfile;
102 char *data_outfile;
103 gboolean save_temps;
104 gboolean write_symbols;
105 gboolean metadata_only;
106 gboolean bind_to_runtime_version;
107 MonoAotMode mode;
108 gboolean no_dlsym;
109 gboolean static_link;
110 gboolean asm_only;
111 gboolean asm_writer;
112 gboolean nodebug;
113 gboolean dwarf_debug;
114 gboolean soft_debug;
115 gboolean log_generics;
116 gboolean log_instances;
117 gboolean gen_msym_dir;
118 char *gen_msym_dir_path;
119 gboolean direct_pinvoke;
120 gboolean direct_icalls;
121 gboolean no_direct_calls;
122 gboolean use_trampolines_page;
123 gboolean no_instances;
124 gboolean gnu_asm;
125 gboolean llvm;
126 gboolean llvm_only;
127 int nthreads;
128 int ntrampolines;
129 int nrgctx_trampolines;
130 int nimt_trampolines;
131 int ngsharedvt_arg_trampolines;
132 int nrgctx_fetch_trampolines;
133 gboolean print_skipped_methods;
134 gboolean stats;
135 char *tool_prefix;
136 char *ld_flags;
137 char *mtriple;
138 char *llvm_path;
139 char *temp_path;
140 char *instances_logfile_path;
141 char *logfile;
142 gboolean dump_json;
143 } MonoAotOptions;
145 typedef enum {
146 METHOD_CAT_NORMAL,
147 METHOD_CAT_GSHAREDVT,
148 METHOD_CAT_INST,
149 METHOD_CAT_WRAPPER,
150 METHOD_CAT_NUM
151 } MethodCategory;
153 typedef struct MonoAotStats {
154 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
155 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
156 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
157 int got_slots, offsets_size;
158 int method_categories [METHOD_CAT_NUM];
159 int got_slot_types [MONO_PATCH_INFO_NUM];
160 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
161 int jit_time, gen_time, link_time;
162 } MonoAotStats;
164 typedef struct GotInfo {
165 GHashTable *patch_to_got_offset;
166 GHashTable **patch_to_got_offset_by_type;
167 GPtrArray *got_patches;
168 } GotInfo;
170 typedef struct MonoAotCompile {
171 MonoImage *image;
172 GPtrArray *methods;
173 GHashTable *method_indexes;
174 GHashTable *method_depth;
175 MonoCompile **cfgs;
176 int cfgs_size;
177 GHashTable **patch_to_plt_entry;
178 GHashTable *plt_offset_to_entry;
179 //GHashTable *patch_to_got_offset;
180 //GHashTable **patch_to_got_offset_by_type;
181 //GPtrArray *got_patches;
182 GotInfo got_info, llvm_got_info;
183 GHashTable *image_hash;
184 GHashTable *method_to_cfg;
185 GHashTable *token_info_hash;
186 GHashTable *method_to_pinvoke_import;
187 GPtrArray *extra_methods;
188 GPtrArray *image_table;
189 GPtrArray *globals;
190 GPtrArray *method_order;
191 GHashTable *export_names;
192 /* Maps MonoClass* -> blob offset */
193 GHashTable *klass_blob_hash;
194 /* Maps MonoMethod* -> blob offset */
195 GHashTable *method_blob_hash;
196 GHashTable *gsharedvt_in_signatures;
197 GHashTable *gsharedvt_out_signatures;
198 guint32 *plt_got_info_offsets;
199 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
200 /* Number of GOT entries reserved for trampolines */
201 guint32 num_trampoline_got_entries;
202 guint32 tramp_page_size;
204 guint32 table_offsets [MONO_AOT_TABLE_NUM];
205 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
206 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
207 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
208 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
210 MonoAotOptions aot_opts;
211 guint32 nmethods;
212 guint32 opts;
213 guint32 simd_opts;
214 MonoMemPool *mempool;
215 MonoAotStats stats;
216 int method_index;
217 char *static_linking_symbol;
218 mono_mutex_t mutex;
219 gboolean gas_line_numbers;
220 /* Whenever to emit an object file directly from llc */
221 gboolean llvm_owriter;
222 gboolean llvm_owriter_supported;
223 MonoImageWriter *w;
224 MonoDwarfWriter *dwarf;
225 FILE *fp;
226 char *tmpbasename;
227 char *tmpfname;
228 char *llvm_sfile;
229 char *llvm_ofile;
230 GSList *cie_program;
231 GHashTable *unwind_info_offsets;
232 GPtrArray *unwind_ops;
233 guint32 unwind_info_offset;
234 char *global_prefix;
235 char *got_symbol;
236 char *llvm_got_symbol;
237 char *plt_symbol;
238 char *llvm_eh_frame_symbol;
239 GHashTable *method_label_hash;
240 const char *temp_prefix;
241 const char *user_symbol_prefix;
242 const char *llvm_label_prefix;
243 const char *inst_directive;
244 int align_pad_value;
245 guint32 label_generator;
246 gboolean llvm;
247 gboolean has_jitted_code;
248 MonoAotFileFlags flags;
249 MonoDynamicStream blob;
250 gboolean blob_closed;
251 GHashTable *typespec_classes;
252 GString *llc_args;
253 GString *as_args;
254 char *assembly_name_sym;
255 GHashTable *plt_entry_debug_sym_cache;
256 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
257 GHashTable *ginst_hash;
258 GHashTable *dwarf_ln_filenames;
259 gboolean global_symbols;
260 int objc_selector_index, objc_selector_index_2;
261 GPtrArray *objc_selectors;
262 GHashTable *objc_selector_to_index;
263 FILE *logfile;
264 FILE *instances_logfile;
265 FILE *data_outfile;
266 int datafile_offset;
267 int gc_name_offset;
268 } MonoAotCompile;
270 typedef struct {
271 int plt_offset;
272 char *symbol, *llvm_symbol, *debug_sym;
273 MonoJumpInfo *ji;
274 gboolean jit_used, llvm_used;
275 } MonoPltEntry;
277 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
278 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
280 /* This points to the current acfg in LLVM mode */
281 static MonoAotCompile *llvm_acfg;
283 #ifdef HAVE_ARRAY_ELEM_INIT
284 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
285 #define MSGSTRFIELD1(line) str##line
286 static const struct msgstr_t {
287 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
288 #include "patch-info.h"
289 #undef PATCH_INFO
290 } opstr = {
291 #define PATCH_INFO(a,b) b,
292 #include "patch-info.h"
293 #undef PATCH_INFO
295 static const gint16 opidx [] = {
296 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
297 #include "patch-info.h"
298 #undef PATCH_INFO
301 static G_GNUC_UNUSED const char*
302 get_patch_name (int info)
304 return (const char*)&opstr + opidx [info];
307 #else
308 #define PATCH_INFO(a,b) b,
309 static const char* const
310 patch_types [MONO_PATCH_INFO_NUM + 1] = {
311 #include "patch-info.h"
312 NULL
315 static G_GNUC_UNUSED const char*
316 get_patch_name (int info)
318 return patch_types [info];
321 #endif
323 static guint32
324 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
326 static char*
327 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
329 static void
330 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out);
332 static void
333 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
335 FILE *output;
336 va_list args;
338 if (acfg->logfile)
339 output = acfg->logfile;
340 else
341 output = stdout;
343 va_start (args, format);
344 vfprintf (output, format, args);
345 va_end (args);
348 static void
349 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
351 FILE *output;
352 va_list args;
354 if (acfg->logfile)
355 output = acfg->logfile;
356 else
357 output = stderr;
359 va_start (args, format);
360 vfprintf (output, format, args);
361 va_end (args);
364 static void
365 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
367 FILE *output;
368 va_list args;
370 if (mono_error_ok (error))
371 return;
373 if (acfg->logfile)
374 output = acfg->logfile;
375 else
376 output = stderr;
378 va_start (args, format);
379 vfprintf (output, format, args);
380 va_end (args);
381 mono_error_cleanup (error);
383 g_error ("FullAOT cannot continue if there are loader errors");
386 /* Wrappers around the image writer functions */
388 #define MAX_SYMBOL_SIZE 256
390 static inline const char *
391 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
393 gsize needed_size = length;
395 g_assert (NULL != symbol);
396 g_assert (NULL != mangled_symbol);
397 g_assert (0 != length);
399 #if defined(TARGET_WIN32) && defined(TARGET_X86)
400 if (symbol && '_' != symbol [0]) {
401 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
402 } else {
403 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
405 #else
406 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
407 #endif
409 g_assert (0 <= needed_size && needed_size < length);
410 return mangled_symbol;
413 static inline char *
414 mangle_symbol_alloc (const char * symbol)
416 g_assert (NULL != symbol);
418 #if defined(TARGET_WIN32) && defined(TARGET_X86)
419 if (symbol && '_' != symbol [0]) {
420 return g_strdup_printf ("_%s", symbol);
422 else {
423 return g_strdup_printf ("%s", symbol);
425 #else
426 return g_strdup_printf ("%s", symbol);
427 #endif
430 static inline void
431 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
433 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
436 #if defined(TARGET_WIN32) && defined(TARGET_X86)
438 static inline void
439 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
441 const char * mangled_symbol_name = name;
442 char * mangled_symbol_name_alloc = NULL;
444 if (TRUE == func) {
445 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
446 mangled_symbol_name = mangled_symbol_name_alloc;
449 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
450 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
452 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
454 if (NULL != mangled_symbol_name_alloc) {
455 g_free (mangled_symbol_name_alloc);
459 #else
461 static inline void
462 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
464 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
467 #endif
469 static inline void
470 emit_label (MonoAotCompile *acfg, const char *name)
472 mono_img_writer_emit_label (acfg->w, name);
475 static inline void
476 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
478 mono_img_writer_emit_bytes (acfg->w, buf, size);
481 static inline void
482 emit_string (MonoAotCompile *acfg, const char *value)
484 mono_img_writer_emit_string (acfg->w, value);
487 static inline void
488 emit_line (MonoAotCompile *acfg)
490 mono_img_writer_emit_line (acfg->w);
493 static inline void
494 emit_alignment (MonoAotCompile *acfg, int size)
496 mono_img_writer_emit_alignment (acfg->w, size);
499 static inline void
500 emit_alignment_code (MonoAotCompile *acfg, int size)
502 if (acfg->align_pad_value)
503 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
504 else
505 mono_img_writer_emit_alignment (acfg->w, size);
508 static inline void
509 emit_padding (MonoAotCompile *acfg, int size)
511 int i;
512 guint8 buf [16];
514 if (acfg->align_pad_value) {
515 for (i = 0; i < 16; ++i)
516 buf [i] = acfg->align_pad_value;
517 } else {
518 memset (buf, 0, sizeof (buf));
521 for (i = 0; i < size; i += 16) {
522 if (size - i < 16)
523 emit_bytes (acfg, buf, size - i);
524 else
525 emit_bytes (acfg, buf, 16);
529 static inline void
530 emit_pointer (MonoAotCompile *acfg, const char *target)
532 mono_img_writer_emit_pointer (acfg->w, target);
535 static inline void
536 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
538 if (prefix [0] != '\0') {
539 char *s = g_strdup_printf ("%s%s", prefix, target);
540 mono_img_writer_emit_pointer (acfg->w, s);
541 g_free (s);
542 } else {
543 mono_img_writer_emit_pointer (acfg->w, target);
547 static inline void
548 emit_int16 (MonoAotCompile *acfg, int value)
550 mono_img_writer_emit_int16 (acfg->w, value);
553 static inline void
554 emit_int32 (MonoAotCompile *acfg, int value)
556 mono_img_writer_emit_int32 (acfg->w, value);
559 static inline void
560 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
562 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
565 static inline void
566 emit_zero_bytes (MonoAotCompile *acfg, int num)
568 mono_img_writer_emit_zero_bytes (acfg->w, num);
571 static inline void
572 emit_byte (MonoAotCompile *acfg, guint8 val)
574 mono_img_writer_emit_byte (acfg->w, val);
577 #if defined(TARGET_WIN32) && defined(TARGET_X86)
579 static G_GNUC_UNUSED void
580 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
582 const char * mangled_symbol_name = name;
583 char * mangled_symbol_name_alloc = NULL;
585 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
586 mangled_symbol_name = mangled_symbol_name_alloc;
588 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
589 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
591 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
593 if (NULL != mangled_symbol_name_alloc) {
594 g_free (mangled_symbol_name_alloc);
598 #else
600 static G_GNUC_UNUSED void
601 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
603 mono_img_writer_emit_global (acfg->w, name, func);
606 #endif
608 static void
609 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
611 if (acfg->aot_opts.no_dlsym) {
612 g_ptr_array_add (acfg->globals, g_strdup (name));
613 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
614 } else {
615 emit_global_inner (acfg, name, func);
619 static void
620 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
622 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
625 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
626 static void
627 emit_info_symbol (MonoAotCompile *acfg, const char *name)
629 char symbol [MAX_SYMBOL_SIZE];
631 if (acfg->llvm) {
632 emit_label (acfg, name);
633 /* LLVM generated code references this */
634 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
635 emit_label (acfg, symbol);
636 emit_global_inner (acfg, symbol, FALSE);
637 } else {
638 emit_label (acfg, name);
642 static void
643 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
645 if (acfg->llvm) {
646 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
647 return;
650 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
651 #ifdef TARGET_MACH
652 /* On apple, all symbols need to be aligned to avoid warnings from ld */
653 emit_alignment (acfg, 4);
654 #endif
655 mono_img_writer_emit_label (acfg->w, name);
656 mono_img_writer_emit_string (acfg->w, value);
659 static G_GNUC_UNUSED void
660 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
662 do {
663 guint8 b = value & 0x7f;
664 value >>= 7;
665 if (value != 0) /* more bytes to come */
666 b |= 0x80;
667 emit_byte (acfg, b);
668 } while (value);
671 static G_GNUC_UNUSED void
672 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
674 gboolean more = 1;
675 gboolean negative = (value < 0);
676 guint32 size = 64;
677 guint8 byte;
679 while (more) {
680 byte = value & 0x7f;
681 value >>= 7;
682 /* the following is unnecessary if the
683 * implementation of >>= uses an arithmetic rather
684 * than logical shift for a signed left operand
686 if (negative)
687 /* sign extend */
688 value |= - ((gint64)1 <<(size - 7));
689 /* sign bit of byte is second high order bit (0x40) */
690 if ((value == 0 && !(byte & 0x40)) ||
691 (value == -1 && (byte & 0x40)))
692 more = 0;
693 else
694 byte |= 0x80;
695 emit_byte (acfg, byte);
699 static G_GNUC_UNUSED void
700 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
702 guint8 *p = buf;
704 do {
705 guint8 b = value & 0x7f;
706 value >>= 7;
707 if (value != 0) /* more bytes to come */
708 b |= 0x80;
709 *p ++ = b;
710 } while (value);
712 *endbuf = p;
715 static G_GNUC_UNUSED void
716 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
718 gboolean more = 1;
719 gboolean negative = (value < 0);
720 guint32 size = 32;
721 guint8 byte;
722 guint8 *p = buf;
724 while (more) {
725 byte = value & 0x7f;
726 value >>= 7;
727 /* the following is unnecessary if the
728 * implementation of >>= uses an arithmetic rather
729 * than logical shift for a signed left operand
731 if (negative)
732 /* sign extend */
733 value |= - (1 <<(size - 7));
734 /* sign bit of byte is second high order bit (0x40) */
735 if ((value == 0 && !(byte & 0x40)) ||
736 (value == -1 && (byte & 0x40)))
737 more = 0;
738 else
739 byte |= 0x80;
740 *p ++= byte;
743 *endbuf = p;
746 static void
747 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
749 // FIXME: Big-endian
750 buf [0] = (val >> 0) & 0xff;
751 buf [1] = (val >> 8) & 0xff;
752 buf [2] = (val >> 16) & 0xff;
753 buf [3] = (val >> 24) & 0xff;
755 *endbuf = buf + 4;
758 static void
759 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
761 buf [0] = (val >> 0) & 0xff;
762 buf [1] = (val >> 8) & 0xff;
764 *endbuf = buf + 2;
767 static void
768 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
770 int len = strlen (s);
772 memcpy (buf, s, len + 1);
773 *endbuf = buf + len + 1;
776 static void
777 emit_unset_mode (MonoAotCompile *acfg)
779 mono_img_writer_emit_unset_mode (acfg->w);
782 static G_GNUC_UNUSED void
783 emit_set_thumb_mode (MonoAotCompile *acfg)
785 emit_unset_mode (acfg);
786 fprintf (acfg->fp, ".code 16\n");
789 static G_GNUC_UNUSED void
790 emit_set_arm_mode (MonoAotCompile *acfg)
792 emit_unset_mode (acfg);
793 fprintf (acfg->fp, ".code 32\n");
796 static inline void
797 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
799 #ifdef TARGET_ARM64
800 int i;
802 g_assert (size % 4 == 0);
803 emit_unset_mode (acfg);
804 for (i = 0; i < size; i += 4)
805 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
806 #else
807 emit_bytes (acfg, buf, size);
808 #endif
811 /* ARCHITECTURE SPECIFIC CODE */
813 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
814 #define EMIT_DWARF_INFO 1
815 #endif
817 #if defined(TARGET_ARM)
818 #define AOT_FUNC_ALIGNMENT 4
819 #else
820 #define AOT_FUNC_ALIGNMENT 16
821 #endif
823 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
824 #define PPC_LD_OP "ld"
825 #define PPC_LDX_OP "ldx"
826 #else
827 #define PPC_LD_OP "lwz"
828 #define PPC_LDX_OP "lwzx"
829 #endif
831 #ifdef TARGET_AMD64
832 #define AOT_TARGET_STR "AMD64"
833 #endif
835 #ifdef TARGET_ARM
836 #ifdef TARGET_MACH
837 #define AOT_TARGET_STR "ARM (MACH)"
838 #else
839 #define AOT_TARGET_STR "ARM (!MACH)"
840 #endif
841 #endif
843 #ifdef TARGET_ARM64
844 #ifdef TARGET_MACH
845 #define AOT_TARGET_STR "ARM64 (MACH)"
846 #else
847 #define AOT_TARGET_STR "ARM64 (!MACH)"
848 #endif
849 #endif
851 #ifdef TARGET_POWERPC64
852 #ifdef __mono_ilp32__
853 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
854 #else
855 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
856 #endif
857 #else
858 #ifdef TARGET_POWERPC
859 #ifdef __mono_ilp32__
860 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
861 #else
862 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
863 #endif
864 #endif
865 #endif
867 #ifdef TARGET_X86
868 #ifdef TARGET_WIN32
869 #define AOT_TARGET_STR "X86 (WIN32)"
870 #elif defined(__native_client_codegen__)
871 #define AOT_TARGET_STR "X86 (native client codegen)"
872 #else
873 #define AOT_TARGET_STR "X86 (!native client codegen)"
874 #endif
875 #endif
877 #ifndef AOT_TARGET_STR
878 #define AOT_TARGET_STR ""
879 #endif
881 static void
882 arch_init (MonoAotCompile *acfg)
884 acfg->llc_args = g_string_new ("");
885 acfg->as_args = g_string_new ("");
886 acfg->llvm_owriter_supported = TRUE;
889 * The prefix LLVM likes to put in front of symbol names on darwin.
890 * The mach-os specs require this for globals, but LLVM puts them in front of all
891 * symbols. We need to handle this, since we need to refer to LLVM generated
892 * symbols.
894 acfg->llvm_label_prefix = "";
895 acfg->user_symbol_prefix = "";
897 #if defined(TARGET_X86)
898 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
899 #endif
901 #if defined(TARGET_AMD64)
902 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
903 /* NOP */
904 acfg->align_pad_value = 0x90;
905 #endif
907 #ifdef TARGET_ARM
908 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
909 g_string_append (acfg->llc_args, "-mattr=+v6");
910 } else {
911 #if defined(ARM_FPU_VFP_HARD)
912 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
913 g_string_append (acfg->as_args, " -mfpu=vfp3");
914 #elif defined(ARM_FPU_VFP)
915 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
916 g_string_append (acfg->as_args, " -mfpu=vfp3");
917 #else
918 g_string_append (acfg->llc_args, " -soft-float");
919 #endif
921 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
922 acfg->thumb_mixed = TRUE;
924 if (acfg->aot_opts.mtriple)
925 mono_arch_set_target (acfg->aot_opts.mtriple);
926 #endif
928 #ifdef TARGET_ARM64
929 acfg->inst_directive = ".inst";
930 if (acfg->aot_opts.mtriple)
931 mono_arch_set_target (acfg->aot_opts.mtriple);
932 #endif
934 #ifdef TARGET_MACH
935 acfg->user_symbol_prefix = "_";
936 acfg->llvm_label_prefix = "_";
937 acfg->inst_directive = ".word";
938 acfg->need_no_dead_strip = TRUE;
939 acfg->aot_opts.gnu_asm = TRUE;
940 #endif
942 #if defined(__linux__) && !defined(TARGET_ARM)
943 acfg->need_pt_gnu_stack = TRUE;
944 #endif
946 #ifdef MONOTOUCH
947 acfg->global_symbols = TRUE;
948 #endif
950 #ifdef TARGET_ANDROID
951 acfg->llvm_owriter_supported = FALSE;
952 #endif
955 #ifdef TARGET_ARM64
958 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
959 static void
960 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
962 int offset;
964 g_assert (acfg->fp);
965 emit_unset_mode (acfg);
966 /* r16==ip0 */
967 offset = (int)(got_slot * sizeof (gpointer));
968 #ifdef TARGET_MACH
969 /* clang's integrated assembler */
970 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
971 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
972 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
973 #else
974 /* Linux GAS */
975 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
976 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
977 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
978 #endif
981 static void
982 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
984 int reg;
986 g_assert (acfg->fp);
987 emit_unset_mode (acfg);
989 /* ldr rt, target */
990 reg = arm_get_ldr_lit_reg (code);
992 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
993 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
994 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
996 *code_size = 12;
999 static void
1000 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1002 g_assert (acfg->fp);
1003 emit_unset_mode (acfg);
1004 if (ji && ji->relocation == MONO_R_ARM64_B) {
1005 fprintf (acfg->fp, "b %s\n", target);
1006 } else {
1007 if (ji)
1008 g_assert (ji->relocation == MONO_R_ARM64_BL);
1009 fprintf (acfg->fp, "bl %s\n", target);
1011 *call_size = 4;
1014 static void
1015 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1017 int reg;
1019 /* ldr rt, target */
1020 reg = arm_get_ldr_lit_reg (code);
1021 arm64_emit_load_got_slot (acfg, reg, got_slot);
1022 *code_size = 12;
1025 static void
1026 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1028 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1029 fprintf (acfg->fp, "br x16\n");
1030 /* Used by mono_aot_get_plt_info_offset () */
1031 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1034 static void
1035 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1037 guint8 buf [256];
1038 guint8 *code;
1039 int imm;
1041 /* The common code */
1042 code = buf;
1043 imm = pagesize;
1044 /* The trampoline address is in IP0 */
1045 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1046 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1047 /* Compute the data slot address */
1048 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1049 /* Trampoline argument */
1050 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1051 /* Address */
1052 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1053 arm_brx (code, ARMREG_IP0);
1055 /* Emit it */
1056 emit_code_bytes (acfg, buf, code - buf);
1058 *size = code - buf;
1061 static void
1062 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1064 guint8 buf [256];
1065 guint8 *code;
1066 int i, count;
1068 count = (pagesize - common_tramp_size) / specific_tramp_size;
1069 for (i = 0; i < count; ++i) {
1070 code = buf;
1071 arm_adrx (code, ARMREG_IP0, code);
1072 /* Branch to the generic code */
1073 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1074 /* This has to be 2 pointers long */
1075 arm_nop (code);
1076 arm_nop (code);
1077 g_assert (code - buf == specific_tramp_size);
1078 emit_code_bytes (acfg, buf, code - buf);
1082 static void
1083 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1085 guint8 buf [128];
1086 guint8 *code;
1087 guint8 *labels [16];
1088 int common_tramp_size;
1089 int specific_tramp_size = 2 * 8;
1090 int imm, pagesize;
1091 char symbol [128];
1093 if (!acfg->aot_opts.use_trampolines_page)
1094 return;
1096 #ifdef TARGET_MACH
1097 /* Have to match the target pagesize */
1098 pagesize = 16384;
1099 #else
1100 pagesize = mono_pagesize ();
1101 #endif
1102 acfg->tramp_page_size = pagesize;
1104 /* The specific trampolines */
1105 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1106 emit_alignment (acfg, pagesize);
1107 emit_global (acfg, symbol, TRUE);
1108 emit_label (acfg, symbol);
1110 /* The common code */
1111 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1112 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1114 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1116 /* The rgctx trampolines */
1117 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1118 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1119 emit_alignment (acfg, pagesize);
1120 emit_global (acfg, symbol, TRUE);
1121 emit_label (acfg, symbol);
1123 /* The common code */
1124 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1125 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1127 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1129 /* The gsharedvt arg trampolines */
1130 /* These are the same as the specific trampolines */
1131 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1132 emit_alignment (acfg, pagesize);
1133 emit_global (acfg, symbol, TRUE);
1134 emit_label (acfg, symbol);
1136 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1137 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1139 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1141 /* The IMT trampolines */
1142 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1143 emit_alignment (acfg, pagesize);
1144 emit_global (acfg, symbol, TRUE);
1145 emit_label (acfg, symbol);
1147 code = buf;
1148 imm = pagesize;
1149 /* The trampoline address is in IP0 */
1150 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1151 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1152 /* Compute the data slot address */
1153 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1154 /* Trampoline argument */
1155 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1157 /* Same as arch_emit_imt_trampoline () */
1158 labels [0] = code;
1159 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1160 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1161 labels [1] = code;
1162 arm_bcc (code, ARMCOND_EQ, 0);
1164 /* End-of-loop check */
1165 labels [2] = code;
1166 arm_cbzx (code, ARMREG_IP0, 0);
1168 /* Loop footer */
1169 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1170 arm_b (code, labels [0]);
1172 /* Match */
1173 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1174 /* Load vtable slot addr */
1175 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1176 /* Load vtable slot */
1177 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1178 arm_brx (code, ARMREG_IP0);
1180 /* No match */
1181 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1182 /* Load fail addr */
1183 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1184 arm_brx (code, ARMREG_IP0);
1186 emit_code_bytes (acfg, buf, code - buf);
1188 common_tramp_size = code - buf;
1189 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1191 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1194 static void
1195 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1197 /* Load argument from second GOT slot */
1198 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1199 /* Load generic trampoline address from first GOT slot */
1200 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1201 fprintf (acfg->fp, "br x16\n");
1202 *tramp_size = 7 * 4;
1205 static void
1206 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1208 emit_unset_mode (acfg);
1209 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1210 fprintf (acfg->fp, "b %s\n", call_target);
1213 static void
1214 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1216 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1218 /* Load argument from first GOT slot */
1219 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1220 /* Load generic trampoline address from second GOT slot */
1221 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1222 fprintf (acfg->fp, "br x16\n");
1223 *tramp_size = 7 * 4;
1226 static void
1227 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1229 guint8 buf [128];
1230 guint8 *code, *labels [16];
1232 /* Load parameter from GOT slot into ip1 */
1233 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1235 code = buf;
1236 labels [0] = code;
1237 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1238 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1239 labels [1] = code;
1240 arm_bcc (code, ARMCOND_EQ, 0);
1242 /* End-of-loop check */
1243 labels [2] = code;
1244 arm_cbzx (code, ARMREG_IP0, 0);
1246 /* Loop footer */
1247 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1248 arm_b (code, labels [0]);
1250 /* Match */
1251 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1252 /* Load vtable slot addr */
1253 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1254 /* Load vtable slot */
1255 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1256 arm_brx (code, ARMREG_IP0);
1258 /* No match */
1259 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1260 /* Load fail addr */
1261 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1262 arm_brx (code, ARMREG_IP0);
1264 emit_code_bytes (acfg, buf, code - buf);
1266 *tramp_size = code - buf + (3 * 4);
1269 static void
1270 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1272 /* Similar to the specific trampolines, but the address is in the second slot */
1273 /* Load argument from first GOT slot */
1274 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1275 /* Load generic trampoline address from second GOT slot */
1276 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1277 fprintf (acfg->fp, "br x16\n");
1278 *tramp_size = 7 * 4;
1282 #endif
1284 #ifdef MONO_ARCH_AOT_SUPPORTED
1286 * arch_emit_direct_call:
1288 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1289 * calling code.
1291 static void
1292 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1294 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1295 /* Need to make sure this is exactly 5 bytes long */
1296 emit_unset_mode (acfg);
1297 fprintf (acfg->fp, "call %s\n", target);
1298 *call_size = 5;
1299 #elif defined(TARGET_ARM)
1300 emit_unset_mode (acfg);
1301 if (thumb)
1302 fprintf (acfg->fp, "blx %s\n", target);
1303 else
1304 fprintf (acfg->fp, "bl %s\n", target);
1305 *call_size = 4;
1306 #elif defined(TARGET_ARM64)
1307 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1308 #elif defined(TARGET_POWERPC)
1309 emit_unset_mode (acfg);
1310 fprintf (acfg->fp, "bl %s\n", target);
1311 *call_size = 4;
1312 #else
1313 g_assert_not_reached ();
1314 #endif
1316 #endif
1319 * PPC32 design:
1320 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1321 * the GOT pointer.
1322 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1323 * in in the 2. slot of every GOT, and require every method to place the GOT
1324 * address in r30, even when it doesn't access the GOT otherwise. This way,
1325 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1329 * PPC64 design:
1330 * PPC64 uses function descriptors which greatly complicate all code, since
1331 * these are used very inconsistently in the runtime. Some functions like
1332 * mono_compile_method () return ftn descriptors, while others like the
1333 * trampoline creation functions do not.
1334 * We assume that all GOT slots contain function descriptors, and create
1335 * descriptors in aot-runtime.c when needed.
1336 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1337 * from function descriptors, we could do the same, but it would require
1338 * rewriting all the ppc/aot code to handle function descriptors properly.
1339 * So instead, we use the same approach as on PPC32.
1340 * This is a horrible mess, but fixing it would probably lead to an even bigger
1341 * one.
1345 * X86 design:
1346 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1349 #ifdef MONO_ARCH_AOT_SUPPORTED
1351 * arch_emit_got_offset:
1353 * The memory pointed to by CODE should hold native code for computing the GOT
1354 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1355 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1357 static void
1358 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1360 #if defined(TARGET_POWERPC64)
1361 emit_unset_mode (acfg);
1363 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1364 * unsupported relocations. So we store the got address into the .Lgot_addr
1365 * symbol which is in the text segment, compute its address, and load it.
1367 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1368 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1369 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1370 fprintf (acfg->fp, "add 30, 30, 0\n");
1371 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1372 acfg->label_generator ++;
1373 *code_size = 16;
1374 #elif defined(TARGET_POWERPC)
1375 emit_unset_mode (acfg);
1376 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1377 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1378 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1379 acfg->label_generator ++;
1380 *code_size = 8;
1381 #else
1382 guint32 offset = mono_arch_get_patch_offset (code);
1383 emit_bytes (acfg, code, offset);
1384 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1386 *code_size = offset + 4;
1387 #endif
1391 * arch_emit_got_access:
1393 * The memory pointed to by CODE should hold native code for loading a GOT
1394 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1395 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1397 static void
1398 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1400 #ifdef TARGET_AMD64
1401 /* mov reg, got+offset(%rip) */
1402 if (acfg->llvm) {
1403 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1404 int dreg;
1405 int rex_r;
1407 /* Decode reg, see amd64_mov_reg_membase () */
1408 rex_r = code [0] & AMD64_REX_R;
1409 g_assert (code [0] == 0x49 + rex_r);
1410 g_assert (code [1] == 0x8b);
1411 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1413 emit_unset_mode (acfg);
1414 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1415 *code_size = 7;
1416 } else {
1417 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1418 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1419 *code_size = mono_arch_get_patch_offset (code) + 4;
1421 #elif defined(TARGET_X86)
1422 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1423 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1424 *code_size = mono_arch_get_patch_offset (code) + 4;
1425 #elif defined(TARGET_ARM)
1426 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1427 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1428 *code_size = mono_arch_get_patch_offset (code) + 4;
1429 #elif defined(TARGET_ARM64)
1430 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1431 arm64_emit_got_access (acfg, code, got_slot, code_size);
1432 #elif defined(TARGET_POWERPC)
1434 guint8 buf [32];
1436 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1437 code = buf;
1438 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1439 g_assert (code - buf == 8);
1440 emit_bytes (acfg, buf, code - buf);
1441 *code_size = code - buf;
1443 #else
1444 g_assert_not_reached ();
1445 #endif
1448 #endif
1450 #ifdef MONO_ARCH_AOT_SUPPORTED
1452 * arch_emit_objc_selector_ref:
1454 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1456 static void
1457 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1459 #if defined(TARGET_ARM)
1460 char symbol1 [MAX_SYMBOL_SIZE];
1461 char symbol2 [MAX_SYMBOL_SIZE];
1462 int lindex = acfg->objc_selector_index_2 ++;
1464 /* Emit ldr.imm/b */
1465 emit_bytes (acfg, code, 8);
1467 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1468 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1470 emit_label (acfg, symbol1);
1471 mono_img_writer_emit_unset_mode (acfg->w);
1472 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1474 *code_size = 12;
1475 #elif defined(TARGET_ARM64)
1476 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1477 #else
1478 g_assert_not_reached ();
1479 #endif
1481 #endif
1484 * arch_emit_plt_entry:
1486 * Emit code for the PLT entry.
1487 * The plt entry should look like this:
1488 * <indirect jump to GOT_SYMBOL + OFFSET>
1489 * <INFO_OFFSET embedded into the instruction stream>
1491 static void
1492 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1494 #if defined(TARGET_X86)
1495 /* jmp *<offset>(%ebx) */
1496 emit_byte (acfg, 0xff);
1497 emit_byte (acfg, 0xa3);
1498 emit_int32 (acfg, offset);
1499 /* Used by mono_aot_get_plt_info_offset */
1500 emit_int32 (acfg, info_offset);
1501 #elif defined(TARGET_AMD64)
1502 emit_unset_mode (acfg);
1503 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1504 /* Used by mono_aot_get_plt_info_offset */
1505 emit_int32 (acfg, info_offset);
1506 acfg->stats.plt_size += 10;
1507 #elif defined(TARGET_ARM)
1508 guint8 buf [256];
1509 guint8 *code;
1511 code = buf;
1512 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1513 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1514 emit_bytes (acfg, buf, code - buf);
1515 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1516 /* Used by mono_aot_get_plt_info_offset */
1517 emit_int32 (acfg, info_offset);
1518 #elif defined(TARGET_ARM64)
1519 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1520 #elif defined(TARGET_POWERPC)
1521 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1522 emit_unset_mode (acfg);
1523 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1524 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1525 fprintf (acfg->fp, "add 11, 11, 30\n");
1526 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1527 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1528 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1529 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1530 #endif
1531 fprintf (acfg->fp, "mtctr 11\n");
1532 fprintf (acfg->fp, "bctr\n");
1533 emit_int32 (acfg, info_offset);
1534 #else
1535 g_assert_not_reached ();
1536 #endif
1540 * arch_emit_llvm_plt_entry:
1542 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1543 * This is only needed on arm to handle thumb interop.
1545 static void
1546 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1548 #if defined(TARGET_ARM)
1549 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1550 /* The caller already transitioned to thumb */
1551 /* The code below should be 12 bytes long */
1552 /* clang has trouble encoding these instructions, so emit the binary */
1553 #if 0
1554 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1555 /* thumb can't encode ld pc, [pc, ip] */
1556 fprintf (acfg->fp, "add ip, pc, ip\n");
1557 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1558 fprintf (acfg->fp, "bx ip\n");
1559 #endif
1560 emit_set_thumb_mode (acfg);
1561 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1562 fprintf (acfg->fp, ".2byte 0x44fc\n");
1563 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1564 fprintf (acfg->fp, ".2byte 0x4760\n");
1565 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1566 emit_int32 (acfg, info_offset);
1567 emit_unset_mode (acfg);
1568 emit_set_arm_mode (acfg);
1569 #else
1570 g_assert_not_reached ();
1571 #endif
1574 /* Save unwind_info in the module and emit the offset to the information at symbol */
1575 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1577 guint32 uw_offset, encoded_len;
1578 guint8 *encoded;
1580 emit_section_change (acfg, RODATA_SECT, 0);
1581 emit_global (acfg, symbol, FALSE);
1582 emit_label (acfg, symbol);
1584 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1585 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1586 g_free (encoded);
1587 emit_int32 (acfg, uw_offset);
1591 * arch_emit_specific_trampoline_pages:
1593 * Emits a page full of trampolines: each trampoline uses its own address to
1594 * lookup both the generic trampoline code and the data argument.
1595 * This page can be remapped in process multiple times so we can get an
1596 * unlimited number of trampolines.
1597 * Specifically this implementation uses the following trick: two memory pages
1598 * are allocated, with the first containing the data and the second containing the trampolines.
1599 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1600 * implementation does all the lifting.
1601 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1602 * on the arm 32 bit system.
1604 static void
1605 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1607 #if defined(TARGET_ARM)
1608 guint8 buf [128];
1609 guint8 *code;
1610 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1611 int i;
1612 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1613 GSList *unwind_ops = NULL;
1614 #define COMMON_TRAMP_SIZE 16
1615 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1616 int imm8, rot_amount;
1617 char symbol [128];
1619 if (!acfg->aot_opts.use_trampolines_page)
1620 return;
1622 acfg->tramp_page_size = pagesize;
1624 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1625 emit_alignment (acfg, pagesize);
1626 emit_global (acfg, symbol, TRUE);
1627 emit_label (acfg, symbol);
1629 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1630 code = buf;
1631 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1632 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1633 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1634 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1635 ARM_NOP (code);
1636 g_assert (code - buf == COMMON_TRAMP_SIZE);
1638 /* Emit it */
1639 emit_bytes (acfg, buf, code - buf);
1641 for (i = 0; i < count; ++i) {
1642 code = buf;
1643 ARM_PUSH (code, 0x5fff);
1644 ARM_BL (code, 0);
1645 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1646 g_assert (code - buf == 8);
1647 emit_bytes (acfg, buf, code - buf);
1650 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1651 * the instruction pointer address, so the generic trampoline at the start of the page
1652 * subtracts 4096 to get to the data page and loads the values
1653 * We again fit the generic trampiline in 16 bytes.
1655 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1656 emit_global (acfg, symbol, TRUE);
1657 emit_label (acfg, symbol);
1658 code = buf;
1659 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1660 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1661 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1662 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1663 ARM_NOP (code);
1664 g_assert (code - buf == COMMON_TRAMP_SIZE);
1666 /* Emit it */
1667 emit_bytes (acfg, buf, code - buf);
1669 for (i = 0; i < count; ++i) {
1670 code = buf;
1671 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1672 ARM_B (code, 0);
1673 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1674 g_assert (code - buf == 8);
1675 emit_bytes (acfg, buf, code - buf);
1679 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1681 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1682 emit_global (acfg, symbol, TRUE);
1683 emit_label (acfg, symbol);
1684 code = buf;
1685 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1686 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1687 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1688 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1689 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1690 g_assert (code - buf == COMMON_TRAMP_SIZE);
1691 /* Emit it */
1692 emit_bytes (acfg, buf, code - buf);
1694 for (i = 0; i < count; ++i) {
1695 code = buf;
1696 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1697 ARM_B (code, 0);
1698 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1699 g_assert (code - buf == 8);
1700 emit_bytes (acfg, buf, code - buf);
1703 /* now the imt trampolines: each specific trampolines puts in the ip register
1704 * the instruction pointer address, so the generic trampoline at the start of the page
1705 * subtracts 4096 to get to the data page and loads the values
1707 #define IMT_TRAMP_SIZE 72
1708 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1709 emit_global (acfg, symbol, TRUE);
1710 emit_label (acfg, symbol);
1711 code = buf;
1712 /* Need at least two free registers, plus a slot for storing the pc */
1713 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1715 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1716 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1717 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1719 /* The IMT method is in v5, r0 has the imt array address */
1721 loop_start = code;
1722 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1723 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1724 imt_found_check = code;
1725 ARM_B_COND (code, ARMCOND_EQ, 0);
1727 /* End-of-loop check */
1728 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1729 loop_end_check = code;
1730 ARM_B_COND (code, ARMCOND_EQ, 0);
1732 /* Loop footer */
1733 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1734 loop_branch_back = code;
1735 ARM_B (code, 0);
1736 arm_patch (loop_branch_back, loop_start);
1738 /* Match */
1739 arm_patch (imt_found_check, code);
1740 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1741 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1742 /* Save it to the third stack slot */
1743 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1744 /* Restore the registers and branch */
1745 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1747 /* No match */
1748 arm_patch (loop_end_check, code);
1749 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1750 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1751 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1752 ARM_NOP (code);
1754 /* Emit it */
1755 g_assert (code - buf == IMT_TRAMP_SIZE);
1756 emit_bytes (acfg, buf, code - buf);
1758 for (i = 0; i < count; ++i) {
1759 code = buf;
1760 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1761 ARM_B (code, 0);
1762 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1763 g_assert (code - buf == 8);
1764 emit_bytes (acfg, buf, code - buf);
1767 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1768 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1769 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1770 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1772 /* Unwind info for specifc trampolines */
1773 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1774 /* We unwind to the original caller, from the stack, since lr is clobbered */
1775 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1776 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1777 save_unwind_info (acfg, symbol, unwind_ops);
1778 mono_free_unwind_info (unwind_ops);
1780 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1781 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1782 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1783 save_unwind_info (acfg, symbol, unwind_ops);
1784 mono_free_unwind_info (unwind_ops);
1786 /* Unwind info for rgctx trampolines */
1787 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1788 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1789 save_unwind_info (acfg, symbol, unwind_ops);
1791 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1792 save_unwind_info (acfg, symbol, unwind_ops);
1793 mono_free_unwind_info (unwind_ops);
1795 /* Unwind info for gsharedvt trampolines */
1796 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1797 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1798 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1799 save_unwind_info (acfg, symbol, unwind_ops);
1800 mono_free_unwind_info (unwind_ops);
1802 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1803 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1804 save_unwind_info (acfg, symbol, unwind_ops);
1805 mono_free_unwind_info (unwind_ops);
1807 /* Unwind info for imt trampolines */
1808 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1809 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1810 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1811 save_unwind_info (acfg, symbol, unwind_ops);
1812 mono_free_unwind_info (unwind_ops);
1814 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1815 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1816 save_unwind_info (acfg, symbol, unwind_ops);
1817 mono_free_unwind_info (unwind_ops);
1818 #elif defined(TARGET_ARM64)
1819 arm64_emit_specific_trampoline_pages (acfg);
1820 #endif
1824 * arch_emit_specific_trampoline:
1826 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1827 * two GOT slots which contain the generic trampoline address and the trampoline
1828 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1830 static void
1831 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1834 * The trampolines created here are variations of the specific
1835 * trampolines created in mono_arch_create_specific_trampoline (). The
1836 * differences are:
1837 * - the generic trampoline address is taken from a got slot.
1838 * - the offset of the got slot where the trampoline argument is stored
1839 * is embedded in the instruction stream, and the generic trampoline
1840 * can load the argument by loading the offset, adding it to the
1841 * address of the trampoline to get the address of the got slot, and
1842 * loading the argument from there.
1843 * - all the trampolines should be of the same length.
1845 #if defined(TARGET_AMD64)
1846 /* This should be exactly 8 bytes long */
1847 *tramp_size = 8;
1848 /* call *<offset>(%rip) */
1849 if (acfg->llvm) {
1850 emit_unset_mode (acfg);
1851 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1852 emit_zero_bytes (acfg, 2);
1853 } else {
1854 emit_byte (acfg, '\x41');
1855 emit_byte (acfg, '\xff');
1856 emit_byte (acfg, '\x15');
1857 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1858 emit_zero_bytes (acfg, 1);
1860 #elif defined(TARGET_ARM)
1861 guint8 buf [128];
1862 guint8 *code;
1864 /* This should be exactly 20 bytes long */
1865 *tramp_size = 20;
1866 code = buf;
1867 ARM_PUSH (code, 0x5fff);
1868 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1869 /* Load the value from the GOT */
1870 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1871 /* Branch to it */
1872 ARM_BLX_REG (code, ARMREG_R1);
1874 g_assert (code - buf == 16);
1876 /* Emit it */
1877 emit_bytes (acfg, buf, code - buf);
1879 * Only one offset is needed, since the second one would be equal to the
1880 * first one.
1882 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1883 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1884 #elif defined(TARGET_ARM64)
1885 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1886 #elif defined(TARGET_POWERPC)
1887 guint8 buf [128];
1888 guint8 *code;
1890 *tramp_size = 4;
1891 code = buf;
1894 * PPC has no ip relative addressing, so we need to compute the address
1895 * of the mscorlib got. That is slow and complex, so instead, we store it
1896 * in the second got slot of every aot image. The caller already computed
1897 * the address of its got and placed it into r30.
1899 emit_unset_mode (acfg);
1900 /* Load mscorlib got address */
1901 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1902 /* Load generic trampoline address */
1903 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1904 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1905 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1906 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1907 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1908 #endif
1909 fprintf (acfg->fp, "mtctr 11\n");
1910 /* Load trampoline argument */
1911 /* On ppc, we pass it normally to the generic trampoline */
1912 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1913 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1914 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1915 /* Branch to generic trampoline */
1916 fprintf (acfg->fp, "bctr\n");
1918 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1919 *tramp_size = 10 * 4;
1920 #else
1921 *tramp_size = 9 * 4;
1922 #endif
1923 #elif defined(TARGET_X86)
1924 guint8 buf [128];
1925 guint8 *code;
1927 /* Similar to the PPC code above */
1929 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1931 code = buf;
1932 /* Load mscorlib got address */
1933 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1934 /* Push trampoline argument */
1935 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1936 /* Load generic trampoline address */
1937 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1938 /* Branch to generic trampoline */
1939 x86_jump_reg (code, X86_ECX);
1941 emit_bytes (acfg, buf, code - buf);
1943 *tramp_size = 17;
1944 g_assert (code - buf == *tramp_size);
1945 #else
1946 g_assert_not_reached ();
1947 #endif
1951 * arch_emit_unbox_trampoline:
1953 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1954 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1956 static void
1957 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1959 #if defined(TARGET_AMD64)
1960 guint8 buf [32];
1961 guint8 *code;
1962 int this_reg;
1964 this_reg = mono_arch_get_this_arg_reg (NULL);
1965 code = buf;
1966 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1968 emit_bytes (acfg, buf, code - buf);
1969 /* jump <method> */
1970 if (acfg->llvm) {
1971 emit_unset_mode (acfg);
1972 fprintf (acfg->fp, "jmp %s\n", call_target);
1973 } else {
1974 emit_byte (acfg, '\xe9');
1975 emit_symbol_diff (acfg, call_target, ".", -4);
1977 #elif defined(TARGET_X86)
1978 guint8 buf [32];
1979 guint8 *code;
1980 int this_pos = 4;
1982 code = buf;
1984 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1986 emit_bytes (acfg, buf, code - buf);
1988 /* jump <method> */
1989 emit_byte (acfg, '\xe9');
1990 emit_symbol_diff (acfg, call_target, ".", -4);
1991 #elif defined(TARGET_ARM)
1992 guint8 buf [128];
1993 guint8 *code;
1995 if (acfg->thumb_mixed && cfg->compile_llvm) {
1996 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1997 fprintf (acfg->fp, "b %s\n", call_target);
1998 fprintf (acfg->fp, ".arm\n");
1999 fprintf (acfg->fp, ".align 2\n");
2000 return;
2003 code = buf;
2005 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2007 emit_bytes (acfg, buf, code - buf);
2008 /* jump to method */
2009 if (acfg->thumb_mixed && cfg->compile_llvm)
2010 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2011 else
2012 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2013 #elif defined(TARGET_ARM64)
2014 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2015 #elif defined(TARGET_POWERPC)
2016 int this_pos = 3;
2018 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2019 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2020 #else
2021 g_assert_not_reached ();
2022 #endif
2026 * arch_emit_static_rgctx_trampoline:
2028 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2029 * two GOT slots which contain the rgctx argument, and the method to jump to.
2030 * TRAMP_SIZE is set to the size of the emitted trampoline.
2031 * These kinds of trampolines cannot be enumerated statically, since there could
2032 * be one trampoline per method instantiation, so we emit the same code for all
2033 * trampolines, and parameterize them using two GOT slots.
2035 static void
2036 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2038 #if defined(TARGET_AMD64)
2039 /* This should be exactly 13 bytes long */
2040 *tramp_size = 13;
2042 if (acfg->llvm) {
2043 emit_unset_mode (acfg);
2044 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2045 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2046 } else {
2047 /* mov <OFFSET>(%rip), %r10 */
2048 emit_byte (acfg, '\x4d');
2049 emit_byte (acfg, '\x8b');
2050 emit_byte (acfg, '\x15');
2051 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2053 /* jmp *<offset>(%rip) */
2054 emit_byte (acfg, '\xff');
2055 emit_byte (acfg, '\x25');
2056 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2058 #elif defined(TARGET_ARM)
2059 guint8 buf [128];
2060 guint8 *code;
2062 /* This should be exactly 24 bytes long */
2063 *tramp_size = 24;
2064 code = buf;
2065 /* Load rgctx value */
2066 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2067 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2068 /* Load branch addr + branch */
2069 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2070 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2072 g_assert (code - buf == 16);
2074 /* Emit it */
2075 emit_bytes (acfg, buf, code - buf);
2076 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2077 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2078 #elif defined(TARGET_ARM64)
2079 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2080 #elif defined(TARGET_POWERPC)
2081 guint8 buf [128];
2082 guint8 *code;
2084 *tramp_size = 4;
2085 code = buf;
2088 * PPC has no ip relative addressing, so we need to compute the address
2089 * of the mscorlib got. That is slow and complex, so instead, we store it
2090 * in the second got slot of every aot image. The caller already computed
2091 * the address of its got and placed it into r30.
2093 emit_unset_mode (acfg);
2094 /* Load mscorlib got address */
2095 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2096 /* Load rgctx */
2097 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2098 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2099 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2100 /* Load target address */
2101 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2102 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2103 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2104 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2105 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2106 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2107 #endif
2108 fprintf (acfg->fp, "mtctr 11\n");
2109 /* Branch to the target address */
2110 fprintf (acfg->fp, "bctr\n");
2112 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2113 *tramp_size = 11 * 4;
2114 #else
2115 *tramp_size = 9 * 4;
2116 #endif
2118 #elif defined(TARGET_X86)
2119 guint8 buf [128];
2120 guint8 *code;
2122 /* Similar to the PPC code above */
2124 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2126 code = buf;
2127 /* Load mscorlib got address */
2128 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2129 /* Load arg */
2130 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2131 /* Branch to the target address */
2132 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2134 emit_bytes (acfg, buf, code - buf);
2136 *tramp_size = 15;
2137 g_assert (code - buf == *tramp_size);
2138 #else
2139 g_assert_not_reached ();
2140 #endif
2144 * arch_emit_imt_trampoline:
2146 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2147 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2148 * key is the IMT key, and ptr holds the address of a memory location holding
2149 * the address to branch to if the IMT arg matches the key. The array is
2150 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2151 * fail_tramp.
2152 * TRAMP_SIZE is set to the size of the emitted trampoline.
2154 static void
2155 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2157 #if defined(TARGET_AMD64)
2158 guint8 *buf, *code;
2159 guint8 *labels [16];
2160 guint8 mov_buf[3];
2161 guint8 *mov_buf_ptr = mov_buf;
2163 const int kSizeOfMove = 7;
2165 code = buf = (guint8 *)g_malloc (256);
2167 /* FIXME: Optimize this, i.e. use binary search etc. */
2168 /* Maybe move the body into a separate function (slower, but much smaller) */
2170 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2172 if (acfg->llvm) {
2173 emit_unset_mode (acfg);
2174 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2177 labels [0] = code;
2178 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2179 labels [1] = code;
2180 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2182 /* Check key */
2183 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2184 labels [2] = code;
2185 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2187 /* Loop footer */
2188 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2189 amd64_jump_code (code, labels [0]);
2191 /* Match */
2192 mono_amd64_patch (labels [2], code);
2193 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2194 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2196 /* No match */
2197 mono_amd64_patch (labels [1], code);
2198 /* Load fail tramp */
2199 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2200 /* Check if there is a fail tramp */
2201 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2202 labels [3] = code;
2203 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2204 /* Jump to fail tramp */
2205 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2207 /* Fail */
2208 mono_amd64_patch (labels [3], code);
2209 x86_breakpoint (code);
2211 if (!acfg->llvm) {
2212 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2213 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2214 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2215 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2216 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2217 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2219 emit_bytes (acfg, buf, code - buf);
2221 *tramp_size = code - buf + kSizeOfMove;
2223 g_free (buf);
2225 #elif defined(TARGET_X86)
2226 guint8 *buf, *code;
2227 guint8 *labels [16];
2229 code = buf = g_malloc (256);
2231 /* Allocate a temporary stack slot */
2232 x86_push_reg (code, X86_EAX);
2233 /* Save EAX */
2234 x86_push_reg (code, X86_EAX);
2236 /* Load mscorlib got address */
2237 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2238 /* Load arg */
2239 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2241 labels [0] = code;
2242 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2243 labels [1] = code;
2244 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2246 /* Check key */
2247 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2248 labels [2] = code;
2249 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2251 /* Loop footer */
2252 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2253 x86_jump_code (code, labels [0]);
2255 /* Match */
2256 mono_x86_patch (labels [2], code);
2257 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2258 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2259 /* Save the target address to the temporary stack location */
2260 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2261 /* Restore EAX */
2262 x86_pop_reg (code, X86_EAX);
2263 /* Jump to the target address */
2264 x86_ret (code);
2266 /* No match */
2267 mono_x86_patch (labels [1], code);
2268 /* Load fail tramp */
2269 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2270 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2271 labels [3] = code;
2272 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2273 /* Jump to fail tramp */
2274 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2275 x86_pop_reg (code, X86_EAX);
2276 x86_ret (code);
2278 /* Fail */
2279 mono_x86_patch (labels [3], code);
2280 x86_breakpoint (code);
2282 emit_bytes (acfg, buf, code - buf);
2284 *tramp_size = code - buf;
2286 g_free (buf);
2288 #elif defined(TARGET_ARM)
2289 guint8 buf [128];
2290 guint8 *code, *code2, *labels [16];
2292 code = buf;
2294 /* The IMT method is in v5 */
2296 /* Need at least two free registers, plus a slot for storing the pc */
2297 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2298 labels [0] = code;
2299 /* Load the parameter from the GOT */
2300 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2301 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2303 labels [1] = code;
2304 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2305 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2306 labels [2] = code;
2307 ARM_B_COND (code, ARMCOND_EQ, 0);
2309 /* End-of-loop check */
2310 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2311 labels [3] = code;
2312 ARM_B_COND (code, ARMCOND_EQ, 0);
2314 /* Loop footer */
2315 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2316 labels [4] = code;
2317 ARM_B (code, 0);
2318 arm_patch (labels [4], labels [1]);
2320 /* Match */
2321 arm_patch (labels [2], code);
2322 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2323 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2324 /* Save it to the third stack slot */
2325 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2326 /* Restore the registers and branch */
2327 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2329 /* No match */
2330 arm_patch (labels [3], code);
2331 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2332 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2333 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2335 /* Fixup offset */
2336 code2 = labels [0];
2337 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2339 emit_bytes (acfg, buf, code - buf);
2340 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2342 *tramp_size = code - buf + 4;
2343 #elif defined(TARGET_ARM64)
2344 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2345 #elif defined(TARGET_POWERPC)
2346 guint8 buf [128];
2347 guint8 *code, *labels [16];
2349 code = buf;
2351 /* Load the mscorlib got address */
2352 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2353 /* Load the parameter from the GOT */
2354 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2355 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2357 /* Load and check key */
2358 labels [1] = code;
2359 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2360 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2361 labels [2] = code;
2362 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2364 /* End-of-loop check */
2365 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2366 labels [3] = code;
2367 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2369 /* Loop footer */
2370 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2371 labels [4] = code;
2372 ppc_b (code, 0);
2373 mono_ppc_patch (labels [4], labels [1]);
2375 /* Match */
2376 mono_ppc_patch (labels [2], code);
2377 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2378 /* r12 now contains the value of the vtable slot */
2379 /* this is not a function descriptor on ppc64 */
2380 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2381 ppc_mtctr (code, ppc_r12);
2382 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2384 /* Fail */
2385 mono_ppc_patch (labels [3], code);
2386 /* FIXME: */
2387 ppc_break (code);
2389 *tramp_size = code - buf;
2391 emit_bytes (acfg, buf, code - buf);
2392 #else
2393 g_assert_not_reached ();
2394 #endif
2398 #if defined (TARGET_AMD64)
2400 static void
2401 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2404 g_assert (acfg->fp);
2405 emit_unset_mode (acfg);
2407 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2410 #endif
2414 * arch_emit_gsharedvt_arg_trampoline:
2416 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2417 * two GOT slots which contain the argument, and the code to jump to.
2418 * TRAMP_SIZE is set to the size of the emitted trampoline.
2419 * These kinds of trampolines cannot be enumerated statically, since there could
2420 * be one trampoline per method instantiation, so we emit the same code for all
2421 * trampolines, and parameterize them using two GOT slots.
2423 static void
2424 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2426 #if defined(TARGET_X86)
2427 guint8 buf [128];
2428 guint8 *code;
2430 /* Similar to the PPC code above */
2432 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2434 code = buf;
2435 /* Load mscorlib got address */
2436 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2437 /* Load arg */
2438 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2439 /* Branch to the target address */
2440 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2442 emit_bytes (acfg, buf, code - buf);
2444 *tramp_size = 15;
2445 g_assert (code - buf == *tramp_size);
2446 #elif defined(TARGET_ARM)
2447 guint8 buf [128];
2448 guint8 *code;
2450 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2451 /* Similar to arch_emit_specific_trampoline () */
2452 *tramp_size = 24;
2453 code = buf;
2454 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2455 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2456 /* Load the arg value from the GOT */
2457 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2458 /* Load the addr from the GOT */
2459 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2460 /* Branch to it */
2461 ARM_BX (code, ARMREG_R1);
2463 g_assert (code - buf == 20);
2465 /* Emit it */
2466 emit_bytes (acfg, buf, code - buf);
2467 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2468 #elif defined(TARGET_ARM64)
2469 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2470 #elif defined (TARGET_AMD64)
2472 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2473 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2474 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2475 fprintf (acfg->fp, "jmp *%%r11\n");
2477 *tramp_size = 0x11;
2478 #else
2479 g_assert_not_reached ();
2480 #endif
2483 /* END OF ARCH SPECIFIC CODE */
2485 static guint32
2486 mono_get_field_token (MonoClassField *field)
2488 MonoClass *klass = field->parent;
2489 int i;
2491 for (i = 0; i < klass->field.count; ++i) {
2492 if (field == &klass->fields [i])
2493 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2496 g_assert_not_reached ();
2497 return 0;
2500 static inline void
2501 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2503 guint8 *p = buf;
2505 //printf ("ENCODE: %d 0x%x.\n", value, value);
2508 * Same encoding as the one used in the metadata, extended to handle values
2509 * greater than 0x1fffffff.
2511 if ((value >= 0) && (value <= 127))
2512 *p++ = value;
2513 else if ((value >= 0) && (value <= 16383)) {
2514 p [0] = 0x80 | (value >> 8);
2515 p [1] = value & 0xff;
2516 p += 2;
2517 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2518 p [0] = (value >> 24) | 0xc0;
2519 p [1] = (value >> 16) & 0xff;
2520 p [2] = (value >> 8) & 0xff;
2521 p [3] = value & 0xff;
2522 p += 4;
2524 else {
2525 p [0] = 0xff;
2526 p [1] = (value >> 24) & 0xff;
2527 p [2] = (value >> 16) & 0xff;
2528 p [3] = (value >> 8) & 0xff;
2529 p [4] = value & 0xff;
2530 p += 5;
2532 if (endbuf)
2533 *endbuf = p;
2536 static void
2537 stream_init (MonoDynamicStream *sh)
2539 sh->index = 0;
2540 sh->alloc_size = 4096;
2541 sh->data = (char *)g_malloc (4096);
2543 /* So offsets are > 0 */
2544 sh->data [0] = 0;
2545 sh->index ++;
2548 static void
2549 make_room_in_stream (MonoDynamicStream *stream, int size)
2551 if (size <= stream->alloc_size)
2552 return;
2554 while (stream->alloc_size <= size) {
2555 if (stream->alloc_size < 4096)
2556 stream->alloc_size = 4096;
2557 else
2558 stream->alloc_size *= 2;
2561 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2564 static guint32
2565 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2567 guint32 idx;
2569 make_room_in_stream (stream, stream->index + len);
2570 memcpy (stream->data + stream->index, data, len);
2571 idx = stream->index;
2572 stream->index += len;
2573 return idx;
2577 * add_to_blob:
2579 * Add data to the binary blob inside the aot image. Returns the offset inside the
2580 * blob where the data was stored.
2582 static guint32
2583 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2585 g_assert (!acfg->blob_closed);
2587 if (acfg->blob.alloc_size == 0)
2588 stream_init (&acfg->blob);
2590 return add_stream_data (&acfg->blob, (char*)data, data_len);
2593 static guint32
2594 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2596 char buf [4] = {0};
2597 guint32 count;
2599 if (acfg->blob.alloc_size == 0)
2600 stream_init (&acfg->blob);
2602 count = acfg->blob.index % align;
2604 /* we assume the stream data will be aligned */
2605 if (count)
2606 add_stream_data (&acfg->blob, buf, 4 - count);
2608 return add_stream_data (&acfg->blob, (char*)data, data_len);
2611 /* Emit a table of data into the aot image */
2612 static void
2613 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2615 if (acfg->data_outfile) {
2616 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2617 fwrite (data,1, size, acfg->data_outfile);
2618 acfg->datafile_offset += size;
2619 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2620 int align = 8 - size % 8;
2621 acfg->datafile_offset += align;
2622 guint8 align_buf [16];
2623 memset (&align_buf, 0, sizeof (align_buf));
2624 fwrite (align_buf, align, 1, acfg->data_outfile);
2625 } else if (acfg->llvm) {
2626 mono_llvm_emit_aot_data (symbol, data, size);
2627 } else {
2628 emit_section_change (acfg, RODATA_SECT, 0);
2629 emit_alignment (acfg, 8);
2630 emit_label (acfg, symbol);
2631 emit_bytes (acfg, data, size);
2636 * emit_offset_table:
2638 * Emit a table of increasing offsets in a compact form using differential encoding.
2639 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2640 * group size, the more compact the table becomes, but the slower it becomes to compute
2641 * a given entry. Returns the size of the table.
2643 static guint32
2644 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2646 gint32 current_offset;
2647 int i, buf_size, ngroups, index_entry_size;
2648 guint8 *p, *buf;
2649 guint8 *data_p, *data_buf;
2650 guint32 *index_offsets;
2652 ngroups = (noffsets + (group_size - 1)) / group_size;
2654 index_offsets = g_new0 (guint32, ngroups);
2656 buf_size = noffsets * 4;
2657 p = buf = (guint8 *)g_malloc0 (buf_size);
2659 current_offset = 0;
2660 for (i = 0; i < noffsets; ++i) {
2661 //printf ("D: %d -> %d\n", i, offsets [i]);
2662 if ((i % group_size) == 0) {
2663 index_offsets [i / group_size] = p - buf;
2664 /* Emit the full value for these entries */
2665 encode_value (offsets [i], p, &p);
2666 } else {
2667 /* The offsets are allowed to be non-increasing */
2668 //g_assert (offsets [i] >= current_offset);
2669 encode_value (offsets [i] - current_offset, p, &p);
2671 current_offset = offsets [i];
2673 data_buf = buf;
2674 data_p = p;
2676 if (ngroups && index_offsets [ngroups - 1] < 65000)
2677 index_entry_size = 2;
2678 else
2679 index_entry_size = 4;
2681 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2682 p = buf = (guint8 *)g_malloc0 (buf_size);
2684 /* Emit the header */
2685 encode_int (noffsets, p, &p);
2686 encode_int (group_size, p, &p);
2687 encode_int (ngroups, p, &p);
2688 encode_int (index_entry_size, p, &p);
2690 /* Emit the index */
2691 for (i = 0; i < ngroups; ++i) {
2692 if (index_entry_size == 2)
2693 encode_int16 (index_offsets [i], p, &p);
2694 else
2695 encode_int (index_offsets [i], p, &p);
2697 /* Emit the data */
2698 memcpy (p, data_buf, data_p - data_buf);
2699 p += data_p - data_buf;
2701 g_assert (p - buf <= buf_size);
2703 emit_aot_data (acfg, table, symbol, buf, p - buf);
2705 g_free (buf);
2706 g_free (data_buf);
2708 return (int)(p - buf);
2711 static guint32
2712 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2714 guint32 index;
2716 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2717 if (index)
2718 return index - 1;
2719 else {
2720 index = g_hash_table_size (cfg->image_hash);
2721 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2722 g_ptr_array_add (cfg->image_table, image);
2723 return index;
2727 static guint32
2728 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2730 int i;
2731 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2733 /* FIXME: Search referenced images as well */
2734 if (!acfg->typespec_classes) {
2735 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2736 for (i = 0; i < len; i++) {
2737 MonoError error;
2738 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2739 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2740 if (!is_ok (&error)) {
2741 mono_error_cleanup (&error);
2742 continue;
2744 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2747 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2750 static void
2751 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2753 static void
2754 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2756 static void
2757 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2759 static void
2760 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2762 static void
2763 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2765 guint8 *p = buf;
2768 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2769 * information.
2772 if (mono_class_is_ginst (klass)) {
2773 guint32 token;
2774 g_assert (klass->type_token);
2776 /* Find a typespec for a class if possible */
2777 token = find_typespec_for_class (acfg, klass);
2778 if (token) {
2779 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2780 encode_value (token, p, &p);
2781 } else {
2782 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2783 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2784 static int count = 0;
2785 guint8 *p1 = p;
2787 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2788 encode_klass_ref (acfg, gclass, p, &p);
2789 encode_ginst (acfg, inst, p, &p);
2791 count += p - p1;
2793 } else if (klass->type_token) {
2794 int iindex = get_image_index (acfg, klass->image);
2796 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2797 if (iindex == 0) {
2798 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2799 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2800 } else {
2801 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2802 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2803 encode_value (get_image_index (acfg, klass->image), p, &p);
2805 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2806 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2807 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2809 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2811 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2812 if (par->gshared_constraint) {
2813 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2814 encode_type (acfg, par->gshared_constraint, p, &p);
2815 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2816 } else {
2817 encode_value (klass->byval_arg.type, p, &p);
2818 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2820 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2822 if (!container->is_anonymous) {
2823 encode_value (container->is_method, p, &p);
2824 if (container->is_method)
2825 encode_method_ref (acfg, container->owner.method, p, &p);
2826 else
2827 encode_klass_ref (acfg, container->owner.klass, p, &p);
2830 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2831 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2832 encode_type (acfg, &klass->byval_arg, p, &p);
2833 } else {
2834 /* Array class */
2835 g_assert (klass->rank > 0);
2836 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2837 encode_value (klass->rank, p, &p);
2838 encode_klass_ref (acfg, klass->element_class, p, &p);
2840 *endbuf = p;
2844 * encode_klass_ref:
2846 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2847 * standard metadata encoding.
2849 static void
2850 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2852 gboolean shared = FALSE;
2855 * The encoding of generic instances is large so emit them only once.
2857 if (mono_class_is_ginst (klass)) {
2858 guint32 token;
2859 g_assert (klass->type_token);
2861 /* Find a typespec for a class if possible */
2862 token = find_typespec_for_class (acfg, klass);
2863 if (!token)
2864 shared = TRUE;
2865 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2866 shared = TRUE;
2869 if (shared) {
2870 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2871 guint8 *buf2, *p;
2873 if (!offset) {
2874 buf2 = (guint8 *)g_malloc (1024);
2875 p = buf2;
2877 encode_klass_ref_inner (acfg, klass, p, &p);
2878 g_assert (p - buf2 < 1024);
2880 offset = add_to_blob (acfg, buf2, p - buf2);
2881 g_free (buf2);
2883 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2884 } else {
2885 offset --;
2888 p = buf;
2889 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2890 encode_value (offset, p, &p);
2891 *endbuf = p;
2892 return;
2895 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2898 static void
2899 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2901 guint32 token = mono_get_field_token (field);
2902 guint8 *p = buf;
2904 encode_klass_ref (cfg, field->parent, p, &p);
2905 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2906 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2907 *endbuf = p;
2910 static void
2911 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2913 guint8 *p = buf;
2914 int i;
2916 encode_value (inst->type_argc, p, &p);
2917 for (i = 0; i < inst->type_argc; ++i)
2918 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2919 *endbuf = p;
2922 static void
2923 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2925 guint8 *p = buf;
2926 MonoGenericInst *inst;
2928 inst = context->class_inst;
2929 if (inst) {
2930 g_assert (inst->type_argc);
2931 encode_ginst (acfg, inst, p, &p);
2932 } else {
2933 encode_value (0, p, &p);
2935 inst = context->method_inst;
2936 if (inst) {
2937 g_assert (inst->type_argc);
2938 encode_ginst (acfg, inst, p, &p);
2939 } else {
2940 encode_value (0, p, &p);
2942 *endbuf = p;
2945 static void
2946 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2948 guint8 *p = buf;
2950 g_assert (t->num_mods == 0);
2951 /* t->attrs can be ignored */
2952 //g_assert (t->attrs == 0);
2954 if (t->pinned) {
2955 *p = MONO_TYPE_PINNED;
2956 ++p;
2958 if (t->byref) {
2959 *p = MONO_TYPE_BYREF;
2960 ++p;
2963 *p = t->type;
2964 p ++;
2966 switch (t->type) {
2967 case MONO_TYPE_VOID:
2968 case MONO_TYPE_BOOLEAN:
2969 case MONO_TYPE_CHAR:
2970 case MONO_TYPE_I1:
2971 case MONO_TYPE_U1:
2972 case MONO_TYPE_I2:
2973 case MONO_TYPE_U2:
2974 case MONO_TYPE_I4:
2975 case MONO_TYPE_U4:
2976 case MONO_TYPE_I8:
2977 case MONO_TYPE_U8:
2978 case MONO_TYPE_R4:
2979 case MONO_TYPE_R8:
2980 case MONO_TYPE_I:
2981 case MONO_TYPE_U:
2982 case MONO_TYPE_STRING:
2983 case MONO_TYPE_OBJECT:
2984 case MONO_TYPE_TYPEDBYREF:
2985 break;
2986 case MONO_TYPE_VALUETYPE:
2987 case MONO_TYPE_CLASS:
2988 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2989 break;
2990 case MONO_TYPE_SZARRAY:
2991 encode_klass_ref (acfg, t->data.klass, p, &p);
2992 break;
2993 case MONO_TYPE_PTR:
2994 encode_type (acfg, t->data.type, p, &p);
2995 break;
2996 case MONO_TYPE_GENERICINST: {
2997 MonoClass *gclass = t->data.generic_class->container_class;
2998 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3000 encode_klass_ref (acfg, gclass, p, &p);
3001 encode_ginst (acfg, inst, p, &p);
3002 break;
3004 case MONO_TYPE_ARRAY: {
3005 MonoArrayType *array = t->data.array;
3006 int i;
3008 encode_klass_ref (acfg, array->eklass, p, &p);
3009 encode_value (array->rank, p, &p);
3010 encode_value (array->numsizes, p, &p);
3011 for (i = 0; i < array->numsizes; ++i)
3012 encode_value (array->sizes [i], p, &p);
3013 encode_value (array->numlobounds, p, &p);
3014 for (i = 0; i < array->numlobounds; ++i)
3015 encode_value (array->lobounds [i], p, &p);
3016 break;
3018 case MONO_TYPE_VAR:
3019 case MONO_TYPE_MVAR:
3020 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3021 break;
3022 default:
3023 g_assert_not_reached ();
3026 *endbuf = p;
3029 static void
3030 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3032 guint8 *p = buf;
3033 guint32 flags = 0;
3034 int i;
3036 /* Similar to the metadata encoding */
3037 if (sig->generic_param_count)
3038 flags |= 0x10;
3039 if (sig->hasthis)
3040 flags |= 0x20;
3041 if (sig->explicit_this)
3042 flags |= 0x40;
3043 flags |= (sig->call_convention & 0x0F);
3045 *p = flags;
3046 ++p;
3047 if (sig->generic_param_count)
3048 encode_value (sig->generic_param_count, p, &p);
3049 encode_value (sig->param_count, p, &p);
3051 encode_type (acfg, sig->ret, p, &p);
3052 for (i = 0; i < sig->param_count; ++i) {
3053 if (sig->sentinelpos == i) {
3054 *p = MONO_TYPE_SENTINEL;
3055 ++p;
3057 encode_type (acfg, sig->params [i], p, &p);
3060 *endbuf = p;
3063 #define MAX_IMAGE_INDEX 250
3065 static void
3066 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3068 guint32 image_index = get_image_index (acfg, method->klass->image);
3069 guint32 token = method->token;
3070 MonoJumpInfoToken *ji;
3071 guint8 *p = buf;
3074 * The encoding for most methods is as follows:
3075 * - image index encoded as a leb128
3076 * - token index encoded as a leb128
3077 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3078 * types of method encodings.
3081 /* Mark methods which can't use aot trampolines because they need the further
3082 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3084 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3085 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3086 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3088 if (method->wrapper_type) {
3089 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3091 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3093 encode_value (method->wrapper_type, p, &p);
3095 switch (method->wrapper_type) {
3096 case MONO_WRAPPER_REMOTING_INVOKE:
3097 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3098 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3099 MonoMethod *m;
3101 m = mono_marshal_method_from_wrapper (method);
3102 g_assert (m);
3103 encode_method_ref (acfg, m, p, &p);
3104 break;
3106 case MONO_WRAPPER_PROXY_ISINST:
3107 case MONO_WRAPPER_LDFLD:
3108 case MONO_WRAPPER_LDFLDA:
3109 case MONO_WRAPPER_STFLD:
3110 case MONO_WRAPPER_ISINST: {
3111 g_assert (info);
3112 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3113 break;
3115 case MONO_WRAPPER_ALLOC: {
3116 /* The GC name is saved once in MonoAotFileInfo */
3117 g_assert (info->d.alloc.alloc_type != -1);
3118 encode_value (info->d.alloc.alloc_type, p, &p);
3119 break;
3121 case MONO_WRAPPER_WRITE_BARRIER: {
3122 g_assert (info);
3123 break;
3125 case MONO_WRAPPER_STELEMREF: {
3126 g_assert (info);
3127 encode_value (info->subtype, p, &p);
3128 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3129 encode_value (info->d.virtual_stelemref.kind, p, &p);
3130 break;
3132 case MONO_WRAPPER_UNKNOWN: {
3133 g_assert (info);
3134 encode_value (info->subtype, p, &p);
3135 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3136 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3137 encode_klass_ref (acfg, method->klass, p, &p);
3138 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3139 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3140 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3141 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3142 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3143 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3144 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3145 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3146 break;
3148 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3149 g_assert (info);
3150 encode_value (info->subtype, p, &p);
3151 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3152 strcpy ((char*)p, method->name);
3153 p += strlen (method->name) + 1;
3154 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3155 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3156 } else {
3157 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3158 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3160 break;
3162 case MONO_WRAPPER_SYNCHRONIZED: {
3163 MonoMethod *m;
3165 m = mono_marshal_method_from_wrapper (method);
3166 g_assert (m);
3167 g_assert (m != method);
3168 encode_method_ref (acfg, m, p, &p);
3169 break;
3171 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3172 g_assert (info);
3173 encode_value (info->subtype, p, &p);
3175 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3176 encode_value (info->d.element_addr.rank, p, &p);
3177 encode_value (info->d.element_addr.elem_size, p, &p);
3178 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3179 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3180 } else {
3181 g_assert_not_reached ();
3183 break;
3185 case MONO_WRAPPER_CASTCLASS: {
3186 g_assert (info);
3187 encode_value (info->subtype, p, &p);
3188 break;
3190 case MONO_WRAPPER_RUNTIME_INVOKE: {
3191 g_assert (info);
3192 encode_value (info->subtype, p, &p);
3193 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3194 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3195 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3196 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3197 break;
3199 case MONO_WRAPPER_DELEGATE_INVOKE:
3200 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3201 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3202 if (method->is_inflated) {
3203 /* These wrappers are identified by their class */
3204 encode_value (1, p, &p);
3205 encode_klass_ref (acfg, method->klass, p, &p);
3206 } else {
3207 MonoMethodSignature *sig = mono_method_signature (method);
3208 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3210 encode_value (0, p, &p);
3211 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3212 encode_value (info ? info->subtype : 0, p, &p);
3213 encode_signature (acfg, sig, p, &p);
3215 break;
3217 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3218 g_assert (info);
3219 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3220 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3221 break;
3223 default:
3224 g_assert_not_reached ();
3226 } else if (mono_method_signature (method)->is_inflated) {
3228 * This is a generic method, find the original token which referenced it and
3229 * encode that.
3230 * Obtain the token from information recorded by the JIT.
3232 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3233 if (ji) {
3234 image_index = get_image_index (acfg, ji->image);
3235 g_assert (image_index < MAX_IMAGE_INDEX);
3236 token = ji->token;
3238 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3239 encode_value (image_index, p, &p);
3240 encode_value (token, p, &p);
3241 } else {
3242 MonoMethod *declaring;
3243 MonoGenericContext *context = mono_method_get_context (method);
3245 g_assert (method->is_inflated);
3246 declaring = ((MonoMethodInflated*)method)->declaring;
3249 * This might be a non-generic method of a generic instance, which
3250 * doesn't have a token since the reference is generated by the JIT
3251 * like Nullable:Box/Unbox, or by generic sharing.
3253 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3254 /* Encode the klass */
3255 encode_klass_ref (acfg, method->klass, p, &p);
3256 /* Encode the method */
3257 image_index = get_image_index (acfg, method->klass->image);
3258 g_assert (image_index < MAX_IMAGE_INDEX);
3259 g_assert (declaring->token);
3260 token = declaring->token;
3261 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3262 encode_value (image_index, p, &p);
3263 encode_value (token, p, &p);
3264 encode_generic_context (acfg, context, p, &p);
3266 } else if (token == 0) {
3267 /* This might be a method of a constructed type like int[,].Set */
3268 /* Obtain the token from information recorded by the JIT */
3269 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3270 if (ji) {
3271 image_index = get_image_index (acfg, ji->image);
3272 g_assert (image_index < MAX_IMAGE_INDEX);
3273 token = ji->token;
3275 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3276 encode_value (image_index, p, &p);
3277 encode_value (token, p, &p);
3278 } else {
3279 /* Array methods */
3280 g_assert (method->klass->rank);
3282 /* Encode directly */
3283 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3284 encode_klass_ref (acfg, method->klass, p, &p);
3285 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3286 encode_value (0, p, &p);
3287 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3288 encode_value (1, p, &p);
3289 else if (!strcmp (method->name, "Get"))
3290 encode_value (2, p, &p);
3291 else if (!strcmp (method->name, "Address"))
3292 encode_value (3, p, &p);
3293 else if (!strcmp (method->name, "Set"))
3294 encode_value (4, p, &p);
3295 else
3296 g_assert_not_reached ();
3298 } else {
3299 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3301 if (image_index >= MONO_AOT_METHODREF_MIN) {
3302 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3303 encode_value (image_index, p, &p);
3304 encode_value (mono_metadata_token_index (token), p, &p);
3305 } else {
3306 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3309 *endbuf = p;
3312 static gint
3313 compare_patches (gconstpointer a, gconstpointer b)
3315 int i, j;
3317 i = (*(MonoJumpInfo**)a)->ip.i;
3318 j = (*(MonoJumpInfo**)b)->ip.i;
3320 if (i < j)
3321 return -1;
3322 else
3323 if (i > j)
3324 return 1;
3325 else
3326 return 0;
3329 static G_GNUC_UNUSED char*
3330 patch_to_string (MonoJumpInfo *patch_info)
3332 GString *str;
3334 str = g_string_new ("");
3336 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3338 switch (patch_info->type) {
3339 case MONO_PATCH_INFO_VTABLE:
3340 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3341 break;
3342 default:
3343 break;
3345 g_string_append_printf (str, ")");
3346 return g_string_free (str, FALSE);
3350 * is_plt_patch:
3352 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3353 * PLT entry.
3355 static inline gboolean
3356 is_plt_patch (MonoJumpInfo *patch_info)
3358 switch (patch_info->type) {
3359 case MONO_PATCH_INFO_METHOD:
3360 case MONO_PATCH_INFO_INTERNAL_METHOD:
3361 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3362 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3363 case MONO_PATCH_INFO_RGCTX_FETCH:
3364 return TRUE;
3365 default:
3366 return FALSE;
3371 * get_plt_symbol:
3373 * Return the symbol identifying the plt entry PLT_OFFSET.
3375 static char*
3376 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3378 #ifdef TARGET_MACH
3380 * The Apple linker reorganizes object files, so it doesn't like branches to local
3381 * labels, since those have no relocations.
3383 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3384 #else
3385 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3386 #endif
3390 * get_plt_entry:
3392 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3394 static MonoPltEntry*
3395 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3397 MonoPltEntry *res;
3398 gboolean synchronized = FALSE;
3399 static int synchronized_symbol_idx;
3401 if (!is_plt_patch (patch_info))
3402 return NULL;
3404 if (!acfg->patch_to_plt_entry [patch_info->type])
3405 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3406 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3408 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3410 * Allocate a separate PLT slot for each such patch, since some plt
3411 * entries will refer to the method itself, and some will refer to the
3412 * wrapper.
3414 res = NULL;
3415 synchronized = TRUE;
3418 if (!res) {
3419 MonoJumpInfo *new_ji;
3421 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3423 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3424 res->plt_offset = acfg->plt_offset;
3425 res->ji = new_ji;
3426 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3427 if (acfg->aot_opts.write_symbols)
3428 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3429 if (synchronized) {
3430 /* Avoid duplicate symbols because we don't cache */
3431 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3432 if (res->debug_sym)
3433 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3434 synchronized_symbol_idx ++;
3436 if (res->debug_sym)
3437 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3438 else
3439 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3441 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3443 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3445 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3446 //mono_print_ji (patch_info); printf ("\n");
3447 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3449 acfg->plt_offset ++;
3452 return res;
3456 * get_got_offset:
3458 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3459 * JI could be found if it exists, otherwise allocates a new one.
3461 static guint32
3462 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3464 guint32 got_offset;
3465 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3467 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3468 if (got_offset)
3469 return got_offset - 1;
3471 if (llvm) {
3472 got_offset = acfg->llvm_got_offset;
3473 acfg->llvm_got_offset ++;
3474 } else {
3475 got_offset = acfg->got_offset;
3476 acfg->got_offset ++;
3479 acfg->stats.got_slots ++;
3480 acfg->stats.got_slot_types [ji->type] ++;
3482 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3483 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3484 g_ptr_array_add (info->got_patches, ji);
3486 return got_offset;
3489 /* Add a method to the list of methods which need to be emitted */
3490 static void
3491 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3493 g_assert (method);
3494 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3495 g_ptr_array_add (acfg->methods, method);
3496 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3497 acfg->nmethods = acfg->methods->len + 1;
3500 if (method->wrapper_type || extra)
3501 g_ptr_array_add (acfg->extra_methods, method);
3504 static gboolean
3505 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3507 /* One instantiation with valuetypes is generated for each async method */
3508 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3509 return TRUE;
3510 else
3511 return FALSE;
3514 static guint32
3515 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3517 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3519 g_assert (index);
3521 return index - 1;
3524 static int
3525 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3527 int index;
3529 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3530 if (index)
3531 return index - 1;
3533 index = acfg->method_index;
3534 add_method_with_index (acfg, method, index, extra);
3536 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3538 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3540 acfg->method_index ++;
3542 return index;
3545 static int
3546 add_method (MonoAotCompile *acfg, MonoMethod *method)
3548 return add_method_full (acfg, method, FALSE, 0);
3551 static void
3552 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3554 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3555 method = mini_get_shared_method (method);
3556 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3557 /* Use the gsharedvt version */
3558 method = mini_get_shared_method_full (method, TRUE, TRUE);
3560 if (acfg->aot_opts.log_generics)
3561 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3563 add_method_full (acfg, method, TRUE, depth);
3566 static void
3567 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3569 add_extra_method_with_depth (acfg, method, 0);
3572 static void
3573 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3575 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3576 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3577 MonoMethod *wrapper;
3578 char *name;
3580 if (!callinfo->sig)
3581 return;
3583 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3584 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3585 g_free (name);
3587 add_method (acfg, wrapper);
3590 static MonoMethod*
3591 get_runtime_invoke_sig (MonoMethodSignature *sig)
3593 MonoMethodBuilder *mb;
3594 MonoMethod *m;
3596 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3597 m = mono_mb_create_method (mb, sig, 16);
3598 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3599 mono_mb_free (mb);
3600 return invoke;
3603 static MonoMethod*
3604 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3606 return mono_marshal_get_runtime_invoke (method, virtual_);
3609 static gboolean
3610 can_marshal_struct (MonoClass *klass)
3612 MonoClassField *field;
3613 gboolean can_marshal = TRUE;
3614 gpointer iter = NULL;
3615 MonoMarshalType *info;
3616 int i;
3618 if ((mono_class_get_flags (klass) & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3619 return FALSE;
3621 info = mono_marshal_load_type_info (klass);
3623 /* Only allow a few field types to avoid asserts in the marshalling code */
3624 while ((field = mono_class_get_fields (klass, &iter))) {
3625 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3626 continue;
3628 switch (field->type->type) {
3629 case MONO_TYPE_I4:
3630 case MONO_TYPE_U4:
3631 case MONO_TYPE_I1:
3632 case MONO_TYPE_U1:
3633 case MONO_TYPE_BOOLEAN:
3634 case MONO_TYPE_I2:
3635 case MONO_TYPE_U2:
3636 case MONO_TYPE_CHAR:
3637 case MONO_TYPE_I8:
3638 case MONO_TYPE_U8:
3639 case MONO_TYPE_I:
3640 case MONO_TYPE_U:
3641 case MONO_TYPE_PTR:
3642 case MONO_TYPE_R4:
3643 case MONO_TYPE_R8:
3644 case MONO_TYPE_STRING:
3645 break;
3646 case MONO_TYPE_VALUETYPE:
3647 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3648 can_marshal = FALSE;
3649 break;
3650 case MONO_TYPE_SZARRAY: {
3651 gboolean has_mspec = FALSE;
3653 if (info) {
3654 for (i = 0; i < info->num_fields; ++i) {
3655 if (info->fields [i].field == field && info->fields [i].mspec)
3656 has_mspec = TRUE;
3659 if (!has_mspec)
3660 can_marshal = FALSE;
3661 break;
3663 default:
3664 can_marshal = FALSE;
3665 break;
3669 /* Special cases */
3670 /* Its hard to compute whenever these can be marshalled or not */
3671 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3672 return TRUE;
3674 return can_marshal;
3677 static void
3678 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3680 /* Create a vtype instantiation */
3681 MonoGenericContext shared_context;
3682 MonoType **args;
3683 MonoGenericInst *inst;
3684 MonoGenericContainer *container;
3685 MonoClass **constraints;
3686 int i;
3688 memset (ctx, 0, sizeof (MonoGenericContext));
3690 if (mono_class_is_gtd (method->klass)) {
3691 shared_context = mono_class_get_generic_container (method->klass)->context;
3692 inst = shared_context.class_inst;
3694 args = g_new0 (MonoType*, inst->type_argc);
3695 for (i = 0; i < inst->type_argc; ++i) {
3696 args [i] = &mono_defaults.int_class->byval_arg;
3698 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3700 if (method->is_generic) {
3701 container = mono_method_get_generic_container (method);
3702 shared_context = container->context;
3703 inst = shared_context.method_inst;
3705 args = g_new0 (MonoType*, inst->type_argc);
3706 for (i = 0; i < container->type_argc; ++i) {
3707 MonoGenericParamInfo *info = &container->type_params [i].info;
3708 gboolean ref_only = FALSE;
3710 if (info && info->constraints) {
3711 constraints = info->constraints;
3713 while (*constraints) {
3714 MonoClass *cklass = *constraints;
3715 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3716 /* Inflaring the method with our vtype would not be valid */
3717 ref_only = TRUE;
3718 constraints ++;
3722 if (ref_only)
3723 args [i] = &mono_defaults.object_class->byval_arg;
3724 else
3725 args [i] = &mono_defaults.int_class->byval_arg;
3727 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3731 static void
3732 add_wrappers (MonoAotCompile *acfg)
3734 MonoMethod *method, *m;
3735 int i, j;
3736 MonoMethodSignature *sig, *csig;
3737 guint32 token;
3740 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3741 * so there is only one wrapper of a given type, or inlining their contents into their
3742 * callers.
3744 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3745 MonoError error;
3746 MonoMethod *method;
3747 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3748 gboolean skip = FALSE;
3750 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3751 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3753 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3754 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3755 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3756 skip = TRUE;
3758 /* Skip methods which can not be handled by get_runtime_invoke () */
3759 sig = mono_method_signature (method);
3760 if (!sig)
3761 continue;
3762 if ((sig->ret->type == MONO_TYPE_PTR) ||
3763 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3764 skip = TRUE;
3765 if (mono_class_is_open_constructed_type (sig->ret))
3766 skip = TRUE;
3768 for (j = 0; j < sig->param_count; j++) {
3769 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3770 skip = TRUE;
3771 if (mono_class_is_open_constructed_type (sig->params [j]))
3772 skip = TRUE;
3775 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3776 if (!mono_class_is_contextbound (method->klass)) {
3777 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3778 gboolean has_nullable = FALSE;
3780 for (j = 0; j < sig->param_count; j++) {
3781 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3782 has_nullable = TRUE;
3785 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3786 /* Supported by the dynamic runtime-invoke wrapper */
3787 skip = TRUE;
3789 if (info)
3790 mono_arch_dyn_call_free (info);
3792 #endif
3794 if (acfg->aot_opts.llvm_only)
3795 /* Supported by the gsharedvt based runtime-invoke wrapper */
3796 skip = TRUE;
3798 if (!skip) {
3799 //printf ("%s\n", mono_method_full_name (method, TRUE));
3800 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3804 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3805 int nallocators;
3807 /* Runtime invoke wrappers */
3809 /* void runtime-invoke () [.cctor] */
3810 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3811 csig->ret = &mono_defaults.void_class->byval_arg;
3812 add_method (acfg, get_runtime_invoke_sig (csig));
3814 /* void runtime-invoke () [Finalize] */
3815 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3816 csig->hasthis = 1;
3817 csig->ret = &mono_defaults.void_class->byval_arg;
3818 add_method (acfg, get_runtime_invoke_sig (csig));
3820 /* void runtime-invoke (string) [exception ctor] */
3821 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3822 csig->hasthis = 1;
3823 csig->ret = &mono_defaults.void_class->byval_arg;
3824 csig->params [0] = &mono_defaults.string_class->byval_arg;
3825 add_method (acfg, get_runtime_invoke_sig (csig));
3827 /* void runtime-invoke (string, string) [exception ctor] */
3828 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3829 csig->hasthis = 1;
3830 csig->ret = &mono_defaults.void_class->byval_arg;
3831 csig->params [0] = &mono_defaults.string_class->byval_arg;
3832 csig->params [1] = &mono_defaults.string_class->byval_arg;
3833 add_method (acfg, get_runtime_invoke_sig (csig));
3835 /* string runtime-invoke () [Exception.ToString ()] */
3836 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3837 csig->hasthis = 1;
3838 csig->ret = &mono_defaults.string_class->byval_arg;
3839 add_method (acfg, get_runtime_invoke_sig (csig));
3841 /* void runtime-invoke (string, Exception) [exception ctor] */
3842 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3843 csig->hasthis = 1;
3844 csig->ret = &mono_defaults.void_class->byval_arg;
3845 csig->params [0] = &mono_defaults.string_class->byval_arg;
3846 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3847 add_method (acfg, get_runtime_invoke_sig (csig));
3849 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
3850 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
3851 csig->hasthis = 1;
3852 csig->ret = &(mono_class_load_from_name (
3853 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3854 csig->params [0] = &mono_defaults.string_class->byval_arg;
3855 csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3856 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
3857 add_method (acfg, get_runtime_invoke_sig (csig));
3859 /* runtime-invoke used by finalizers */
3860 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3862 /* This is used by mono_runtime_capture_context () */
3863 method = mono_get_context_capture_method ();
3864 if (method)
3865 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3867 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3868 if (!acfg->aot_opts.llvm_only)
3869 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3870 #endif
3872 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3873 if (acfg->aot_opts.llvm_only) {
3874 int variants;
3876 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3877 for (variants = 0; variants < 4; ++variants) {
3878 for (i = 0; i < 16; ++i) {
3879 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3880 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3882 g_free (sig);
3887 /* stelemref */
3888 add_method (acfg, mono_marshal_get_stelemref ());
3890 if (MONO_ARCH_HAVE_TLS_GET) {
3891 /* Managed Allocators */
3892 nallocators = mono_gc_get_managed_allocator_types ();
3893 for (i = 0; i < nallocators; ++i) {
3894 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3895 add_method (acfg, m);
3896 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3897 add_method (acfg, m);
3901 /* write barriers */
3902 if (mono_gc_is_moving ()) {
3903 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3904 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3907 /* Stelemref wrappers */
3909 MonoMethod **wrappers;
3910 int nwrappers;
3912 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3913 for (i = 0; i < nwrappers; ++i)
3914 add_method (acfg, wrappers [i]);
3915 g_free (wrappers);
3918 /* castclass_with_check wrapper */
3919 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3920 /* isinst_with_check wrapper */
3921 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3923 /* JIT icall wrappers */
3924 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3925 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3929 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3930 * we use the original method instead at runtime.
3931 * Since full-aot doesn't support remoting, this is not a problem.
3933 #if 0
3934 /* remoting-invoke wrappers */
3935 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3936 MonoError error;
3937 MonoMethodSignature *sig;
3939 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3940 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3941 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3943 sig = mono_method_signature (method);
3945 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3946 m = mono_marshal_get_remoting_invoke_with_check (method);
3948 add_method (acfg, m);
3951 #endif
3953 /* delegate-invoke wrappers */
3954 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3955 MonoError error;
3956 MonoClass *klass;
3957 MonoCustomAttrInfo *cattr;
3959 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3960 klass = mono_class_get_checked (acfg->image, token, &error);
3962 if (!klass) {
3963 mono_error_cleanup (&error);
3964 continue;
3967 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3968 continue;
3970 if (!mono_class_is_gtd (klass)) {
3971 method = mono_get_delegate_invoke (klass);
3973 m = mono_marshal_get_delegate_invoke (method, NULL);
3975 add_method (acfg, m);
3977 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3978 if (method)
3979 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3981 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3982 if (method)
3983 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3985 cattr = mono_custom_attrs_from_class_checked (klass, &error);
3986 if (!is_ok (&error)) {
3987 mono_error_cleanup (&error);
3988 continue;
3991 if (cattr) {
3992 int j;
3994 for (j = 0; j < cattr->num_attrs; ++j)
3995 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3996 break;
3997 if (j < cattr->num_attrs) {
3998 MonoMethod *invoke;
3999 MonoMethod *wrapper;
4000 MonoMethod *del_invoke;
4002 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4003 invoke = mono_get_delegate_invoke (klass);
4004 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4005 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4006 add_method (acfg, wrapper);
4007 add_method (acfg, del_invoke);
4010 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4011 MonoError error;
4012 MonoGenericContext ctx;
4013 MonoMethod *inst, *gshared;
4016 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4018 /* Invoke */
4019 method = mono_get_delegate_invoke (klass);
4020 create_gsharedvt_inst (acfg, method, &ctx);
4022 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4023 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4025 m = mono_marshal_get_delegate_invoke (inst, NULL);
4026 g_assert (m->is_inflated);
4028 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4029 add_extra_method (acfg, gshared);
4031 /* begin-invoke */
4032 method = mono_get_delegate_begin_invoke (klass);
4033 create_gsharedvt_inst (acfg, method, &ctx);
4035 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4036 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4038 m = mono_marshal_get_delegate_begin_invoke (inst);
4039 g_assert (m->is_inflated);
4041 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4042 add_extra_method (acfg, gshared);
4044 /* end-invoke */
4045 method = mono_get_delegate_end_invoke (klass);
4046 create_gsharedvt_inst (acfg, method, &ctx);
4048 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4049 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4051 m = mono_marshal_get_delegate_end_invoke (inst);
4052 g_assert (m->is_inflated);
4054 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4055 add_extra_method (acfg, gshared);
4060 /* array access wrappers */
4061 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4062 MonoError error;
4063 MonoClass *klass;
4065 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4066 klass = mono_class_get_checked (acfg->image, token, &error);
4068 if (!klass) {
4069 mono_error_cleanup (&error);
4070 continue;
4073 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4074 MonoMethod *m, *wrapper;
4076 /* Add runtime-invoke wrappers too */
4078 m = mono_class_get_method_from_name (klass, "Get", -1);
4079 g_assert (m);
4080 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4081 add_extra_method (acfg, wrapper);
4082 if (!acfg->aot_opts.llvm_only)
4083 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4085 m = mono_class_get_method_from_name (klass, "Set", -1);
4086 g_assert (m);
4087 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4088 add_extra_method (acfg, wrapper);
4089 if (!acfg->aot_opts.llvm_only)
4090 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4094 /* Synchronized wrappers */
4095 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4096 MonoError error;
4097 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4098 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4099 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4101 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4102 if (method->is_generic) {
4103 // FIXME:
4104 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4105 MonoError error;
4106 MonoGenericContext ctx;
4107 MonoMethod *inst, *gshared, *m;
4110 * Create a generic wrapper for a generic instance, and AOT that.
4112 create_gsharedvt_inst (acfg, method, &ctx);
4113 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4114 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4115 m = mono_marshal_get_synchronized_wrapper (inst);
4116 g_assert (m->is_inflated);
4117 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4118 add_method (acfg, gshared);
4119 } else {
4120 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4125 /* pinvoke wrappers */
4126 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4127 MonoError error;
4128 MonoMethod *method;
4129 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4131 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4132 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4134 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4135 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4136 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4139 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4140 if (acfg->aot_opts.llvm_only) {
4141 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4142 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE);
4147 /* native-to-managed wrappers */
4148 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4149 MonoError error;
4150 MonoMethod *method;
4151 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4152 MonoCustomAttrInfo *cattr;
4153 int j;
4155 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4156 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4159 * Only generate native-to-managed wrappers for methods which have an
4160 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4161 * name to avoid defining a new assembly to contain it.
4163 cattr = mono_custom_attrs_from_method_checked (method, &error);
4164 if (!is_ok (&error)) {
4165 char *name = mono_method_get_full_name (method);
4166 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4167 g_free (name);
4170 if (cattr) {
4171 for (j = 0; j < cattr->num_attrs; ++j)
4172 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4173 break;
4174 if (j < cattr->num_attrs) {
4175 MonoCustomAttrEntry *e = &cattr->attrs [j];
4176 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4177 const char *p = (const char*)e->data;
4178 const char *named;
4179 int slen, num_named, named_type;
4180 char *n;
4181 MonoType *t;
4182 MonoClass *klass;
4183 char *export_name = NULL;
4184 MonoMethod *wrapper;
4186 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4187 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4188 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4189 mono_method_full_name (method, TRUE));
4190 exit (1);
4193 g_assert (sig->param_count == 1);
4194 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4197 * Decode the cattr manually since we can't create objects
4198 * during aot compilation.
4201 /* Skip prolog */
4202 p += 2;
4204 /* From load_cattr_value () in reflection.c */
4205 slen = mono_metadata_decode_value (p, &p);
4206 n = (char *)g_memdup (p, slen + 1);
4207 n [slen] = 0;
4208 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4209 g_assert (t);
4210 mono_error_assert_ok (&error);
4211 g_free (n);
4213 klass = mono_class_from_mono_type (t);
4214 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4216 p += slen;
4218 num_named = read16 (p);
4219 p += 2;
4221 g_assert (num_named < 2);
4222 if (num_named == 1) {
4223 int name_len;
4224 char *name;
4226 /* parse ExportSymbol attribute */
4227 named = p;
4228 named_type = *named;
4229 named += 1;
4230 /* data_type = *named; */
4231 named += 1;
4233 name_len = mono_metadata_decode_blob_size (named, &named);
4234 name = (char *)g_malloc (name_len + 1);
4235 memcpy (name, named, name_len);
4236 name [name_len] = 0;
4237 named += name_len;
4239 g_assert (named_type == 0x54);
4240 g_assert (!strcmp (name, "ExportSymbol"));
4242 /* load_cattr_value (), string case */
4243 g_assert (*named != (char)0xff);
4244 slen = mono_metadata_decode_value (named, &named);
4245 export_name = (char *)g_malloc (slen + 1);
4246 memcpy (export_name, named, slen);
4247 export_name [slen] = 0;
4248 named += slen;
4251 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4252 add_method (acfg, wrapper);
4253 if (export_name)
4254 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4256 g_free (cattr);
4259 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4260 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4261 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4265 /* StructureToPtr/PtrToStructure wrappers */
4266 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4267 MonoError error;
4268 MonoClass *klass;
4270 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4271 klass = mono_class_get_checked (acfg->image, token, &error);
4273 if (!klass) {
4274 mono_error_cleanup (&error);
4275 continue;
4278 if (klass->valuetype && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4279 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4280 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4281 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4286 static gboolean
4287 has_type_vars (MonoClass *klass)
4289 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4290 return TRUE;
4291 if (klass->rank)
4292 return has_type_vars (klass->element_class);
4293 if (mono_class_is_ginst (klass)) {
4294 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4295 if (context->class_inst) {
4296 int i;
4298 for (i = 0; i < context->class_inst->type_argc; ++i)
4299 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4300 return TRUE;
4303 if (mono_class_is_gtd (klass))
4304 return TRUE;
4305 return FALSE;
4308 static gboolean
4309 is_vt_inst (MonoGenericInst *inst)
4311 int i;
4313 for (i = 0; i < inst->type_argc; ++i) {
4314 MonoType *t = inst->type_argv [i];
4315 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4316 return TRUE;
4318 return FALSE;
4321 static gboolean
4322 method_has_type_vars (MonoMethod *method)
4324 if (has_type_vars (method->klass))
4325 return TRUE;
4327 if (method->is_inflated) {
4328 MonoGenericContext *context = mono_method_get_context (method);
4329 if (context->method_inst) {
4330 int i;
4332 for (i = 0; i < context->method_inst->type_argc; ++i)
4333 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4334 return TRUE;
4337 return FALSE;
4340 static
4341 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4343 return opts->mode == MONO_AOT_MODE_FULL;
4346 static
4347 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4349 return opts->mode == MONO_AOT_MODE_HYBRID;
4352 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4354 static void
4355 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4357 /* This might lead to a huge code blowup so only do it if neccesary */
4358 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4359 return;
4361 add_generic_class_with_depth (acfg, klass, 0, ref);
4364 static gboolean
4365 check_type_depth (MonoType *t, int depth)
4367 int i;
4369 if (depth > 8)
4370 return TRUE;
4372 switch (t->type) {
4373 case MONO_TYPE_GENERICINST: {
4374 MonoGenericClass *gklass = t->data.generic_class;
4375 MonoGenericInst *ginst = gklass->context.class_inst;
4377 if (ginst) {
4378 for (i = 0; i < ginst->type_argc; ++i) {
4379 if (check_type_depth (ginst->type_argv [i], depth + 1))
4380 return TRUE;
4383 break;
4385 default:
4386 break;
4389 return FALSE;
4392 static void
4393 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4396 * add_generic_class:
4398 * Add all methods of a generic class.
4400 static void
4401 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4403 MonoMethod *method;
4404 MonoClassField *field;
4405 gpointer iter;
4406 gboolean use_gsharedvt = FALSE;
4408 if (!acfg->ginst_hash)
4409 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4411 mono_class_init (klass);
4413 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4414 return;
4416 if (has_type_vars (klass))
4417 return;
4419 if (!mono_class_is_ginst (klass) && !klass->rank)
4420 return;
4422 if (mono_class_has_failure (klass))
4423 return;
4425 if (!acfg->ginst_hash)
4426 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4428 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4429 return;
4431 if (check_type_depth (&klass->byval_arg, 0))
4432 return;
4434 if (acfg->aot_opts.log_generics)
4435 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4437 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4440 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4441 * Enable this only for some classes since gsharedvt might not support all methods.
4443 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst (mono_class_get_generic_class (klass)->context.class_inst) &&
4444 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4445 use_gsharedvt = TRUE;
4447 iter = NULL;
4448 while ((method = mono_class_get_methods (klass, &iter))) {
4449 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4451 * This is partial sharing, and we can't handle it yet
4453 continue;
4456 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4457 /* Already added */
4458 add_types_from_method_header (acfg, method);
4459 continue;
4462 if (method->is_generic)
4463 /* FIXME: */
4464 continue;
4467 * FIXME: Instances which are referenced by these methods are not added,
4468 * for example Array.Resize<int> for List<int>.Add ().
4470 add_extra_method_with_depth (acfg, method, depth + 1);
4473 iter = NULL;
4474 while ((field = mono_class_get_fields (klass, &iter))) {
4475 if (field->type->type == MONO_TYPE_GENERICINST)
4476 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4479 if (klass->delegate) {
4480 method = mono_get_delegate_invoke (klass);
4482 method = mono_marshal_get_delegate_invoke (method, NULL);
4484 if (acfg->aot_opts.log_generics)
4485 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4487 add_method (acfg, method);
4490 /* Add superclasses */
4491 if (klass->parent)
4492 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4495 * For ICollection<T>, add instances of the helper methods
4496 * in Array, since a T[] could be cast to ICollection<T>.
4498 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4499 (!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"))) {
4500 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4501 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4502 gpointer iter;
4503 char *name_prefix;
4505 if (!strcmp (klass->name, "IEnumerator`1"))
4506 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4507 else
4508 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4510 /* Add the T[]/InternalEnumerator class */
4511 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4512 MonoError error;
4513 MonoClass *nclass;
4515 iter = NULL;
4516 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4517 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4518 break;
4520 g_assert (nclass);
4521 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), &error);
4522 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4523 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4526 iter = NULL;
4527 while ((method = mono_class_get_methods (array_class, &iter))) {
4528 if (strstr (method->name, name_prefix)) {
4529 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4531 add_extra_method_with_depth (acfg, m, depth);
4535 g_free (name_prefix);
4538 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4539 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4540 MonoError error;
4541 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4542 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4543 MonoGenericContext ctx;
4544 MonoType *args [16];
4546 memset (&ctx, 0, sizeof (ctx));
4548 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4550 args [0] = &tclass->byval_arg;
4551 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4553 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4554 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4556 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4557 MonoClass *gcomparer_inst;
4558 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4559 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4560 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4562 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4566 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4567 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4568 MonoError error;
4569 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4570 MonoClass *iface, *gcomparer, *iface_inst;
4571 MonoGenericContext ctx;
4572 MonoType *args [16];
4574 memset (&ctx, 0, sizeof (ctx));
4576 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4577 g_assert (iface);
4578 args [0] = &tclass->byval_arg;
4579 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4581 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4582 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4584 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4585 MonoClass *gcomparer_inst;
4586 MonoError error;
4588 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4589 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4590 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4591 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4595 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4596 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4597 MonoClass *enum_comparer;
4598 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4599 MonoGenericContext ctx;
4600 MonoType *args [16];
4602 if (mono_class_is_enum (tclass)) {
4603 MonoClass *enum_comparer_inst;
4604 MonoError error;
4606 memset (&ctx, 0, sizeof (ctx));
4607 args [0] = &tclass->byval_arg;
4608 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4610 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4611 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4612 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4613 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4617 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4618 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4619 MonoClass *comparer;
4620 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4621 MonoGenericContext ctx;
4622 MonoType *args [16];
4624 if (mono_class_is_enum (tclass)) {
4625 MonoClass *comparer_inst;
4626 MonoError error;
4628 memset (&ctx, 0, sizeof (ctx));
4629 args [0] = &tclass->byval_arg;
4630 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4632 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4633 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4634 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4635 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4640 static void
4641 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4643 int i;
4644 MonoGenericContext ctx;
4645 MonoType *args [16];
4647 if (acfg->aot_opts.no_instances)
4648 return;
4650 memset (&ctx, 0, sizeof (ctx));
4652 for (i = 0; i < ninsts; ++i) {
4653 MonoError error;
4654 MonoClass *generic_inst;
4655 args [0] = insts [i];
4656 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4657 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4658 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4659 add_generic_class (acfg, generic_inst, force, "");
4663 static void
4664 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4666 MonoError error;
4667 MonoMethodHeader *header;
4668 MonoMethodSignature *sig;
4669 int j, depth;
4671 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4673 sig = mono_method_signature (method);
4675 if (sig) {
4676 for (j = 0; j < sig->param_count; ++j)
4677 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4678 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4681 header = mono_method_get_header_checked (method, &error);
4683 if (header) {
4684 for (j = 0; j < header->num_locals; ++j)
4685 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4686 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4687 mono_metadata_free_mh (header);
4688 } else {
4689 mono_error_cleanup (&error); /* FIXME report the error */
4695 * add_generic_instances:
4697 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4699 static void
4700 add_generic_instances (MonoAotCompile *acfg)
4702 int i;
4703 guint32 token;
4704 MonoMethod *method;
4705 MonoGenericContext *context;
4707 if (acfg->aot_opts.no_instances)
4708 return;
4710 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4711 MonoError error;
4712 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4713 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4715 if (!method) {
4716 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4717 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4718 mono_error_cleanup (&error);
4719 continue;
4722 if (method->klass->image != acfg->image)
4723 continue;
4725 context = mono_method_get_context (method);
4727 if (context && ((context->class_inst && context->class_inst->is_open)))
4728 continue;
4731 * For open methods, create an instantiation which can be passed to the JIT.
4732 * FIXME: Handle class_inst as well.
4734 if (context && context->method_inst && context->method_inst->is_open) {
4735 MonoError error;
4736 MonoGenericContext shared_context;
4737 MonoGenericInst *inst;
4738 MonoType **type_argv;
4739 int i;
4740 MonoMethod *declaring_method;
4741 gboolean supported = TRUE;
4743 /* Check that the context doesn't contain open constructed types */
4744 if (context->class_inst) {
4745 inst = context->class_inst;
4746 for (i = 0; i < inst->type_argc; ++i) {
4747 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)
4748 continue;
4749 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4750 supported = FALSE;
4753 if (context->method_inst) {
4754 inst = context->method_inst;
4755 for (i = 0; i < inst->type_argc; ++i) {
4756 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)
4757 continue;
4758 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4759 supported = FALSE;
4763 if (!supported)
4764 continue;
4766 memset (&shared_context, 0, sizeof (MonoGenericContext));
4768 inst = context->class_inst;
4769 if (inst) {
4770 type_argv = g_new0 (MonoType*, inst->type_argc);
4771 for (i = 0; i < inst->type_argc; ++i) {
4772 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)
4773 type_argv [i] = &mono_defaults.object_class->byval_arg;
4774 else
4775 type_argv [i] = inst->type_argv [i];
4778 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4779 g_free (type_argv);
4782 inst = context->method_inst;
4783 if (inst) {
4784 type_argv = g_new0 (MonoType*, inst->type_argc);
4785 for (i = 0; i < inst->type_argc; ++i) {
4786 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)
4787 type_argv [i] = &mono_defaults.object_class->byval_arg;
4788 else
4789 type_argv [i] = inst->type_argv [i];
4792 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4793 g_free (type_argv);
4796 if (method->is_generic || mono_class_is_gtd (method->klass))
4797 declaring_method = method;
4798 else
4799 declaring_method = mono_method_get_declaring_generic_method (method);
4801 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4802 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4806 * If the method is fully sharable, it was already added in place of its
4807 * generic definition.
4809 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4810 continue;
4813 * FIXME: Partially shared methods are not shared here, so we end up with
4814 * many identical methods.
4816 add_extra_method (acfg, method);
4819 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4820 MonoError error;
4821 MonoClass *klass;
4823 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4825 klass = mono_class_get_checked (acfg->image, token, &error);
4826 if (!klass || klass->rank) {
4827 mono_error_cleanup (&error);
4828 continue;
4831 add_generic_class (acfg, klass, FALSE, "typespec");
4834 /* Add types of args/locals */
4835 for (i = 0; i < acfg->methods->len; ++i) {
4836 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4837 add_types_from_method_header (acfg, method);
4840 if (acfg->image == mono_defaults.corlib) {
4841 MonoClass *klass;
4842 MonoType *insts [256];
4843 int ninsts = 0;
4845 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4846 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4847 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4848 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4849 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4850 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4851 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4852 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4853 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4854 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4855 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4856 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4858 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4859 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4860 if (klass)
4861 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4862 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4863 if (klass)
4864 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4866 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4868 MonoClass *enum_comparer;
4869 MonoType *insts [16];
4870 int ninsts;
4872 ninsts = 0;
4873 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4874 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4875 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4876 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4877 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4878 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4880 ninsts = 0;
4881 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4882 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4883 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4885 ninsts = 0;
4886 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4887 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4888 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4890 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4891 ninsts = 0;
4892 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4893 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4894 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4897 /* Add instances of the array generic interfaces for primitive types */
4898 /* This will add instances of the InternalArray_ helper methods in Array too */
4899 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4900 if (klass)
4901 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4903 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4904 if (klass)
4905 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4907 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4908 if (klass)
4909 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4912 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4913 * used for all instances of GetGenericValueImpl by the AOT runtime.
4916 MonoGenericContext ctx;
4917 MonoType *args [16];
4918 MonoMethod *get_method;
4919 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4921 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4923 if (get_method) {
4924 MonoError error;
4925 memset (&ctx, 0, sizeof (ctx));
4926 args [0] = &mono_defaults.object_class->byval_arg;
4927 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4928 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4929 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4933 /* Same for CompareExchange<T>/Exchange<T> */
4935 MonoGenericContext ctx;
4936 MonoType *args [16];
4937 MonoMethod *m;
4938 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4939 gpointer iter = NULL;
4941 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4942 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4943 MonoError error;
4944 memset (&ctx, 0, sizeof (ctx));
4945 args [0] = &mono_defaults.object_class->byval_arg;
4946 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4947 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4948 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4953 /* Same for Volatile.Read/Write<T> */
4955 MonoGenericContext ctx;
4956 MonoType *args [16];
4957 MonoMethod *m;
4958 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4959 gpointer iter = NULL;
4961 if (volatile_klass) {
4962 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4963 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4964 MonoError error;
4965 memset (&ctx, 0, sizeof (ctx));
4966 args [0] = &mono_defaults.object_class->byval_arg;
4967 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4968 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4969 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4975 /* object[] accessor wrappers. */
4976 for (i = 1; i < 4; ++i) {
4977 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
4978 MonoMethod *m;
4980 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
4981 g_assert (m);
4983 m = mono_marshal_get_array_accessor_wrapper (m);
4984 add_extra_method (acfg, m);
4986 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
4987 g_assert (m);
4989 m = mono_marshal_get_array_accessor_wrapper (m);
4990 add_extra_method (acfg, m);
4992 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
4993 g_assert (m);
4995 m = mono_marshal_get_array_accessor_wrapper (m);
4996 add_extra_method (acfg, m);
5002 * is_direct_callable:
5004 * Return whenever the method identified by JI is directly callable without
5005 * going through the PLT.
5007 static gboolean
5008 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5010 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5011 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5012 if (callee_cfg) {
5013 gboolean direct_callable = TRUE;
5015 if (direct_callable && !(!callee_cfg->has_got_slots && (mono_class_get_flags (callee_cfg->method->klass) & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
5016 direct_callable = FALSE;
5017 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5018 // FIXME: Maybe call the wrapper directly ?
5019 direct_callable = FALSE;
5021 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5022 /* Disable this so all calls go through load_method (), see the
5023 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5024 * mono_debugger_agent_init ().
5026 direct_callable = FALSE;
5029 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5030 /* sgen does some initialization when the allocator method is created */
5031 direct_callable = FALSE;
5032 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5033 /* we don't know at compile time whether sgen is concurrent or not */
5034 direct_callable = FALSE;
5036 if (direct_callable)
5037 return TRUE;
5039 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5040 if (acfg->aot_opts.direct_pinvoke)
5041 return TRUE;
5042 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5043 if (acfg->aot_opts.direct_icalls)
5044 return TRUE;
5045 return FALSE;
5048 return FALSE;
5051 #ifdef MONO_ARCH_AOT_SUPPORTED
5052 static const char *
5053 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5055 MonoImage *image = method->klass->image;
5056 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5057 MonoTableInfo *tables = image->tables;
5058 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5059 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5060 guint32 im_cols [MONO_IMPLMAP_SIZE];
5061 char *import;
5063 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5064 if (import != NULL)
5065 return import;
5067 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5068 return NULL;
5070 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5072 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5073 return NULL;
5075 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5077 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5079 return import;
5081 #else
5082 static const char *
5083 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5085 return NULL;
5087 #endif
5089 static gint
5090 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5092 if (a->native_offset == b->native_offset)
5093 return a->il_offset - b->il_offset;
5094 else
5095 return a->native_offset - b->native_offset;
5099 * compute_line_numbers:
5101 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5102 * entry.
5104 static MonoDebugSourceLocation**
5105 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5107 MonoDebugMethodInfo *minfo;
5108 MonoDebugLineNumberEntry *ln_array;
5109 MonoDebugSourceLocation *loc;
5110 int i, prev_line, prev_il_offset;
5111 int *native_to_il_offset = NULL;
5112 MonoDebugSourceLocation **res;
5113 gboolean first;
5115 minfo = mono_debug_lookup_method (method);
5116 if (!minfo)
5117 return NULL;
5118 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5119 if (debug_info->code_size != code_size)
5120 return NULL;
5122 g_assert (code_size);
5124 /* Compute the native->IL offset mapping */
5126 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5127 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5129 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5131 native_to_il_offset = g_new0 (int, code_size + 1);
5133 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5134 int j;
5135 MonoDebugLineNumberEntry *lne = &ln_array [i];
5137 if (i == 0) {
5138 for (j = 0; j < lne->native_offset; ++j)
5139 native_to_il_offset [j] = -1;
5142 if (i < debug_info->num_line_numbers - 1) {
5143 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5145 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5146 native_to_il_offset [j] = lne->il_offset;
5147 } else {
5148 for (j = lne->native_offset; j < code_size; ++j)
5149 native_to_il_offset [j] = lne->il_offset;
5152 g_free (ln_array);
5154 /* Compute the native->line number mapping */
5155 res = g_new0 (MonoDebugSourceLocation*, code_size);
5156 prev_il_offset = -1;
5157 prev_line = -1;
5158 first = TRUE;
5159 for (i = 0; i < code_size; ++i) {
5160 int il_offset = native_to_il_offset [i];
5162 if (il_offset == -1 || il_offset == prev_il_offset)
5163 continue;
5164 prev_il_offset = il_offset;
5165 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
5166 if (!(loc && loc->source_file))
5167 continue;
5168 if (loc->row == prev_line) {
5169 mono_debug_symfile_free_location (loc);
5170 continue;
5172 prev_line = loc->row;
5173 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5174 if (first)
5175 /* This will cover the prolog too */
5176 res [0] = loc;
5177 else
5178 res [i] = loc;
5179 first = FALSE;
5181 return res;
5184 static int
5185 get_file_index (MonoAotCompile *acfg, const char *source_file)
5187 int findex;
5189 // FIXME: Free these
5190 if (!acfg->dwarf_ln_filenames)
5191 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5192 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5193 if (!findex) {
5194 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5195 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5196 emit_unset_mode (acfg);
5197 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5199 return findex;
5202 #ifdef TARGET_ARM64
5203 #define INST_LEN 4
5204 #else
5205 #define INST_LEN 1
5206 #endif
5209 * emit_and_reloc_code:
5211 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5212 * is true, calls are made through the GOT too. This is used for emitting trampolines
5213 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5214 * since trampolines are needed to make PTL work.
5216 static void
5217 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5219 int i, pindex, start_index;
5220 GPtrArray *patches;
5221 MonoJumpInfo *patch_info;
5222 MonoDebugSourceLocation **locs = NULL;
5223 gboolean skip, prologue_end = FALSE;
5224 #ifdef MONO_ARCH_AOT_SUPPORTED
5225 gboolean direct_call, external_call;
5226 guint32 got_slot;
5227 const char *direct_call_target = 0;
5228 const char *direct_pinvoke;
5229 #endif
5231 if (acfg->gas_line_numbers && method && debug_info) {
5232 locs = compute_line_numbers (method, code_len, debug_info);
5233 if (!locs) {
5234 int findex = get_file_index (acfg, "<unknown>");
5235 emit_unset_mode (acfg);
5236 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5240 /* Collect and sort relocations */
5241 patches = g_ptr_array_new ();
5242 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5243 g_ptr_array_add (patches, patch_info);
5244 g_ptr_array_sort (patches, compare_patches);
5246 start_index = 0;
5247 for (i = 0; i < code_len; i += INST_LEN) {
5248 patch_info = NULL;
5249 for (pindex = start_index; pindex < patches->len; ++pindex) {
5250 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5251 if (patch_info->ip.i >= i)
5252 break;
5255 if (locs && locs [i]) {
5256 MonoDebugSourceLocation *loc = locs [i];
5257 int findex;
5258 const char *options;
5260 findex = get_file_index (acfg, loc->source_file);
5261 emit_unset_mode (acfg);
5262 if (!prologue_end)
5263 options = " prologue_end";
5264 else
5265 options = "";
5266 prologue_end = TRUE;
5267 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5268 mono_debug_symfile_free_location (loc);
5271 skip = FALSE;
5272 #ifdef MONO_ARCH_AOT_SUPPORTED
5273 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5274 start_index = pindex;
5276 switch (patch_info->type) {
5277 case MONO_PATCH_INFO_NONE:
5278 break;
5279 case MONO_PATCH_INFO_GOT_OFFSET: {
5280 int code_size;
5282 arch_emit_got_offset (acfg, code + i, &code_size);
5283 i += code_size - INST_LEN;
5284 skip = TRUE;
5285 patch_info->type = MONO_PATCH_INFO_NONE;
5286 break;
5288 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5289 int code_size, index;
5290 char *selector = (char *)patch_info->data.target;
5292 if (!acfg->objc_selector_to_index)
5293 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5294 if (!acfg->objc_selectors)
5295 acfg->objc_selectors = g_ptr_array_new ();
5296 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5297 if (index)
5298 index --;
5299 else {
5300 index = acfg->objc_selector_index;
5301 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5302 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5303 acfg->objc_selector_index ++;
5306 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5307 i += code_size - INST_LEN;
5308 skip = TRUE;
5309 patch_info->type = MONO_PATCH_INFO_NONE;
5310 break;
5312 default: {
5314 * If this patch is a call, try emitting a direct call instead of
5315 * through a PLT entry. This is possible if the called method is in
5316 * the same assembly and requires no initialization.
5318 direct_call = FALSE;
5319 external_call = FALSE;
5320 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5321 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5322 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5323 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5324 direct_call = TRUE;
5325 direct_call_target = callee_cfg->asm_symbol;
5326 patch_info->type = MONO_PATCH_INFO_NONE;
5327 acfg->stats.direct_calls ++;
5330 acfg->stats.all_calls ++;
5331 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5332 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5333 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5334 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5335 else
5336 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5337 if (direct_pinvoke) {
5338 direct_call = TRUE;
5339 g_assert (strlen (direct_pinvoke) < 1000);
5340 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5343 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5344 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5345 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5346 /* Call to a C function implementing a jit icall */
5347 direct_call = TRUE;
5348 external_call = TRUE;
5349 g_assert (strlen (sym) < 1000);
5350 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5352 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5353 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5354 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5355 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5356 /* Call to a jit icall without a wrapper */
5357 direct_call = TRUE;
5358 external_call = TRUE;
5359 g_assert (strlen (sym) < 1000);
5360 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5364 if (direct_call) {
5365 patch_info->type = MONO_PATCH_INFO_NONE;
5366 acfg->stats.direct_calls ++;
5369 if (!got_only && !direct_call) {
5370 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5371 if (plt_entry) {
5372 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5373 direct_call = TRUE;
5374 direct_call_target = plt_entry->symbol;
5376 /* Nullify the patch */
5377 patch_info->type = MONO_PATCH_INFO_NONE;
5378 plt_entry->jit_used = TRUE;
5382 if (direct_call) {
5383 int call_size;
5385 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5386 i += call_size - INST_LEN;
5387 } else {
5388 int code_size;
5390 got_slot = get_got_offset (acfg, FALSE, patch_info);
5392 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5393 i += code_size - INST_LEN;
5395 skip = TRUE;
5399 #endif /* MONO_ARCH_AOT_SUPPORTED */
5401 if (!skip) {
5402 /* Find next patch */
5403 patch_info = NULL;
5404 for (pindex = start_index; pindex < patches->len; ++pindex) {
5405 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5406 if (patch_info->ip.i >= i)
5407 break;
5410 /* Try to emit multiple bytes at once */
5411 if (pindex < patches->len && patch_info->ip.i > i) {
5412 int limit;
5414 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5415 if (locs && locs [limit])
5416 break;
5419 emit_code_bytes (acfg, code + i, limit - i);
5420 i = limit - INST_LEN;
5421 } else {
5422 emit_code_bytes (acfg, code + i, INST_LEN);
5427 g_ptr_array_free (patches, TRUE);
5428 g_free (locs);
5432 * sanitize_symbol:
5434 * Return a modified version of S which only includes characters permissible in symbols.
5436 static char*
5437 sanitize_symbol (MonoAotCompile *acfg, char *s)
5439 gboolean process = FALSE;
5440 int i, len;
5441 GString *gs;
5442 char *res;
5444 if (!s)
5445 return s;
5447 len = strlen (s);
5448 for (i = 0; i < len; ++i)
5449 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5450 process = TRUE;
5451 if (!process)
5452 return s;
5454 gs = g_string_sized_new (len);
5455 for (i = 0; i < len; ++i) {
5456 guint8 c = s [i];
5457 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5458 g_string_append_c (gs, c);
5459 } else if (c > 0x7f) {
5460 /* multi-byte utf8 */
5461 g_string_append_printf (gs, "_0x%x", c);
5462 i ++;
5463 c = s [i];
5464 while (c >> 6 == 0x2) {
5465 g_string_append_printf (gs, "%x", c);
5466 i ++;
5467 c = s [i];
5469 g_string_append_printf (gs, "_");
5470 i --;
5471 } else {
5472 g_string_append_c (gs, '_');
5476 res = mono_mempool_strdup (acfg->mempool, gs->str);
5477 g_string_free (gs, TRUE);
5478 return res;
5481 static char*
5482 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5484 char *name1, *name2, *cached;
5485 int i, j, len, count;
5486 MonoMethod *cached_method;
5488 name1 = mono_method_full_name (method, TRUE);
5490 #ifdef TARGET_MACH
5491 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5492 if ((!prefix || !*prefix) && name1 [0] == 'L')
5493 prefix = "_";
5494 #endif
5496 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5497 char adjustedPrefix [MAX_SYMBOL_SIZE];
5498 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5499 #endif
5501 len = strlen (name1);
5502 name2 = (char *)malloc (strlen (prefix) + len + 16);
5503 memcpy (name2, prefix, strlen (prefix));
5504 j = strlen (prefix);
5505 for (i = 0; i < len; ++i) {
5506 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5507 name2 [j ++] = '_';
5508 } else if (isalnum (name1 [i])) {
5509 name2 [j ++] = name1 [i];
5510 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5511 i += 2;
5512 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5513 name2 [j ++] = '_';
5514 i++;
5515 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5516 } else
5517 name2 [j ++] = '_';
5519 name2 [j] = '\0';
5521 g_free (name1);
5523 count = 0;
5524 while (TRUE) {
5525 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5526 if (!(cached_method && cached_method != method))
5527 break;
5528 sprintf (name2 + j, "_%d", count);
5529 count ++;
5532 cached = g_strdup (name2);
5533 g_hash_table_insert (cache, cached, method);
5535 return name2;
5538 static void
5539 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5541 MonoMethod *method;
5542 int method_index;
5543 guint8 *code;
5544 char *debug_sym = NULL;
5545 char *symbol = NULL;
5546 int func_alignment = AOT_FUNC_ALIGNMENT;
5547 char *export_name;
5549 method = cfg->orig_method;
5550 code = cfg->native_code;
5552 method_index = get_method_index (acfg, method);
5553 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5555 /* Make the labels local */
5556 emit_section_change (acfg, ".text", 0);
5557 emit_alignment_code (acfg, func_alignment);
5559 if (acfg->global_symbols && acfg->need_no_dead_strip)
5560 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5562 emit_label (acfg, cfg->asm_symbol);
5564 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5566 * Write a C style symbol for every method, this has two uses:
5567 * - it works on platforms where the dwarf debugging info is not
5568 * yet supported.
5569 * - it allows the setting of breakpoints of aot-ed methods.
5571 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5572 cfg->asm_debug_symbol = g_strdup (debug_sym);
5574 if (acfg->need_no_dead_strip)
5575 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5576 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5577 emit_label (acfg, debug_sym);
5580 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5581 if (export_name) {
5582 /* Emit a global symbol for the method */
5583 emit_global_inner (acfg, export_name, TRUE);
5584 emit_label (acfg, export_name);
5587 if (cfg->verbose_level > 0)
5588 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5590 acfg->stats.code_size += cfg->code_len;
5592 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5594 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 ()));
5596 emit_line (acfg);
5598 if (acfg->aot_opts.write_symbols) {
5599 if (debug_sym)
5600 emit_symbol_size (acfg, debug_sym, ".");
5601 else
5602 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5603 g_free (debug_sym);
5606 emit_label (acfg, symbol);
5607 g_free (symbol);
5611 * encode_patch:
5613 * Encode PATCH_INFO into its disk representation.
5615 static void
5616 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5618 guint8 *p = buf;
5620 switch (patch_info->type) {
5621 case MONO_PATCH_INFO_NONE:
5622 break;
5623 case MONO_PATCH_INFO_IMAGE:
5624 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5625 break;
5626 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5627 case MONO_PATCH_INFO_JIT_TLS_ID:
5628 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5629 case MONO_PATCH_INFO_GC_NURSERY_START:
5630 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5631 break;
5632 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5633 encode_value (patch_info->data.index, p, &p);
5634 break;
5635 case MONO_PATCH_INFO_METHOD_REL:
5636 encode_value ((gint)patch_info->data.offset, p, &p);
5637 break;
5638 case MONO_PATCH_INFO_SWITCH: {
5639 gpointer *table = (gpointer *)patch_info->data.table->table;
5640 int k;
5642 encode_value (patch_info->data.table->table_size, p, &p);
5643 for (k = 0; k < patch_info->data.table->table_size; k++)
5644 encode_value ((int)(gssize)table [k], p, &p);
5645 break;
5647 case MONO_PATCH_INFO_METHODCONST:
5648 case MONO_PATCH_INFO_METHOD:
5649 case MONO_PATCH_INFO_METHOD_JUMP:
5650 case MONO_PATCH_INFO_ICALL_ADDR:
5651 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5652 case MONO_PATCH_INFO_METHOD_RGCTX:
5653 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5654 encode_method_ref (acfg, patch_info->data.method, p, &p);
5655 break;
5656 case MONO_PATCH_INFO_AOT_JIT_INFO:
5657 encode_value (patch_info->data.index, p, &p);
5658 break;
5659 case MONO_PATCH_INFO_INTERNAL_METHOD:
5660 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5661 guint32 len = strlen (patch_info->data.name);
5663 encode_value (len, p, &p);
5665 memcpy (p, patch_info->data.name, len);
5666 p += len;
5667 *p++ = '\0';
5668 break;
5670 case MONO_PATCH_INFO_LDSTR: {
5671 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5672 guint32 token = patch_info->data.token->token;
5673 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5674 encode_value (image_index, p, &p);
5675 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5676 break;
5678 case MONO_PATCH_INFO_RVA:
5679 case MONO_PATCH_INFO_DECLSEC:
5680 case MONO_PATCH_INFO_LDTOKEN:
5681 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5682 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5683 encode_value (patch_info->data.token->token, p, &p);
5684 encode_value (patch_info->data.token->has_context, p, &p);
5685 if (patch_info->data.token->has_context)
5686 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5687 break;
5688 case MONO_PATCH_INFO_EXC_NAME: {
5689 MonoClass *ex_class;
5691 ex_class =
5692 mono_class_load_from_name (mono_defaults.exception_class->image,
5693 "System", (const char *)patch_info->data.target);
5694 encode_klass_ref (acfg, ex_class, p, &p);
5695 break;
5697 case MONO_PATCH_INFO_R4:
5698 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5699 break;
5700 case MONO_PATCH_INFO_R8:
5701 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5702 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5703 break;
5704 case MONO_PATCH_INFO_VTABLE:
5705 case MONO_PATCH_INFO_CLASS:
5706 case MONO_PATCH_INFO_IID:
5707 case MONO_PATCH_INFO_ADJUSTED_IID:
5708 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5709 break;
5710 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5711 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5712 if (patch_info->data.del_tramp->method) {
5713 encode_value (1, p, &p);
5714 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5715 } else {
5716 encode_value (0, p, &p);
5718 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5719 break;
5720 case MONO_PATCH_INFO_FIELD:
5721 case MONO_PATCH_INFO_SFLDA:
5722 encode_field_info (acfg, patch_info->data.field, p, &p);
5723 break;
5724 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5725 break;
5726 case MONO_PATCH_INFO_RGCTX_FETCH:
5727 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5728 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5729 guint32 offset;
5730 guint8 *buf2, *p2;
5733 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5734 * reference the same method, so encode the method only once.
5736 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5737 if (!offset) {
5738 buf2 = (guint8 *)g_malloc (1024);
5739 p2 = buf2;
5741 encode_method_ref (acfg, entry->method, p2, &p2);
5742 g_assert (p2 - buf2 < 1024);
5744 offset = add_to_blob (acfg, buf2, p2 - buf2);
5745 g_free (buf2);
5747 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5748 } else {
5749 offset --;
5752 encode_value (offset, p, &p);
5753 g_assert ((int)entry->info_type < 256);
5754 g_assert (entry->data->type < 256);
5755 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5756 encode_patch (acfg, entry->data, p, &p);
5757 break;
5759 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5760 case MONO_PATCH_INFO_AOT_MODULE:
5761 break;
5762 case MONO_PATCH_INFO_SIGNATURE:
5763 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5764 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5765 break;
5766 case MONO_PATCH_INFO_TLS_OFFSET:
5767 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5768 break;
5769 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5770 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5771 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5772 break;
5773 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5774 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5775 int i;
5777 encode_method_ref (acfg, info->method, p, &p);
5778 encode_value (info->num_entries, p, &p);
5779 for (i = 0; i < info->num_entries; ++i) {
5780 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5782 encode_value (template_->info_type, p, &p);
5783 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5784 case MONO_PATCH_INFO_CLASS:
5785 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5786 break;
5787 case MONO_PATCH_INFO_FIELD:
5788 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5789 break;
5790 default:
5791 g_assert_not_reached ();
5792 break;
5795 break;
5797 case MONO_PATCH_INFO_LDSTR_LIT: {
5798 const char *s = (const char *)patch_info->data.target;
5799 int len = strlen (s);
5801 encode_value (len, p, &p);
5802 memcpy (p, s, len + 1);
5803 p += len + 1;
5804 break;
5806 case MONO_PATCH_INFO_VIRT_METHOD:
5807 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5808 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5809 break;
5810 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5811 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5812 break;
5813 default:
5814 g_warning ("unable to handle jump info %d", patch_info->type);
5815 g_assert_not_reached ();
5818 *endbuf = p;
5821 static void
5822 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5824 guint8 *p = buf;
5825 guint32 pindex, offset;
5826 MonoJumpInfo *patch_info;
5828 encode_value (n_patches, p, &p);
5830 for (pindex = 0; pindex < patches->len; ++pindex) {
5831 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5833 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5834 /* Nothing to do */
5835 continue;
5837 offset = get_got_offset (acfg, llvm, patch_info);
5838 encode_value (offset, p, &p);
5841 *endbuf = p;
5844 static void
5845 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5847 MonoMethod *method;
5848 int pindex, buf_size, n_patches;
5849 GPtrArray *patches;
5850 MonoJumpInfo *patch_info;
5851 guint32 method_index;
5852 guint8 *p, *buf;
5853 guint32 first_got_offset;
5855 method = cfg->orig_method;
5857 method_index = get_method_index (acfg, method);
5859 /* Sort relocations */
5860 patches = g_ptr_array_new ();
5861 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5862 g_ptr_array_add (patches, patch_info);
5863 g_ptr_array_sort (patches, compare_patches);
5865 first_got_offset = acfg->cfgs [method_index]->got_offset;
5867 /**********************/
5868 /* Encode method info */
5869 /**********************/
5871 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5872 p = buf = (guint8 *)g_malloc (buf_size);
5874 if (mono_class_get_cctor (method->klass)) {
5875 encode_value (1, p, &p);
5876 encode_klass_ref (acfg, method->klass, p, &p);
5877 } else {
5878 /* Not needed when loading the method */
5879 encode_value (0, p, &p);
5882 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5884 n_patches = 0;
5885 for (pindex = 0; pindex < patches->len; ++pindex) {
5886 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5888 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5889 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5890 patch_info->type = MONO_PATCH_INFO_NONE;
5891 /* Nothing to do */
5892 continue;
5895 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5896 /* Stored in a GOT slot initialized at module load time */
5897 patch_info->type = MONO_PATCH_INFO_NONE;
5898 continue;
5901 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5902 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5903 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5904 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5905 /* Stored in a GOT slot initialized at module load time */
5906 patch_info->type = MONO_PATCH_INFO_NONE;
5907 continue;
5910 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5911 /* Calls are made through the PLT */
5912 patch_info->type = MONO_PATCH_INFO_NONE;
5913 continue;
5916 n_patches ++;
5919 if (n_patches)
5920 g_assert (cfg->has_got_slots);
5922 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5924 g_ptr_array_free (patches, TRUE);
5926 acfg->stats.info_size += p - buf;
5928 g_assert (p - buf < buf_size);
5930 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5931 g_free (buf);
5934 static guint32
5935 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5937 guint32 cache_index;
5938 guint32 offset;
5940 /* Reuse the unwind module to canonize and store unwind info entries */
5941 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5943 /* Use +/- 1 to distinguish 0s from missing entries */
5944 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5945 if (offset)
5946 return offset - 1;
5947 else {
5948 guint8 buf [16];
5949 guint8 *p;
5952 * It would be easier to use assembler symbols, but the caller needs an
5953 * offset now.
5955 offset = acfg->unwind_info_offset;
5956 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5957 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5959 p = buf;
5960 encode_value (encoded_len, p, &p);
5962 acfg->unwind_info_offset += encoded_len + (p - buf);
5963 return offset;
5967 static void
5968 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5970 int i, k, buf_size;
5971 guint32 debug_info_size, seq_points_size;
5972 guint8 *code;
5973 MonoMethodHeader *header;
5974 guint8 *p, *buf, *debug_info;
5975 MonoJitInfo *jinfo = cfg->jit_info;
5976 guint32 flags;
5977 gboolean use_unwind_ops = FALSE;
5978 MonoSeqPointInfo *seq_points;
5980 code = cfg->native_code;
5981 header = cfg->header;
5983 if (!acfg->aot_opts.nodebug) {
5984 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5985 } else {
5986 debug_info = NULL;
5987 debug_info_size = 0;
5990 seq_points = cfg->seq_point_info;
5991 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5993 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5995 p = buf = (guint8 *)g_malloc (buf_size);
5997 use_unwind_ops = cfg->unwind_ops != NULL;
5999 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);
6001 encode_value (flags, p, &p);
6003 if (use_unwind_ops) {
6004 guint32 encoded_len;
6005 guint8 *encoded;
6006 guint32 unwind_desc;
6008 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6010 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6011 encode_value (unwind_desc, p, &p);
6013 g_free (encoded);
6014 } else {
6015 encode_value (jinfo->unwind_info, p, &p);
6018 /*Encode the number of holes before the number of clauses to make decoding easier*/
6019 if (jinfo->has_try_block_holes) {
6020 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6021 encode_value (table->num_holes, p, &p);
6024 if (jinfo->has_arch_eh_info) {
6026 * In AOT mode, the code length is calculated from the address of the previous method,
6027 * which could include alignment padding, so calculating the start of the epilog as
6028 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6030 encode_value (jinfo->code_size, p, &p);
6033 /* Exception table */
6034 if (cfg->compile_llvm) {
6036 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6037 * since the information is only available to llc. Instead, we let llc save the data
6038 * into the LSDA, and read it from there at runtime.
6040 /* The assembly might be CIL stripped so emit the data ourselves */
6041 if (header->num_clauses)
6042 encode_value (header->num_clauses, p, &p);
6044 for (k = 0; k < header->num_clauses; ++k) {
6045 MonoExceptionClause *clause;
6047 clause = &header->clauses [k];
6049 encode_value (clause->flags, p, &p);
6050 if (clause->data.catch_class) {
6051 encode_value (1, p, &p);
6052 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6053 } else {
6054 encode_value (0, p, &p);
6057 /* Emit the IL ranges too, since they might not be available at runtime */
6058 encode_value (clause->try_offset, p, &p);
6059 encode_value (clause->try_len, p, &p);
6060 encode_value (clause->handler_offset, p, &p);
6061 encode_value (clause->handler_len, p, &p);
6063 /* Emit a list of nesting clauses */
6064 for (i = 0; i < header->num_clauses; ++i) {
6065 gint32 cindex1 = k;
6066 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6067 gint32 cindex2 = i;
6068 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6070 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6071 encode_value (i, p, &p);
6073 encode_value (-1, p, &p);
6075 } else {
6076 if (jinfo->num_clauses)
6077 encode_value (jinfo->num_clauses, p, &p);
6079 for (k = 0; k < jinfo->num_clauses; ++k) {
6080 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6082 encode_value (ei->flags, p, &p);
6083 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6084 /* Not used for catch clauses */
6085 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6086 encode_value (ei->exvar_offset, p, &p);
6087 #else
6088 encode_value (ei->exvar_offset, p, &p);
6089 #endif
6091 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6092 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6093 else {
6094 if (ei->data.catch_class) {
6095 guint8 *buf2, *p2;
6096 int len;
6098 buf2 = (guint8 *)g_malloc (4096);
6099 p2 = buf2;
6100 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6101 len = p2 - buf2;
6102 g_assert (len < 4096);
6103 encode_value (len, p, &p);
6104 memcpy (p, buf2, len);
6105 p += p2 - buf2;
6106 g_free (buf2);
6107 } else {
6108 encode_value (0, p, &p);
6112 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6113 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6114 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6118 if (jinfo->has_try_block_holes) {
6119 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6120 for (i = 0; i < table->num_holes; ++i) {
6121 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6122 encode_value (hole->clause, p, &p);
6123 encode_value (hole->length, p, &p);
6124 encode_value (hole->offset, p, &p);
6128 if (jinfo->has_arch_eh_info) {
6129 MonoArchEHJitInfo *eh_info;
6131 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6132 encode_value (eh_info->stack_size, p, &p);
6133 encode_value (eh_info->epilog_size, p, &p);
6136 if (jinfo->has_generic_jit_info) {
6137 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6138 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6139 guint8 *buf2, *p2;
6140 int len;
6142 encode_value (gi->nlocs, p, &p);
6143 if (gi->nlocs) {
6144 for (i = 0; i < gi->nlocs; ++i) {
6145 MonoDwarfLocListEntry *entry = &gi->locations [i];
6147 encode_value (entry->is_reg ? 1 : 0, p, &p);
6148 encode_value (entry->reg, p, &p);
6149 if (!entry->is_reg)
6150 encode_value (entry->offset, p, &p);
6151 if (i == 0)
6152 g_assert (entry->from == 0);
6153 else
6154 encode_value (entry->from, p, &p);
6155 encode_value (entry->to, p, &p);
6157 } else {
6158 if (!cfg->compile_llvm) {
6159 encode_value (gi->has_this ? 1 : 0, p, &p);
6160 encode_value (gi->this_reg, p, &p);
6161 encode_value (gi->this_offset, p, &p);
6166 * Need to encode jinfo->method too, since it is not equal to 'method'
6167 * when using generic sharing.
6169 buf2 = (guint8 *)g_malloc (4096);
6170 p2 = buf2;
6171 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6172 len = p2 - buf2;
6173 g_assert (len < 4096);
6174 encode_value (len, p, &p);
6175 memcpy (p, buf2, len);
6176 p += p2 - buf2;
6177 g_free (buf2);
6179 if (gsctx && gsctx->is_gsharedvt) {
6180 encode_value (1, p, &p);
6181 } else {
6182 encode_value (0, p, &p);
6186 if (seq_points_size)
6187 p += mono_seq_point_info_write (seq_points, p);
6189 g_assert (debug_info_size < buf_size);
6191 encode_value (debug_info_size, p, &p);
6192 if (debug_info_size) {
6193 memcpy (p, debug_info, debug_info_size);
6194 p += debug_info_size;
6195 g_free (debug_info);
6198 /* GC Map */
6199 if (cfg->gc_map) {
6200 encode_value (cfg->gc_map_size, p, &p);
6201 /* The GC map requires 4 bytes of alignment */
6202 while ((gsize)p % 4)
6203 p ++;
6204 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6205 p += cfg->gc_map_size;
6208 acfg->stats.ex_info_size += p - buf;
6210 g_assert (p - buf < buf_size);
6212 /* Emit info */
6213 /* The GC Map requires 4 byte alignment */
6214 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6215 g_free (buf);
6218 static guint32
6219 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6221 MonoError error;
6222 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6223 guint8 *p, *buf;
6224 int i, buf_size, res;
6225 gboolean no_special_static, cant_encode;
6226 gpointer iter = NULL;
6228 if (!klass) {
6229 mono_error_cleanup (&error);
6231 buf_size = 16;
6233 p = buf = (guint8 *)g_malloc (buf_size);
6235 /* Mark as unusable */
6236 encode_value (-1, p, &p);
6238 res = add_to_blob (acfg, buf, p - buf);
6239 g_free (buf);
6241 return res;
6244 buf_size = 10240 + (klass->vtable_size * 16);
6245 p = buf = (guint8 *)g_malloc (buf_size);
6247 g_assert (klass);
6249 mono_class_init (klass);
6251 mono_class_get_nested_types (klass, &iter);
6252 g_assert (klass->nested_classes_inited);
6254 mono_class_setup_vtable (klass);
6257 * Emit all the information which is required for creating vtables so
6258 * the runtime does not need to create the MonoMethod structures which
6259 * take up a lot of space.
6262 no_special_static = !mono_class_has_special_static_fields (klass);
6264 /* Check whenever we have enough info to encode the vtable */
6265 cant_encode = FALSE;
6266 for (i = 0; i < klass->vtable_size; ++i) {
6267 MonoMethod *cm = klass->vtable [i];
6269 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6270 cant_encode = TRUE;
6273 mono_class_has_finalizer (klass);
6275 if (mono_class_is_gtd (klass) || cant_encode) {
6276 encode_value (-1, p, &p);
6277 } else {
6278 encode_value (klass->vtable_size, p, &p);
6279 encode_value ((mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | ((klass->ext && klass->ext->nested_classes) ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
6280 if (klass->has_cctor)
6281 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6282 if (klass->has_finalize)
6283 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6285 encode_value (klass->instance_size, p, &p);
6286 encode_value (mono_class_data_size (klass), p, &p);
6287 encode_value (klass->packing_size, p, &p);
6288 encode_value (klass->min_align, p, &p);
6290 for (i = 0; i < klass->vtable_size; ++i) {
6291 MonoMethod *cm = klass->vtable [i];
6293 if (cm)
6294 encode_method_ref (acfg, cm, p, &p);
6295 else
6296 encode_value (0, p, &p);
6300 acfg->stats.class_info_size += p - buf;
6302 g_assert (p - buf < buf_size);
6303 res = add_to_blob (acfg, buf, p - buf);
6304 g_free (buf);
6306 return res;
6309 static char*
6310 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6312 char *debug_sym = NULL;
6313 char *prefix;
6315 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6316 /* Need to add a prefix to create unique symbols */
6317 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6318 } else {
6319 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6320 prefix = mangle_symbol_alloc ("plt_");
6321 #else
6322 prefix = g_strdup ("plt_");
6323 #endif
6326 switch (ji->type) {
6327 case MONO_PATCH_INFO_METHOD:
6328 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6329 break;
6330 case MONO_PATCH_INFO_INTERNAL_METHOD:
6331 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6332 break;
6333 case MONO_PATCH_INFO_RGCTX_FETCH:
6334 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6335 break;
6336 case MONO_PATCH_INFO_ICALL_ADDR:
6337 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6338 char *s = get_debug_sym (ji->data.method, "", cache);
6340 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6341 g_free (s);
6342 break;
6344 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6345 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6346 break;
6347 default:
6348 break;
6351 g_free (prefix);
6353 return sanitize_symbol (acfg, debug_sym);
6357 * Calls made from AOTed code are routed through a table of jumps similar to the
6358 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6359 * control to the AOT runtime through a trampoline.
6361 static void
6362 emit_plt (MonoAotCompile *acfg)
6364 int i;
6366 if (acfg->aot_opts.llvm_only) {
6367 g_assert (acfg->plt_offset == 1);
6368 return;
6371 emit_line (acfg);
6373 emit_section_change (acfg, ".text", 0);
6374 emit_alignment_code (acfg, 16);
6375 emit_info_symbol (acfg, "plt");
6376 emit_label (acfg, acfg->plt_symbol);
6378 for (i = 0; i < acfg->plt_offset; ++i) {
6379 char *debug_sym = NULL;
6380 MonoPltEntry *plt_entry = NULL;
6382 if (i == 0)
6384 * The first plt entry is unused.
6386 continue;
6388 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6390 debug_sym = plt_entry->debug_sym;
6392 if (acfg->thumb_mixed && !plt_entry->jit_used)
6393 /* Emit only a thumb version */
6394 continue;
6396 /* Skip plt entries not actually called */
6397 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6398 continue;
6400 if (acfg->llvm && !acfg->thumb_mixed) {
6401 emit_label (acfg, plt_entry->llvm_symbol);
6402 if (acfg->llvm) {
6403 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6404 #if defined(TARGET_MACH)
6405 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6406 #endif
6410 if (debug_sym) {
6411 if (acfg->need_no_dead_strip) {
6412 emit_unset_mode (acfg);
6413 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6415 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6416 emit_label (acfg, debug_sym);
6419 emit_label (acfg, plt_entry->symbol);
6421 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6423 if (debug_sym)
6424 emit_symbol_size (acfg, debug_sym, ".");
6427 if (acfg->thumb_mixed) {
6428 /* Make sure the ARM symbols don't alias the thumb ones */
6429 emit_zero_bytes (acfg, 16);
6432 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6433 * code.
6435 for (i = 0; i < acfg->plt_offset; ++i) {
6436 char *debug_sym = NULL;
6437 MonoPltEntry *plt_entry = NULL;
6439 if (i == 0)
6440 continue;
6442 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6444 /* Skip plt entries not actually called by LLVM code */
6445 if (!plt_entry->llvm_used)
6446 continue;
6448 if (acfg->aot_opts.write_symbols) {
6449 if (plt_entry->debug_sym)
6450 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6453 if (debug_sym) {
6454 #if defined(TARGET_MACH)
6455 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6456 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6457 #endif
6458 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6459 emit_label (acfg, debug_sym);
6461 fprintf (acfg->fp, "\n.thumb_func\n");
6463 emit_label (acfg, plt_entry->llvm_symbol);
6465 if (acfg->llvm)
6466 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6468 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6470 if (debug_sym) {
6471 emit_symbol_size (acfg, debug_sym, ".");
6472 g_free (debug_sym);
6477 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6479 emit_info_symbol (acfg, "plt_end");
6483 * emit_trampoline_full:
6485 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6486 * create_jit_info_for_trampoline ().
6488 static G_GNUC_UNUSED void
6489 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6491 char start_symbol [MAX_SYMBOL_SIZE];
6492 char end_symbol [MAX_SYMBOL_SIZE];
6493 char symbol [MAX_SYMBOL_SIZE];
6494 guint32 buf_size, info_offset;
6495 MonoJumpInfo *patch_info;
6496 guint8 *buf, *p;
6497 GPtrArray *patches;
6498 char *name;
6499 guint8 *code;
6500 guint32 code_size;
6501 MonoJumpInfo *ji;
6502 GSList *unwind_ops;
6504 g_assert (info);
6506 name = info->name;
6507 code = info->code;
6508 code_size = info->code_size;
6509 ji = info->ji;
6510 unwind_ops = info->unwind_ops;
6512 /* Emit code */
6514 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6516 emit_section_change (acfg, ".text", 0);
6517 emit_global (acfg, start_symbol, TRUE);
6518 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6519 emit_label (acfg, start_symbol);
6521 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6522 emit_label (acfg, symbol);
6525 * The code should access everything through the GOT, so we pass
6526 * TRUE here.
6528 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6530 emit_symbol_size (acfg, start_symbol, ".");
6532 if (emit_tinfo) {
6533 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6534 emit_label (acfg, end_symbol);
6537 /* Emit info */
6539 /* Sort relocations */
6540 patches = g_ptr_array_new ();
6541 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6542 if (patch_info->type != MONO_PATCH_INFO_NONE)
6543 g_ptr_array_add (patches, patch_info);
6544 g_ptr_array_sort (patches, compare_patches);
6546 buf_size = patches->len * 128 + 128;
6547 buf = (guint8 *)g_malloc (buf_size);
6548 p = buf;
6550 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6551 g_assert (p - buf < buf_size);
6552 g_ptr_array_free (patches, TRUE);
6554 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6556 info_offset = add_to_blob (acfg, buf, p - buf);
6558 emit_section_change (acfg, RODATA_SECT, 0);
6559 emit_global (acfg, symbol, FALSE);
6560 emit_label (acfg, symbol);
6562 emit_int32 (acfg, info_offset);
6564 if (emit_tinfo) {
6565 guint8 *encoded;
6566 guint32 encoded_len;
6567 guint32 uw_offset;
6570 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6572 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6573 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6574 g_free (encoded);
6576 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6577 emit_int32 (acfg, uw_offset);
6580 /* Emit debug info */
6581 if (unwind_ops) {
6582 char symbol2 [MAX_SYMBOL_SIZE];
6584 sprintf (symbol, "%s", name);
6585 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6587 if (acfg->dwarf)
6588 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6591 g_free (buf);
6594 static G_GNUC_UNUSED void
6595 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6597 emit_trampoline_full (acfg, got_offset, info, TRUE);
6600 static void
6601 emit_trampolines (MonoAotCompile *acfg)
6603 char symbol [MAX_SYMBOL_SIZE];
6604 char end_symbol [MAX_SYMBOL_SIZE];
6605 int i, tramp_got_offset;
6606 int ntype;
6607 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6608 int tramp_type;
6609 #endif
6611 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6612 return;
6614 g_assert (acfg->image->assembly);
6616 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6617 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6618 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6619 MonoTrampInfo *info;
6622 * Emit the generic trampolines.
6624 * We could save some code by treating the generic trampolines as a wrapper
6625 * method, but that approach has its own complexities, so we choose the simpler
6626 * method.
6628 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6629 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6630 #ifdef DISABLE_REMOTING
6631 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6632 continue;
6633 #endif
6634 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6635 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6636 continue;
6637 #endif
6638 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6639 emit_trampoline (acfg, acfg->got_offset, info);
6642 /* Emit the exception related code pieces */
6643 mono_arch_get_restore_context (&info, TRUE);
6644 emit_trampoline (acfg, acfg->got_offset, info);
6645 mono_arch_get_call_filter (&info, TRUE);
6646 emit_trampoline (acfg, acfg->got_offset, info);
6647 mono_arch_get_throw_exception (&info, TRUE);
6648 emit_trampoline (acfg, acfg->got_offset, info);
6649 mono_arch_get_rethrow_exception (&info, TRUE);
6650 emit_trampoline (acfg, acfg->got_offset, info);
6651 mono_arch_get_throw_corlib_exception (&info, TRUE);
6652 emit_trampoline (acfg, acfg->got_offset, info);
6654 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6655 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6656 emit_trampoline (acfg, acfg->got_offset, info);
6657 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6658 emit_trampoline (acfg, acfg->got_offset, info);
6659 #endif
6661 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6662 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6663 if (info) {
6664 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6666 /* Create a separate out trampoline for more information in stack traces */
6667 info->name = g_strdup ("gsharedvt_out_trampoline");
6668 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6670 #endif
6672 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6674 GSList *l = mono_arch_get_trampolines (TRUE);
6676 while (l) {
6677 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6679 emit_trampoline (acfg, acfg->got_offset, info);
6680 l = l->next;
6683 #endif
6685 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6686 int offset;
6688 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6689 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6690 emit_trampoline (acfg, acfg->got_offset, info);
6691 g_free (info);
6693 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6694 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6695 emit_trampoline (acfg, acfg->got_offset, info);
6696 g_free (info);
6699 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6700 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6701 emit_trampoline (acfg, acfg->got_offset, info);
6702 #endif
6705 GSList *l;
6707 /* delegate_invoke_impl trampolines */
6708 l = mono_arch_get_delegate_invoke_impls ();
6709 while (l) {
6710 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6712 emit_trampoline (acfg, acfg->got_offset, info);
6713 l = l->next;
6717 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6718 mono_arch_create_handler_block_trampoline (&info, TRUE);
6719 emit_trampoline (acfg, acfg->got_offset, info);
6720 #endif
6722 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6724 /* Emit trampolines which are numerous */
6727 * These include the following:
6728 * - specific trampolines
6729 * - static rgctx invoke trampolines
6730 * - imt trampolines
6731 * These trampolines have the same code, they are parameterized by GOT
6732 * slots.
6733 * They are defined in this file, in the arch_... routines instead of
6734 * in tramp-<ARCH>.c, since it is easier to do it this way.
6738 * When running in aot-only mode, we can't create specific trampolines at
6739 * runtime, so we create a few, and save them in the AOT file.
6740 * Normal trampolines embed their argument as a literal inside the
6741 * trampoline code, we can't do that here, so instead we embed an offset
6742 * which needs to be added to the trampoline address to get the address of
6743 * the GOT slot which contains the argument value.
6744 * The generated trampolines jump to the generic trampolines using another
6745 * GOT slot, which will be setup by the AOT loader to point to the
6746 * generic trampoline code of the given type.
6750 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6751 * each class).
6754 emit_section_change (acfg, ".text", 0);
6756 tramp_got_offset = acfg->got_offset;
6758 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6759 switch (ntype) {
6760 case MONO_AOT_TRAMP_SPECIFIC:
6761 sprintf (symbol, "specific_trampolines");
6762 break;
6763 case MONO_AOT_TRAMP_STATIC_RGCTX:
6764 sprintf (symbol, "static_rgctx_trampolines");
6765 break;
6766 case MONO_AOT_TRAMP_IMT:
6767 sprintf (symbol, "imt_trampolines");
6768 break;
6769 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6770 sprintf (symbol, "gsharedvt_arg_trampolines");
6771 break;
6772 default:
6773 g_assert_not_reached ();
6776 sprintf (end_symbol, "%s_e", symbol);
6778 if (acfg->aot_opts.write_symbols)
6779 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6781 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6782 emit_info_symbol (acfg, symbol);
6784 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6786 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6787 int tramp_size = 0;
6789 switch (ntype) {
6790 case MONO_AOT_TRAMP_SPECIFIC:
6791 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6792 tramp_got_offset += 2;
6793 break;
6794 case MONO_AOT_TRAMP_STATIC_RGCTX:
6795 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6796 tramp_got_offset += 2;
6797 break;
6798 case MONO_AOT_TRAMP_IMT:
6799 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6800 tramp_got_offset += 1;
6801 break;
6802 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6803 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6804 tramp_got_offset += 2;
6805 break;
6806 default:
6807 g_assert_not_reached ();
6809 if (!acfg->trampoline_size [ntype]) {
6810 g_assert (tramp_size);
6811 acfg->trampoline_size [ntype] = tramp_size;
6815 emit_label (acfg, end_symbol);
6816 emit_int32 (acfg, 0);
6819 arch_emit_specific_trampoline_pages (acfg);
6821 /* Reserve some entries at the end of the GOT for our use */
6822 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6825 acfg->got_offset += acfg->num_trampoline_got_entries;
6828 static gboolean
6829 str_begins_with (const char *str1, const char *str2)
6831 int len = strlen (str2);
6832 return strncmp (str1, str2, len) == 0;
6835 void*
6836 mono_aot_readonly_field_override (MonoClassField *field)
6838 ReadOnlyValue *rdv;
6839 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6840 char *p = rdv->name;
6841 int len;
6842 len = strlen (field->parent->name_space);
6843 if (strncmp (p, field->parent->name_space, len))
6844 continue;
6845 p += len;
6846 if (*p++ != '.')
6847 continue;
6848 len = strlen (field->parent->name);
6849 if (strncmp (p, field->parent->name, len))
6850 continue;
6851 p += len;
6852 if (*p++ != '.')
6853 continue;
6854 if (strcmp (p, field->name))
6855 continue;
6856 switch (rdv->type) {
6857 case MONO_TYPE_I1:
6858 return &rdv->value.i1;
6859 case MONO_TYPE_I2:
6860 return &rdv->value.i2;
6861 case MONO_TYPE_I4:
6862 return &rdv->value.i4;
6863 default:
6864 break;
6867 return NULL;
6870 static void
6871 add_readonly_value (MonoAotOptions *opts, const char *val)
6873 ReadOnlyValue *rdv;
6874 const char *fval;
6875 const char *tval;
6876 /* the format of val is:
6877 * namespace.typename.fieldname=type/value
6878 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6880 fval = strrchr (val, '/');
6881 if (!fval) {
6882 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6883 exit (1);
6885 tval = strrchr (val, '=');
6886 if (!tval) {
6887 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6888 exit (1);
6890 rdv = g_new0 (ReadOnlyValue, 1);
6891 rdv->name = (char *)g_malloc0 (tval - val + 1);
6892 memcpy (rdv->name, val, tval - val);
6893 tval++;
6894 fval++;
6895 if (strncmp (tval, "i1", 2) == 0) {
6896 rdv->value.i1 = atoi (fval);
6897 rdv->type = MONO_TYPE_I1;
6898 } else if (strncmp (tval, "i2", 2) == 0) {
6899 rdv->value.i2 = atoi (fval);
6900 rdv->type = MONO_TYPE_I2;
6901 } else if (strncmp (tval, "i4", 2) == 0) {
6902 rdv->value.i4 = atoi (fval);
6903 rdv->type = MONO_TYPE_I4;
6904 } else {
6905 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6906 exit (1);
6908 rdv->next = readonly_values;
6909 readonly_values = rdv;
6912 static gchar *
6913 clean_path (gchar * path)
6915 if (!path)
6916 return NULL;
6918 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6919 return path;
6921 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6922 g_free (path);
6924 return clean;
6927 static gchar *
6928 wrap_path (gchar * path)
6930 int len;
6931 if (!path)
6932 return NULL;
6934 // If the string contains no spaces, just return the original string.
6935 if (strstr (path, " ") == NULL)
6936 return path;
6938 // If the string is already wrapped in quotes, return it.
6939 len = strlen (path);
6940 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6941 return path;
6943 // If the string contains spaces, then wrap it in quotes.
6944 gchar *clean = g_strdup_printf ("\"%s\"", path);
6946 return clean;
6949 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
6950 static void
6951 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
6953 ptrdiff_t len = end-start;
6954 if (len > 0)
6955 g_ptr_array_add (args, g_strndup (start, len));
6958 static GPtrArray *
6959 mono_aot_split_options (const char *aot_options)
6961 enum MonoAotOptionState {
6962 MONO_AOT_OPTION_STATE_DEFAULT,
6963 MONO_AOT_OPTION_STATE_STRING,
6964 MONO_AOT_OPTION_STATE_ESCAPE,
6967 GPtrArray *args = g_ptr_array_new ();
6968 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6969 gchar const *opt_start = aot_options;
6970 gboolean end_of_string = FALSE;
6971 gchar cur;
6973 g_return_val_if_fail (aot_options != NULL, NULL);
6975 while ((cur = *aot_options) != '\0') {
6976 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6977 goto next;
6979 switch (cur) {
6980 case '"':
6981 // If we find a quote, then if we're in the default case then
6982 // it means we've found the start of a string, if not then it
6983 // means we've found the end of the string and should switch
6984 // back to the default case.
6985 switch (state) {
6986 case MONO_AOT_OPTION_STATE_DEFAULT:
6987 state = MONO_AOT_OPTION_STATE_STRING;
6988 break;
6989 case MONO_AOT_OPTION_STATE_STRING:
6990 state = MONO_AOT_OPTION_STATE_DEFAULT;
6991 break;
6992 case MONO_AOT_OPTION_STATE_ESCAPE:
6993 g_assert_not_reached ();
6994 break;
6996 break;
6997 case '\\':
6998 // If we've found an escaping operator, then this means we
6999 // should not process the next character if inside a string.
7000 if (state == MONO_AOT_OPTION_STATE_STRING)
7001 state = MONO_AOT_OPTION_STATE_ESCAPE;
7002 break;
7003 case ',':
7004 // If we're in the default state then this means we've found
7005 // an option, store it for later processing.
7006 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7007 goto new_opt;
7008 break;
7011 next:
7012 aot_options++;
7013 restart:
7014 // If the next character is end of string, then process the last option.
7015 if (*(aot_options) == '\0') {
7016 end_of_string = TRUE;
7017 goto new_opt;
7019 continue;
7021 new_opt:
7022 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7023 opt_start = ++aot_options;
7024 if (end_of_string)
7025 break;
7026 goto restart; // Check for null and continue loop
7029 return args;
7032 static void
7033 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7035 GPtrArray* args;
7037 args = mono_aot_split_options (aot_options ? aot_options : "");
7038 for (int i = 0; i < args->len; ++i) {
7039 const char *arg = (const char *)g_ptr_array_index (args, i);
7041 if (str_begins_with (arg, "outfile=")) {
7042 opts->outfile = g_strdup (arg + strlen ("outfile="));
7043 } else if (str_begins_with (arg, "llvm-outfile=")) {
7044 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7045 } else if (str_begins_with (arg, "temp-path=")) {
7046 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7047 } else if (str_begins_with (arg, "save-temps")) {
7048 opts->save_temps = TRUE;
7049 } else if (str_begins_with (arg, "keep-temps")) {
7050 opts->save_temps = TRUE;
7051 } else if (str_begins_with (arg, "write-symbols")) {
7052 opts->write_symbols = TRUE;
7053 } else if (str_begins_with (arg, "no-write-symbols")) {
7054 opts->write_symbols = FALSE;
7055 } else if (str_begins_with (arg, "metadata-only")) {
7056 opts->metadata_only = TRUE;
7057 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7058 opts->bind_to_runtime_version = TRUE;
7059 } else if (str_begins_with (arg, "full")) {
7060 opts->mode = MONO_AOT_MODE_FULL;
7061 } else if (str_begins_with (arg, "hybrid")) {
7062 opts->mode = MONO_AOT_MODE_HYBRID;
7063 } else if (str_begins_with (arg, "threads=")) {
7064 opts->nthreads = atoi (arg + strlen ("threads="));
7065 } else if (str_begins_with (arg, "static")) {
7066 opts->static_link = TRUE;
7067 opts->no_dlsym = TRUE;
7068 } else if (str_begins_with (arg, "asmonly")) {
7069 opts->asm_only = TRUE;
7070 } else if (str_begins_with (arg, "asmwriter")) {
7071 opts->asm_writer = TRUE;
7072 } else if (str_begins_with (arg, "nodebug")) {
7073 opts->nodebug = TRUE;
7074 } else if (str_begins_with (arg, "dwarfdebug")) {
7075 opts->dwarf_debug = TRUE;
7076 } else if (str_begins_with (arg, "nopagetrampolines")) {
7077 opts->use_trampolines_page = FALSE;
7078 } else if (str_begins_with (arg, "ntrampolines=")) {
7079 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7080 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7081 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7082 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7083 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7084 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7085 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7086 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7087 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7088 } else if (str_begins_with (arg, "tool-prefix=")) {
7089 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7090 } else if (str_begins_with (arg, "ld-flags=")) {
7091 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7092 } else if (str_begins_with (arg, "soft-debug")) {
7093 opts->soft_debug = TRUE;
7094 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7095 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7096 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7097 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7098 } else if (str_begins_with (arg, "msym-dir=")) {
7099 debug_options.no_seq_points_compact_data = FALSE;
7100 opts->gen_msym_dir = TRUE;
7101 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7102 } else if (str_begins_with (arg, "direct-pinvoke")) {
7103 opts->direct_pinvoke = TRUE;
7104 } else if (str_begins_with (arg, "direct-icalls")) {
7105 opts->direct_icalls = TRUE;
7106 } else if (str_begins_with (arg, "no-direct-calls")) {
7107 opts->no_direct_calls = TRUE;
7108 } else if (str_begins_with (arg, "print-skipped")) {
7109 opts->print_skipped_methods = TRUE;
7110 } else if (str_begins_with (arg, "stats")) {
7111 opts->stats = TRUE;
7112 } else if (str_begins_with (arg, "no-instances")) {
7113 opts->no_instances = TRUE;
7114 } else if (str_begins_with (arg, "log-generics")) {
7115 opts->log_generics = TRUE;
7116 } else if (str_begins_with (arg, "log-instances=")) {
7117 opts->log_instances = TRUE;
7118 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7119 } else if (str_begins_with (arg, "log-instances")) {
7120 opts->log_instances = TRUE;
7121 } else if (str_begins_with (arg, "internal-logfile=")) {
7122 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7123 } else if (str_begins_with (arg, "mtriple=")) {
7124 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7125 } else if (str_begins_with (arg, "llvm-path=")) {
7126 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7127 } else if (!strcmp (arg, "llvm")) {
7128 opts->llvm = TRUE;
7129 } else if (str_begins_with (arg, "readonly-value=")) {
7130 add_readonly_value (opts, arg + strlen ("readonly-value="));
7131 } else if (str_begins_with (arg, "info")) {
7132 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7133 exit (0);
7134 } else if (str_begins_with (arg, "gc-maps")) {
7135 mini_gc_enable_gc_maps_for_aot ();
7136 } else if (str_begins_with (arg, "dump")) {
7137 opts->dump_json = TRUE;
7138 } else if (str_begins_with (arg, "llvmonly")) {
7139 opts->mode = MONO_AOT_MODE_FULL;
7140 opts->llvm = TRUE;
7141 opts->llvm_only = TRUE;
7142 } else if (str_begins_with (arg, "data-outfile=")) {
7143 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7144 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7145 printf ("Supported options for --aot:\n");
7146 printf (" outfile=\n");
7147 printf (" llvm-outfile=\n");
7148 printf (" llvm-path=\n");
7149 printf (" temp-path=\n");
7150 printf (" save-temps\n");
7151 printf (" keep-temps\n");
7152 printf (" write-symbols\n");
7153 printf (" metadata-only\n");
7154 printf (" bind-to-runtime-version\n");
7155 printf (" full\n");
7156 printf (" threads=\n");
7157 printf (" static\n");
7158 printf (" asmonly\n");
7159 printf (" asmwriter\n");
7160 printf (" nodebug\n");
7161 printf (" dwarfdebug\n");
7162 printf (" ntrampolines=\n");
7163 printf (" nrgctx-trampolines=\n");
7164 printf (" nimt-trampolines=\n");
7165 printf (" ngsharedvt-trampolines=\n");
7166 printf (" tool-prefix=\n");
7167 printf (" readonly-value=\n");
7168 printf (" soft-debug\n");
7169 printf (" msym-dir=\n");
7170 printf (" gc-maps\n");
7171 printf (" print-skipped\n");
7172 printf (" no-instances\n");
7173 printf (" stats\n");
7174 printf (" dump\n");
7175 printf (" info\n");
7176 printf (" help/?\n");
7177 exit (0);
7178 } else {
7179 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7180 exit (1);
7183 g_free ((gpointer) arg);
7186 if (opts->use_trampolines_page) {
7187 opts->ntrampolines = 0;
7188 opts->nrgctx_trampolines = 0;
7189 opts->nimt_trampolines = 0;
7190 opts->ngsharedvt_arg_trampolines = 0;
7193 g_ptr_array_free (args, /*free_seg=*/TRUE);
7196 static void
7197 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7199 MonoMethod *method = (MonoMethod*)key;
7200 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7201 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7202 MonoJumpInfoToken *new_ji;
7204 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7205 new_ji->image = ji->image;
7206 new_ji->token = ji->token;
7207 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7210 static gboolean
7211 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7213 if (klass->type_token)
7214 return TRUE;
7215 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7216 return TRUE;
7217 if (klass->rank)
7218 return can_encode_class (acfg, klass->element_class);
7219 return FALSE;
7222 static gboolean
7223 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7225 if (method->wrapper_type) {
7226 switch (method->wrapper_type) {
7227 case MONO_WRAPPER_NONE:
7228 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7229 case MONO_WRAPPER_XDOMAIN_INVOKE:
7230 case MONO_WRAPPER_STFLD:
7231 case MONO_WRAPPER_LDFLD:
7232 case MONO_WRAPPER_LDFLDA:
7233 case MONO_WRAPPER_STELEMREF:
7234 case MONO_WRAPPER_ISINST:
7235 case MONO_WRAPPER_PROXY_ISINST:
7236 case MONO_WRAPPER_ALLOC:
7237 case MONO_WRAPPER_REMOTING_INVOKE:
7238 case MONO_WRAPPER_UNKNOWN:
7239 case MONO_WRAPPER_WRITE_BARRIER:
7240 case MONO_WRAPPER_DELEGATE_INVOKE:
7241 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7242 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7243 case MONO_WRAPPER_SYNCHRONIZED:
7244 break;
7245 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7246 case MONO_WRAPPER_CASTCLASS: {
7247 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7249 if (info)
7250 return TRUE;
7251 else
7252 return FALSE;
7253 break;
7255 default:
7256 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7257 return FALSE;
7259 } else {
7260 if (!method->token) {
7261 /* The method is part of a constructed type like Int[,].Set (). */
7262 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7263 if (method->klass->rank)
7264 return TRUE;
7265 return FALSE;
7269 return TRUE;
7272 static gboolean
7273 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7275 switch (patch_info->type) {
7276 case MONO_PATCH_INFO_METHOD:
7277 case MONO_PATCH_INFO_METHODCONST:
7278 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7279 MonoMethod *method = patch_info->data.method;
7281 return can_encode_method (acfg, method);
7283 case MONO_PATCH_INFO_VTABLE:
7284 case MONO_PATCH_INFO_CLASS:
7285 case MONO_PATCH_INFO_IID:
7286 case MONO_PATCH_INFO_ADJUSTED_IID:
7287 if (!can_encode_class (acfg, patch_info->data.klass)) {
7288 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7289 return FALSE;
7291 break;
7292 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7293 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7294 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7295 return FALSE;
7297 break;
7299 case MONO_PATCH_INFO_RGCTX_FETCH:
7300 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7301 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7303 if (!can_encode_method (acfg, entry->method))
7304 return FALSE;
7305 if (!can_encode_patch (acfg, entry->data))
7306 return FALSE;
7307 break;
7309 default:
7310 break;
7313 return TRUE;
7316 static gboolean
7317 is_concrete_type (MonoType *t)
7319 MonoClass *klass;
7320 int i;
7322 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7323 return FALSE;
7324 if (t->type == MONO_TYPE_GENERICINST) {
7325 MonoGenericContext *orig_ctx;
7326 MonoGenericInst *inst;
7327 MonoType *arg;
7329 if (!MONO_TYPE_ISSTRUCT (t))
7330 return TRUE;
7331 klass = mono_class_from_mono_type (t);
7332 orig_ctx = &mono_class_get_generic_class (klass)->context;
7334 inst = orig_ctx->class_inst;
7335 if (inst) {
7336 for (i = 0; i < inst->type_argc; ++i) {
7337 arg = mini_get_underlying_type (inst->type_argv [i]);
7338 if (!is_concrete_type (arg))
7339 return FALSE;
7342 inst = orig_ctx->method_inst;
7343 if (inst) {
7344 for (i = 0; i < inst->type_argc; ++i) {
7345 arg = mini_get_underlying_type (inst->type_argv [i]);
7346 if (!is_concrete_type (arg))
7347 return FALSE;
7351 return TRUE;
7354 /* LOCKING: Assumes the loader lock is held */
7355 static void
7356 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7358 MonoMethod *wrapper;
7359 gboolean concrete = TRUE;
7360 gboolean add_in = gsharedvt_in;
7361 gboolean add_out = gsharedvt_out;
7363 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7364 add_in = FALSE;
7365 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7366 add_out = FALSE;
7368 if (!add_in && !add_out)
7369 return;
7371 if (mini_is_gsharedvt_variable_signature (sig))
7372 return;
7374 if (add_in)
7375 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7376 if (add_out)
7377 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7379 if (!sig->has_type_parameters) {
7380 //printf ("%s\n", mono_signature_full_name (sig));
7382 if (gsharedvt_in) {
7383 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7384 add_extra_method (acfg, wrapper);
7386 if (gsharedvt_out) {
7387 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7388 add_extra_method (acfg, wrapper);
7390 } else {
7391 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7392 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7393 int i;
7395 //printf ("%s\n", mono_signature_full_name (sig));
7397 copy->ret = mini_get_underlying_type (sig->ret);
7398 if (!is_concrete_type (copy->ret))
7399 concrete = FALSE;
7400 for (i = 0; i < sig->param_count; ++i) {
7401 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7402 if (!is_concrete_type (copy->params [i]))
7403 concrete = FALSE;
7405 if (concrete) {
7406 copy->has_type_parameters = 0;
7408 if (gsharedvt_in) {
7409 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7410 add_extra_method (acfg, wrapper);
7413 if (gsharedvt_out) {
7414 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7415 add_extra_method (acfg, wrapper);
7418 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7424 * compile_method:
7426 * AOT compile a given method.
7427 * This function might be called by multiple threads, so it must be thread-safe.
7429 static void
7430 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7432 MonoCompile *cfg;
7433 MonoJumpInfo *patch_info;
7434 gboolean skip;
7435 int index, depth;
7436 MonoMethod *wrapped;
7437 GTimer *jit_timer;
7438 JitFlags flags;
7440 if (acfg->aot_opts.metadata_only)
7441 return;
7443 mono_acfg_lock (acfg);
7444 index = get_method_index (acfg, method);
7445 mono_acfg_unlock (acfg);
7447 /* fixme: maybe we can also precompile wrapper methods */
7448 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7449 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7450 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7451 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7452 return;
7455 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7456 return;
7458 wrapped = mono_marshal_method_from_wrapper (method);
7459 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7460 // FIXME: The wrapper should be generic too, but it is not
7461 return;
7463 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7464 return;
7466 InterlockedIncrement (&acfg->stats.mcount);
7468 #if 0
7469 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7470 InterlockedIncrement (&acfg->stats.genericcount);
7471 return;
7473 #endif
7475 //acfg->aot_opts.print_skipped_methods = TRUE;
7478 * Since these methods are the only ones which are compiled with
7479 * AOT support, and they are not used by runtime startup/shutdown code,
7480 * the runtime will not see AOT methods during AOT compilation,so it
7481 * does not need to support them by creating a fake GOT etc.
7483 flags = JIT_FLAG_AOT;
7484 if (mono_aot_mode_is_full (&acfg->aot_opts))
7485 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7486 if (acfg->llvm)
7487 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7488 if (acfg->aot_opts.llvm_only)
7489 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7490 if (acfg->aot_opts.no_direct_calls)
7491 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7493 jit_timer = mono_time_track_start ();
7494 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7495 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7497 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7498 if (acfg->aot_opts.print_skipped_methods)
7499 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7500 InterlockedIncrement (&acfg->stats.genericcount);
7501 return;
7503 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7504 if (acfg->aot_opts.print_skipped_methods)
7505 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7506 /* Let the exception happen at runtime */
7507 return;
7510 if (cfg->disable_aot) {
7511 if (acfg->aot_opts.print_skipped_methods)
7512 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7513 InterlockedIncrement (&acfg->stats.ocount);
7514 return;
7516 cfg->method_index = index;
7518 /* Nullify patches which need no aot processing */
7519 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7520 switch (patch_info->type) {
7521 case MONO_PATCH_INFO_LABEL:
7522 case MONO_PATCH_INFO_BB:
7523 patch_info->type = MONO_PATCH_INFO_NONE;
7524 break;
7525 default:
7526 break;
7530 /* Collect method->token associations from the cfg */
7531 mono_acfg_lock (acfg);
7532 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7533 mono_acfg_unlock (acfg);
7534 g_hash_table_destroy (cfg->token_info_hash);
7535 cfg->token_info_hash = NULL;
7538 * Check for absolute addresses.
7540 skip = FALSE;
7541 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7542 switch (patch_info->type) {
7543 case MONO_PATCH_INFO_ABS:
7544 /* unable to handle this */
7545 skip = TRUE;
7546 break;
7547 default:
7548 break;
7552 if (skip) {
7553 if (acfg->aot_opts.print_skipped_methods)
7554 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7555 InterlockedIncrement (&acfg->stats.abscount);
7556 return;
7559 /* Lock for the rest of the code */
7560 mono_acfg_lock (acfg);
7562 if (cfg->gsharedvt)
7563 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7564 else if (cfg->gshared)
7565 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7566 else if (cfg->method->wrapper_type)
7567 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7568 else
7569 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7572 * Check for methods/klasses we can't encode.
7574 skip = FALSE;
7575 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7576 if (!can_encode_patch (acfg, patch_info))
7577 skip = TRUE;
7580 if (skip) {
7581 if (acfg->aot_opts.print_skipped_methods)
7582 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7583 acfg->stats.ocount++;
7584 mono_acfg_unlock (acfg);
7585 return;
7588 if (!cfg->compile_llvm)
7589 acfg->has_jitted_code = TRUE;
7591 if (method->is_inflated && acfg->aot_opts.log_instances) {
7592 if (acfg->instances_logfile)
7593 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7594 else
7595 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7598 /* Adds generic instances referenced by this method */
7600 * The depth is used to avoid infinite loops when generic virtual recursion is
7601 * encountered.
7603 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7604 if (!acfg->aot_opts.no_instances && depth < 32) {
7605 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7606 switch (patch_info->type) {
7607 case MONO_PATCH_INFO_RGCTX_FETCH:
7608 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7609 case MONO_PATCH_INFO_METHOD: {
7610 MonoMethod *m = NULL;
7612 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7613 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7615 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7616 m = e->data->data.method;
7617 } else {
7618 m = patch_info->data.method;
7621 if (!m)
7622 break;
7623 if (m->is_inflated) {
7624 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7625 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7626 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7627 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7628 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7629 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7630 } else {
7631 add_extra_method_with_depth (acfg, m, depth + 1);
7632 add_types_from_method_header (acfg, m);
7635 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7637 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7638 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7640 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7641 add_extra_method_with_depth (acfg, m, depth + 1);
7643 break;
7645 case MONO_PATCH_INFO_VTABLE: {
7646 MonoClass *klass = patch_info->data.klass;
7648 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7649 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7650 break;
7652 case MONO_PATCH_INFO_SFLDA: {
7653 MonoClass *klass = patch_info->data.field->parent;
7655 /* The .cctor needs to run at runtime. */
7656 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))
7657 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7658 break;
7660 default:
7661 break;
7666 /* Determine whenever the method has GOT slots */
7667 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7668 switch (patch_info->type) {
7669 case MONO_PATCH_INFO_GOT_OFFSET:
7670 case MONO_PATCH_INFO_NONE:
7671 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7672 case MONO_PATCH_INFO_GC_NURSERY_START:
7673 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7674 break;
7675 case MONO_PATCH_INFO_IMAGE:
7676 /* The assembly is stored in GOT slot 0 */
7677 if (patch_info->data.image != acfg->image)
7678 cfg->has_got_slots = TRUE;
7679 break;
7680 default:
7681 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7682 cfg->has_got_slots = TRUE;
7683 break;
7687 if (!cfg->has_got_slots)
7688 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7690 /* Add gsharedvt wrappers for signatures used by the method */
7691 if (acfg->aot_opts.llvm_only) {
7692 GSList *l;
7694 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7695 /* These only need out wrappers */
7696 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7698 for (l = cfg->signatures; l; l = l->next) {
7699 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7701 /* These only need in wrappers */
7702 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7707 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7709 /* Make a copy of the patch info which is in the mempool */
7711 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7713 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7714 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7716 if (!patches)
7717 patches = new_patch_info;
7718 else
7719 patches_end->next = new_patch_info;
7720 patches_end = new_patch_info;
7722 cfg->patch_info = patches;
7724 /* Make a copy of the unwind info */
7726 GSList *l, *unwind_ops;
7727 MonoUnwindOp *op;
7729 unwind_ops = NULL;
7730 for (l = cfg->unwind_ops; l; l = l->next) {
7731 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7732 memcpy (op, l->data, sizeof (MonoUnwindOp));
7733 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7735 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7737 /* Make a copy of the argument/local info */
7739 MonoError error;
7740 MonoInst **args, **locals;
7741 MonoMethodSignature *sig;
7742 MonoMethodHeader *header;
7743 int i;
7745 sig = mono_method_signature (method);
7746 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7747 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7748 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7749 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7751 cfg->args = args;
7753 header = mono_method_get_header_checked (method, &error);
7754 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7755 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7756 for (i = 0; i < header->num_locals; ++i) {
7757 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7758 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7760 mono_metadata_free_mh (header);
7761 cfg->locals = locals;
7764 /* Free some fields used by cfg to conserve memory */
7765 mono_empty_compile (cfg);
7767 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7769 while (index >= acfg->cfgs_size) {
7770 MonoCompile **new_cfgs;
7771 int new_size;
7773 new_size = acfg->cfgs_size * 2;
7774 new_cfgs = g_new0 (MonoCompile*, new_size);
7775 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7776 g_free (acfg->cfgs);
7777 acfg->cfgs = new_cfgs;
7778 acfg->cfgs_size = new_size;
7780 acfg->cfgs [index] = cfg;
7782 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7784 mono_update_jit_stats (cfg);
7787 if (cfg->orig_method->wrapper_type)
7788 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7791 mono_acfg_unlock (acfg);
7793 InterlockedIncrement (&acfg->stats.ccount);
7796 static gsize WINAPI
7797 compile_thread_main (gpointer user_data)
7799 MonoDomain *domain = ((MonoDomain **)user_data) [0];
7800 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [1];
7801 GPtrArray *methods = ((GPtrArray **)user_data) [2];
7802 int i;
7804 MonoError error;
7805 MonoThread *thread = mono_thread_attach (domain);
7806 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "AOT compiler"), TRUE, &error);
7807 mono_error_assert_ok (&error);
7809 for (i = 0; i < methods->len; ++i)
7810 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7812 return 0;
7815 static void
7816 load_profile_files (MonoAotCompile *acfg)
7818 FILE *infile;
7819 char *tmp;
7820 int file_index, res, method_index, i;
7821 char ver [256];
7822 guint32 token;
7823 GList *unordered, *l;
7824 gboolean found;
7826 file_index = 0;
7827 while (TRUE) {
7828 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7830 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7831 g_free (tmp);
7832 break;
7835 infile = fopen (tmp, "r");
7836 g_assert (infile);
7838 printf ("Using profile data file '%s'\n", tmp);
7839 g_free (tmp);
7841 file_index ++;
7843 res = fscanf (infile, "%32s\n", ver);
7844 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7845 printf ("Profile file has wrong version or invalid.\n");
7846 fclose (infile);
7847 continue;
7850 while (TRUE) {
7851 char name [1024];
7852 MonoMethodDesc *desc;
7853 MonoMethod *method;
7855 if (fgets (name, 1023, infile) == NULL)
7856 break;
7858 /* Kill the newline */
7859 if (strlen (name) > 0)
7860 name [strlen (name) - 1] = '\0';
7862 desc = mono_method_desc_new (name, TRUE);
7864 method = mono_method_desc_search_in_image (desc, acfg->image);
7866 if (method && mono_method_get_token (method)) {
7867 token = mono_method_get_token (method);
7868 method_index = mono_metadata_token_index (token) - 1;
7870 found = FALSE;
7871 for (i = 0; i < acfg->method_order->len; ++i) {
7872 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7873 found = TRUE;
7874 break;
7877 if (!found)
7878 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7879 } else {
7880 //printf ("No method found matching '%s'.\n", name);
7883 fclose (infile);
7886 /* Add missing methods */
7887 unordered = NULL;
7888 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7889 found = FALSE;
7890 for (i = 0; i < acfg->method_order->len; ++i) {
7891 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7892 found = TRUE;
7893 break;
7896 if (!found)
7897 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7899 unordered = g_list_reverse (unordered);
7900 for (l = unordered; l; l = l->next)
7901 g_ptr_array_add (acfg->method_order, l->data);
7904 /* Used by the LLVM backend */
7905 guint32
7906 mono_aot_get_got_offset (MonoJumpInfo *ji)
7908 return get_got_offset (llvm_acfg, TRUE, ji);
7912 * mono_aot_is_shared_got_offset:
7914 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7915 * when the AOT image is loaded.
7917 gboolean
7918 mono_aot_is_shared_got_offset (int offset)
7920 return offset < llvm_acfg->nshared_got_entries;
7923 char*
7924 mono_aot_get_method_name (MonoCompile *cfg)
7926 if (llvm_acfg->aot_opts.static_link)
7927 /* Include the assembly name too to avoid duplicate symbol errors */
7928 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7929 else
7930 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7934 * mono_aot_is_linkonce_method:
7936 * Return whenever METHOD should be emitted with linkonce linkage,
7937 * eliminating duplicate copies when compiling in static mode.
7939 gboolean
7940 mono_aot_is_linkonce_method (MonoMethod *method)
7942 return FALSE;
7943 #if 0
7944 WrapperInfo *info;
7946 // FIXME: Add more cases
7947 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7948 return FALSE;
7949 info = mono_marshal_get_wrapper_info (method);
7950 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7951 return TRUE;
7952 return FALSE;
7953 #endif
7956 static gboolean
7957 append_mangled_type (GString *s, MonoType *t)
7959 if (t->byref)
7960 g_string_append_printf (s, "b");
7961 switch (t->type) {
7962 case MONO_TYPE_VOID:
7963 g_string_append_printf (s, "void_");
7964 break;
7965 case MONO_TYPE_I1:
7966 g_string_append_printf (s, "i1");
7967 break;
7968 case MONO_TYPE_U1:
7969 g_string_append_printf (s, "u1");
7970 break;
7971 case MONO_TYPE_I2:
7972 g_string_append_printf (s, "i2");
7973 break;
7974 case MONO_TYPE_U2:
7975 g_string_append_printf (s, "u2");
7976 break;
7977 case MONO_TYPE_I4:
7978 g_string_append_printf (s, "i4");
7979 break;
7980 case MONO_TYPE_U4:
7981 g_string_append_printf (s, "u4");
7982 break;
7983 case MONO_TYPE_I8:
7984 g_string_append_printf (s, "i8");
7985 break;
7986 case MONO_TYPE_U8:
7987 g_string_append_printf (s, "u8");
7988 break;
7989 case MONO_TYPE_I:
7990 g_string_append_printf (s, "ii");
7991 break;
7992 case MONO_TYPE_U:
7993 g_string_append_printf (s, "ui");
7994 break;
7995 case MONO_TYPE_R4:
7996 g_string_append_printf (s, "fl");
7997 break;
7998 case MONO_TYPE_R8:
7999 g_string_append_printf (s, "do");
8000 break;
8001 default: {
8002 char *fullname = mono_type_full_name (t);
8003 GString *temp;
8004 char *temps;
8005 int i, len;
8008 * Have to create a mangled name which is:
8009 * - a valid symbol
8010 * - unique
8012 temp = g_string_new ("");
8013 len = strlen (fullname);
8014 for (i = 0; i < len; ++i) {
8015 char c = fullname [i];
8016 if (isalnum (c)) {
8017 g_string_append_c (temp, c);
8018 } else if (c == '_') {
8019 g_string_append_c (temp, '_');
8020 g_string_append_c (temp, '_');
8021 } else {
8022 g_string_append_c (temp, '_');
8023 g_string_append_printf (temp, "%x", (int)c);
8026 temps = g_string_free (temp, FALSE);
8027 /* Include the length to avoid different length type names aliasing each other */
8028 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8029 g_free (temps);
8030 return TRUE;
8033 return TRUE;
8036 static gboolean
8037 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8039 int i;
8040 gboolean supported;
8042 supported = append_mangled_type (s, sig->ret);
8043 if (!supported)
8044 return FALSE;
8045 if (sig->hasthis)
8046 g_string_append_printf (s, "this_");
8047 for (i = 0; i < sig->param_count; ++i) {
8048 supported = append_mangled_type (s, sig->params [i]);
8049 if (!supported)
8050 return FALSE;
8053 return TRUE;
8057 * mono_aot_get_mangled_method_name:
8059 * Return a unique mangled name for METHOD, or NULL.
8061 char*
8062 mono_aot_get_mangled_method_name (MonoMethod *method)
8064 WrapperInfo *info;
8065 GString *s;
8066 gboolean supported;
8068 // FIXME: Add more cases
8069 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8070 return NULL;
8071 info = mono_marshal_get_wrapper_info (method);
8072 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8073 return NULL;
8075 s = g_string_new ("");
8077 g_string_append_printf (s, "aot_method_w_");
8079 switch (info->subtype) {
8080 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8081 g_string_append_printf (s, "gsharedvt_in_");
8082 break;
8083 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8084 g_string_append_printf (s, "gsharedvt_out_");
8085 break;
8086 default:
8087 g_assert_not_reached ();
8088 break;
8091 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8092 if (!supported) {
8093 g_string_free (s, TRUE);
8094 return NULL;
8097 return g_string_free (s, FALSE);
8100 gboolean
8101 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8103 return is_direct_callable (llvm_acfg, NULL, patch_info);
8106 void
8107 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8109 MonoPltEntry *plt_entry;
8111 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8112 plt_entry->llvm_used = FALSE;
8115 char*
8116 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8118 const char *sym = NULL;
8120 if (llvm_acfg->aot_opts.direct_icalls) {
8121 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8122 /* Call to a C function implementing a jit icall */
8123 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8124 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8125 MonoMethod *method = (MonoMethod *)data;
8126 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8127 sym = mono_lookup_icall_symbol (method);
8128 else if (llvm_acfg->aot_opts.direct_pinvoke)
8129 sym = get_pinvoke_import (llvm_acfg, method);
8131 if (sym)
8132 return g_strdup (sym);
8134 return NULL;
8137 char*
8138 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8140 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8141 MonoPltEntry *plt_entry;
8142 const char *sym = NULL;
8144 ji->type = type;
8145 ji->data.target = data;
8147 if (!can_encode_patch (llvm_acfg, ji))
8148 return NULL;
8150 if (llvm_acfg->aot_opts.direct_icalls) {
8151 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8152 /* Call to a C function implementing a jit icall */
8153 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8154 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8155 MonoMethod *method = (MonoMethod *)data;
8156 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8157 sym = mono_lookup_icall_symbol (method);
8159 if (sym)
8160 return g_strdup (sym);
8163 plt_entry = get_plt_entry (llvm_acfg, ji);
8164 plt_entry->llvm_used = TRUE;
8166 #if defined(TARGET_MACH)
8167 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8168 #else
8169 return g_strdup_printf (plt_entry->llvm_symbol);
8170 #endif
8174 mono_aot_get_method_index (MonoMethod *method)
8176 g_assert (llvm_acfg);
8177 return get_method_index (llvm_acfg, method);
8180 MonoJumpInfo*
8181 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8183 MonoJumpInfo *res;
8185 mono_acfg_lock (llvm_acfg);
8186 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8187 mono_acfg_unlock (llvm_acfg);
8189 return res;
8192 static int
8193 execute_system (const char * command)
8195 int status = 0;
8197 #if _WIN32
8198 // We need an extra set of quotes around the whole command to properly handle commands
8199 // with spaces since internally the command is called through "cmd /c.
8200 command = g_strdup_printf ("\"%s\"", command);
8202 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
8203 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8204 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
8205 status = _wsystem (wstr);
8206 g_free (wstr);
8208 g_free (command);
8209 #elif defined (HAVE_SYSTEM)
8210 status = system (command);
8211 #else
8212 g_assert_not_reached ();
8213 #endif
8215 return status;
8218 #ifdef ENABLE_LLVM
8221 * emit_llvm_file:
8223 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8224 * tools.
8226 static gboolean
8227 emit_llvm_file (MonoAotCompile *acfg)
8229 char *command, *opts, *tempbc, *optbc, *output_fname;
8231 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8232 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8233 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8234 } else {
8235 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8236 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8239 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8242 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8243 * a lot of time, and doesn't seem to save much space.
8244 * The following optimizations cannot be enabled:
8245 * - 'tailcallelim'
8246 * - 'jump-threading' changes our blockaddress references to int constants.
8247 * - 'basiccg' fails because it contains:
8248 * if (CS && !isa<IntrinsicInst>(II)) {
8249 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8250 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8251 * The opt list below was produced by taking the output of:
8252 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8253 * then removing tailcallelim + the global opts.
8254 * strip-dead-prototypes deletes unused intrinsics definitions.
8256 /* The dse pass is disabled because of #13734 and #17616 */
8258 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8259 * // If we have no DataLayout information around, then the size of the store
8260 * // is inferrable from the pointee type. If they are the same type, then
8261 * // we know that the store is safe.
8262 * if (AA.getDataLayout() == 0 &&
8263 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8264 * return OverwriteComplete;
8265 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8267 if (acfg->aot_opts.llvm_only)
8268 // FIXME: This doesn't work yet
8269 opts = g_strdup ("");
8270 else
8271 #if LLVM_API_VERSION > 100
8272 opts = g_strdup ("-O2 -disable-tail-calls");
8273 #else
8274 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");
8275 #endif
8276 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8277 aot_printf (acfg, "Executing opt: %s\n", command);
8278 if (execute_system (command) != 0)
8279 return FALSE;
8280 g_free (opts);
8282 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8283 /* Nothing else to do */
8284 return TRUE;
8286 if (acfg->aot_opts.llvm_only) {
8287 /* Use the stock clang from xcode */
8288 // FIXME: arch
8289 command = g_strdup_printf ("clang++ -fexceptions -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
8291 aot_printf (acfg, "Executing clang: %s\n", command);
8292 if (execute_system (command) != 0)
8293 return FALSE;
8294 return TRUE;
8297 if (!acfg->llc_args)
8298 acfg->llc_args = g_string_new ("");
8300 /* Verbose asm slows down llc greatly */
8301 g_string_append (acfg->llc_args, " -asm-verbose=false");
8303 if (acfg->aot_opts.mtriple)
8304 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8306 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8308 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8310 #if LLVM_API_VERSION > 100
8311 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8312 #endif
8314 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8315 /* ios requires PIC code now */
8316 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8317 #else
8318 if (llvm_acfg->aot_opts.static_link)
8319 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8320 else
8321 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8322 #endif
8324 if (acfg->llvm_owriter) {
8325 /* Emit an object file directly */
8326 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8327 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8328 } else {
8329 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8331 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8332 g_free (output_fname);
8334 aot_printf (acfg, "Executing llc: %s\n", command);
8336 if (execute_system (command) != 0)
8337 return FALSE;
8338 return TRUE;
8340 #endif
8342 static void
8343 emit_code (MonoAotCompile *acfg)
8345 int oindex, i, prev_index;
8346 gboolean saved_unbox_info = FALSE;
8347 char symbol [MAX_SYMBOL_SIZE];
8349 if (acfg->aot_opts.llvm_only)
8350 return;
8352 #if defined(TARGET_POWERPC64)
8353 sprintf (symbol, ".Lgot_addr");
8354 emit_section_change (acfg, ".text", 0);
8355 emit_alignment (acfg, 8);
8356 emit_label (acfg, symbol);
8357 emit_pointer (acfg, acfg->got_symbol);
8358 #endif
8361 * This global symbol is used to compute the address of each method using the
8362 * code_offsets array. It is also used to compute the memory ranges occupied by
8363 * AOT code, so it must be equal to the address of the first emitted method.
8365 emit_section_change (acfg, ".text", 0);
8366 emit_alignment_code (acfg, 8);
8367 emit_info_symbol (acfg, "jit_code_start");
8370 * Emit some padding so the local symbol for the first method doesn't have the
8371 * same address as 'methods'.
8373 emit_padding (acfg, 16);
8375 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8376 MonoCompile *cfg;
8377 MonoMethod *method;
8379 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8381 cfg = acfg->cfgs [i];
8383 if (!cfg)
8384 continue;
8386 method = cfg->orig_method;
8388 /* Emit unbox trampoline */
8389 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8390 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8392 emit_section_change (acfg, ".text", 0);
8394 if (acfg->thumb_mixed && cfg->compile_llvm) {
8395 emit_set_thumb_mode (acfg);
8396 fprintf (acfg->fp, "\n.thumb_func\n");
8399 emit_label (acfg, symbol);
8401 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8403 if (acfg->thumb_mixed && cfg->compile_llvm)
8404 emit_set_arm_mode (acfg);
8406 if (!saved_unbox_info) {
8407 char user_symbol [128];
8408 GSList *unwind_ops;
8409 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8411 emit_label (acfg, "ut_end");
8413 unwind_ops = mono_unwind_get_cie_program ();
8414 save_unwind_info (acfg, user_symbol, unwind_ops);
8415 mono_free_unwind_info (unwind_ops);
8417 /* Save the unbox trampoline size */
8418 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8420 saved_unbox_info = TRUE;
8424 if (cfg->compile_llvm)
8425 acfg->stats.llvm_count ++;
8426 else
8427 emit_method_code (acfg, cfg);
8430 emit_section_change (acfg, ".text", 0);
8431 emit_alignment_code (acfg, 8);
8432 emit_info_symbol (acfg, "jit_code_end");
8434 /* To distinguish it from the next symbol */
8435 emit_padding (acfg, 4);
8438 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8439 * from optimizing them away, since it doesn't see that code_offsets references them.
8440 * JITted methods don't need this since they are referenced using assembler local
8441 * symbols.
8442 * FIXME: This is why write-symbols doesn't work on OSX ?
8444 if (acfg->llvm && acfg->need_no_dead_strip) {
8445 fprintf (acfg->fp, "\n");
8446 for (i = 0; i < acfg->nmethods; ++i) {
8447 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8448 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8453 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8454 * This is PIE code, and the linker can update it if needed.
8457 sprintf (symbol, "method_addresses");
8458 emit_section_change (acfg, ".text", 1);
8459 emit_alignment_code (acfg, 8);
8460 emit_info_symbol (acfg, symbol);
8461 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8462 emit_unset_mode (acfg);
8463 if (acfg->need_no_dead_strip)
8464 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8466 for (i = 0; i < acfg->nmethods; ++i) {
8467 #ifdef MONO_ARCH_AOT_SUPPORTED
8468 int call_size;
8470 if (acfg->cfgs [i]) {
8471 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8472 } else {
8473 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8475 #endif
8478 sprintf (symbol, "method_addresses_end");
8479 emit_label (acfg, symbol);
8480 emit_line (acfg);
8482 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8483 sprintf (symbol, "unbox_trampolines");
8484 emit_section_change (acfg, RODATA_SECT, 0);
8485 emit_alignment (acfg, 8);
8486 emit_info_symbol (acfg, symbol);
8488 prev_index = -1;
8489 for (i = 0; i < acfg->nmethods; ++i) {
8490 MonoCompile *cfg;
8491 MonoMethod *method;
8492 int index;
8494 cfg = acfg->cfgs [i];
8495 if (!cfg)
8496 continue;
8498 method = cfg->orig_method;
8500 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8501 index = get_method_index (acfg, method);
8503 emit_int32 (acfg, index);
8504 /* Make sure the table is sorted by index */
8505 g_assert (index > prev_index);
8506 prev_index = index;
8509 sprintf (symbol, "unbox_trampolines_end");
8510 emit_info_symbol (acfg, symbol);
8511 emit_int32 (acfg, 0);
8513 /* Emit a separate table with the trampoline addresses/offsets */
8514 sprintf (symbol, "unbox_trampoline_addresses");
8515 emit_section_change (acfg, ".text", 0);
8516 emit_alignment_code (acfg, 8);
8517 emit_info_symbol (acfg, symbol);
8519 for (i = 0; i < acfg->nmethods; ++i) {
8520 MonoCompile *cfg;
8521 MonoMethod *method;
8522 int index;
8524 cfg = acfg->cfgs [i];
8525 if (!cfg)
8526 continue;
8528 method = cfg->orig_method;
8530 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8531 #ifdef MONO_ARCH_AOT_SUPPORTED
8532 int call_size;
8534 index = get_method_index (acfg, method);
8535 sprintf (symbol, "ut_%d", index);
8537 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8538 #endif
8541 emit_int32 (acfg, 0);
8544 static void
8545 emit_info (MonoAotCompile *acfg)
8547 int oindex, i;
8548 gint32 *offsets;
8550 offsets = g_new0 (gint32, acfg->nmethods);
8552 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8553 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8555 if (acfg->cfgs [i]) {
8556 emit_method_info (acfg, acfg->cfgs [i]);
8557 offsets [i] = acfg->cfgs [i]->method_info_offset;
8558 } else {
8559 offsets [i] = 0;
8563 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8565 g_free (offsets);
8568 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8570 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8571 #define mix(a,b,c) { \
8572 a -= c; a ^= rot(c, 4); c += b; \
8573 b -= a; b ^= rot(a, 6); a += c; \
8574 c -= b; c ^= rot(b, 8); b += a; \
8575 a -= c; a ^= rot(c,16); c += b; \
8576 b -= a; b ^= rot(a,19); a += c; \
8577 c -= b; c ^= rot(b, 4); b += a; \
8579 #define final(a,b,c) { \
8580 c ^= b; c -= rot(b,14); \
8581 a ^= c; a -= rot(c,11); \
8582 b ^= a; b -= rot(a,25); \
8583 c ^= b; c -= rot(b,16); \
8584 a ^= c; a -= rot(c,4); \
8585 b ^= a; b -= rot(a,14); \
8586 c ^= b; c -= rot(b,24); \
8589 static guint
8590 mono_aot_type_hash (MonoType *t1)
8592 guint hash = t1->type;
8594 hash |= t1->byref << 6; /* do not collide with t1->type values */
8595 switch (t1->type) {
8596 case MONO_TYPE_VALUETYPE:
8597 case MONO_TYPE_CLASS:
8598 case MONO_TYPE_SZARRAY:
8599 /* check if the distribution is good enough */
8600 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8601 case MONO_TYPE_PTR:
8602 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8603 case MONO_TYPE_ARRAY:
8604 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8605 case MONO_TYPE_GENERICINST:
8606 return ((hash << 5) - hash) ^ 0;
8607 default:
8608 return hash;
8613 * mono_aot_method_hash:
8615 * Return a hash code for methods which only depends on metadata.
8617 guint32
8618 mono_aot_method_hash (MonoMethod *method)
8620 MonoMethodSignature *sig;
8621 MonoClass *klass;
8622 int i, hindex;
8623 int hashes_count;
8624 guint32 *hashes_start, *hashes;
8625 guint32 a, b, c;
8626 MonoGenericInst *class_ginst = NULL;
8627 MonoGenericInst *ginst = NULL;
8629 /* Similar to the hash in mono_method_get_imt_slot () */
8631 sig = mono_method_signature (method);
8633 if (mono_class_is_ginst (method->klass))
8634 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
8635 if (method->is_inflated)
8636 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8638 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8639 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8640 hashes = hashes_start;
8642 /* Some wrappers are assigned to random classes */
8643 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8644 klass = method->klass;
8645 else
8646 klass = mono_defaults.object_class;
8648 if (!method->wrapper_type) {
8649 char *full_name;
8651 if (mono_class_is_ginst (klass))
8652 full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
8653 else
8654 full_name = mono_type_full_name (&klass->byval_arg);
8656 hashes [0] = mono_metadata_str_hash (full_name);
8657 hashes [1] = 0;
8658 g_free (full_name);
8659 } else {
8660 hashes [0] = mono_metadata_str_hash (klass->name);
8661 hashes [1] = mono_metadata_str_hash (klass->name_space);
8663 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8664 /* The method name includes a stringified pointer */
8665 hashes [2] = 0;
8666 else
8667 hashes [2] = mono_metadata_str_hash (method->name);
8668 hashes [3] = method->wrapper_type;
8669 hashes [4] = mono_aot_type_hash (sig->ret);
8670 hindex = 5;
8671 for (i = 0; i < sig->param_count; i++) {
8672 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8674 if (class_ginst) {
8675 for (i = 0; i < class_ginst->type_argc; ++i)
8676 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8678 if (ginst) {
8679 for (i = 0; i < ginst->type_argc; ++i)
8680 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8682 g_assert (hindex == hashes_count);
8684 /* Setup internal state */
8685 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8687 /* Handle most of the hashes */
8688 while (hashes_count > 3) {
8689 a += hashes [0];
8690 b += hashes [1];
8691 c += hashes [2];
8692 mix (a,b,c);
8693 hashes_count -= 3;
8694 hashes += 3;
8697 /* Handle the last 3 hashes (all the case statements fall through) */
8698 switch (hashes_count) {
8699 case 3 : c += hashes [2];
8700 case 2 : b += hashes [1];
8701 case 1 : a += hashes [0];
8702 final (a,b,c);
8703 case 0: /* nothing left to add */
8704 break;
8707 g_free (hashes_start);
8709 return c;
8711 #undef rot
8712 #undef mix
8713 #undef final
8716 * mono_aot_get_array_helper_from_wrapper;
8718 * Get the helper method in Array called by an array wrapper method.
8720 MonoMethod*
8721 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8723 MonoMethod *m;
8724 const char *prefix;
8725 MonoGenericContext ctx;
8726 MonoType *args [16];
8727 char *mname, *iname, *s, *s2, *helper_name = NULL;
8729 prefix = "System.Collections.Generic";
8730 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8731 s2 = strstr (s, "`1.");
8732 g_assert (s2);
8733 s2 [0] = '\0';
8734 iname = s;
8735 mname = s2 + 3;
8737 //printf ("X: %s %s\n", iname, mname);
8739 if (!strcmp (iname, "IList"))
8740 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8741 else
8742 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8743 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8744 g_assert (m);
8745 g_free (helper_name);
8746 g_free (s);
8748 if (m->is_generic) {
8749 MonoError error;
8750 memset (&ctx, 0, sizeof (ctx));
8751 args [0] = &method->klass->element_class->byval_arg;
8752 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8753 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8754 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8757 return m;
8760 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8762 typedef struct HashEntry {
8763 guint32 key, value, index;
8764 struct HashEntry *next;
8765 } HashEntry;
8768 * emit_extra_methods:
8770 * Emit methods which are not in the METHOD table, like wrappers.
8772 static void
8773 emit_extra_methods (MonoAotCompile *acfg)
8775 int i, table_size, buf_size;
8776 guint8 *p, *buf;
8777 guint32 *info_offsets;
8778 guint32 hash;
8779 GPtrArray *table;
8780 HashEntry *entry, *new_entry;
8781 int nmethods, max_chain_length;
8782 int *chain_lengths;
8784 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8786 /* Emit method info */
8787 nmethods = 0;
8788 for (i = 0; i < acfg->extra_methods->len; ++i) {
8789 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8790 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8792 if (!cfg)
8793 continue;
8795 buf_size = 10240;
8796 p = buf = (guint8 *)g_malloc (buf_size);
8798 nmethods ++;
8800 method = cfg->method_to_register;
8802 encode_method_ref (acfg, method, p, &p);
8804 g_assert ((p - buf) < buf_size);
8806 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8807 g_free (buf);
8811 * Construct a chained hash table for mapping indexes in extra_method_info to
8812 * method indexes.
8814 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8815 table = g_ptr_array_sized_new (table_size);
8816 for (i = 0; i < table_size; ++i)
8817 g_ptr_array_add (table, NULL);
8818 chain_lengths = g_new0 (int, table_size);
8819 max_chain_length = 0;
8820 for (i = 0; i < acfg->extra_methods->len; ++i) {
8821 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8822 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8823 guint32 key, value;
8825 if (!cfg)
8826 continue;
8828 key = info_offsets [i];
8829 value = get_method_index (acfg, method);
8831 hash = mono_aot_method_hash (method) % table_size;
8832 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8834 chain_lengths [hash] ++;
8835 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8837 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8838 new_entry->key = key;
8839 new_entry->value = value;
8841 entry = (HashEntry *)g_ptr_array_index (table, hash);
8842 if (entry == NULL) {
8843 new_entry->index = hash;
8844 g_ptr_array_index (table, hash) = new_entry;
8845 } else {
8846 while (entry->next)
8847 entry = entry->next;
8849 entry->next = new_entry;
8850 new_entry->index = table->len;
8851 g_ptr_array_add (table, new_entry);
8854 g_free (chain_lengths);
8856 //printf ("MAX: %d\n", max_chain_length);
8858 buf_size = table->len * 12 + 4;
8859 p = buf = (guint8 *)g_malloc (buf_size);
8860 encode_int (table_size, p, &p);
8862 for (i = 0; i < table->len; ++i) {
8863 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8865 if (entry == NULL) {
8866 encode_int (0, p, &p);
8867 encode_int (0, p, &p);
8868 encode_int (0, p, &p);
8869 } else {
8870 //g_assert (entry->key > 0);
8871 encode_int (entry->key, p, &p);
8872 encode_int (entry->value, p, &p);
8873 if (entry->next)
8874 encode_int (entry->next->index, p, &p);
8875 else
8876 encode_int (0, p, &p);
8879 g_assert (p - buf <= buf_size);
8881 /* Emit the table */
8882 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8884 g_free (buf);
8887 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8888 * This is used by mono_aot_find_jit_info ().
8890 buf_size = acfg->extra_methods->len * 8 + 4;
8891 p = buf = (guint8 *)g_malloc (buf_size);
8892 encode_int (acfg->extra_methods->len, p, &p);
8893 for (i = 0; i < acfg->extra_methods->len; ++i) {
8894 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8896 encode_int (get_method_index (acfg, method), p, &p);
8897 encode_int (info_offsets [i], p, &p);
8899 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8901 g_free (buf);
8902 g_free (info_offsets);
8903 g_ptr_array_free (table, TRUE);
8906 static void
8907 generate_aotid (guint8* aotid)
8909 gpointer rand_handle;
8910 MonoError error;
8912 mono_rand_open ();
8913 rand_handle = mono_rand_init (NULL, 0);
8915 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
8916 mono_error_assert_ok (&error);
8918 mono_rand_close (rand_handle);
8921 static void
8922 emit_exception_info (MonoAotCompile *acfg)
8924 int i;
8925 gint32 *offsets;
8926 SeqPointData sp_data;
8927 gboolean seq_points_to_file = FALSE;
8929 offsets = g_new0 (gint32, acfg->nmethods);
8930 for (i = 0; i < acfg->nmethods; ++i) {
8931 if (acfg->cfgs [i]) {
8932 MonoCompile *cfg = acfg->cfgs [i];
8934 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8935 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8936 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
8937 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8938 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8940 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8941 offsets [i] = cfg->ex_info_offset;
8943 if (method_seq_points_to_file) {
8944 if (!seq_points_to_file) {
8945 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8946 seq_points_to_file = TRUE;
8948 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8950 } else {
8951 offsets [i] = 0;
8955 if (seq_points_to_file) {
8956 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
8957 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
8958 char *image_basename = g_path_get_basename (acfg->image->name);
8959 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
8960 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
8962 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
8963 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
8964 exit (1);
8967 mono_seq_point_data_write (&sp_data, aot_file_path);
8968 mono_seq_point_data_free (&sp_data);
8970 g_free (aotid);
8971 g_free (dir);
8972 g_free (image_basename);
8973 g_free (aot_file);
8974 g_free (aot_file_path);
8977 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8978 g_free (offsets);
8981 static void
8982 emit_unwind_info (MonoAotCompile *acfg)
8984 int i;
8985 char symbol [128];
8987 if (acfg->aot_opts.llvm_only) {
8988 g_assert (acfg->unwind_ops->len == 0);
8989 return;
8993 * The unwind info contains a lot of duplicates so we emit each unique
8994 * entry once, and only store the offset from the start of the table in the
8995 * exception info.
8998 sprintf (symbol, "unwind_info");
8999 emit_section_change (acfg, RODATA_SECT, 1);
9000 emit_alignment (acfg, 8);
9001 emit_info_symbol (acfg, symbol);
9003 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9004 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9005 guint8 *unwind_info;
9006 guint32 unwind_info_len;
9007 guint8 buf [16];
9008 guint8 *p;
9010 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9012 p = buf;
9013 encode_value (unwind_info_len, p, &p);
9014 emit_bytes (acfg, buf, p - buf);
9015 emit_bytes (acfg, unwind_info, unwind_info_len);
9017 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9021 static void
9022 emit_class_info (MonoAotCompile *acfg)
9024 int i;
9025 gint32 *offsets;
9027 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9028 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9029 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9031 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);
9032 g_free (offsets);
9035 typedef struct ClassNameTableEntry {
9036 guint32 token, index;
9037 struct ClassNameTableEntry *next;
9038 } ClassNameTableEntry;
9040 static void
9041 emit_class_name_table (MonoAotCompile *acfg)
9043 int i, table_size, buf_size;
9044 guint32 token, hash;
9045 MonoClass *klass;
9046 GPtrArray *table;
9047 char *full_name;
9048 guint8 *buf, *p;
9049 ClassNameTableEntry *entry, *new_entry;
9052 * Construct a chained hash table for mapping class names to typedef tokens.
9054 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9055 table = g_ptr_array_sized_new (table_size);
9056 for (i = 0; i < table_size; ++i)
9057 g_ptr_array_add (table, NULL);
9058 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9059 MonoError error;
9060 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9061 klass = mono_class_get_checked (acfg->image, token, &error);
9062 if (!klass) {
9063 mono_error_cleanup (&error);
9064 continue;
9066 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9067 hash = mono_metadata_str_hash (full_name) % table_size;
9068 g_free (full_name);
9070 /* FIXME: Allocate from the mempool */
9071 new_entry = g_new0 (ClassNameTableEntry, 1);
9072 new_entry->token = token;
9074 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9075 if (entry == NULL) {
9076 new_entry->index = hash;
9077 g_ptr_array_index (table, hash) = new_entry;
9078 } else {
9079 while (entry->next)
9080 entry = entry->next;
9082 entry->next = new_entry;
9083 new_entry->index = table->len;
9084 g_ptr_array_add (table, new_entry);
9088 /* Emit the table */
9089 buf_size = table->len * 4 + 4;
9090 p = buf = (guint8 *)g_malloc0 (buf_size);
9092 /* FIXME: Optimize memory usage */
9093 g_assert (table_size < 65000);
9094 encode_int16 (table_size, p, &p);
9095 g_assert (table->len < 65000);
9096 for (i = 0; i < table->len; ++i) {
9097 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9099 if (entry == NULL) {
9100 encode_int16 (0, p, &p);
9101 encode_int16 (0, p, &p);
9102 } else {
9103 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9104 if (entry->next)
9105 encode_int16 (entry->next->index, p, &p);
9106 else
9107 encode_int16 (0, p, &p);
9109 g_free (entry);
9111 g_assert (p - buf <= buf_size);
9112 g_ptr_array_free (table, TRUE);
9114 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9116 g_free (buf);
9119 static void
9120 emit_image_table (MonoAotCompile *acfg)
9122 int i, buf_size;
9123 guint8 *buf, *p;
9126 * The image table is small but referenced in a lot of places.
9127 * So we emit it at once, and reference its elements by an index.
9129 buf_size = acfg->image_table->len * 28 + 4;
9130 for (i = 0; i < acfg->image_table->len; i++) {
9131 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9132 MonoAssemblyName *aname = &image->assembly->aname;
9134 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9137 buf = p = (guint8 *)g_malloc0 (buf_size);
9138 encode_int (acfg->image_table->len, p, &p);
9139 for (i = 0; i < acfg->image_table->len; i++) {
9140 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9141 MonoAssemblyName *aname = &image->assembly->aname;
9143 /* FIXME: Support multi-module assemblies */
9144 g_assert (image->assembly->image == image);
9146 encode_string (image->assembly_name, p, &p);
9147 encode_string (image->guid, p, &p);
9148 encode_string (aname->culture ? aname->culture : "", p, &p);
9149 encode_string ((const char*)aname->public_key_token, p, &p);
9151 while (GPOINTER_TO_UINT (p) % 8 != 0)
9152 p ++;
9154 encode_int (aname->flags, p, &p);
9155 encode_int (aname->major, p, &p);
9156 encode_int (aname->minor, p, &p);
9157 encode_int (aname->build, p, &p);
9158 encode_int (aname->revision, p, &p);
9160 g_assert (p - buf <= buf_size);
9162 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9164 g_free (buf);
9167 static void
9168 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9170 int i, first_plt_got_patch = 0, buf_size;
9171 guint8 *p, *buf;
9172 guint32 *got_info_offsets;
9173 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9175 /* Add the patches needed by the PLT to the GOT */
9176 if (!llvm) {
9177 acfg->plt_got_offset_base = acfg->got_offset;
9178 first_plt_got_patch = info->got_patches->len;
9179 for (i = 1; i < acfg->plt_offset; ++i) {
9180 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9182 g_ptr_array_add (info->got_patches, plt_entry->ji);
9184 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9187 acfg->got_offset += acfg->plt_offset;
9191 * FIXME:
9192 * - optimize offsets table.
9193 * - reduce number of exported symbols.
9194 * - emit info for a klass only once.
9195 * - determine when a method uses a GOT slot which is guaranteed to be already
9196 * initialized.
9197 * - clean up and document the code.
9198 * - use String.Empty in class libs.
9201 /* Encode info required to decode shared GOT entries */
9202 buf_size = info->got_patches->len * 128;
9203 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9204 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9205 if (!llvm) {
9206 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9207 /* Unused */
9208 if (acfg->plt_offset)
9209 acfg->plt_got_info_offsets [0] = 0;
9211 for (i = 0; i < info->got_patches->len; ++i) {
9212 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9213 guint8 *p2;
9215 p = buf;
9217 encode_value (ji->type, p, &p);
9218 p2 = p;
9219 encode_patch (acfg, ji, p, &p);
9220 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9221 g_assert (p - buf <= buf_size);
9222 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9224 if (!llvm && i >= first_plt_got_patch)
9225 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9226 acfg->stats.got_info_size += p - buf;
9229 /* Emit got_info_offsets table */
9231 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9232 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);
9235 static void
9236 emit_got (MonoAotCompile *acfg)
9238 char symbol [MAX_SYMBOL_SIZE];
9240 if (acfg->aot_opts.llvm_only)
9241 return;
9243 /* Don't make GOT global so accesses to it don't need relocations */
9244 sprintf (symbol, "%s", acfg->got_symbol);
9246 #ifdef TARGET_MACH
9247 emit_unset_mode (acfg);
9248 fprintf (acfg->fp, ".section __DATA, __bss\n");
9249 emit_alignment (acfg, 8);
9250 if (acfg->llvm)
9251 emit_info_symbol (acfg, "jit_got");
9252 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9253 #else
9254 emit_section_change (acfg, ".bss", 0);
9255 emit_alignment (acfg, 8);
9256 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9257 emit_label (acfg, symbol);
9258 if (acfg->llvm)
9259 emit_info_symbol (acfg, "jit_got");
9260 if (acfg->got_offset > 0)
9261 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9262 #endif
9264 sprintf (symbol, "got_end");
9265 emit_label (acfg, symbol);
9268 typedef struct GlobalsTableEntry {
9269 guint32 value, index;
9270 struct GlobalsTableEntry *next;
9271 } GlobalsTableEntry;
9273 static void
9274 emit_globals (MonoAotCompile *acfg)
9276 int i, table_size;
9277 guint32 hash;
9278 GPtrArray *table;
9279 char symbol [1024];
9280 GlobalsTableEntry *entry, *new_entry;
9282 if (!acfg->aot_opts.static_link)
9283 return;
9284 if (acfg->aot_opts.llvm_only) {
9285 g_assert (acfg->globals->len == 0);
9286 return;
9290 * When static linking, we emit a table containing our globals.
9294 * Construct a chained hash table for mapping global names to their index in
9295 * the globals table.
9297 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9298 table = g_ptr_array_sized_new (table_size);
9299 for (i = 0; i < table_size; ++i)
9300 g_ptr_array_add (table, NULL);
9301 for (i = 0; i < acfg->globals->len; ++i) {
9302 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9304 hash = mono_metadata_str_hash (name) % table_size;
9306 /* FIXME: Allocate from the mempool */
9307 new_entry = g_new0 (GlobalsTableEntry, 1);
9308 new_entry->value = i;
9310 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9311 if (entry == NULL) {
9312 new_entry->index = hash;
9313 g_ptr_array_index (table, hash) = new_entry;
9314 } else {
9315 while (entry->next)
9316 entry = entry->next;
9318 entry->next = new_entry;
9319 new_entry->index = table->len;
9320 g_ptr_array_add (table, new_entry);
9324 /* Emit the table */
9325 sprintf (symbol, ".Lglobals_hash");
9326 emit_section_change (acfg, RODATA_SECT, 0);
9327 emit_alignment (acfg, 8);
9328 emit_label (acfg, symbol);
9330 /* FIXME: Optimize memory usage */
9331 g_assert (table_size < 65000);
9332 emit_int16 (acfg, table_size);
9333 for (i = 0; i < table->len; ++i) {
9334 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9336 if (entry == NULL) {
9337 emit_int16 (acfg, 0);
9338 emit_int16 (acfg, 0);
9339 } else {
9340 emit_int16 (acfg, entry->value + 1);
9341 if (entry->next)
9342 emit_int16 (acfg, entry->next->index);
9343 else
9344 emit_int16 (acfg, 0);
9348 /* Emit the names */
9349 for (i = 0; i < acfg->globals->len; ++i) {
9350 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9352 sprintf (symbol, "name_%d", i);
9353 emit_section_change (acfg, RODATA_SECT, 1);
9354 #ifdef TARGET_MACH
9355 emit_alignment (acfg, 4);
9356 #endif
9357 emit_label (acfg, symbol);
9358 emit_string (acfg, name);
9361 /* Emit the globals table */
9362 sprintf (symbol, "globals");
9363 emit_section_change (acfg, ".data", 0);
9364 /* This is not a global, since it is accessed by the init function */
9365 emit_alignment (acfg, 8);
9366 emit_info_symbol (acfg, symbol);
9368 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9369 emit_pointer (acfg, symbol);
9371 for (i = 0; i < acfg->globals->len; ++i) {
9372 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9374 sprintf (symbol, "name_%d", i);
9375 emit_pointer (acfg, symbol);
9377 g_assert (strlen (name) < sizeof (symbol));
9378 sprintf (symbol, "%s", name);
9379 emit_pointer (acfg, symbol);
9381 /* Null terminate the table */
9382 emit_int32 (acfg, 0);
9383 emit_int32 (acfg, 0);
9386 static void
9387 emit_mem_end (MonoAotCompile *acfg)
9389 char symbol [128];
9391 if (acfg->aot_opts.llvm_only)
9392 return;
9394 sprintf (symbol, "mem_end");
9395 emit_section_change (acfg, ".text", 1);
9396 emit_alignment_code (acfg, 8);
9397 emit_label (acfg, symbol);
9400 static void
9401 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9403 int i;
9405 info->version = MONO_AOT_FILE_VERSION;
9406 info->plt_got_offset_base = acfg->plt_got_offset_base;
9407 info->got_size = acfg->got_offset * sizeof (gpointer);
9408 info->plt_size = acfg->plt_offset;
9409 info->nmethods = acfg->nmethods;
9410 info->flags = acfg->flags;
9411 info->opts = acfg->opts;
9412 info->simd_opts = acfg->simd_opts;
9413 info->gc_name_index = acfg->gc_name_offset;
9414 info->datafile_size = acfg->datafile_offset;
9415 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9416 info->table_offsets [i] = acfg->table_offsets [i];
9417 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9418 info->num_trampolines [i] = acfg->num_trampolines [i];
9419 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9420 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9421 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9422 info->trampoline_size [i] = acfg->trampoline_size [i];
9423 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9425 info->double_align = MONO_ABI_ALIGNOF (double);
9426 info->long_align = MONO_ABI_ALIGNOF (gint64);
9427 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9428 info->tramp_page_size = acfg->tramp_page_size;
9429 info->nshared_got_entries = acfg->nshared_got_entries;
9430 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9431 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9433 memcpy(&info->aotid, acfg->image->aotid, 16);
9436 static void
9437 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9439 char symbol [MAX_SYMBOL_SIZE];
9440 int i, sindex;
9441 const char **symbols;
9443 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9444 sindex = 0;
9445 symbols [sindex ++] = acfg->got_symbol;
9446 if (acfg->llvm) {
9447 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9448 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9449 } else {
9450 symbols [sindex ++] = NULL;
9451 symbols [sindex ++] = NULL;
9453 /* llvm_get_method */
9454 symbols [sindex ++] = NULL;
9455 /* llvm_get_unbox_tramp */
9456 symbols [sindex ++] = NULL;
9457 if (!acfg->aot_opts.llvm_only) {
9458 symbols [sindex ++] = "jit_code_start";
9459 symbols [sindex ++] = "jit_code_end";
9460 symbols [sindex ++] = "method_addresses";
9461 } else {
9462 symbols [sindex ++] = NULL;
9463 symbols [sindex ++] = NULL;
9464 symbols [sindex ++] = NULL;
9466 if (acfg->data_outfile) {
9467 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9468 symbols [sindex ++] = NULL;
9469 } else {
9470 symbols [sindex ++] = "blob";
9471 symbols [sindex ++] = "class_name_table";
9472 symbols [sindex ++] = "class_info_offsets";
9473 symbols [sindex ++] = "method_info_offsets";
9474 symbols [sindex ++] = "ex_info_offsets";
9475 symbols [sindex ++] = "extra_method_info_offsets";
9476 symbols [sindex ++] = "extra_method_table";
9477 symbols [sindex ++] = "got_info_offsets";
9478 if (acfg->llvm)
9479 symbols [sindex ++] = "llvm_got_info_offsets";
9480 else
9481 symbols [sindex ++] = NULL;
9482 symbols [sindex ++] = "image_table";
9484 symbols [sindex ++] = "mem_end";
9485 symbols [sindex ++] = "assembly_guid";
9486 symbols [sindex ++] = "runtime_version";
9487 if (acfg->num_trampoline_got_entries) {
9488 symbols [sindex ++] = "specific_trampolines";
9489 symbols [sindex ++] = "static_rgctx_trampolines";
9490 symbols [sindex ++] = "imt_trampolines";
9491 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9492 } else {
9493 symbols [sindex ++] = NULL;
9494 symbols [sindex ++] = NULL;
9495 symbols [sindex ++] = NULL;
9496 symbols [sindex ++] = NULL;
9498 if (acfg->aot_opts.static_link) {
9499 symbols [sindex ++] = "globals";
9500 } else {
9501 symbols [sindex ++] = NULL;
9503 symbols [sindex ++] = "assembly_name";
9504 symbols [sindex ++] = "plt";
9505 symbols [sindex ++] = "plt_end";
9506 symbols [sindex ++] = "unwind_info";
9507 if (!acfg->aot_opts.llvm_only) {
9508 symbols [sindex ++] = "unbox_trampolines";
9509 symbols [sindex ++] = "unbox_trampolines_end";
9510 symbols [sindex ++] = "unbox_trampoline_addresses";
9511 } else {
9512 symbols [sindex ++] = NULL;
9513 symbols [sindex ++] = NULL;
9514 symbols [sindex ++] = NULL;
9517 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9519 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9520 emit_section_change (acfg, ".data", 0);
9521 emit_alignment (acfg, 8);
9522 emit_label (acfg, symbol);
9523 if (!acfg->aot_opts.static_link)
9524 emit_global (acfg, symbol, FALSE);
9526 /* The data emitted here must match MonoAotFileInfo. */
9528 emit_int32 (acfg, info->version);
9529 emit_int32 (acfg, info->dummy);
9532 * We emit pointers to our data structures instead of emitting global symbols which
9533 * point to them, to reduce the number of globals, and because using globals leads to
9534 * various problems (i.e. arm/thumb).
9536 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9537 emit_pointer (acfg, symbols [i]);
9539 emit_int32 (acfg, info->plt_got_offset_base);
9540 emit_int32 (acfg, info->got_size);
9541 emit_int32 (acfg, info->plt_size);
9542 emit_int32 (acfg, info->nmethods);
9543 emit_int32 (acfg, info->flags);
9544 emit_int32 (acfg, info->opts);
9545 emit_int32 (acfg, info->simd_opts);
9546 emit_int32 (acfg, info->gc_name_index);
9547 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9548 emit_int32 (acfg, info->double_align);
9549 emit_int32 (acfg, info->long_align);
9550 emit_int32 (acfg, info->generic_tramp_num);
9551 emit_int32 (acfg, info->tramp_page_size);
9552 emit_int32 (acfg, info->nshared_got_entries);
9553 emit_int32 (acfg, info->datafile_size);
9555 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9556 emit_int32 (acfg, info->table_offsets [i]);
9557 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9558 emit_int32 (acfg, info->num_trampolines [i]);
9559 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9560 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9561 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9562 emit_int32 (acfg, info->trampoline_size [i]);
9563 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9564 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9566 emit_bytes (acfg, info->aotid, 16);
9568 if (acfg->aot_opts.static_link) {
9569 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9570 emit_alignment (acfg, sizeof (gpointer));
9571 emit_label (acfg, acfg->static_linking_symbol);
9572 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9577 * Emit a structure containing all the information not stored elsewhere.
9579 static void
9580 emit_file_info (MonoAotCompile *acfg)
9582 char *build_info;
9583 MonoAotFileInfo *info;
9585 if (acfg->aot_opts.bind_to_runtime_version) {
9586 build_info = mono_get_runtime_build_info ();
9587 emit_string_symbol (acfg, "runtime_version", build_info);
9588 g_free (build_info);
9589 } else {
9590 emit_string_symbol (acfg, "runtime_version", "");
9593 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9595 /* Emit a string holding the assembly name */
9596 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9598 info = g_new0 (MonoAotFileInfo, 1);
9599 init_aot_file_info (acfg, info);
9601 if (acfg->aot_opts.static_link) {
9602 char symbol [MAX_SYMBOL_SIZE];
9603 char *p;
9606 * Emit a global symbol which can be passed by an embedding app to
9607 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9608 * structure.
9610 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9612 /* Get rid of characters which cannot occur in symbols */
9613 p = symbol;
9614 for (p = symbol; *p; ++p) {
9615 if (!(isalnum (*p) || *p == '_'))
9616 *p = '_';
9618 acfg->static_linking_symbol = g_strdup (symbol);
9621 if (acfg->llvm)
9622 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9623 else
9624 emit_aot_file_info (acfg, info);
9627 static void
9628 emit_blob (MonoAotCompile *acfg)
9630 acfg->blob_closed = TRUE;
9632 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9635 static void
9636 emit_objc_selectors (MonoAotCompile *acfg)
9638 int i;
9639 char symbol [128];
9641 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9642 return;
9645 * From
9646 * cat > foo.m << EOF
9647 * void *ret ()
9649 * return @selector(print:);
9651 * EOF
9654 mono_img_writer_emit_unset_mode (acfg->w);
9655 g_assert (acfg->fp);
9656 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9657 fprintf (acfg->fp, ".align 3\n");
9658 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9659 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9660 emit_label (acfg, symbol);
9661 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9662 emit_pointer (acfg, symbol);
9665 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9666 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9667 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9668 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9671 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9672 fprintf (acfg->fp, ".align 3\n");
9673 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9674 fprintf (acfg->fp, ".long 0\n");
9675 fprintf (acfg->fp, ".long 16\n");
9678 static void
9679 emit_dwarf_info (MonoAotCompile *acfg)
9681 #ifdef EMIT_DWARF_INFO
9682 int i;
9683 char symbol2 [128];
9685 /* DIEs for methods */
9686 for (i = 0; i < acfg->nmethods; ++i) {
9687 MonoCompile *cfg = acfg->cfgs [i];
9689 if (!cfg)
9690 continue;
9692 // FIXME: LLVM doesn't define .Lme_...
9693 if (cfg->compile_llvm)
9694 continue;
9696 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9698 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 ()));
9700 #endif
9703 static gboolean
9704 collect_methods (MonoAotCompile *acfg)
9706 int mindex, i;
9707 MonoImage *image = acfg->image;
9709 /* Collect methods */
9710 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9711 MonoError error;
9712 MonoMethod *method;
9713 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9715 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9717 if (!method) {
9718 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9719 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9720 mono_error_cleanup (&error);
9721 return FALSE;
9724 /* Load all methods eagerly to skip the slower lazy loading code */
9725 mono_class_setup_methods (method->klass);
9727 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9728 /* Compile the wrapper instead */
9729 /* We do this here instead of add_wrappers () because it is easy to do it here */
9730 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9731 method = wrapper;
9734 /* FIXME: Some mscorlib methods don't have debug info */
9736 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9737 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9738 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9739 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9740 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9741 if (!mono_debug_lookup_method (method)) {
9742 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9743 exit (1);
9749 if (method->is_generic || mono_class_is_gtd (method->klass))
9750 /* Compile the ref shared version instead */
9751 method = mini_get_shared_method (method);
9753 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9754 add_method_with_index (acfg, method, i, FALSE);
9755 acfg->method_index ++;
9758 /* gsharedvt methods */
9759 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9760 MonoError error;
9761 MonoMethod *method;
9762 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9764 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9765 continue;
9767 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9768 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9770 if (method->is_generic || mono_class_is_gtd (method->klass)) {
9771 MonoMethod *gshared;
9773 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9774 add_extra_method (acfg, gshared);
9778 add_generic_instances (acfg);
9780 if (mono_aot_mode_is_full (&acfg->aot_opts))
9781 add_wrappers (acfg);
9782 return TRUE;
9785 static void
9786 compile_methods (MonoAotCompile *acfg)
9788 int i, methods_len;
9790 if (acfg->aot_opts.nthreads > 0) {
9791 GPtrArray *frag;
9792 int len, j;
9793 GPtrArray *threads;
9794 MonoThreadHandle *thread_handle;
9795 gpointer *user_data;
9796 MonoMethod **methods;
9798 methods_len = acfg->methods->len;
9800 len = acfg->methods->len / acfg->aot_opts.nthreads;
9801 g_assert (len > 0);
9803 * Partition the list of methods into fragments, and hand it to threads to
9804 * process.
9806 threads = g_ptr_array_new ();
9807 /* Make a copy since acfg->methods is modified by compile_method () */
9808 methods = g_new0 (MonoMethod*, methods_len);
9809 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9810 for (i = 0; i < methods_len; ++i)
9811 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9812 i = 0;
9813 while (i < methods_len) {
9814 frag = g_ptr_array_new ();
9815 for (j = 0; j < len; ++j) {
9816 if (i < methods_len) {
9817 g_ptr_array_add (frag, methods [i]);
9818 i ++;
9822 user_data = g_new0 (gpointer, 3);
9823 user_data [0] = mono_domain_get ();
9824 user_data [1] = acfg;
9825 user_data [2] = frag;
9827 thread_handle = mono_threads_create_thread (compile_thread_main, (gpointer) user_data, NULL, NULL);
9828 g_ptr_array_add (threads, thread_handle);
9830 g_free (methods);
9832 for (i = 0; i < threads->len; ++i) {
9833 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), INFINITE, FALSE);
9834 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
9836 } else {
9837 methods_len = 0;
9840 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9841 for (i = methods_len; i < acfg->methods->len; ++i) {
9842 /* This can new methods to acfg->methods */
9843 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9847 static int
9848 compile_asm (MonoAotCompile *acfg)
9850 char *command, *objfile;
9851 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9852 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9853 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9855 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9856 #define AS_OPTIONS "--64"
9857 #elif defined(TARGET_POWERPC64)
9858 #define AS_OPTIONS "-a64 -mppc64"
9859 #elif defined(sparc) && SIZEOF_VOID_P == 8
9860 #define AS_OPTIONS "-xarch=v9"
9861 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9862 #define AS_OPTIONS "-arch i386"
9863 #else
9864 #define AS_OPTIONS ""
9865 #endif
9867 #ifdef __native_client_codegen__
9868 #if defined(TARGET_AMD64)
9869 #define AS_NAME "nacl64-as"
9870 #else
9871 #define AS_NAME "nacl-as"
9872 #endif
9873 #elif defined(TARGET_OSX)
9874 #define AS_NAME "clang"
9875 #else
9876 #define AS_NAME "as"
9877 #endif
9879 #if defined(sparc)
9880 #define LD_NAME "ld"
9881 #define LD_OPTIONS "-shared -G"
9882 #elif defined(__ppc__) && defined(TARGET_MACH)
9883 #define LD_NAME "gcc"
9884 #define LD_OPTIONS "-dynamiclib"
9885 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9886 #define LD_NAME "clang"
9887 #define LD_OPTIONS "--shared"
9888 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9889 #define LD_NAME "gcc"
9890 #define LD_OPTIONS "-shared"
9891 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9892 #define LD_NAME "clang"
9893 #define LD_OPTIONS "-m32 -dynamiclib"
9894 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9895 #define LD_NAME "gcc"
9896 #define LD_OPTIONS "--shared"
9897 #elif defined(TARGET_POWERPC64)
9898 #define LD_OPTIONS "-m elf64ppc"
9899 #endif
9901 #ifndef LD_OPTIONS
9902 #define LD_OPTIONS ""
9903 #endif
9905 if (acfg->aot_opts.asm_only) {
9906 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9907 if (acfg->aot_opts.static_link)
9908 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9909 if (acfg->llvm)
9910 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9911 return 0;
9914 if (acfg->aot_opts.static_link) {
9915 if (acfg->aot_opts.outfile)
9916 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9917 else
9918 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9919 } else {
9920 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9923 #ifdef TARGET_OSX
9924 g_string_append (acfg->as_args, "-c -x assembler");
9925 #endif
9927 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9928 acfg->as_args ? acfg->as_args->str : "",
9929 wrap_path (objfile), wrap_path (acfg->tmpfname));
9930 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9931 if (execute_system (command) != 0) {
9932 g_free (command);
9933 g_free (objfile);
9934 return 1;
9937 if (acfg->llvm && !acfg->llvm_owriter) {
9938 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9939 acfg->as_args ? acfg->as_args->str : "",
9940 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9941 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9942 if (execute_system (command) != 0) {
9943 g_free (command);
9944 g_free (objfile);
9945 return 1;
9949 g_free (command);
9951 if (acfg->aot_opts.static_link) {
9952 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9953 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9954 g_free (objfile);
9955 return 0;
9958 if (acfg->aot_opts.outfile)
9959 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9960 else
9961 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9963 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9965 if (acfg->llvm) {
9966 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9967 } else {
9968 llvm_ofile = g_strdup ("");
9971 /* replace the ; flags separators with spaces */
9972 g_strdelimit (ld_flags, ";", ' ');
9974 if (acfg->aot_opts.llvm_only)
9975 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9977 #ifdef LD_NAME
9978 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
9979 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9980 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9981 #else
9982 // Default (linux)
9983 if (acfg->aot_opts.tool_prefix) {
9984 /* Cross compiling */
9985 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9986 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9987 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9988 } else {
9989 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
9990 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9991 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9993 if (acfg->llvm) {
9994 command = g_strdup_printf ("clang++ %s", args);
9995 } else {
9996 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
9998 g_free (args);
10001 #endif
10002 aot_printf (acfg, "Executing the native linker: %s\n", command);
10003 if (execute_system (command) != 0) {
10004 g_free (tmp_outfile_name);
10005 g_free (outfile_name);
10006 g_free (command);
10007 g_free (objfile);
10008 g_free (ld_flags);
10009 return 1;
10012 g_free (command);
10014 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10015 printf ("Stripping the binary: %s\n", com);
10016 execute_system (com);
10017 g_free (com);*/
10019 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10021 * gas generates 'mapping symbols' each time code and data is mixed, which
10022 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10024 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10025 aot_printf (acfg, "Stripping the binary: %s\n", command);
10026 if (execute_system (command) != 0) {
10027 g_free (tmp_outfile_name);
10028 g_free (outfile_name);
10029 g_free (command);
10030 g_free (objfile);
10031 return 1;
10033 #endif
10035 if (0 != rename (tmp_outfile_name, outfile_name)) {
10036 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10037 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10038 unlink (outfile_name);
10039 rename (tmp_outfile_name, outfile_name);
10043 #if defined(TARGET_MACH)
10044 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10045 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10046 if (execute_system (command) != 0) {
10047 return 1;
10049 #endif
10051 if (!acfg->aot_opts.save_temps)
10052 unlink (objfile);
10054 g_free (tmp_outfile_name);
10055 g_free (outfile_name);
10056 g_free (objfile);
10058 if (acfg->aot_opts.save_temps)
10059 aot_printf (acfg, "Retained input file.\n");
10060 else
10061 unlink (acfg->tmpfname);
10063 return 0;
10066 static void init_got_info (GotInfo *info)
10068 int i;
10070 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10071 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10072 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10073 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10074 info->got_patches = g_ptr_array_new ();
10077 static MonoAotCompile*
10078 acfg_create (MonoAssembly *ass, guint32 opts)
10080 MonoImage *image = ass->image;
10081 MonoAotCompile *acfg;
10083 acfg = g_new0 (MonoAotCompile, 1);
10084 acfg->methods = g_ptr_array_new ();
10085 acfg->method_indexes = g_hash_table_new (NULL, NULL);
10086 acfg->method_depth = g_hash_table_new (NULL, NULL);
10087 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10088 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10089 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10090 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10091 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10092 acfg->image_hash = g_hash_table_new (NULL, NULL);
10093 acfg->image_table = g_ptr_array_new ();
10094 acfg->globals = g_ptr_array_new ();
10095 acfg->image = image;
10096 acfg->opts = opts;
10097 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10098 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10099 acfg->mempool = mono_mempool_new ();
10100 acfg->extra_methods = g_ptr_array_new ();
10101 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10102 acfg->unwind_ops = g_ptr_array_new ();
10103 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10104 acfg->method_order = g_ptr_array_new ();
10105 acfg->export_names = g_hash_table_new (NULL, NULL);
10106 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10107 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10108 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10109 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10110 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10111 mono_os_mutex_init_recursive (&acfg->mutex);
10113 init_got_info (&acfg->got_info);
10114 init_got_info (&acfg->llvm_got_info);
10116 return acfg;
10119 static void
10120 got_info_free (GotInfo *info)
10122 int i;
10124 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10125 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10126 g_free (info->patch_to_got_offset_by_type);
10127 g_hash_table_destroy (info->patch_to_got_offset);
10128 g_ptr_array_free (info->got_patches, TRUE);
10131 static void
10132 acfg_free (MonoAotCompile *acfg)
10134 int i;
10136 mono_img_writer_destroy (acfg->w);
10137 for (i = 0; i < acfg->nmethods; ++i)
10138 if (acfg->cfgs [i])
10139 mono_destroy_compile (acfg->cfgs [i]);
10141 g_free (acfg->cfgs);
10143 g_free (acfg->static_linking_symbol);
10144 g_free (acfg->got_symbol);
10145 g_free (acfg->plt_symbol);
10146 g_ptr_array_free (acfg->methods, TRUE);
10147 g_ptr_array_free (acfg->image_table, TRUE);
10148 g_ptr_array_free (acfg->globals, TRUE);
10149 g_ptr_array_free (acfg->unwind_ops, TRUE);
10150 g_hash_table_destroy (acfg->method_indexes);
10151 g_hash_table_destroy (acfg->method_depth);
10152 g_hash_table_destroy (acfg->plt_offset_to_entry);
10153 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10154 if (acfg->patch_to_plt_entry [i])
10155 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10157 g_free (acfg->patch_to_plt_entry);
10158 g_hash_table_destroy (acfg->method_to_cfg);
10159 g_hash_table_destroy (acfg->token_info_hash);
10160 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10161 g_hash_table_destroy (acfg->image_hash);
10162 g_hash_table_destroy (acfg->unwind_info_offsets);
10163 g_hash_table_destroy (acfg->method_label_hash);
10164 if (acfg->typespec_classes)
10165 g_hash_table_destroy (acfg->typespec_classes);
10166 g_hash_table_destroy (acfg->export_names);
10167 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10168 g_hash_table_destroy (acfg->klass_blob_hash);
10169 g_hash_table_destroy (acfg->method_blob_hash);
10170 got_info_free (&acfg->got_info);
10171 got_info_free (&acfg->llvm_got_info);
10172 mono_mempool_destroy (acfg->mempool);
10173 g_free (acfg);
10176 #define WRAPPER(e,n) n,
10177 static const char* const
10178 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10179 #include "mono/metadata/wrapper-types.h"
10180 NULL
10183 static G_GNUC_UNUSED const char*
10184 get_wrapper_type_name (int type)
10186 return wrapper_type_names [type];
10189 //#define DUMP_PLT
10190 //#define DUMP_GOT
10192 static void aot_dump (MonoAotCompile *acfg)
10194 FILE *dumpfile;
10195 char * dumpname;
10197 JsonWriter writer;
10198 mono_json_writer_init (&writer);
10200 mono_json_writer_object_begin(&writer);
10202 // Methods
10203 mono_json_writer_indent (&writer);
10204 mono_json_writer_object_key(&writer, "methods");
10205 mono_json_writer_array_begin (&writer);
10207 int i;
10208 for (i = 0; i < acfg->nmethods; ++i) {
10209 MonoCompile *cfg;
10210 MonoMethod *method;
10211 MonoClass *klass;
10213 cfg = acfg->cfgs [i];
10214 if (!cfg)
10215 continue;
10217 method = cfg->orig_method;
10219 mono_json_writer_indent (&writer);
10220 mono_json_writer_object_begin(&writer);
10222 mono_json_writer_indent (&writer);
10223 mono_json_writer_object_key(&writer, "name");
10224 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10226 mono_json_writer_indent (&writer);
10227 mono_json_writer_object_key(&writer, "signature");
10228 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10230 mono_json_writer_indent (&writer);
10231 mono_json_writer_object_key(&writer, "code_size");
10232 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10234 klass = method->klass;
10236 mono_json_writer_indent (&writer);
10237 mono_json_writer_object_key(&writer, "class");
10238 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10240 mono_json_writer_indent (&writer);
10241 mono_json_writer_object_key(&writer, "namespace");
10242 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10244 mono_json_writer_indent (&writer);
10245 mono_json_writer_object_key(&writer, "wrapper_type");
10246 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10248 mono_json_writer_indent_pop (&writer);
10249 mono_json_writer_indent (&writer);
10250 mono_json_writer_object_end (&writer);
10251 mono_json_writer_printf (&writer, ",\n");
10254 mono_json_writer_indent_pop (&writer);
10255 mono_json_writer_indent (&writer);
10256 mono_json_writer_array_end (&writer);
10257 mono_json_writer_printf (&writer, ",\n");
10259 // PLT entries
10260 #ifdef DUMP_PLT
10261 mono_json_writer_indent_push (&writer);
10262 mono_json_writer_indent (&writer);
10263 mono_json_writer_object_key(&writer, "plt");
10264 mono_json_writer_array_begin (&writer);
10266 for (i = 0; i < acfg->plt_offset; ++i) {
10267 MonoPltEntry *plt_entry = NULL;
10268 MonoJumpInfo *ji;
10270 if (i == 0)
10272 * The first plt entry is unused.
10274 continue;
10276 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10277 ji = plt_entry->ji;
10279 mono_json_writer_indent (&writer);
10280 mono_json_writer_printf (&writer, "{ ");
10281 mono_json_writer_object_key(&writer, "symbol");
10282 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10285 mono_json_writer_indent_pop (&writer);
10286 mono_json_writer_indent (&writer);
10287 mono_json_writer_array_end (&writer);
10288 mono_json_writer_printf (&writer, ",\n");
10289 #endif
10291 // GOT entries
10292 #ifdef DUMP_GOT
10293 mono_json_writer_indent_push (&writer);
10294 mono_json_writer_indent (&writer);
10295 mono_json_writer_object_key(&writer, "got");
10296 mono_json_writer_array_begin (&writer);
10298 mono_json_writer_indent_push (&writer);
10299 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10300 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10302 mono_json_writer_indent (&writer);
10303 mono_json_writer_printf (&writer, "{ ");
10304 mono_json_writer_object_key(&writer, "patch_name");
10305 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10308 mono_json_writer_indent_pop (&writer);
10309 mono_json_writer_indent (&writer);
10310 mono_json_writer_array_end (&writer);
10311 mono_json_writer_printf (&writer, ",\n");
10312 #endif
10314 mono_json_writer_indent_pop (&writer);
10315 mono_json_writer_indent (&writer);
10316 mono_json_writer_object_end (&writer);
10318 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10319 dumpfile = fopen (dumpname, "w+");
10320 g_free (dumpname);
10322 fprintf (dumpfile, "%s", writer.text->str);
10323 fclose (dumpfile);
10325 mono_json_writer_destroy (&writer);
10328 static const char *preinited_jit_icalls[] = {
10329 "mono_aot_init_llvm_method",
10330 "mono_aot_init_gshared_method_this",
10331 "mono_aot_init_gshared_method_mrgctx",
10332 "mono_aot_init_gshared_method_vtable",
10333 "mono_llvm_throw_corlib_exception",
10334 "mono_init_vtable_slot",
10335 "mono_helper_ldstr_mscorlib"
10338 static void
10339 add_preinit_got_slots (MonoAotCompile *acfg)
10341 MonoJumpInfo *ji;
10342 int i;
10345 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10346 * during method initialization etc.
10349 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10350 ji->type = MONO_PATCH_INFO_IMAGE;
10351 ji->data.image = acfg->image;
10352 get_got_offset (acfg, FALSE, ji);
10353 get_got_offset (acfg, TRUE, ji);
10355 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10356 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10357 get_got_offset (acfg, FALSE, ji);
10358 get_got_offset (acfg, TRUE, ji);
10360 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10361 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10362 get_got_offset (acfg, FALSE, ji);
10363 get_got_offset (acfg, TRUE, ji);
10365 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10366 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10367 get_got_offset (acfg, FALSE, ji);
10368 get_got_offset (acfg, TRUE, ji);
10370 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10371 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
10372 get_got_offset (acfg, FALSE, ji);
10373 get_got_offset (acfg, TRUE, ji);
10375 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10376 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10377 get_got_offset (acfg, FALSE, ji);
10378 get_got_offset (acfg, TRUE, ji);
10380 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10381 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10382 get_got_offset (acfg, FALSE, ji);
10383 get_got_offset (acfg, TRUE, ji);
10385 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10386 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
10387 get_got_offset (acfg, FALSE, ji);
10388 get_got_offset (acfg, TRUE, ji);
10390 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10391 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10392 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10393 ji->data.name = preinited_jit_icalls [i];
10394 get_got_offset (acfg, FALSE, ji);
10395 get_got_offset (acfg, TRUE, ji);
10398 acfg->nshared_got_entries = acfg->got_offset;
10402 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10404 MonoImage *image = ass->image;
10405 int i, res;
10406 gint64 all_sizes;
10407 MonoAotCompile *acfg;
10408 char *outfile_name, *tmp_outfile_name, *p;
10409 char llvm_stats_msg [256];
10410 TV_DECLARE (atv);
10411 TV_DECLARE (btv);
10413 acfg = acfg_create (ass, opts);
10415 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10416 acfg->aot_opts.write_symbols = TRUE;
10417 acfg->aot_opts.ntrampolines = 4096;
10418 acfg->aot_opts.nrgctx_trampolines = 4096;
10419 acfg->aot_opts.nimt_trampolines = 512;
10420 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10421 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10422 acfg->aot_opts.llvm_path = g_strdup ("");
10423 acfg->aot_opts.temp_path = g_strdup ("");
10424 #ifdef MONOTOUCH
10425 acfg->aot_opts.use_trampolines_page = TRUE;
10426 #endif
10428 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10430 if (acfg->aot_opts.logfile) {
10431 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10434 if (acfg->aot_opts.data_outfile) {
10435 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10436 if (!acfg->data_outfile) {
10437 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10438 return 1;
10440 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10443 //acfg->aot_opts.print_skipped_methods = TRUE;
10445 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10446 if (acfg->opts & MONO_OPT_GSHAREDVT) {
10447 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10448 return 1;
10450 if (acfg->aot_opts.llvm_only) {
10451 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10452 return 1;
10454 #else
10455 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
10456 acfg->opts |= MONO_OPT_GSHAREDVT;
10457 #endif
10459 #if !defined(ENABLE_LLVM)
10460 if (acfg->aot_opts.llvm_only) {
10461 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
10462 return 1;
10464 #endif
10466 if (acfg->opts & MONO_OPT_GSHAREDVT)
10467 mono_set_generic_sharing_vt_supported (TRUE);
10469 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10471 generate_aotid ((guint8*) &acfg->image->aotid);
10473 char *aotid = mono_guid_to_string (acfg->image->aotid);
10474 aot_printf (acfg, "AOTID %s\n", aotid);
10475 g_free (aotid);
10477 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10478 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10479 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10480 return 1;
10482 #endif
10484 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10485 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10486 return 1;
10489 if (acfg->aot_opts.static_link)
10490 acfg->aot_opts.asm_writer = TRUE;
10492 if (acfg->aot_opts.soft_debug) {
10493 MonoDebugOptions *opt = mini_get_debug_options ();
10495 opt->mdb_optimizations = TRUE;
10496 opt->gen_sdb_seq_points = TRUE;
10498 if (!mono_debug_enabled ()) {
10499 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10500 return 1;
10502 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10505 if (mono_use_llvm || acfg->aot_opts.llvm) {
10506 acfg->llvm = TRUE;
10507 acfg->aot_opts.asm_writer = TRUE;
10508 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10510 if (acfg->aot_opts.soft_debug) {
10511 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10512 return 1;
10515 mini_llvm_init ();
10517 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10518 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
10519 return 1;
10523 if (mono_aot_mode_is_full (&acfg->aot_opts))
10524 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10526 if (mono_threads_is_coop_enabled ())
10527 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10529 if (acfg->aot_opts.instances_logfile_path) {
10530 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10531 if (!acfg->instances_logfile) {
10532 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10533 return 1;
10537 load_profile_files (acfg);
10539 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10540 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10541 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10542 #endif
10543 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10544 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10545 if (acfg->opts & MONO_OPT_GSHAREDVT)
10546 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10547 #endif
10549 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10551 arch_init (acfg);
10553 if (mono_use_llvm || acfg->aot_opts.llvm) {
10556 * Emit all LLVM code into a separate assembly/object file and link with it
10557 * normally.
10559 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
10560 acfg->llvm_owriter = TRUE;
10561 } else if (acfg->aot_opts.llvm_outfile) {
10562 int len = strlen (acfg->aot_opts.llvm_outfile);
10564 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10565 acfg->llvm_owriter = TRUE;
10569 if (acfg->llvm && acfg->thumb_mixed)
10570 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10571 if (acfg->aot_opts.llvm_only)
10572 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10574 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10575 /* Get rid of characters which cannot occur in symbols */
10576 for (p = acfg->assembly_name_sym; *p; ++p) {
10577 if (!(isalnum (*p) || *p == '_'))
10578 *p = '_';
10581 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10582 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10583 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10584 if (acfg->llvm) {
10585 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10586 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10589 acfg->method_index = 1;
10591 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
10592 mono_set_partial_sharing_supported (TRUE);
10594 res = collect_methods (acfg);
10595 if (!res)
10596 return 1;
10598 acfg->cfgs_size = acfg->methods->len + 32;
10599 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10601 /* PLT offset 0 is reserved for the PLT trampoline */
10602 acfg->plt_offset = 1;
10603 add_preinit_got_slots (acfg);
10605 #ifdef ENABLE_LLVM
10606 if (acfg->llvm) {
10607 llvm_acfg = acfg;
10608 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10610 #endif
10612 TV_GETTIME (atv);
10614 compile_methods (acfg);
10616 TV_GETTIME (btv);
10618 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10620 TV_GETTIME (atv);
10622 #ifdef ENABLE_LLVM
10623 if (acfg->llvm) {
10624 if (acfg->aot_opts.asm_only) {
10625 if (acfg->aot_opts.outfile) {
10626 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10627 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10628 } else {
10629 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10630 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10632 g_assert (acfg->aot_opts.llvm_outfile);
10633 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10634 if (acfg->llvm_owriter)
10635 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10636 else
10637 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10638 } else {
10639 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10640 g_strdup_printf ("%s", "temp") :
10641 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10643 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10644 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10645 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10648 #endif
10650 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10651 if (acfg->aot_opts.outfile)
10652 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10653 else
10654 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10655 acfg->fp = fopen (acfg->tmpfname, "w+");
10656 } else {
10657 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10658 acfg->fp = fdopen (i, "w+");
10660 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10661 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10662 return 1;
10664 if (acfg->fp)
10665 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10667 tmp_outfile_name = NULL;
10668 outfile_name = NULL;
10670 /* Compute symbols for methods */
10671 for (i = 0; i < acfg->nmethods; ++i) {
10672 if (acfg->cfgs [i]) {
10673 MonoCompile *cfg = acfg->cfgs [i];
10674 int method_index = get_method_index (acfg, cfg->orig_method);
10676 if (COMPILE_LLVM (cfg))
10677 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10678 else if (acfg->global_symbols || acfg->llvm)
10679 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10680 else
10681 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10682 cfg->asm_debug_symbol = cfg->asm_symbol;
10686 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
10688 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10690 acfg->gas_line_numbers = TRUE;
10693 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10694 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10695 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10696 return 1;
10698 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
10701 if (acfg->w)
10702 mono_img_writer_emit_start (acfg->w);
10704 if (acfg->dwarf)
10705 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10707 emit_code (acfg);
10709 emit_info (acfg);
10711 emit_extra_methods (acfg);
10713 emit_trampolines (acfg);
10715 emit_class_name_table (acfg);
10717 emit_got_info (acfg, FALSE);
10718 if (acfg->llvm)
10719 emit_got_info (acfg, TRUE);
10721 emit_exception_info (acfg);
10723 emit_unwind_info (acfg);
10725 emit_class_info (acfg);
10727 emit_plt (acfg);
10729 emit_image_table (acfg);
10731 emit_got (acfg);
10735 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10736 * in another.
10738 const char *gc_name = mono_gc_get_gc_name ();
10739 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10742 emit_blob (acfg);
10744 emit_objc_selectors (acfg);
10746 emit_globals (acfg);
10748 emit_file_info (acfg);
10750 if (acfg->dwarf) {
10751 emit_dwarf_info (acfg);
10752 mono_dwarf_writer_close (acfg->dwarf);
10755 emit_mem_end (acfg);
10757 if (acfg->need_pt_gnu_stack) {
10758 /* This is required so the .so doesn't have an executable stack */
10759 /* The bin writer already emits this */
10760 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10763 if (acfg->aot_opts.data_outfile)
10764 fclose (acfg->data_outfile);
10766 #ifdef ENABLE_LLVM
10767 if (acfg->llvm) {
10768 gboolean res;
10770 res = emit_llvm_file (acfg);
10771 if (!res)
10772 return 1;
10774 #endif
10776 TV_GETTIME (btv);
10778 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10780 if (acfg->llvm)
10781 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10782 else
10783 strcpy (llvm_stats_msg, "");
10785 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;
10787 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",
10788 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10789 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10790 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10791 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10792 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10793 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,
10794 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10795 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10796 (int)(acfg->got_offset * sizeof (gpointer)));
10797 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10798 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10799 llvm_stats_msg,
10800 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10801 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10802 if (acfg->stats.genericcount)
10803 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10804 if (acfg->stats.abscount)
10805 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10806 if (acfg->stats.lmfcount)
10807 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10808 if (acfg->stats.ocount)
10809 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10811 TV_GETTIME (atv);
10812 if (acfg->w) {
10813 res = mono_img_writer_emit_writeout (acfg->w);
10814 if (res != 0) {
10815 acfg_free (acfg);
10816 return res;
10818 res = compile_asm (acfg);
10819 if (res != 0) {
10820 acfg_free (acfg);
10821 return res;
10824 TV_GETTIME (btv);
10825 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10827 if (acfg->aot_opts.stats) {
10828 int i;
10830 aot_printf (acfg, "GOT slot distribution:\n");
10831 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10832 if (acfg->stats.got_slot_types [i])
10833 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]);
10834 aot_printf (acfg, "\nMethod stats:\n");
10835 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10836 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10837 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10838 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10841 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);
10843 if (acfg->aot_opts.dump_json)
10844 aot_dump (acfg);
10846 acfg_free (acfg);
10848 return 0;
10851 #else
10853 /* AOT disabled */
10855 void*
10856 mono_aot_readonly_field_override (MonoClassField *field)
10858 return NULL;
10862 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10864 return 0;
10867 gboolean
10868 mono_aot_is_shared_got_offset (int offset)
10870 return FALSE;
10873 #endif