Under full-aot process the types of method arguments that are called from other metho...
[mono-project.git] / mono / mini / aot-compiler.c
blob3a52d3f3f09458015936029d8a310dda5fdd8c2e
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)
13 /* Remaining AOT-only work:
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
16 * relocations.
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
23 * - every shared method has a MonoGenericJitInfo structure which is only really
24 * used for handling catch clauses with open types, not a very common use case.
26 #include "config.h"
27 #include <sys/types.h>
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #ifdef HAVE_STDINT_H
32 #include <stdint.h>
33 #endif
34 #include <fcntl.h>
35 #include <ctype.h>
36 #include <string.h>
37 #ifndef HOST_WIN32
38 #include <sys/time.h>
39 #else
40 #include <winsock2.h>
41 #include <windows.h>
42 #endif
44 #include <errno.h>
45 #include <sys/stat.h>
48 #include <mono/metadata/tabledefs.h>
49 #include <mono/metadata/class.h>
50 #include <mono/metadata/object.h>
51 #include <mono/metadata/tokentype.h>
52 #include <mono/metadata/appdomain.h>
53 #include <mono/metadata/debug-helpers.h>
54 #include <mono/metadata/assembly.h>
55 #include <mono/metadata/metadata-internals.h>
56 #include <mono/metadata/marshal.h>
57 #include <mono/metadata/gc-internal.h>
58 #include <mono/metadata/monitor.h>
59 #include <mono/metadata/mempool-internals.h>
60 #include <mono/metadata/mono-endian.h>
61 #include <mono/metadata/threads-types.h>
62 #include <mono/utils/mono-logger-internal.h>
63 #include <mono/utils/mono-compiler.h>
64 #include <mono/utils/mono-time.h>
65 #include <mono/utils/mono-mmap.h>
67 #include "mini.h"
68 #include "image-writer.h"
69 #include "dwarfwriter.h"
71 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
73 #if defined(__linux__) || defined(__native_client_codegen__)
74 #define RODATA_SECT ".rodata"
75 #else
76 #define RODATA_SECT ".text"
77 #endif
79 #define TV_DECLARE(name) gint64 name
80 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
81 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
83 #ifdef TARGET_WIN32
84 #define SHARED_EXT ".dll"
85 #elif defined(__ppc__) && defined(__APPLE__)
86 #define SHARED_EXT ".dylib"
87 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
88 #define SHARED_EXT ".dylib"
89 #else
90 #define SHARED_EXT ".so"
91 #endif
93 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
94 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
95 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
97 typedef struct MonoAotOptions {
98 char *outfile;
99 gboolean save_temps;
100 gboolean write_symbols;
101 gboolean metadata_only;
102 gboolean bind_to_runtime_version;
103 gboolean full_aot;
104 gboolean no_dlsym;
105 gboolean static_link;
106 gboolean asm_only;
107 gboolean asm_writer;
108 gboolean nodebug;
109 gboolean soft_debug;
110 gboolean direct_pinvoke;
111 int nthreads;
112 int ntrampolines;
113 int nrgctx_trampolines;
114 int nimt_trampolines;
115 gboolean print_skipped_methods;
116 gboolean stats;
117 char *tool_prefix;
118 gboolean autoreg;
119 char *mtriple;
120 char *llvm_path;
121 } MonoAotOptions;
123 typedef struct MonoAotStats {
124 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
125 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
126 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
127 int got_slots, offsets_size;
128 int got_slot_types [MONO_PATCH_INFO_NONE];
129 int jit_time, gen_time, link_time;
130 } MonoAotStats;
132 typedef struct MonoAotCompile {
133 MonoImage *image;
134 GPtrArray *methods;
135 GHashTable *method_indexes;
136 GHashTable *method_depth;
137 MonoCompile **cfgs;
138 int cfgs_size;
139 GHashTable *patch_to_plt_entry;
140 GHashTable *plt_offset_to_entry;
141 GHashTable *patch_to_got_offset;
142 GHashTable **patch_to_got_offset_by_type;
143 GPtrArray *got_patches;
144 GHashTable *image_hash;
145 GHashTable *method_to_cfg;
146 GHashTable *token_info_hash;
147 GHashTable *method_to_pinvoke_import;
148 GPtrArray *extra_methods;
149 GPtrArray *image_table;
150 GPtrArray *globals;
151 GPtrArray *method_order;
152 guint32 *plt_got_info_offsets;
153 guint32 got_offset, plt_offset, plt_got_offset_base;
154 guint32 final_got_size;
155 /* Number of GOT entries reserved for trampolines */
156 guint32 num_trampoline_got_entries;
158 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
159 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
160 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
162 MonoAotOptions aot_opts;
163 guint32 nmethods;
164 guint32 opts;
165 MonoMemPool *mempool;
166 MonoAotStats stats;
167 int method_index;
168 char *static_linking_symbol;
169 CRITICAL_SECTION mutex;
170 gboolean use_bin_writer;
171 MonoImageWriter *w;
172 MonoDwarfWriter *dwarf;
173 FILE *fp;
174 char *tmpfname;
175 GSList *cie_program;
176 GHashTable *unwind_info_offsets;
177 GPtrArray *unwind_ops;
178 guint32 unwind_info_offset;
179 char *got_symbol_base;
180 char *got_symbol;
181 char *plt_symbol;
182 GHashTable *method_label_hash;
183 const char *temp_prefix;
184 const char *llvm_label_prefix;
185 guint32 label_generator;
186 gboolean llvm;
187 MonoAotFileFlags flags;
188 MonoDynamicStream blob;
189 MonoClass **typespec_classes;
190 GString *llc_args;
191 GString *as_args;
192 char *assembly_name_sym;
193 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
194 GHashTable *ginst_hash;
195 } MonoAotCompile;
197 typedef struct {
198 int plt_offset;
199 char *symbol, *llvm_symbol, *debug_sym;
200 MonoJumpInfo *ji;
201 gboolean jit_used, llvm_used;
202 } MonoPltEntry;
204 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
205 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
207 /* This points to the current acfg in LLVM mode */
208 static MonoAotCompile *llvm_acfg;
210 #ifdef HAVE_ARRAY_ELEM_INIT
211 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
212 #define MSGSTRFIELD1(line) str##line
213 static const struct msgstr_t {
214 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
215 #include "patch-info.h"
216 #undef PATCH_INFO
217 } opstr = {
218 #define PATCH_INFO(a,b) b,
219 #include "patch-info.h"
220 #undef PATCH_INFO
222 static const gint16 opidx [] = {
223 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
224 #include "patch-info.h"
225 #undef PATCH_INFO
228 static G_GNUC_UNUSED const char*
229 get_patch_name (int info)
231 return (const char*)&opstr + opidx [info];
234 #else
235 #define PATCH_INFO(a,b) b,
236 static const char* const
237 patch_types [MONO_PATCH_INFO_NUM + 1] = {
238 #include "patch-info.h"
239 NULL
242 static G_GNUC_UNUSED const char*
243 get_patch_name (int info)
245 return patch_types [info];
248 #endif
250 /* Wrappers around the image writer functions */
252 static inline void
253 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
255 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
258 static inline void
259 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
261 img_writer_emit_push_section (acfg->w, section_name, subsection);
264 static inline void
265 emit_pop_section (MonoAotCompile *acfg)
267 img_writer_emit_pop_section (acfg->w);
270 static inline void
271 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
273 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
276 static inline void
277 emit_label (MonoAotCompile *acfg, const char *name)
279 img_writer_emit_label (acfg->w, name);
282 static inline void
283 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
285 img_writer_emit_bytes (acfg->w, buf, size);
288 static inline void
289 emit_string (MonoAotCompile *acfg, const char *value)
291 img_writer_emit_string (acfg->w, value);
294 static inline void
295 emit_line (MonoAotCompile *acfg)
297 img_writer_emit_line (acfg->w);
300 static inline void
301 emit_alignment (MonoAotCompile *acfg, int size)
303 img_writer_emit_alignment (acfg->w, size);
306 static inline void
307 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
309 img_writer_emit_pointer_unaligned (acfg->w, target);
312 static inline void
313 emit_pointer (MonoAotCompile *acfg, const char *target)
315 img_writer_emit_pointer (acfg->w, target);
318 static inline void
319 emit_int16 (MonoAotCompile *acfg, int value)
321 img_writer_emit_int16 (acfg->w, value);
324 static inline void
325 emit_int32 (MonoAotCompile *acfg, int value)
327 img_writer_emit_int32 (acfg->w, value);
330 static inline void
331 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
333 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
336 static inline void
337 emit_zero_bytes (MonoAotCompile *acfg, int num)
339 img_writer_emit_zero_bytes (acfg->w, num);
342 static inline void
343 emit_byte (MonoAotCompile *acfg, guint8 val)
345 img_writer_emit_byte (acfg->w, val);
348 #ifdef __native_client_codegen__
349 static inline void
350 emit_nacl_call_alignment (MonoAotCompile *acfg)
352 img_writer_emit_nacl_call_alignment (acfg->w);
354 #endif
356 static G_GNUC_UNUSED void
357 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
359 img_writer_emit_global (acfg->w, name, func);
362 static void
363 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
365 if (acfg->aot_opts.no_dlsym) {
366 g_ptr_array_add (acfg->globals, g_strdup (name));
367 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
368 } else {
369 img_writer_emit_global (acfg->w, name, func);
373 static void
374 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
376 img_writer_emit_symbol_size (acfg->w, name, end_label);
379 static void
380 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
382 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
383 img_writer_emit_label (acfg->w, name);
384 img_writer_emit_string (acfg->w, value);
387 static G_GNUC_UNUSED void
388 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
390 do {
391 guint8 b = value & 0x7f;
392 value >>= 7;
393 if (value != 0) /* more bytes to come */
394 b |= 0x80;
395 emit_byte (acfg, b);
396 } while (value);
399 static G_GNUC_UNUSED void
400 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
402 gboolean more = 1;
403 gboolean negative = (value < 0);
404 guint32 size = 64;
405 guint8 byte;
407 while (more) {
408 byte = value & 0x7f;
409 value >>= 7;
410 /* the following is unnecessary if the
411 * implementation of >>= uses an arithmetic rather
412 * than logical shift for a signed left operand
414 if (negative)
415 /* sign extend */
416 value |= - ((gint64)1 <<(size - 7));
417 /* sign bit of byte is second high order bit (0x40) */
418 if ((value == 0 && !(byte & 0x40)) ||
419 (value == -1 && (byte & 0x40)))
420 more = 0;
421 else
422 byte |= 0x80;
423 emit_byte (acfg, byte);
427 static G_GNUC_UNUSED void
428 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
430 guint8 *p = buf;
432 do {
433 guint8 b = value & 0x7f;
434 value >>= 7;
435 if (value != 0) /* more bytes to come */
436 b |= 0x80;
437 *p ++ = b;
438 } while (value);
440 *endbuf = p;
443 static G_GNUC_UNUSED void
444 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
446 gboolean more = 1;
447 gboolean negative = (value < 0);
448 guint32 size = 32;
449 guint8 byte;
450 guint8 *p = buf;
452 while (more) {
453 byte = value & 0x7f;
454 value >>= 7;
455 /* the following is unnecessary if the
456 * implementation of >>= uses an arithmetic rather
457 * than logical shift for a signed left operand
459 if (negative)
460 /* sign extend */
461 value |= - (1 <<(size - 7));
462 /* sign bit of byte is second high order bit (0x40) */
463 if ((value == 0 && !(byte & 0x40)) ||
464 (value == -1 && (byte & 0x40)))
465 more = 0;
466 else
467 byte |= 0x80;
468 *p ++= byte;
471 *endbuf = p;
474 /* ARCHITECTURE SPECIFIC CODE */
476 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
477 #define EMIT_DWARF_INFO 1
478 #endif
480 #if defined(TARGET_ARM)
481 #define AOT_FUNC_ALIGNMENT 4
482 #else
483 #define AOT_FUNC_ALIGNMENT 16
484 #endif
485 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
486 #undef AOT_FUNC_ALIGNMENT
487 #define AOT_FUNC_ALIGNMENT 32
488 #endif
490 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
491 #define PPC_LD_OP "ld"
492 #define PPC_LDX_OP "ldx"
493 #else
494 #define PPC_LD_OP "lwz"
495 #define PPC_LDX_OP "lwzx"
496 #endif
498 static void
499 arch_init (MonoAotCompile *acfg)
501 acfg->llc_args = g_string_new ("");
502 acfg->as_args = g_string_new ("");
505 * The prefix LLVM likes to put in front of symbol names on darwin.
506 * The mach-os specs require this for globals, but LLVM puts them in front of all
507 * symbols. We need to handle this, since we need to refer to LLVM generated
508 * symbols.
510 acfg->llvm_label_prefix = "";
512 #ifdef TARGET_ARM
513 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
514 g_string_append (acfg->llc_args, "-mattr=+v6");
515 } else {
516 #ifdef ARM_FPU_VFP
517 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
518 g_string_append (acfg->as_args, " -mfpu=vfp3");
519 #else
520 g_string_append (acfg->llc_args, " -soft-float");
521 #endif
523 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
524 acfg->thumb_mixed = TRUE;
526 if (acfg->aot_opts.mtriple)
527 mono_arch_set_target (acfg->aot_opts.mtriple);
528 #endif
530 #ifdef __APPLE__
531 acfg->llvm_label_prefix = "_";
532 acfg->need_no_dead_strip = TRUE;
533 #endif
535 #if defined(__linux__) && !defined(TARGET_ARM)
536 acfg->need_pt_gnu_stack = TRUE;
537 #endif
541 * arch_emit_direct_call:
543 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
544 * calling code.
546 static void
547 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
549 #if defined(TARGET_X86) || defined(TARGET_AMD64)
550 /* Need to make sure this is exactly 5 bytes long */
551 emit_byte (acfg, '\xe8');
552 emit_symbol_diff (acfg, target, ".", -4);
553 *call_size = 5;
554 #elif defined(TARGET_ARM)
555 if (acfg->use_bin_writer) {
556 guint8 buf [4];
557 guint8 *code;
559 code = buf;
560 ARM_BL (code, 0);
562 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
563 emit_bytes (acfg, buf, 4);
564 } else {
565 img_writer_emit_unset_mode (acfg->w);
566 fprintf (acfg->fp, "bl %s\n", target);
568 *call_size = 4;
569 #elif defined(TARGET_POWERPC)
570 if (acfg->use_bin_writer) {
571 g_assert_not_reached ();
572 } else {
573 img_writer_emit_unset_mode (acfg->w);
574 fprintf (acfg->fp, "bl %s\n", target);
575 *call_size = 4;
577 #else
578 g_assert_not_reached ();
579 #endif
583 * PPC32 design:
584 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
585 * the GOT pointer.
586 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
587 * in in the 2. slot of every GOT, and require every method to place the GOT
588 * address in r30, even when it doesn't access the GOT otherwise. This way,
589 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
593 * PPC64 design:
594 * PPC64 uses function descriptors which greatly complicate all code, since
595 * these are used very inconsistently in the runtime. Some functions like
596 * mono_compile_method () return ftn descriptors, while others like the
597 * trampoline creation functions do not.
598 * We assume that all GOT slots contain function descriptors, and create
599 * descriptors in aot-runtime.c when needed.
600 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
601 * from function descriptors, we could do the same, but it would require
602 * rewriting all the ppc/aot code to handle function descriptors properly.
603 * So instead, we use the same approach as on PPC32.
604 * This is a horrible mess, but fixing it would probably lead to an even bigger
605 * one.
609 * X86 design:
610 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
613 #ifdef MONO_ARCH_AOT_SUPPORTED
615 * arch_emit_got_offset:
617 * The memory pointed to by CODE should hold native code for computing the GOT
618 * address. Emit this code while patching it with the offset between code and
619 * the GOT. CODE_SIZE is set to the number of bytes emitted.
621 static void
622 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
624 #if defined(TARGET_POWERPC64)
625 g_assert (!acfg->use_bin_writer);
626 img_writer_emit_unset_mode (acfg->w);
628 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
629 * unsupported relocations. So we store the got address into the .Lgot_addr
630 * symbol which is in the text segment, compute its address, and load it.
632 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
633 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
634 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
635 fprintf (acfg->fp, "add 30, 30, 0\n");
636 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
637 acfg->label_generator ++;
638 *code_size = 16;
639 #elif defined(TARGET_POWERPC)
640 g_assert (!acfg->use_bin_writer);
641 img_writer_emit_unset_mode (acfg->w);
642 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
643 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
644 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
645 acfg->label_generator ++;
646 *code_size = 8;
647 #else
648 guint32 offset = mono_arch_get_patch_offset (code);
649 emit_bytes (acfg, code, offset);
650 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
652 *code_size = offset + 4;
653 #endif
657 * arch_emit_got_access:
659 * The memory pointed to by CODE should hold native code for loading a GOT
660 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
661 * CODE_SIZE is set to the number of bytes emitted.
663 static void
664 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
666 /* Emit beginning of instruction */
667 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
669 /* Emit the offset */
670 #ifdef TARGET_AMD64
671 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
672 *code_size = mono_arch_get_patch_offset (code) + 4;
673 #elif defined(TARGET_X86)
674 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
675 *code_size = mono_arch_get_patch_offset (code) + 4;
676 #elif defined(TARGET_ARM)
677 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
678 *code_size = mono_arch_get_patch_offset (code) + 4;
679 #elif defined(TARGET_POWERPC)
681 guint8 buf [32];
682 guint8 *code;
684 code = buf;
685 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
686 g_assert (code - buf == 8);
687 emit_bytes (acfg, buf, code - buf);
688 *code_size = code - buf;
690 #else
691 g_assert_not_reached ();
692 #endif
695 #endif
698 * arch_emit_plt_entry:
700 * Emit code for the PLT entry with index INDEX.
702 static void
703 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
705 #if defined(TARGET_X86)
706 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
707 #if defined(__default_codegen__)
708 /* jmp *<offset>(%ebx) */
709 emit_byte (acfg, 0xff);
710 emit_byte (acfg, 0xa3);
711 emit_int32 (acfg, offset);
712 /* Used by mono_aot_get_plt_info_offset */
713 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
714 #elif defined(__native_client_codegen__)
715 const guint8 kSizeOfNaClJmp = 11;
716 guint8 bytes[kSizeOfNaClJmp];
717 guint8 *pbytes = &bytes[0];
719 x86_jump_membase32 (pbytes, X86_EBX, offset);
720 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
721 /* four bytes of data, used by mono_arch_patch_plt_entry */
722 /* For Native Client, make this work with data embedded in push. */
723 emit_byte (acfg, 0x68); /* hide data in a push */
724 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
725 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
726 #endif /*__native_client_codegen__*/
727 #elif defined(TARGET_AMD64)
728 #if defined(__default_codegen__)
730 * We can't emit jumps because they are 32 bits only so they can't be patched.
731 * So we make indirect calls through GOT entries which are patched by the AOT
732 * loader to point to .Lpd entries.
734 /* jmpq *<offset>(%rip) */
735 emit_byte (acfg, '\xff');
736 emit_byte (acfg, '\x25');
737 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
738 /* Used by mono_aot_get_plt_info_offset */
739 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
740 #elif defined(__native_client_codegen__)
741 guint8 buf [256];
742 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
743 guint8 *code = buf_aligned;
745 /* mov <OFFSET>(%rip), %r11d */
746 emit_byte (acfg, '\x45');
747 emit_byte (acfg, '\x8b');
748 emit_byte (acfg, '\x1d');
749 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
751 amd64_jump_reg (code, AMD64_R11);
752 /* This should be constant for the plt patch */
753 g_assert ((size_t)(code-buf_aligned) == 10);
754 emit_bytes (acfg, buf_aligned, code - buf_aligned);
756 /* Hide data in a push imm32 so it passes validation */
757 emit_byte (acfg, 0x68); /* push */
758 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
759 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
760 #endif /*__native_client_codegen__*/
761 #elif defined(TARGET_ARM)
762 guint8 buf [256];
763 guint8 *code;
765 code = buf;
766 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
767 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
768 emit_bytes (acfg, buf, code - buf);
769 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
770 /* Used by mono_aot_get_plt_info_offset */
771 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
772 #elif defined(TARGET_POWERPC)
773 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
775 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
776 g_assert (!acfg->use_bin_writer);
777 img_writer_emit_unset_mode (acfg->w);
778 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
779 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
780 fprintf (acfg->fp, "add 11, 11, 30\n");
781 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
782 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
783 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
784 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
785 #endif
786 fprintf (acfg->fp, "mtctr 11\n");
787 fprintf (acfg->fp, "bctr\n");
788 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
789 #else
790 g_assert_not_reached ();
791 #endif
794 static void
795 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
797 #if defined(TARGET_ARM)
798 #if 0
799 /* LLVM calls the PLT entries using bl, so emit a stub */
800 /* FIXME: Too much overhead on every call */
801 fprintf (acfg->fp, ".thumb_func\n");
802 fprintf (acfg->fp, "bx pc\n");
803 fprintf (acfg->fp, "nop\n");
804 fprintf (acfg->fp, ".arm\n");
805 #endif
806 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
807 /* The caller already transitioned to thumb */
808 /* The code below should be 12 bytes long */
809 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
810 /* thumb can't encode ld pc, [pc, ip] */
811 fprintf (acfg->fp, "add ip, pc, ip\n");
812 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
813 fprintf (acfg->fp, "bx ip\n");
814 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
815 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
816 #else
817 g_assert_not_reached ();
818 #endif
822 * arch_emit_specific_trampoline:
824 * Emit code for a specific trampoline. OFFSET is the offset of the first of
825 * two GOT slots which contain the generic trampoline address and the trampoline
826 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
828 static void
829 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
832 * The trampolines created here are variations of the specific
833 * trampolines created in mono_arch_create_specific_trampoline (). The
834 * differences are:
835 * - the generic trampoline address is taken from a got slot.
836 * - the offset of the got slot where the trampoline argument is stored
837 * is embedded in the instruction stream, and the generic trampoline
838 * can load the argument by loading the offset, adding it to the
839 * address of the trampoline to get the address of the got slot, and
840 * loading the argument from there.
841 * - all the trampolines should be of the same length.
843 #if defined(TARGET_AMD64)
844 #if defined(__default_codegen__)
845 /* This should be exactly 16 bytes long */
846 *tramp_size = 16;
847 /* call *<offset>(%rip) */
848 emit_byte (acfg, '\x41');
849 emit_byte (acfg, '\xff');
850 emit_byte (acfg, '\x15');
851 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
852 /* This should be relative to the start of the trampoline */
853 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
854 emit_zero_bytes (acfg, 5);
855 #elif defined(__native_client_codegen__)
856 guint8 buf [256];
857 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
858 guint8 *code = buf_aligned;
859 guint8 *call_start;
860 size_t call_len;
861 int got_offset;
863 /* Emit this call in 'code' so we can find out how long it is. */
864 amd64_call_reg (code, AMD64_R11);
865 call_start = mono_arch_nacl_skip_nops (buf_aligned);
866 call_len = code - call_start;
868 /* The tramp_size is twice the NaCl alignment because it starts with */
869 /* a call which needs to be aligned to the end of the boundary. */
870 *tramp_size = kNaClAlignment*2;
872 /* Emit nops to align call site below which is 7 bytes plus */
873 /* the length of the call sequence emitted above. */
874 /* Note: this requires the specific trampoline starts on a */
875 /* kNaclAlignedment aligned address, which it does because */
876 /* it's its own function that is aligned. */
877 guint8 nop_buf[256];
878 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
879 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
880 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
882 /* The trampoline is stored at the offset'th pointer, the -4 is */
883 /* present because RIP relative addressing starts at the end of */
884 /* the current instruction, while the label "." is relative to */
885 /* the beginning of the current asm location, which in this case */
886 /* is not the mov instruction, but the offset itself, due to the */
887 /* way the bytes and ints are emitted here. */
888 got_offset = (offset * sizeof(gpointer)) - 4;
890 /* mov <OFFSET>(%rip), %r11d */
891 emit_byte (acfg, '\x45');
892 emit_byte (acfg, '\x8b');
893 emit_byte (acfg, '\x1d');
894 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
896 /* naclcall %r11 */
897 emit_bytes (acfg, call_start, call_len);
899 /* The arg is stored at the offset+1 pointer, relative to beginning */
900 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
901 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
903 /* We can't emit this data directly, hide in a "push imm32" */
904 emit_byte (acfg, '\x68'); /* push */
905 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
906 emit_alignment (acfg, kNaClAlignment);
907 #endif /*__native_client_codegen__*/
908 #elif defined(TARGET_ARM)
909 guint8 buf [128];
910 guint8 *code;
912 /* This should be exactly 20 bytes long */
913 *tramp_size = 20;
914 code = buf;
915 ARM_PUSH (code, 0x5fff);
916 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
917 /* Load the value from the GOT */
918 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
919 /* Branch to it */
920 ARM_BLX_REG (code, ARMREG_R1);
922 g_assert (code - buf == 16);
924 /* Emit it */
925 emit_bytes (acfg, buf, code - buf);
927 * Only one offset is needed, since the second one would be equal to the
928 * first one.
930 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
931 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
932 #elif defined(TARGET_POWERPC)
933 guint8 buf [128];
934 guint8 *code;
936 *tramp_size = 4;
937 code = buf;
939 g_assert (!acfg->use_bin_writer);
942 * PPC has no ip relative addressing, so we need to compute the address
943 * of the mscorlib got. That is slow and complex, so instead, we store it
944 * in the second got slot of every aot image. The caller already computed
945 * the address of its got and placed it into r30.
947 img_writer_emit_unset_mode (acfg->w);
948 /* Load mscorlib got address */
949 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
950 /* Load generic trampoline address */
951 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
952 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
953 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
954 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
955 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
956 #endif
957 fprintf (acfg->fp, "mtctr 11\n");
958 /* Load trampoline argument */
959 /* On ppc, we pass it normally to the generic trampoline */
960 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
961 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
962 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
963 /* Branch to generic trampoline */
964 fprintf (acfg->fp, "bctr\n");
966 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
967 *tramp_size = 10 * 4;
968 #else
969 *tramp_size = 9 * 4;
970 #endif
971 #elif defined(TARGET_X86)
972 guint8 buf [128];
973 guint8 *code;
975 /* Similar to the PPC code above */
977 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
979 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
980 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
981 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
982 #endif
984 code = buf;
985 /* Load mscorlib got address */
986 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
987 /* Push trampoline argument */
988 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
989 /* Load generic trampoline address */
990 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
991 /* Branch to generic trampoline */
992 x86_jump_reg (code, X86_ECX);
994 #ifdef __native_client_codegen__
996 /* emit nops to next 32 byte alignment */
997 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
998 while (code < (buf + a)) x86_nop(code);
1000 #endif
1001 emit_bytes (acfg, buf, code - buf);
1003 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1004 g_assert (code - buf == *tramp_size);
1005 #else
1006 g_assert_not_reached ();
1007 #endif
1011 * arch_emit_unbox_trampoline:
1013 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1014 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1016 static void
1017 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1019 #if defined(TARGET_AMD64)
1020 guint8 buf [32];
1021 guint8 *code;
1022 int this_reg;
1024 this_reg = mono_arch_get_this_arg_reg (NULL);
1025 code = buf;
1026 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1028 emit_bytes (acfg, buf, code - buf);
1029 /* jump <method> */
1030 emit_byte (acfg, '\xe9');
1031 emit_symbol_diff (acfg, call_target, ".", -4);
1032 #elif defined(TARGET_X86)
1033 guint8 buf [32];
1034 guint8 *code;
1035 int this_pos = 4;
1037 code = buf;
1039 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1041 emit_bytes (acfg, buf, code - buf);
1043 /* jump <method> */
1044 emit_byte (acfg, '\xe9');
1045 emit_symbol_diff (acfg, call_target, ".", -4);
1046 #elif defined(TARGET_ARM)
1047 guint8 buf [128];
1048 guint8 *code;
1050 if (acfg->thumb_mixed && cfg->compile_llvm) {
1051 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1052 fprintf (acfg->fp, "b %s\n", call_target);
1053 fprintf (acfg->fp, ".arm\n");
1054 return;
1057 code = buf;
1059 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1061 emit_bytes (acfg, buf, code - buf);
1062 /* jump to method */
1063 if (acfg->use_bin_writer) {
1064 guint8 buf [4];
1065 guint8 *code;
1067 code = buf;
1068 ARM_B (code, 0);
1070 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1071 emit_bytes (acfg, buf, 4);
1072 } else {
1073 if (acfg->thumb_mixed && cfg->compile_llvm)
1074 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1075 else
1076 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1078 #elif defined(TARGET_POWERPC)
1079 int this_pos = 3;
1081 g_assert (!acfg->use_bin_writer);
1083 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1084 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1085 #else
1086 g_assert_not_reached ();
1087 #endif
1091 * arch_emit_static_rgctx_trampoline:
1093 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1094 * two GOT slots which contain the rgctx argument, and the method to jump to.
1095 * TRAMP_SIZE is set to the size of the emitted trampoline.
1096 * These kinds of trampolines cannot be enumerated statically, since there could
1097 * be one trampoline per method instantiation, so we emit the same code for all
1098 * trampolines, and parameterize them using two GOT slots.
1100 static void
1101 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1103 #if defined(TARGET_AMD64)
1104 #if defined(__default_codegen__)
1105 /* This should be exactly 13 bytes long */
1106 *tramp_size = 13;
1108 /* mov <OFFSET>(%rip), %r10 */
1109 emit_byte (acfg, '\x4d');
1110 emit_byte (acfg, '\x8b');
1111 emit_byte (acfg, '\x15');
1112 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1114 /* jmp *<offset>(%rip) */
1115 emit_byte (acfg, '\xff');
1116 emit_byte (acfg, '\x25');
1117 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1118 #elif defined(__native_client_codegen__)
1119 guint8 buf [128];
1120 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1121 guint8 *code = buf_aligned;
1123 /* mov <OFFSET>(%rip), %r10d */
1124 emit_byte (acfg, '\x45');
1125 emit_byte (acfg, '\x8b');
1126 emit_byte (acfg, '\x15');
1127 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1129 /* mov <OFFSET>(%rip), %r11d */
1130 emit_byte (acfg, '\x45');
1131 emit_byte (acfg, '\x8b');
1132 emit_byte (acfg, '\x1d');
1133 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1135 /* nacljmp *%r11 */
1136 amd64_jump_reg (code, AMD64_R11);
1137 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1139 emit_alignment (acfg, kNaClAlignment);
1140 *tramp_size = kNaClAlignment;
1141 #endif /*__native_client_codegen__*/
1143 #elif defined(TARGET_ARM)
1144 guint8 buf [128];
1145 guint8 *code;
1147 /* This should be exactly 24 bytes long */
1148 *tramp_size = 24;
1149 code = buf;
1150 /* Load rgctx value */
1151 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1152 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1153 /* Load branch addr + branch */
1154 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1155 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1157 g_assert (code - buf == 16);
1159 /* Emit it */
1160 emit_bytes (acfg, buf, code - buf);
1161 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1162 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1163 #elif defined(TARGET_POWERPC)
1164 guint8 buf [128];
1165 guint8 *code;
1167 *tramp_size = 4;
1168 code = buf;
1170 g_assert (!acfg->use_bin_writer);
1173 * PPC has no ip relative addressing, so we need to compute the address
1174 * of the mscorlib got. That is slow and complex, so instead, we store it
1175 * in the second got slot of every aot image. The caller already computed
1176 * the address of its got and placed it into r30.
1178 img_writer_emit_unset_mode (acfg->w);
1179 /* Load mscorlib got address */
1180 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1181 /* Load rgctx */
1182 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1183 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1184 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1185 /* Load target address */
1186 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1187 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1188 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1189 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1190 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1191 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1192 #endif
1193 fprintf (acfg->fp, "mtctr 11\n");
1194 /* Branch to the target address */
1195 fprintf (acfg->fp, "bctr\n");
1197 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1198 *tramp_size = 11 * 4;
1199 #else
1200 *tramp_size = 9 * 4;
1201 #endif
1203 #elif defined(TARGET_X86)
1204 guint8 buf [128];
1205 guint8 *code;
1207 /* Similar to the PPC code above */
1209 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1211 code = buf;
1212 /* Load mscorlib got address */
1213 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1214 /* Load arg */
1215 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1216 /* Branch to the target address */
1217 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1219 #ifdef __native_client_codegen__
1221 /* emit nops to next 32 byte alignment */
1222 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1223 while (code < (buf + a)) x86_nop(code);
1225 #endif
1227 emit_bytes (acfg, buf, code - buf);
1229 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1230 g_assert (code - buf == *tramp_size);
1231 #else
1232 g_assert_not_reached ();
1233 #endif
1237 * arch_emit_imt_thunk:
1239 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1240 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1241 * key is the IMT key, and ptr holds the address of a memory location holding
1242 * the address to branch to if the IMT arg matches the key. The array is
1243 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1244 * fail_tramp.
1245 * TRAMP_SIZE is set to the size of the emitted trampoline.
1247 static void
1248 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1250 #if defined(TARGET_AMD64)
1251 guint8 *buf, *code;
1252 #if defined(__native_client_codegen__)
1253 guint8 *buf_alloc;
1254 #endif
1255 guint8 *labels [3];
1256 guint8 mov_buf[3];
1257 guint8 *mov_buf_ptr = mov_buf;
1259 const int kSizeOfMove = 7;
1260 #if defined(__default_codegen__)
1261 code = buf = g_malloc (256);
1262 #elif defined(__native_client_codegen__)
1263 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1264 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1265 /* The RIP relative move below is emitted first */
1266 buf += kSizeOfMove;
1267 code = buf;
1268 #endif
1270 /* FIXME: Optimize this, i.e. use binary search etc. */
1271 /* Maybe move the body into a separate function (slower, but much smaller) */
1273 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1275 labels [0] = code;
1276 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1277 labels [1] = code;
1278 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1280 /* Check key */
1281 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1282 labels [2] = code;
1283 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1285 /* Loop footer */
1286 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1287 amd64_jump_code (code, labels [0]);
1289 /* Match */
1290 mono_amd64_patch (labels [2], code);
1291 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1292 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1294 /* No match */
1295 /* FIXME: */
1296 mono_amd64_patch (labels [1], code);
1297 x86_breakpoint (code);
1299 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1300 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1301 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1302 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1303 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1304 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1306 emit_bytes (acfg, buf, code - buf);
1308 *tramp_size = code - buf + kSizeOfMove;
1309 #if defined(__native_client_codegen__)
1310 /* The tramp will be padded to the next kNaClAlignment bundle. */
1311 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1312 #endif
1314 #if defined(__default_codegen__)
1315 g_free (buf);
1316 #elif defined(__native_client_codegen__)
1317 g_free (buf_alloc);
1318 #endif
1320 #elif defined(TARGET_X86)
1321 guint8 *buf, *code;
1322 #ifdef __native_client_codegen__
1323 guint8 *buf_alloc;
1324 #endif
1325 guint8 *labels [3];
1327 #if defined(__default_codegen__)
1328 code = buf = g_malloc (256);
1329 #elif defined(__native_client_codegen__)
1330 buf_alloc = g_malloc (256 + kNaClAlignment);
1331 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1332 #endif
1334 /* Allocate a temporary stack slot */
1335 x86_push_reg (code, X86_EAX);
1336 /* Save EAX */
1337 x86_push_reg (code, X86_EAX);
1339 /* Load mscorlib got address */
1340 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1341 /* Load arg */
1342 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1344 labels [0] = code;
1345 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1346 labels [1] = code;
1347 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1349 /* Check key */
1350 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1351 labels [2] = code;
1352 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1354 /* Loop footer */
1355 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1356 x86_jump_code (code, labels [0]);
1358 /* Match */
1359 mono_x86_patch (labels [2], code);
1360 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1361 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1362 /* Save the target address to the temporary stack location */
1363 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1364 /* Restore EAX */
1365 x86_pop_reg (code, X86_EAX);
1366 /* Jump to the target address */
1367 x86_ret (code);
1369 /* No match */
1370 /* FIXME: */
1371 mono_x86_patch (labels [1], code);
1372 x86_breakpoint (code);
1374 #ifdef __native_client_codegen__
1376 /* emit nops to next 32 byte alignment */
1377 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1378 while (code < (buf + a)) x86_nop(code);
1380 #endif
1381 emit_bytes (acfg, buf, code - buf);
1383 *tramp_size = code - buf;
1385 #if defined(__default_codegen__)
1386 g_free (buf);
1387 #elif defined(__native_client_codegen__)
1388 g_free (buf_alloc);
1389 #endif
1391 #elif defined(TARGET_ARM)
1392 guint8 buf [128];
1393 guint8 *code, *code2, *labels [16];
1395 code = buf;
1397 /* The IMT method is in v5 */
1399 /* Need at least two free registers, plus a slot for storing the pc */
1400 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1401 labels [0] = code;
1402 /* Load the parameter from the GOT */
1403 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1404 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1406 labels [1] = code;
1407 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1408 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1409 labels [2] = code;
1410 ARM_B_COND (code, ARMCOND_EQ, 0);
1412 /* End-of-loop check */
1413 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1414 labels [3] = code;
1415 ARM_B_COND (code, ARMCOND_EQ, 0);
1417 /* Loop footer */
1418 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1419 labels [4] = code;
1420 ARM_B (code, 0);
1421 arm_patch (labels [4], labels [1]);
1423 /* Match */
1424 arm_patch (labels [2], code);
1425 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1426 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1427 /* Save it to the third stack slot */
1428 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1429 /* Restore the registers and branch */
1430 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1432 /* No match */
1433 arm_patch (labels [3], code);
1434 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1435 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1436 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1438 /* Fixup offset */
1439 code2 = labels [0];
1440 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1442 emit_bytes (acfg, buf, code - buf);
1443 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1445 *tramp_size = code - buf + 4;
1446 #elif defined(TARGET_POWERPC)
1447 guint8 buf [128];
1448 guint8 *code, *labels [16];
1450 code = buf;
1452 /* Load the mscorlib got address */
1453 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1454 /* Load the parameter from the GOT */
1455 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1456 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1458 /* Load and check key */
1459 labels [1] = code;
1460 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1461 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1462 labels [2] = code;
1463 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1465 /* End-of-loop check */
1466 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1467 labels [3] = code;
1468 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1470 /* Loop footer */
1471 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1472 labels [4] = code;
1473 ppc_b (code, 0);
1474 mono_ppc_patch (labels [4], labels [1]);
1476 /* Match */
1477 mono_ppc_patch (labels [2], code);
1478 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1479 /* r11 now contains the value of the vtable slot */
1480 /* this is not a function descriptor on ppc64 */
1481 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1482 ppc_mtctr (code, ppc_r11);
1483 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1485 /* Fail */
1486 mono_ppc_patch (labels [3], code);
1487 /* FIXME: */
1488 ppc_break (code);
1490 *tramp_size = code - buf;
1492 emit_bytes (acfg, buf, code - buf);
1493 #else
1494 g_assert_not_reached ();
1495 #endif
1498 static void
1499 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1501 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1502 /* Based on code generated by gcc */
1503 img_writer_emit_unset_mode (acfg->w);
1505 fprintf (acfg->fp,
1506 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1507 ".section .ctors,\"aw\",@progbits\n"
1508 ".align 2\n"
1509 ".globl %s\n"
1510 ".long %s\n"
1511 ".section .opd,\"aw\"\n"
1512 ".align 2\n"
1513 "%s:\n"
1514 ".long .%s,.TOC.@tocbase32\n"
1515 ".size %s,.-%s\n"
1516 ".section .text\n"
1517 ".type .%s,@function\n"
1518 ".align 2\n"
1519 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1520 #else
1521 ".section .ctors,\"aw\",@progbits\n"
1522 ".align 2\n"
1523 ".globl %1$s\n"
1524 ".long %1$s\n"
1525 ".section .opd,\"aw\"\n"
1526 ".align 2\n"
1527 "%1$s:\n"
1528 ".long .%1$s,.TOC.@tocbase32\n"
1529 ".size %1$s,.-%1$s\n"
1530 ".section .text\n"
1531 ".type .%1$s,@function\n"
1532 ".align 2\n"
1533 ".%1$s:\n", symbol);
1534 #endif
1537 fprintf (acfg->fp,
1538 "stdu 1,-128(1)\n"
1539 "mflr 0\n"
1540 "std 31,120(1)\n"
1541 "std 0,144(1)\n"
1543 ".Lautoreg:\n"
1544 "lis 3, .Lglobals@h\n"
1545 "ori 3, 3, .Lglobals@l\n"
1546 "bl .mono_aot_register_module\n"
1547 "ld 11,0(1)\n"
1548 "ld 0,16(11)\n"
1549 "mtlr 0\n"
1550 "ld 31,-8(11)\n"
1551 "mr 1,11\n"
1552 "blr\n"
1554 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1555 fprintf (acfg->fp,
1556 ".size .%s,.-.%s\n", symbol, symbol);
1557 #else
1558 fprintf (acfg->fp,
1559 ".size .%1$s,.-.%1$s\n", symbol);
1560 #endif
1561 #else
1562 #endif
1565 /* END OF ARCH SPECIFIC CODE */
1567 static guint32
1568 mono_get_field_token (MonoClassField *field)
1570 MonoClass *klass = field->parent;
1571 int i;
1573 for (i = 0; i < klass->field.count; ++i) {
1574 if (field == &klass->fields [i])
1575 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1578 g_assert_not_reached ();
1579 return 0;
1582 static inline void
1583 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1585 guint8 *p = buf;
1587 //printf ("ENCODE: %d 0x%x.\n", value, value);
1590 * Same encoding as the one used in the metadata, extended to handle values
1591 * greater than 0x1fffffff.
1593 if ((value >= 0) && (value <= 127))
1594 *p++ = value;
1595 else if ((value >= 0) && (value <= 16383)) {
1596 p [0] = 0x80 | (value >> 8);
1597 p [1] = value & 0xff;
1598 p += 2;
1599 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1600 p [0] = (value >> 24) | 0xc0;
1601 p [1] = (value >> 16) & 0xff;
1602 p [2] = (value >> 8) & 0xff;
1603 p [3] = value & 0xff;
1604 p += 4;
1606 else {
1607 p [0] = 0xff;
1608 p [1] = (value >> 24) & 0xff;
1609 p [2] = (value >> 16) & 0xff;
1610 p [3] = (value >> 8) & 0xff;
1611 p [4] = value & 0xff;
1612 p += 5;
1614 if (endbuf)
1615 *endbuf = p;
1618 static void
1619 stream_init (MonoDynamicStream *sh)
1621 sh->index = 0;
1622 sh->alloc_size = 4096;
1623 sh->data = g_malloc (4096);
1625 /* So offsets are > 0 */
1626 sh->data [0] = 0;
1627 sh->index ++;
1630 static void
1631 make_room_in_stream (MonoDynamicStream *stream, int size)
1633 if (size <= stream->alloc_size)
1634 return;
1636 while (stream->alloc_size <= size) {
1637 if (stream->alloc_size < 4096)
1638 stream->alloc_size = 4096;
1639 else
1640 stream->alloc_size *= 2;
1643 stream->data = g_realloc (stream->data, stream->alloc_size);
1646 static guint32
1647 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1649 guint32 idx;
1651 make_room_in_stream (stream, stream->index + len);
1652 memcpy (stream->data + stream->index, data, len);
1653 idx = stream->index;
1654 stream->index += len;
1655 return idx;
1659 * add_to_blob:
1661 * Add data to the binary blob inside the aot image. Returns the offset inside the
1662 * blob where the data was stored.
1664 static guint32
1665 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1667 if (acfg->blob.alloc_size == 0)
1668 stream_init (&acfg->blob);
1670 return add_stream_data (&acfg->blob, (char*)data, data_len);
1673 static guint32
1674 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1676 char buf [4] = {0};
1677 guint32 count;
1679 if (acfg->blob.alloc_size == 0)
1680 stream_init (&acfg->blob);
1682 count = acfg->blob.index % align;
1684 /* we assume the stream data will be aligned */
1685 if (count)
1686 add_stream_data (&acfg->blob, buf, 4 - count);
1688 return add_stream_data (&acfg->blob, (char*)data, data_len);
1692 * emit_offset_table:
1694 * Emit a table of increasing offsets in a compact form using differential encoding.
1695 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1696 * group size, the more compact the table becomes, but the slower it becomes to compute
1697 * a given entry. Returns the size of the table.
1699 static guint32
1700 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1702 gint32 current_offset;
1703 int i, buf_size, ngroups, index_entry_size;
1704 guint8 *p, *buf;
1705 guint32 *index_offsets;
1707 ngroups = (noffsets + (group_size - 1)) / group_size;
1709 index_offsets = g_new0 (guint32, ngroups);
1711 buf_size = noffsets * 4;
1712 p = buf = g_malloc0 (buf_size);
1714 current_offset = 0;
1715 for (i = 0; i < noffsets; ++i) {
1716 //printf ("D: %d -> %d\n", i, offsets [i]);
1717 if ((i % group_size) == 0) {
1718 index_offsets [i / group_size] = p - buf;
1719 /* Emit the full value for these entries */
1720 encode_value (offsets [i], p, &p);
1721 } else {
1722 /* The offsets are allowed to be non-increasing */
1723 //g_assert (offsets [i] >= current_offset);
1724 encode_value (offsets [i] - current_offset, p, &p);
1726 current_offset = offsets [i];
1729 if (ngroups && index_offsets [ngroups - 1] < 65000)
1730 index_entry_size = 2;
1731 else
1732 index_entry_size = 4;
1734 /* Emit the header */
1735 emit_int32 (acfg, noffsets);
1736 emit_int32 (acfg, group_size);
1737 emit_int32 (acfg, ngroups);
1738 emit_int32 (acfg, index_entry_size);
1740 /* Emit the index */
1741 for (i = 0; i < ngroups; ++i) {
1742 if (index_entry_size == 2)
1743 emit_int16 (acfg, index_offsets [i]);
1744 else
1745 emit_int32 (acfg, index_offsets [i]);
1748 /* Emit the data */
1749 emit_bytes (acfg, buf, p - buf);
1751 return (int)(p - buf) + (ngroups * 4);
1754 static guint32
1755 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1757 guint32 index;
1759 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1760 if (index)
1761 return index - 1;
1762 else {
1763 index = g_hash_table_size (cfg->image_hash);
1764 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1765 g_ptr_array_add (cfg->image_table, image);
1766 return index;
1770 static guint32
1771 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1773 int i;
1774 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1776 /* FIXME: Search referenced images as well */
1777 if (!acfg->typespec_classes) {
1778 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1779 for (i = 0; i < len; ++i) {
1780 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1783 for (i = 0; i < len; ++i) {
1784 if (acfg->typespec_classes [i] == klass)
1785 break;
1788 if (i < len)
1789 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1790 else
1791 return 0;
1794 static void
1795 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1798 * encode_klass_ref:
1800 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1801 * standard metadata encoding.
1803 static void
1804 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1806 guint8 *p = buf;
1808 if (klass->generic_class) {
1809 guint32 token;
1810 g_assert (klass->type_token);
1812 /* Find a typespec for a class if possible */
1813 token = find_typespec_for_class (acfg, klass);
1814 if (token) {
1815 encode_value (token, p, &p);
1816 encode_value (get_image_index (acfg, acfg->image), p, &p);
1817 } else {
1818 MonoClass *gclass = klass->generic_class->container_class;
1819 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1820 int i;
1822 /* Encode it ourselves */
1823 /* Marker */
1824 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1825 encode_value (MONO_TYPE_GENERICINST, p, &p);
1826 encode_klass_ref (acfg, gclass, p, &p);
1827 encode_value (inst->type_argc, p, &p);
1828 for (i = 0; i < inst->type_argc; ++i)
1829 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1831 } else if (klass->type_token) {
1832 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1833 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1834 encode_value (get_image_index (acfg, klass->image), p, &p);
1835 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1836 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1837 g_assert (container);
1839 /* Marker */
1840 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1841 encode_value (klass->byval_arg.type, p, &p);
1843 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1845 encode_value (container->is_method, p, &p);
1846 if (container->is_method)
1847 encode_method_ref (acfg, container->owner.method, p, &p);
1848 else
1849 encode_klass_ref (acfg, container->owner.klass, p, &p);
1850 } else {
1851 /* Array class */
1852 g_assert (klass->rank > 0);
1853 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1854 encode_value (get_image_index (acfg, klass->image), p, &p);
1855 encode_value (klass->rank, p, &p);
1856 encode_klass_ref (acfg, klass->element_class, p, &p);
1858 *endbuf = p;
1861 static void
1862 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1864 guint32 token = mono_get_field_token (field);
1865 guint8 *p = buf;
1867 encode_klass_ref (cfg, field->parent, p, &p);
1868 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1869 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1870 *endbuf = p;
1873 static void
1874 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1876 guint8 *p = buf;
1877 int i;
1878 MonoGenericInst *inst;
1880 /* Encode the context */
1881 inst = context->class_inst;
1882 encode_value (inst ? 1 : 0, p, &p);
1883 if (inst) {
1884 encode_value (inst->type_argc, p, &p);
1885 for (i = 0; i < inst->type_argc; ++i)
1886 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1888 inst = context->method_inst;
1889 encode_value (inst ? 1 : 0, p, &p);
1890 if (inst) {
1891 encode_value (inst->type_argc, p, &p);
1892 for (i = 0; i < inst->type_argc; ++i)
1893 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1896 *endbuf = p;
1899 #define MAX_IMAGE_INDEX 250
1901 static void
1902 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1904 guint32 image_index = get_image_index (acfg, method->klass->image);
1905 guint32 token = method->token;
1906 MonoJumpInfoToken *ji;
1907 guint8 *p = buf;
1908 char *name;
1911 * The encoding for most methods is as follows:
1912 * - image index encoded as a leb128
1913 * - token index encoded as a leb128
1914 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1915 * types of method encodings.
1918 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1920 /* Mark methods which can't use aot trampolines because they need the further
1921 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1923 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1924 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1925 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1928 * Some wrapper methods are shared using their signature, encode their
1929 * stringified signature instead.
1930 * FIXME: Optimize disk usage
1932 name = NULL;
1933 if (method->wrapper_type) {
1934 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1935 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1936 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1937 name = mono_aot_wrapper_name (method);
1938 } else if (mono_marshal_method_from_wrapper (method) != method) {
1939 /* Direct wrapper, encode it normally */
1940 } else {
1941 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1943 g_free (tmpsig);
1944 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1945 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1946 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1947 g_free (tmpsig);
1948 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1949 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1950 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1951 g_free (tmpsig);
1952 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1953 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1954 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1955 g_free (tmpsig);
1959 if (name) {
1960 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1961 strcpy ((char*)p, name);
1962 p += strlen (name) + 1;
1963 g_free (name);
1964 } else if (method->wrapper_type) {
1965 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1967 encode_value (method->wrapper_type, p, &p);
1969 switch (method->wrapper_type) {
1970 case MONO_WRAPPER_REMOTING_INVOKE:
1971 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1972 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1973 MonoMethod *m;
1975 m = mono_marshal_method_from_wrapper (method);
1976 g_assert (m);
1977 encode_method_ref (acfg, m, p, &p);
1978 break;
1980 case MONO_WRAPPER_PROXY_ISINST:
1981 case MONO_WRAPPER_LDFLD:
1982 case MONO_WRAPPER_LDFLDA:
1983 case MONO_WRAPPER_STFLD:
1984 case MONO_WRAPPER_ISINST: {
1985 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1986 encode_klass_ref (acfg, proxy_class, p, &p);
1987 break;
1989 case MONO_WRAPPER_LDFLD_REMOTE:
1990 case MONO_WRAPPER_STFLD_REMOTE:
1991 break;
1992 case MONO_WRAPPER_ALLOC: {
1993 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1995 /* The GC name is saved once in MonoAotFileInfo */
1996 g_assert (info->alloc_type != -1);
1997 encode_value (info->alloc_type, p, &p);
1998 break;
2000 case MONO_WRAPPER_WRITE_BARRIER:
2001 break;
2002 case MONO_WRAPPER_STELEMREF: {
2003 MonoClass *klass = mono_marshal_get_wrapper_info (method);
2005 /* Make sure this is the 'normal' stelemref wrapper, not the virtual one */
2006 g_assert (!klass);
2007 break;
2009 case MONO_WRAPPER_UNKNOWN:
2010 if (strcmp (method->name, "FastMonitorEnter") == 0) {
2011 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
2012 } else if (strcmp (method->name, "FastMonitorExit") == 0) {
2013 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
2014 } else if (strcmp (method->name, "PtrToStructure") == 0) {
2015 encode_value (MONO_AOT_WRAPPER_PTR_TO_STRUCTURE, p, &p);
2016 encode_klass_ref (acfg, method->klass, p, &p);
2017 } else if (strcmp (method->name, "StructureToPtr") == 0) {
2018 encode_value (MONO_AOT_WRAPPER_STRUCTURE_TO_PTR, p, &p);
2019 encode_klass_ref (acfg, method->klass, p, &p);
2020 } else {
2021 g_assert_not_reached ();
2023 break;
2024 case MONO_WRAPPER_SYNCHRONIZED:
2025 case MONO_WRAPPER_MANAGED_TO_NATIVE:
2026 case MONO_WRAPPER_RUNTIME_INVOKE: {
2027 MonoMethod *m;
2029 m = mono_marshal_method_from_wrapper (method);
2030 g_assert (m);
2031 g_assert (m != method);
2032 encode_method_ref (acfg, m, p, &p);
2033 break;
2035 case MONO_WRAPPER_MANAGED_TO_MANAGED:
2036 if (!strcmp (method->name, "ElementAddr")) {
2037 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2039 g_assert (info);
2040 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
2041 encode_value (info->rank, p, &p);
2042 encode_value (info->elem_size, p, &p);
2043 } else {
2044 g_assert_not_reached ();
2046 break;
2047 case MONO_WRAPPER_CASTCLASS:
2048 if (!strcmp (method->name, "__castclass_with_cache")) {
2049 encode_value (MONO_AOT_WRAPPER_CASTCLASS_WITH_CACHE, p, &p);
2050 } else if (!strcmp (method->name, "__isinst_with_cache")) {
2051 encode_value (MONO_AOT_WRAPPER_ISINST_WITH_CACHE, p, &p);
2052 } else {
2053 g_assert_not_reached ();
2055 break;
2056 default:
2057 g_assert_not_reached ();
2059 } else if (mono_method_signature (method)->is_inflated) {
2061 * This is a generic method, find the original token which referenced it and
2062 * encode that.
2063 * Obtain the token from information recorded by the JIT.
2065 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2066 if (ji) {
2067 image_index = get_image_index (acfg, ji->image);
2068 g_assert (image_index < MAX_IMAGE_INDEX);
2069 token = ji->token;
2071 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2072 encode_value (image_index, p, &p);
2073 encode_value (token, p, &p);
2074 } else {
2075 MonoMethod *declaring;
2076 MonoGenericContext *context = mono_method_get_context (method);
2078 g_assert (method->is_inflated);
2079 declaring = ((MonoMethodInflated*)method)->declaring;
2082 * This might be a non-generic method of a generic instance, which
2083 * doesn't have a token since the reference is generated by the JIT
2084 * like Nullable:Box/Unbox, or by generic sharing.
2087 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2088 /* Encode the klass */
2089 encode_klass_ref (acfg, method->klass, p, &p);
2090 /* Encode the method */
2091 image_index = get_image_index (acfg, method->klass->image);
2092 g_assert (image_index < MAX_IMAGE_INDEX);
2093 g_assert (declaring->token);
2094 token = declaring->token;
2095 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2096 encode_value (image_index, p, &p);
2097 encode_value (token, p, &p);
2098 encode_generic_context (acfg, context, p, &p);
2100 } else if (token == 0) {
2101 /* This might be a method of a constructed type like int[,].Set */
2102 /* Obtain the token from information recorded by the JIT */
2103 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2104 if (ji) {
2105 image_index = get_image_index (acfg, ji->image);
2106 g_assert (image_index < MAX_IMAGE_INDEX);
2107 token = ji->token;
2109 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2110 encode_value (image_index, p, &p);
2111 encode_value (token, p, &p);
2112 } else {
2113 /* Array methods */
2114 g_assert (method->klass->rank);
2116 /* Encode directly */
2117 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2118 encode_klass_ref (acfg, method->klass, p, &p);
2119 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2120 encode_value (0, p, &p);
2121 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2122 encode_value (1, p, &p);
2123 else if (!strcmp (method->name, "Get"))
2124 encode_value (2, p, &p);
2125 else if (!strcmp (method->name, "Address"))
2126 encode_value (3, p, &p);
2127 else if (!strcmp (method->name, "Set"))
2128 encode_value (4, p, &p);
2129 else
2130 g_assert_not_reached ();
2132 } else {
2133 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2134 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2136 *endbuf = p;
2139 static gint
2140 compare_patches (gconstpointer a, gconstpointer b)
2142 int i, j;
2144 i = (*(MonoJumpInfo**)a)->ip.i;
2145 j = (*(MonoJumpInfo**)b)->ip.i;
2147 if (i < j)
2148 return -1;
2149 else
2150 if (i > j)
2151 return 1;
2152 else
2153 return 0;
2156 static G_GNUC_UNUSED char*
2157 patch_to_string (MonoJumpInfo *patch_info)
2159 GString *str;
2161 str = g_string_new ("");
2163 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2165 switch (patch_info->type) {
2166 case MONO_PATCH_INFO_VTABLE:
2167 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2168 break;
2169 default:
2170 break;
2172 g_string_append_printf (str, ")");
2173 return g_string_free (str, FALSE);
2177 * is_plt_patch:
2179 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2180 * PLT entry.
2182 static inline gboolean
2183 is_plt_patch (MonoJumpInfo *patch_info)
2185 switch (patch_info->type) {
2186 case MONO_PATCH_INFO_METHOD:
2187 case MONO_PATCH_INFO_INTERNAL_METHOD:
2188 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2189 case MONO_PATCH_INFO_ICALL_ADDR:
2190 case MONO_PATCH_INFO_CLASS_INIT:
2191 case MONO_PATCH_INFO_RGCTX_FETCH:
2192 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2193 case MONO_PATCH_INFO_MONITOR_ENTER:
2194 case MONO_PATCH_INFO_MONITOR_EXIT:
2195 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2196 return TRUE;
2197 default:
2198 return FALSE;
2203 * get_plt_symbol:
2205 * Return the symbol identifying the plt entry PLT_OFFSET.
2207 static char*
2208 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2210 #ifdef __APPLE__
2212 * The Apple linker reorganizes object files, so it doesn't like branches to local
2213 * labels, since those have no relocations.
2215 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2216 #else
2217 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2218 #endif
2222 * get_plt_entry:
2224 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2226 static MonoPltEntry*
2227 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2229 MonoPltEntry *res;
2231 if (!is_plt_patch (patch_info))
2232 return NULL;
2234 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2236 // FIXME: This breaks the calculation of final_got_size
2237 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2239 * Allocate a separate PLT slot for each such patch, since some plt
2240 * entries will refer to the method itself, and some will refer to the
2241 * wrapper.
2243 res = NULL;
2246 if (!res) {
2247 MonoJumpInfo *new_ji;
2249 g_assert (!acfg->final_got_size);
2251 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2253 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2254 res->plt_offset = acfg->plt_offset;
2255 res->ji = new_ji;
2256 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2257 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2259 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2261 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2263 acfg->plt_offset ++;
2266 return res;
2270 * get_got_offset:
2272 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2273 * JI could be found if it exists, otherwise allocates a new one.
2275 static guint32
2276 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2278 guint32 got_offset;
2280 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2281 if (got_offset)
2282 return got_offset - 1;
2284 got_offset = acfg->got_offset;
2285 acfg->got_offset ++;
2287 if (acfg->final_got_size)
2288 g_assert (got_offset < acfg->final_got_size);
2290 acfg->stats.got_slots ++;
2291 acfg->stats.got_slot_types [ji->type] ++;
2293 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2294 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2295 g_ptr_array_add (acfg->got_patches, ji);
2297 return got_offset;
2300 /* Add a method to the list of methods which need to be emitted */
2301 static void
2302 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2304 g_assert (method);
2305 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2306 g_ptr_array_add (acfg->methods, method);
2307 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2308 acfg->nmethods = acfg->methods->len + 1;
2311 if (method->wrapper_type || extra)
2312 g_ptr_array_add (acfg->extra_methods, method);
2315 static guint32
2316 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2318 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2320 g_assert (index);
2322 return index - 1;
2325 static int
2326 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2328 int index;
2330 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2331 if (index)
2332 return index - 1;
2334 index = acfg->method_index;
2335 add_method_with_index (acfg, method, index, extra);
2337 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2339 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2341 acfg->method_index ++;
2343 return index;
2346 static int
2347 add_method (MonoAotCompile *acfg, MonoMethod *method)
2349 return add_method_full (acfg, method, FALSE, 0);
2352 static void
2353 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2355 add_method_full (acfg, method, TRUE, 0);
2358 static void
2359 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2361 add_method_full (acfg, method, TRUE, depth);
2364 static void
2365 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2367 MonoAotCompile *acfg = user_data;
2368 MonoJitICallInfo *callinfo = value;
2369 MonoMethod *wrapper;
2370 char *name;
2372 if (!callinfo->sig)
2373 return;
2375 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2376 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2377 g_free (name);
2379 add_method (acfg, wrapper);
2382 static MonoMethod*
2383 get_runtime_invoke_sig (MonoMethodSignature *sig)
2385 MonoMethodBuilder *mb;
2386 MonoMethod *m;
2388 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2389 m = mono_mb_create_method (mb, sig, 16);
2390 return mono_marshal_get_runtime_invoke (m, FALSE);
2393 static gboolean
2394 can_marshal_struct (MonoClass *klass)
2396 MonoClassField *field;
2397 gboolean can_marshal = TRUE;
2398 gpointer iter = NULL;
2400 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2401 return FALSE;
2403 /* Only allow a few field types to avoid asserts in the marshalling code */
2404 while ((field = mono_class_get_fields (klass, &iter))) {
2405 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2406 continue;
2408 switch (field->type->type) {
2409 case MONO_TYPE_I4:
2410 case MONO_TYPE_U4:
2411 case MONO_TYPE_I1:
2412 case MONO_TYPE_U1:
2413 case MONO_TYPE_BOOLEAN:
2414 case MONO_TYPE_I2:
2415 case MONO_TYPE_U2:
2416 case MONO_TYPE_CHAR:
2417 case MONO_TYPE_I8:
2418 case MONO_TYPE_U8:
2419 case MONO_TYPE_I:
2420 case MONO_TYPE_U:
2421 case MONO_TYPE_PTR:
2422 case MONO_TYPE_R4:
2423 case MONO_TYPE_R8:
2424 case MONO_TYPE_STRING:
2425 break;
2426 case MONO_TYPE_VALUETYPE:
2427 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2428 can_marshal = FALSE;
2429 break;
2430 default:
2431 can_marshal = FALSE;
2432 break;
2436 /* Special cases */
2437 /* Its hard to compute whenever these can be marshalled or not */
2438 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2439 return TRUE;
2441 return can_marshal;
2444 static void
2445 add_wrappers (MonoAotCompile *acfg)
2447 MonoMethod *method, *m;
2448 int i, j;
2449 MonoMethodSignature *sig, *csig;
2450 guint32 token;
2453 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2454 * so there is only one wrapper of a given type, or inlining their contents into their
2455 * callers.
2459 * FIXME: This depends on the fact that different wrappers have different
2460 * names.
2463 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2464 MonoMethod *method;
2465 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2466 gboolean skip = FALSE;
2468 method = mono_get_method (acfg->image, token, NULL);
2470 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2471 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2472 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2473 skip = TRUE;
2475 if (method->is_generic || method->klass->generic_container)
2476 skip = TRUE;
2478 /* Skip methods which can not be handled by get_runtime_invoke () */
2479 sig = mono_method_signature (method);
2480 if (!sig)
2481 continue;
2482 if ((sig->ret->type == MONO_TYPE_PTR) ||
2483 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2484 skip = TRUE;
2486 for (j = 0; j < sig->param_count; j++) {
2487 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2488 skip = TRUE;
2491 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2492 if (!method->klass->contextbound) {
2493 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2494 gboolean has_nullable = FALSE;
2496 for (j = 0; j < sig->param_count; j++) {
2497 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2498 has_nullable = TRUE;
2501 if (info && !has_nullable) {
2502 /* Supported by the dynamic runtime-invoke wrapper */
2503 skip = TRUE;
2504 g_free (info);
2507 #endif
2509 if (!skip) {
2510 //printf ("%s\n", mono_method_full_name (method, TRUE));
2511 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2515 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2516 #ifdef MONO_ARCH_HAVE_TLS_GET
2517 MonoMethodDesc *desc;
2518 MonoMethod *orig_method;
2519 int nallocators;
2520 #endif
2522 /* Runtime invoke wrappers */
2524 /* void runtime-invoke () [.cctor] */
2525 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2526 csig->ret = &mono_defaults.void_class->byval_arg;
2527 add_method (acfg, get_runtime_invoke_sig (csig));
2529 /* void runtime-invoke () [Finalize] */
2530 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2531 csig->hasthis = 1;
2532 csig->ret = &mono_defaults.void_class->byval_arg;
2533 add_method (acfg, get_runtime_invoke_sig (csig));
2535 /* void runtime-invoke (string) [exception ctor] */
2536 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2537 csig->hasthis = 1;
2538 csig->ret = &mono_defaults.void_class->byval_arg;
2539 csig->params [0] = &mono_defaults.string_class->byval_arg;
2540 add_method (acfg, get_runtime_invoke_sig (csig));
2542 /* void runtime-invoke (string, string) [exception ctor] */
2543 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2544 csig->hasthis = 1;
2545 csig->ret = &mono_defaults.void_class->byval_arg;
2546 csig->params [0] = &mono_defaults.string_class->byval_arg;
2547 csig->params [1] = &mono_defaults.string_class->byval_arg;
2548 add_method (acfg, get_runtime_invoke_sig (csig));
2550 /* string runtime-invoke () [Exception.ToString ()] */
2551 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2552 csig->hasthis = 1;
2553 csig->ret = &mono_defaults.string_class->byval_arg;
2554 add_method (acfg, get_runtime_invoke_sig (csig));
2556 /* void runtime-invoke (string, Exception) [exception ctor] */
2557 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2558 csig->hasthis = 1;
2559 csig->ret = &mono_defaults.void_class->byval_arg;
2560 csig->params [0] = &mono_defaults.string_class->byval_arg;
2561 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2562 add_method (acfg, get_runtime_invoke_sig (csig));
2564 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2565 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2566 csig->hasthis = 1;
2567 csig->ret = &(mono_class_from_name (
2568 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2569 csig->params [0] = &mono_defaults.string_class->byval_arg;
2570 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2571 add_method (acfg, get_runtime_invoke_sig (csig));
2573 /* runtime-invoke used by finalizers */
2574 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2576 /* This is used by mono_runtime_capture_context () */
2577 method = mono_get_context_capture_method ();
2578 if (method)
2579 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2581 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2582 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2583 #endif
2585 /* JIT icall wrappers */
2586 /* FIXME: locking */
2587 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2589 /* stelemref */
2590 add_method (acfg, mono_marshal_get_stelemref ());
2592 #ifdef MONO_ARCH_HAVE_TLS_GET
2593 /* Managed Allocators */
2594 nallocators = mono_gc_get_managed_allocator_types ();
2595 for (i = 0; i < nallocators; ++i) {
2596 m = mono_gc_get_managed_allocator_by_type (i);
2597 if (m)
2598 add_method (acfg, m);
2601 /* Monitor Enter/Exit */
2602 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2603 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2604 g_assert (orig_method);
2605 mono_method_desc_free (desc);
2606 method = mono_monitor_get_fast_path (orig_method);
2607 if (method)
2608 add_method (acfg, method);
2610 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2611 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2612 g_assert (orig_method);
2613 mono_method_desc_free (desc);
2614 method = mono_monitor_get_fast_path (orig_method);
2615 if (method)
2616 add_method (acfg, method);
2617 #endif
2619 /* Stelemref wrappers */
2620 /* There is only a constant number of these, iterating over all types should handle them all */
2621 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2622 MonoClass *klass;
2624 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2625 klass = mono_class_get (acfg->image, token);
2626 if (klass)
2627 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2628 else
2629 mono_loader_clear_error ();
2632 /* castclass_with_check wrapper */
2633 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2634 /* isinst_with_check wrapper */
2635 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2639 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2640 * we use the original method instead at runtime.
2641 * Since full-aot doesn't support remoting, this is not a problem.
2643 #if 0
2644 /* remoting-invoke wrappers */
2645 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2646 MonoMethodSignature *sig;
2648 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2649 method = mono_get_method (acfg->image, token, NULL);
2651 sig = mono_method_signature (method);
2653 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2654 m = mono_marshal_get_remoting_invoke_with_check (method);
2656 add_method (acfg, m);
2659 #endif
2661 /* delegate-invoke wrappers */
2662 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2663 MonoClass *klass;
2665 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2666 klass = mono_class_get (acfg->image, token);
2668 if (!klass) {
2669 mono_loader_clear_error ();
2670 continue;
2673 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2674 method = mono_get_delegate_invoke (klass);
2676 m = mono_marshal_get_delegate_invoke (method, NULL);
2678 add_method (acfg, m);
2680 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2681 if (method)
2682 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2684 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2685 if (method)
2686 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2690 /* Synchronized wrappers */
2691 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2692 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2693 method = mono_get_method (acfg->image, token, NULL);
2695 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2696 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2699 /* pinvoke wrappers */
2700 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2701 MonoMethod *method;
2702 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2704 method = mono_get_method (acfg->image, token, NULL);
2706 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2707 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2708 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2712 /* native-to-managed wrappers */
2713 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2714 MonoMethod *method;
2715 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2716 MonoCustomAttrInfo *cattr;
2717 int j;
2719 method = mono_get_method (acfg->image, token, NULL);
2722 * Only generate native-to-managed wrappers for methods which have an
2723 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2724 * name to avoid defining a new assembly to contain it.
2726 cattr = mono_custom_attrs_from_method (method);
2728 if (cattr) {
2729 for (j = 0; j < cattr->num_attrs; ++j)
2730 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2731 break;
2732 if (j < cattr->num_attrs) {
2733 MonoCustomAttrEntry *e = &cattr->attrs [j];
2734 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2735 const char *p = (const char*)e->data;
2736 int slen;
2737 char *n;
2738 MonoType *t;
2739 MonoClass *klass;
2741 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
2742 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
2743 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
2744 mono_method_full_name (method, TRUE));
2745 exit (1);
2748 g_assert (sig->param_count == 1);
2749 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2752 * Decode the cattr manually since we can't create objects
2753 * during aot compilation.
2756 /* Skip prolog */
2757 p += 2;
2759 /* From load_cattr_value () in reflection.c */
2760 slen = mono_metadata_decode_value (p, &p);
2761 n = g_memdup (p, slen + 1);
2762 n [slen] = 0;
2763 t = mono_reflection_type_from_name (n, acfg->image);
2764 g_assert (t);
2765 g_free (n);
2767 klass = mono_class_from_mono_type (t);
2768 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2770 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2774 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2775 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2776 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2780 /* StructureToPtr/PtrToStructure wrappers */
2781 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2782 MonoClass *klass;
2784 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2785 klass = mono_class_get (acfg->image, token);
2787 if (!klass) {
2788 mono_loader_clear_error ();
2789 continue;
2792 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2793 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2794 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2799 static gboolean
2800 has_type_vars (MonoClass *klass)
2802 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2803 return TRUE;
2804 if (klass->rank)
2805 return has_type_vars (klass->element_class);
2806 if (klass->generic_class) {
2807 MonoGenericContext *context = &klass->generic_class->context;
2808 if (context->class_inst) {
2809 int i;
2811 for (i = 0; i < context->class_inst->type_argc; ++i)
2812 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2813 return TRUE;
2816 return FALSE;
2819 static gboolean
2820 method_has_type_vars (MonoMethod *method)
2822 if (has_type_vars (method->klass))
2823 return TRUE;
2825 if (method->is_inflated) {
2826 MonoGenericContext *context = mono_method_get_context (method);
2827 if (context->method_inst) {
2828 int i;
2830 for (i = 0; i < context->method_inst->type_argc; ++i)
2831 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2832 return TRUE;
2835 return FALSE;
2838 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2840 static void
2841 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2843 /* This might lead to a huge code blowup so only do it if neccesary */
2844 if (!acfg->aot_opts.full_aot && !force)
2845 return;
2847 add_generic_class_with_depth (acfg, klass, 0);
2850 static gboolean
2851 check_type_depth (MonoType *t, int depth)
2853 int i;
2855 if (depth > 8)
2856 return TRUE;
2858 switch (t->type) {
2859 case MONO_TYPE_GENERICINST: {
2860 MonoGenericClass *gklass = t->data.generic_class;
2861 MonoGenericInst *ginst = gklass->context.class_inst;
2863 if (ginst) {
2864 for (i = 0; i < ginst->type_argc; ++i) {
2865 if (check_type_depth (ginst->type_argv [i], depth + 1))
2866 return TRUE;
2869 break;
2871 default:
2872 break;
2875 return FALSE;
2879 * add_generic_class:
2881 * Add all methods of a generic class.
2883 static void
2884 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2886 MonoMethod *method;
2887 gpointer iter;
2889 mono_class_init (klass);
2891 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2892 return;
2894 if (has_type_vars (klass))
2895 return;
2897 if (!klass->generic_class && !klass->rank)
2898 return;
2900 if (!acfg->ginst_hash)
2901 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
2903 if (g_hash_table_lookup (acfg->ginst_hash, klass))
2904 return;
2906 if (check_type_depth (&klass->byval_arg, 0))
2907 return;
2909 g_hash_table_insert (acfg->ginst_hash, klass, klass);
2911 iter = NULL;
2912 while ((method = mono_class_get_methods (klass, &iter))) {
2913 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2914 /* Already added */
2915 continue;
2917 if (method->is_generic)
2918 /* FIXME: */
2919 continue;
2922 * FIXME: Instances which are referenced by these methods are not added,
2923 * for example Array.Resize<int> for List<int>.Add ().
2925 add_extra_method_with_depth (acfg, method, depth + 1);
2928 if (klass->delegate) {
2929 method = mono_get_delegate_invoke (klass);
2931 method = mono_marshal_get_delegate_invoke (method, NULL);
2933 add_method (acfg, method);
2936 /* Add superclasses */
2937 if (klass->parent)
2938 add_generic_class_with_depth (acfg, klass->parent, depth);
2941 * For ICollection<T>, add instances of the helper methods
2942 * in Array, since a T[] could be cast to ICollection<T>.
2944 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2945 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2946 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2947 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2948 gpointer iter;
2949 char *name_prefix;
2951 if (!strcmp (klass->name, "IEnumerator`1"))
2952 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2953 else
2954 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2956 /* Add the T[]/InternalEnumerator class */
2957 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2958 MonoClass *nclass;
2960 iter = NULL;
2961 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2962 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2963 break;
2965 g_assert (nclass);
2966 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2967 add_generic_class (acfg, nclass, FALSE);
2970 iter = NULL;
2971 while ((method = mono_class_get_methods (array_class, &iter))) {
2972 if (strstr (method->name, name_prefix)) {
2973 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2974 add_extra_method_with_depth (acfg, m, depth);
2978 g_free (name_prefix);
2981 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2982 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2983 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2984 MonoClass *icomparable, *gcomparer;
2985 MonoGenericContext ctx;
2986 MonoType *args [16];
2988 memset (&ctx, 0, sizeof (ctx));
2990 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2991 g_assert (icomparable);
2992 args [0] = &tclass->byval_arg;
2993 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2995 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2996 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2997 g_assert (gcomparer);
2998 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3002 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3003 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3004 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3005 MonoClass *iface, *gcomparer;
3006 MonoGenericContext ctx;
3007 MonoType *args [16];
3009 memset (&ctx, 0, sizeof (ctx));
3011 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3012 g_assert (iface);
3013 args [0] = &tclass->byval_arg;
3014 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3016 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3017 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3018 g_assert (gcomparer);
3019 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3024 static void
3025 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3027 int i;
3028 MonoGenericContext ctx;
3029 MonoType *args [16];
3031 memset (&ctx, 0, sizeof (ctx));
3033 for (i = 0; i < ninsts; ++i) {
3034 args [0] = insts [i];
3035 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3036 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
3040 static void
3041 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3043 MonoMethodHeader *header;
3044 MonoMethodSignature *sig;
3045 int j, depth;
3047 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3049 sig = mono_method_signature (method);
3051 if (sig) {
3052 for (j = 0; j < sig->param_count; ++j)
3053 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3054 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1);
3057 header = mono_method_get_header (method);
3059 if (header) {
3060 for (j = 0; j < header->num_locals; ++j)
3061 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3062 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1);
3067 * add_generic_instances:
3069 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3071 static void
3072 add_generic_instances (MonoAotCompile *acfg)
3074 int i;
3075 guint32 token;
3076 MonoMethod *method;
3077 MonoGenericContext *context;
3079 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3080 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3081 method = mono_get_method (acfg->image, token, NULL);
3083 if (!method)
3084 continue;
3086 if (method->klass->image != acfg->image)
3087 continue;
3089 context = mono_method_get_context (method);
3091 if (context && ((context->class_inst && context->class_inst->is_open)))
3092 continue;
3095 * For open methods, create an instantiation which can be passed to the JIT.
3096 * FIXME: Handle class_inst as well.
3098 if (context && context->method_inst && context->method_inst->is_open) {
3099 MonoGenericContext shared_context;
3100 MonoGenericInst *inst;
3101 MonoType **type_argv;
3102 int i;
3103 MonoMethod *declaring_method;
3104 gboolean supported = TRUE;
3106 /* Check that the context doesn't contain open constructed types */
3107 if (context->class_inst) {
3108 inst = context->class_inst;
3109 for (i = 0; i < inst->type_argc; ++i) {
3110 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)
3111 continue;
3112 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3113 supported = FALSE;
3116 if (context->method_inst) {
3117 inst = context->method_inst;
3118 for (i = 0; i < inst->type_argc; ++i) {
3119 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)
3120 continue;
3121 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3122 supported = FALSE;
3126 if (!supported)
3127 continue;
3129 memset (&shared_context, 0, sizeof (MonoGenericContext));
3131 inst = context->class_inst;
3132 if (inst) {
3133 type_argv = g_new0 (MonoType*, inst->type_argc);
3134 for (i = 0; i < inst->type_argc; ++i) {
3135 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)
3136 type_argv [i] = &mono_defaults.object_class->byval_arg;
3137 else
3138 type_argv [i] = inst->type_argv [i];
3141 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3142 g_free (type_argv);
3145 inst = context->method_inst;
3146 if (inst) {
3147 type_argv = g_new0 (MonoType*, inst->type_argc);
3148 for (i = 0; i < inst->type_argc; ++i) {
3149 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)
3150 type_argv [i] = &mono_defaults.object_class->byval_arg;
3151 else
3152 type_argv [i] = inst->type_argv [i];
3155 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3156 g_free (type_argv);
3159 if (method->is_generic || method->klass->generic_container)
3160 declaring_method = method;
3161 else
3162 declaring_method = mono_method_get_declaring_generic_method (method);
3164 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3168 * If the method is fully sharable, it was already added in place of its
3169 * generic definition.
3171 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3172 continue;
3175 * FIXME: Partially shared methods are not shared here, so we end up with
3176 * many identical methods.
3178 add_extra_method (acfg, method);
3181 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3182 MonoClass *klass;
3184 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3186 klass = mono_class_get (acfg->image, token);
3187 if (!klass || klass->rank) {
3188 mono_loader_clear_error ();
3189 continue;
3192 add_generic_class (acfg, klass, FALSE);
3195 /* Add types of args/locals */
3196 for (i = 0; i < acfg->methods->len; ++i) {
3197 method = g_ptr_array_index (acfg->methods, i);
3198 add_types_from_method_header (acfg, method);
3201 if (acfg->image == mono_defaults.corlib) {
3202 MonoClass *klass;
3203 MonoType *insts [256];
3204 int ninsts = 0;
3206 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3207 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3208 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3209 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3210 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3211 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3212 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3213 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3214 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3215 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3216 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3217 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3219 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3220 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3221 if (klass)
3222 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3223 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3224 if (klass)
3225 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3227 /* Add instances of the array generic interfaces for primitive types */
3228 /* This will add instances of the InternalArray_ helper methods in Array too */
3229 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3230 if (klass)
3231 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3232 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3233 if (klass)
3234 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3235 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3236 if (klass)
3237 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3240 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3241 * used for all instances of GetGenericValueImpl by the AOT runtime.
3244 MonoGenericContext ctx;
3245 MonoType *args [16];
3246 MonoMethod *get_method;
3247 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3249 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3251 if (get_method) {
3252 memset (&ctx, 0, sizeof (ctx));
3253 args [0] = &mono_defaults.object_class->byval_arg;
3254 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3255 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3259 /* Same for CompareExchange<T>/Exchange<T> */
3261 MonoGenericContext ctx;
3262 MonoType *args [16];
3263 MonoMethod *m;
3264 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3265 gpointer iter = NULL;
3267 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
3268 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
3269 memset (&ctx, 0, sizeof (ctx));
3270 args [0] = &mono_defaults.object_class->byval_arg;
3271 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3272 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
3280 * is_direct_callable:
3282 * Return whenever the method identified by JI is directly callable without
3283 * going through the PLT.
3285 static gboolean
3286 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3288 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3289 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3290 if (callee_cfg) {
3291 gboolean direct_callable = TRUE;
3293 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3294 direct_callable = FALSE;
3295 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3296 // FIXME: Maybe call the wrapper directly ?
3297 direct_callable = FALSE;
3299 if (direct_callable)
3300 return TRUE;
3302 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3303 if (acfg->aot_opts.direct_pinvoke)
3304 return TRUE;
3307 return FALSE;
3310 static const char *
3311 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
3313 MonoImage *image = method->klass->image;
3314 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
3315 MonoTableInfo *tables = image->tables;
3316 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3317 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3318 guint32 im_cols [MONO_IMPLMAP_SIZE];
3319 char *import;
3320 const char *prefix;
3322 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
3323 if (import != NULL)
3324 return import;
3326 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
3327 return NULL;
3329 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3331 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
3332 return NULL;
3334 #if defined(__APPLE__)
3335 prefix = "_";
3336 #else
3337 prefix = "";
3338 #endif
3340 import = g_strdup_printf ("%s%s", prefix, mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
3342 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
3344 return import;
3348 * emit_and_reloc_code:
3350 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3351 * is true, calls are made through the GOT too. This is used for emitting trampolines
3352 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3353 * since trampolines are needed to make PTL work.
3355 static void
3356 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3358 int i, pindex, start_index, method_index;
3359 GPtrArray *patches;
3360 MonoJumpInfo *patch_info;
3361 MonoMethodHeader *header;
3362 gboolean skip, direct_call;
3363 guint32 got_slot;
3364 char direct_call_target [1024];
3365 const char *direct_pinvoke;
3367 if (method) {
3368 header = mono_method_get_header (method);
3370 method_index = get_method_index (acfg, method);
3373 /* Collect and sort relocations */
3374 patches = g_ptr_array_new ();
3375 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3376 g_ptr_array_add (patches, patch_info);
3377 g_ptr_array_sort (patches, compare_patches);
3379 start_index = 0;
3380 for (i = 0; i < code_len; i++) {
3381 patch_info = NULL;
3382 for (pindex = start_index; pindex < patches->len; ++pindex) {
3383 patch_info = g_ptr_array_index (patches, pindex);
3384 if (patch_info->ip.i >= i)
3385 break;
3388 #ifdef MONO_ARCH_AOT_SUPPORTED
3389 skip = FALSE;
3390 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3391 start_index = pindex;
3393 switch (patch_info->type) {
3394 case MONO_PATCH_INFO_NONE:
3395 break;
3396 case MONO_PATCH_INFO_GOT_OFFSET: {
3397 int code_size;
3399 arch_emit_got_offset (acfg, code + i, &code_size);
3400 i += code_size - 1;
3401 skip = TRUE;
3402 patch_info->type = MONO_PATCH_INFO_NONE;
3403 break;
3405 default: {
3407 * If this patch is a call, try emitting a direct call instead of
3408 * through a PLT entry. This is possible if the called method is in
3409 * the same assembly and requires no initialization.
3411 direct_call = FALSE;
3412 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3413 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3414 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3415 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3416 direct_call = TRUE;
3417 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3418 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3419 patch_info->type = MONO_PATCH_INFO_NONE;
3420 acfg->stats.direct_calls ++;
3423 acfg->stats.all_calls ++;
3424 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) && (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3425 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3426 direct_call = TRUE;
3427 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
3428 g_assert (strlen (direct_pinvoke) < 1000);
3429 sprintf (direct_call_target, "%s", direct_pinvoke);
3430 patch_info->type = MONO_PATCH_INFO_NONE;
3431 acfg->stats.direct_calls ++;
3435 if (!got_only && !direct_call) {
3436 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3437 if (plt_entry) {
3438 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3439 direct_call = TRUE;
3440 sprintf (direct_call_target, "%s", plt_entry->symbol);
3442 /* Nullify the patch */
3443 patch_info->type = MONO_PATCH_INFO_NONE;
3444 plt_entry->jit_used = TRUE;
3448 if (direct_call) {
3449 int call_size;
3451 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3452 i += call_size - 1;
3453 } else {
3454 int code_size;
3456 got_slot = get_got_offset (acfg, patch_info);
3458 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3459 i += code_size - 1;
3461 skip = TRUE;
3465 #endif /* MONO_ARCH_AOT_SUPPORTED */
3467 if (!skip) {
3468 /* Find next patch */
3469 patch_info = NULL;
3470 for (pindex = start_index; pindex < patches->len; ++pindex) {
3471 patch_info = g_ptr_array_index (patches, pindex);
3472 if (patch_info->ip.i >= i)
3473 break;
3476 /* Try to emit multiple bytes at once */
3477 if (pindex < patches->len && patch_info->ip.i > i) {
3478 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3479 i = patch_info->ip.i - 1;
3480 } else {
3481 emit_bytes (acfg, code + i, 1);
3488 * sanitize_symbol:
3490 * Modify SYMBOL so it only includes characters permissible in symbols.
3492 static void
3493 sanitize_symbol (char *symbol)
3495 int i, len = strlen (symbol);
3497 for (i = 0; i < len; ++i)
3498 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3499 symbol [i] = '_';
3502 static char*
3503 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3505 char *name1, *name2, *cached;
3506 int i, j, len, count;
3508 name1 = mono_method_full_name (method, TRUE);
3509 len = strlen (name1);
3510 name2 = malloc (strlen (prefix) + len + 16);
3511 memcpy (name2, prefix, strlen (prefix));
3512 j = strlen (prefix);
3513 for (i = 0; i < len; ++i) {
3514 if (isalnum (name1 [i])) {
3515 name2 [j ++] = name1 [i];
3516 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3517 i += 2;
3518 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3519 name2 [j ++] = '_';
3520 i++;
3521 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3522 } else
3523 name2 [j ++] = '_';
3525 name2 [j] = '\0';
3527 g_free (name1);
3529 count = 0;
3530 while (g_hash_table_lookup (cache, name2)) {
3531 sprintf (name2 + j, "_%d", count);
3532 count ++;
3535 cached = g_strdup (name2);
3536 g_hash_table_insert (cache, cached, cached);
3538 return name2;
3541 static void
3542 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3544 MonoMethod *method;
3545 int method_index;
3546 guint8 *code;
3547 char *debug_sym = NULL;
3548 char symbol [128];
3549 int func_alignment = AOT_FUNC_ALIGNMENT;
3550 MonoMethodHeader *header;
3552 method = cfg->orig_method;
3553 code = cfg->native_code;
3554 header = cfg->header;
3556 method_index = get_method_index (acfg, method);
3558 /* Make the labels local */
3559 sprintf (symbol, "%s", cfg->asm_symbol);
3561 emit_section_change (acfg, ".text", 0);
3562 emit_alignment (acfg, func_alignment);
3563 emit_label (acfg, symbol);
3565 if (acfg->aot_opts.write_symbols) {
3567 * Write a C style symbol for every method, this has two uses:
3568 * - it works on platforms where the dwarf debugging info is not
3569 * yet supported.
3570 * - it allows the setting of breakpoints of aot-ed methods.
3572 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3574 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3575 if (acfg->need_no_dead_strip)
3576 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
3577 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3578 emit_label (acfg, debug_sym);
3581 if (cfg->verbose_level > 0)
3582 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3584 acfg->stats.code_size += cfg->code_len;
3586 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3588 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3590 emit_line (acfg);
3592 if (acfg->aot_opts.write_symbols) {
3593 emit_symbol_size (acfg, debug_sym, ".");
3594 g_free (debug_sym);
3597 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3598 emit_label (acfg, symbol);
3602 * encode_patch:
3604 * Encode PATCH_INFO into its disk representation.
3606 static void
3607 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3609 guint8 *p = buf;
3611 switch (patch_info->type) {
3612 case MONO_PATCH_INFO_NONE:
3613 break;
3614 case MONO_PATCH_INFO_IMAGE:
3615 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3616 break;
3617 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3618 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3619 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3620 break;
3621 case MONO_PATCH_INFO_METHOD_REL:
3622 encode_value ((gint)patch_info->data.offset, p, &p);
3623 break;
3624 case MONO_PATCH_INFO_SWITCH: {
3625 gpointer *table = (gpointer *)patch_info->data.table->table;
3626 int k;
3628 encode_value (patch_info->data.table->table_size, p, &p);
3629 for (k = 0; k < patch_info->data.table->table_size; k++)
3630 encode_value ((int)(gssize)table [k], p, &p);
3631 break;
3633 case MONO_PATCH_INFO_METHODCONST:
3634 case MONO_PATCH_INFO_METHOD:
3635 case MONO_PATCH_INFO_METHOD_JUMP:
3636 case MONO_PATCH_INFO_ICALL_ADDR:
3637 case MONO_PATCH_INFO_METHOD_RGCTX:
3638 encode_method_ref (acfg, patch_info->data.method, p, &p);
3639 break;
3640 case MONO_PATCH_INFO_INTERNAL_METHOD:
3641 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3642 guint32 len = strlen (patch_info->data.name);
3644 encode_value (len, p, &p);
3646 memcpy (p, patch_info->data.name, len);
3647 p += len;
3648 *p++ = '\0';
3649 break;
3651 case MONO_PATCH_INFO_LDSTR: {
3652 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3653 guint32 token = patch_info->data.token->token;
3654 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3655 encode_value (image_index, p, &p);
3656 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3657 break;
3659 case MONO_PATCH_INFO_RVA:
3660 case MONO_PATCH_INFO_DECLSEC:
3661 case MONO_PATCH_INFO_LDTOKEN:
3662 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3663 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3664 encode_value (patch_info->data.token->token, p, &p);
3665 encode_value (patch_info->data.token->has_context, p, &p);
3666 if (patch_info->data.token->has_context)
3667 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3668 break;
3669 case MONO_PATCH_INFO_EXC_NAME: {
3670 MonoClass *ex_class;
3672 ex_class =
3673 mono_class_from_name (mono_defaults.exception_class->image,
3674 "System", patch_info->data.target);
3675 g_assert (ex_class);
3676 encode_klass_ref (acfg, ex_class, p, &p);
3677 break;
3679 case MONO_PATCH_INFO_R4:
3680 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3681 break;
3682 case MONO_PATCH_INFO_R8:
3683 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3684 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3685 break;
3686 case MONO_PATCH_INFO_VTABLE:
3687 case MONO_PATCH_INFO_CLASS:
3688 case MONO_PATCH_INFO_IID:
3689 case MONO_PATCH_INFO_ADJUSTED_IID:
3690 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3691 break;
3692 case MONO_PATCH_INFO_CLASS_INIT:
3693 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3694 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3695 break;
3696 case MONO_PATCH_INFO_FIELD:
3697 case MONO_PATCH_INFO_SFLDA:
3698 encode_field_info (acfg, patch_info->data.field, p, &p);
3699 break;
3700 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3701 break;
3702 case MONO_PATCH_INFO_RGCTX_FETCH: {
3703 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3705 encode_method_ref (acfg, entry->method, p, &p);
3706 encode_value (entry->in_mrgctx, p, &p);
3707 encode_value (entry->info_type, p, &p);
3708 encode_value (entry->data->type, p, &p);
3709 encode_patch (acfg, entry->data, p, &p);
3710 break;
3712 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3713 case MONO_PATCH_INFO_MONITOR_ENTER:
3714 case MONO_PATCH_INFO_MONITOR_EXIT:
3715 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3716 break;
3717 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3718 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3719 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3720 break;
3721 default:
3722 g_warning ("unable to handle jump info %d", patch_info->type);
3723 g_assert_not_reached ();
3726 *endbuf = p;
3729 static void
3730 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3732 guint8 *p = buf;
3733 guint32 pindex, offset;
3734 MonoJumpInfo *patch_info;
3736 encode_value (n_patches, p, &p);
3738 for (pindex = 0; pindex < patches->len; ++pindex) {
3739 patch_info = g_ptr_array_index (patches, pindex);
3741 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3742 /* Nothing to do */
3743 continue;
3745 offset = get_got_offset (acfg, patch_info);
3746 encode_value (offset, p, &p);
3749 *endbuf = p;
3752 static void
3753 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3755 MonoMethod *method;
3756 GList *l;
3757 int pindex, buf_size, n_patches;
3758 guint8 *code;
3759 GPtrArray *patches;
3760 MonoJumpInfo *patch_info;
3761 MonoMethodHeader *header;
3762 guint32 method_index;
3763 guint8 *p, *buf;
3764 guint32 first_got_offset;
3766 method = cfg->orig_method;
3767 code = cfg->native_code;
3768 header = mono_method_get_header (method);
3770 method_index = get_method_index (acfg, method);
3772 /* Sort relocations */
3773 patches = g_ptr_array_new ();
3774 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3775 g_ptr_array_add (patches, patch_info);
3776 g_ptr_array_sort (patches, compare_patches);
3778 first_got_offset = acfg->cfgs [method_index]->got_offset;
3780 /**********************/
3781 /* Encode method info */
3782 /**********************/
3784 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3785 p = buf = g_malloc (buf_size);
3787 if (mono_class_get_cctor (method->klass))
3788 encode_klass_ref (acfg, method->klass, p, &p);
3789 else
3790 /* Not needed when loading the method */
3791 encode_value (0, p, &p);
3793 /* String table */
3794 if (cfg->opt & MONO_OPT_SHARED) {
3795 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3796 for (l = cfg->ldstr_list; l; l = l->next) {
3797 encode_value ((long)l->data, p, &p);
3800 else
3801 /* Used only in shared mode */
3802 g_assert (!cfg->ldstr_list);
3804 n_patches = 0;
3805 for (pindex = 0; pindex < patches->len; ++pindex) {
3806 patch_info = g_ptr_array_index (patches, pindex);
3808 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3809 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3810 patch_info->type = MONO_PATCH_INFO_NONE;
3811 /* Nothing to do */
3812 continue;
3815 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3816 /* Stored in a GOT slot initialized at module load time */
3817 patch_info->type = MONO_PATCH_INFO_NONE;
3818 continue;
3821 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3822 /* Stored in a GOT slot initialized at module load time */
3823 patch_info->type = MONO_PATCH_INFO_NONE;
3824 continue;
3827 if (is_plt_patch (patch_info)) {
3828 /* Calls are made through the PLT */
3829 patch_info->type = MONO_PATCH_INFO_NONE;
3830 continue;
3833 n_patches ++;
3836 if (n_patches)
3837 g_assert (cfg->has_got_slots);
3839 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3841 acfg->stats.info_size += p - buf;
3843 g_assert (p - buf < buf_size);
3845 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3846 g_free (buf);
3849 static guint32
3850 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3852 guint32 cache_index;
3853 guint32 offset;
3855 /* Reuse the unwind module to canonize and store unwind info entries */
3856 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3858 /* Use +/- 1 to distinguish 0s from missing entries */
3859 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3860 if (offset)
3861 return offset - 1;
3862 else {
3863 guint8 buf [16];
3864 guint8 *p;
3867 * It would be easier to use assembler symbols, but the caller needs an
3868 * offset now.
3870 offset = acfg->unwind_info_offset;
3871 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3872 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3874 p = buf;
3875 encode_value (encoded_len, p, &p);
3877 acfg->unwind_info_offset += encoded_len + (p - buf);
3878 return offset;
3882 static void
3883 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3885 MonoMethod *method;
3886 int i, k, buf_size, method_index;
3887 guint32 debug_info_size;
3888 guint8 *code;
3889 MonoMethodHeader *header;
3890 guint8 *p, *buf, *debug_info;
3891 MonoJitInfo *jinfo = cfg->jit_info;
3892 guint32 flags;
3893 gboolean use_unwind_ops = FALSE;
3894 MonoSeqPointInfo *seq_points;
3896 method = cfg->orig_method;
3897 code = cfg->native_code;
3898 header = cfg->header;
3900 method_index = get_method_index (acfg, method);
3902 if (!acfg->aot_opts.nodebug) {
3903 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3904 } else {
3905 debug_info = NULL;
3906 debug_info_size = 0;
3909 seq_points = cfg->seq_point_info;
3911 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
3912 p = buf = g_malloc (buf_size);
3914 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3915 use_unwind_ops = cfg->unwind_ops != NULL;
3916 #endif
3918 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 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);
3920 encode_value (flags, p, &p);
3922 if (use_unwind_ops) {
3923 guint32 encoded_len;
3924 guint8 *encoded;
3927 * This is a duplicate of the data in the .debug_frame section, but that
3928 * section cannot be accessed using the dl interface.
3930 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3931 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3932 g_free (encoded);
3933 } else {
3934 encode_value (jinfo->used_regs, p, &p);
3937 /*Encode the number of holes before the number of clauses to make decoding easier*/
3938 if (jinfo->has_try_block_holes) {
3939 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3940 encode_value (table->num_holes, p, &p);
3943 /* Exception table */
3944 if (cfg->compile_llvm) {
3946 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3947 * since the information is only available to llc. Instead, we let llc save the data
3948 * into the LSDA, and read it from there at runtime.
3950 /* The assembly might be CIL stripped so emit the data ourselves */
3951 if (header->num_clauses)
3952 encode_value (header->num_clauses, p, &p);
3954 for (k = 0; k < header->num_clauses; ++k) {
3955 MonoExceptionClause *clause;
3957 clause = &header->clauses [k];
3959 encode_value (clause->flags, p, &p);
3960 if (clause->data.catch_class) {
3961 encode_value (1, p, &p);
3962 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3963 } else {
3964 encode_value (0, p, &p);
3967 /* Emit a list of nesting clauses */
3968 for (i = 0; i < header->num_clauses; ++i) {
3969 gint32 cindex1 = k;
3970 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3971 gint32 cindex2 = i;
3972 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3974 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3975 encode_value (i, p, &p);
3977 encode_value (-1, p, &p);
3979 } else {
3980 if (jinfo->num_clauses)
3981 encode_value (jinfo->num_clauses, p, &p);
3983 for (k = 0; k < jinfo->num_clauses; ++k) {
3984 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3986 encode_value (ei->flags, p, &p);
3987 encode_value (ei->exvar_offset, p, &p);
3989 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3990 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3991 else {
3992 if (ei->data.catch_class) {
3993 encode_value (1, p, &p);
3994 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3995 } else {
3996 encode_value (0, p, &p);
4000 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4001 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4002 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4006 if (jinfo->has_generic_jit_info) {
4007 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4009 if (!cfg->compile_llvm) {
4010 encode_value (gi->has_this ? 1 : 0, p, &p);
4011 encode_value (gi->this_reg, p, &p);
4012 encode_value (gi->this_offset, p, &p);
4016 * Need to encode jinfo->method too, since it is not equal to 'method'
4017 * when using generic sharing.
4019 encode_method_ref (acfg, jinfo->method, p, &p);
4022 if (jinfo->has_try_block_holes) {
4023 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4024 for (i = 0; i < table->num_holes; ++i) {
4025 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4026 encode_value (hole->clause, p, &p);
4027 encode_value (hole->length, p, &p);
4028 encode_value (hole->offset, p, &p);
4032 if (jinfo->has_arch_eh_info) {
4033 MonoArchEHJitInfo *eh_info;
4035 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
4036 encode_value (eh_info->stack_size, p, &p);
4039 if (seq_points) {
4040 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4042 encode_value (seq_points->len, p, &p);
4043 last_il_offset = last_native_offset = 0;
4044 for (i = 0; i < seq_points->len; ++i) {
4045 SeqPoint *sp = &seq_points->seq_points [i];
4046 il_offset = sp->il_offset;
4047 native_offset = sp->native_offset;
4048 encode_value (il_offset - last_il_offset, p, &p);
4049 encode_value (native_offset - last_native_offset, p, &p);
4050 last_il_offset = il_offset;
4051 last_native_offset = native_offset;
4053 encode_value (sp->next_len, p, &p);
4054 for (j = 0; j < sp->next_len; ++j)
4055 encode_value (sp->next [j], p, &p);
4059 g_assert (debug_info_size < buf_size);
4061 encode_value (debug_info_size, p, &p);
4062 if (debug_info_size) {
4063 memcpy (p, debug_info, debug_info_size);
4064 p += debug_info_size;
4065 g_free (debug_info);
4068 /* GC Map */
4069 if (cfg->gc_map) {
4070 encode_value (cfg->gc_map_size, p, &p);
4071 /* The GC map requires 4 bytes of alignment */
4072 while ((gsize)p % 4)
4073 p ++;
4074 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4075 p += cfg->gc_map_size;
4078 acfg->stats.ex_info_size += p - buf;
4080 g_assert (p - buf < buf_size);
4082 /* Emit info */
4083 /* The GC Map requires 4 byte alignment */
4084 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4085 g_free (buf);
4088 static guint32
4089 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4091 MonoClass *klass = mono_class_get (acfg->image, token);
4092 guint8 *p, *buf;
4093 int i, buf_size, res;
4094 gboolean no_special_static, cant_encode;
4095 gpointer iter = NULL;
4097 if (!klass) {
4098 mono_loader_clear_error ();
4100 buf_size = 16;
4102 p = buf = g_malloc (buf_size);
4104 /* Mark as unusable */
4105 encode_value (-1, p, &p);
4107 res = add_to_blob (acfg, buf, p - buf);
4108 g_free (buf);
4110 return res;
4113 buf_size = 10240 + (klass->vtable_size * 16);
4114 p = buf = g_malloc (buf_size);
4116 g_assert (klass);
4118 mono_class_init (klass);
4120 mono_class_get_nested_types (klass, &iter);
4121 g_assert (klass->nested_classes_inited);
4123 mono_class_setup_vtable (klass);
4126 * Emit all the information which is required for creating vtables so
4127 * the runtime does not need to create the MonoMethod structures which
4128 * take up a lot of space.
4131 no_special_static = !mono_class_has_special_static_fields (klass);
4133 /* Check whenever we have enough info to encode the vtable */
4134 cant_encode = FALSE;
4135 for (i = 0; i < klass->vtable_size; ++i) {
4136 MonoMethod *cm = klass->vtable [i];
4138 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4139 cant_encode = TRUE;
4142 if (klass->generic_container || cant_encode) {
4143 encode_value (-1, p, &p);
4144 } else {
4145 encode_value (klass->vtable_size, p, &p);
4146 encode_value ((klass->generic_container ? (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);
4147 if (klass->has_cctor)
4148 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4149 if (klass->has_finalize)
4150 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4152 encode_value (klass->instance_size, p, &p);
4153 encode_value (mono_class_data_size (klass), p, &p);
4154 encode_value (klass->packing_size, p, &p);
4155 encode_value (klass->min_align, p, &p);
4157 for (i = 0; i < klass->vtable_size; ++i) {
4158 MonoMethod *cm = klass->vtable [i];
4160 if (cm)
4161 encode_method_ref (acfg, cm, p, &p);
4162 else
4163 encode_value (0, p, &p);
4167 acfg->stats.class_info_size += p - buf;
4169 g_assert (p - buf < buf_size);
4170 res = add_to_blob (acfg, buf, p - buf);
4171 g_free (buf);
4173 return res;
4176 static char*
4177 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4179 char *debug_sym = NULL;
4181 switch (ji->type) {
4182 case MONO_PATCH_INFO_METHOD:
4183 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4184 break;
4185 case MONO_PATCH_INFO_INTERNAL_METHOD:
4186 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4187 break;
4188 case MONO_PATCH_INFO_CLASS_INIT:
4189 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4190 sanitize_symbol (debug_sym);
4191 break;
4192 case MONO_PATCH_INFO_RGCTX_FETCH:
4193 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4194 break;
4195 case MONO_PATCH_INFO_ICALL_ADDR: {
4196 char *s = get_debug_sym (ji->data.method, "", cache);
4198 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4199 g_free (s);
4200 break;
4202 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4203 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4204 break;
4205 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4206 debug_sym = g_strdup_printf ("plt__generic_class_init");
4207 break;
4208 default:
4209 break;
4212 return debug_sym;
4216 * Calls made from AOTed code are routed through a table of jumps similar to the
4217 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4218 * control to the AOT runtime through a trampoline.
4220 static void
4221 emit_plt (MonoAotCompile *acfg)
4223 char symbol [128];
4224 int i;
4225 GHashTable *cache;
4227 cache = g_hash_table_new (g_str_hash, g_str_equal);
4229 emit_line (acfg);
4230 sprintf (symbol, "plt");
4232 emit_section_change (acfg, ".text", 0);
4233 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4234 emit_label (acfg, symbol);
4235 emit_label (acfg, acfg->plt_symbol);
4237 for (i = 0; i < acfg->plt_offset; ++i) {
4238 char *debug_sym = NULL;
4239 MonoPltEntry *plt_entry = NULL;
4240 MonoJumpInfo *ji;
4242 if (i == 0)
4244 * The first plt entry is unused.
4246 continue;
4248 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4249 ji = plt_entry->ji;
4251 if (acfg->llvm) {
4253 * If the target is directly callable, alias the plt symbol to point to
4254 * the method code.
4255 * FIXME: Use this to simplify emit_and_reloc_code ().
4256 * FIXME: Avoid the got slot.
4257 * FIXME: Add support to the binary writer.
4259 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4260 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4262 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4263 /* LLVM calls the PLT entries using bl, so emit a stub */
4264 fprintf (acfg->fp, "\n.thumb_func\n");
4265 emit_label (acfg, plt_entry->llvm_symbol);
4266 fprintf (acfg->fp, "bx pc\n");
4267 fprintf (acfg->fp, "nop\n");
4268 fprintf (acfg->fp, ".arm\n");
4269 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4270 } else {
4271 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4273 continue;
4277 if (acfg->aot_opts.write_symbols)
4278 plt_entry->debug_sym = get_plt_entry_debug_sym (acfg, ji, cache);
4279 debug_sym = plt_entry->debug_sym;
4281 if (acfg->thumb_mixed && !plt_entry->jit_used)
4282 /* Emit only a thumb version */
4283 continue;
4285 if (!acfg->thumb_mixed)
4286 emit_label (acfg, plt_entry->llvm_symbol);
4288 if (debug_sym) {
4289 if (acfg->need_no_dead_strip)
4290 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4291 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4292 emit_label (acfg, debug_sym);
4295 emit_label (acfg, plt_entry->symbol);
4297 arch_emit_plt_entry (acfg, i);
4299 if (debug_sym)
4300 emit_symbol_size (acfg, debug_sym, ".");
4303 if (acfg->thumb_mixed) {
4304 /* Make sure the ARM symbols don't alias the thumb ones */
4305 emit_zero_bytes (acfg, 16);
4308 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4309 * code.
4311 for (i = 0; i < acfg->plt_offset; ++i) {
4312 char *debug_sym = NULL;
4313 MonoPltEntry *plt_entry = NULL;
4314 MonoJumpInfo *ji;
4316 if (i == 0)
4317 continue;
4319 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4320 ji = plt_entry->ji;
4322 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4323 continue;
4325 /* Skip plt entries not actually called by LLVM code */
4326 if (!plt_entry->llvm_used)
4327 continue;
4329 if (acfg->aot_opts.write_symbols) {
4330 if (plt_entry->debug_sym)
4331 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4334 if (debug_sym) {
4335 #if defined(__APPLE__)
4336 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4337 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4338 #endif
4339 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4340 emit_label (acfg, debug_sym);
4342 fprintf (acfg->fp, "\n.thumb_func\n");
4344 emit_label (acfg, plt_entry->llvm_symbol);
4346 arch_emit_llvm_plt_entry (acfg, i);
4348 if (debug_sym) {
4349 emit_symbol_size (acfg, debug_sym, ".");
4350 g_free (debug_sym);
4355 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4357 sprintf (symbol, "plt_end");
4358 emit_label (acfg, symbol);
4360 g_hash_table_destroy (cache);
4363 static G_GNUC_UNUSED void
4364 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4366 char start_symbol [256];
4367 char symbol [256];
4368 guint32 buf_size, info_offset;
4369 MonoJumpInfo *patch_info;
4370 guint8 *buf, *p;
4371 GPtrArray *patches;
4372 char *name;
4373 guint8 *code;
4374 guint32 code_size;
4375 MonoJumpInfo *ji;
4376 GSList *unwind_ops;
4378 name = info->name;
4379 code = info->code;
4380 code_size = info->code_size;
4381 ji = info->ji;
4382 unwind_ops = info->unwind_ops;
4384 #ifdef __native_client_codegen__
4385 mono_nacl_fix_patches (code, ji);
4386 #endif
4388 /* Emit code */
4390 sprintf (start_symbol, "%s", name);
4392 emit_section_change (acfg, ".text", 0);
4393 emit_global (acfg, start_symbol, TRUE);
4394 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4395 emit_label (acfg, start_symbol);
4397 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4398 emit_label (acfg, symbol);
4401 * The code should access everything through the GOT, so we pass
4402 * TRUE here.
4404 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4406 emit_symbol_size (acfg, start_symbol, ".");
4408 /* Emit info */
4410 /* Sort relocations */
4411 patches = g_ptr_array_new ();
4412 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4413 if (patch_info->type != MONO_PATCH_INFO_NONE)
4414 g_ptr_array_add (patches, patch_info);
4415 g_ptr_array_sort (patches, compare_patches);
4417 buf_size = patches->len * 128 + 128;
4418 buf = g_malloc (buf_size);
4419 p = buf;
4421 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4422 g_assert (p - buf < buf_size);
4424 sprintf (symbol, "%s_p", name);
4426 info_offset = add_to_blob (acfg, buf, p - buf);
4428 emit_section_change (acfg, RODATA_SECT, 0);
4429 emit_global (acfg, symbol, FALSE);
4430 emit_label (acfg, symbol);
4432 emit_int32 (acfg, info_offset);
4434 /* Emit debug info */
4435 if (unwind_ops) {
4436 char symbol2 [256];
4438 sprintf (symbol, "%s", name);
4439 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4441 if (acfg->dwarf)
4442 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4446 static void
4447 emit_trampolines (MonoAotCompile *acfg)
4449 char symbol [256];
4450 int i, tramp_got_offset;
4451 MonoAotTrampoline ntype;
4452 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4453 int tramp_type;
4454 guint8 *code;
4455 #endif
4457 if (!acfg->aot_opts.full_aot)
4458 return;
4460 g_assert (acfg->image->assembly);
4462 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4463 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4464 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4465 MonoTrampInfo *info;
4468 * Emit the generic trampolines.
4470 * We could save some code by treating the generic trampolines as a wrapper
4471 * method, but that approach has its own complexities, so we choose the simpler
4472 * method.
4474 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4475 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4476 emit_trampoline (acfg, acfg->got_offset, info);
4479 mono_arch_get_nullified_class_init_trampoline (&info);
4480 emit_trampoline (acfg, acfg->got_offset, info);
4481 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4482 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4483 emit_trampoline (acfg, acfg->got_offset, info);
4484 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4485 emit_trampoline (acfg, acfg->got_offset, info);
4486 #endif
4488 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4489 emit_trampoline (acfg, acfg->got_offset, info);
4491 /* Emit the exception related code pieces */
4492 code = mono_arch_get_restore_context (&info, TRUE);
4493 emit_trampoline (acfg, acfg->got_offset, info);
4494 code = mono_arch_get_call_filter (&info, TRUE);
4495 emit_trampoline (acfg, acfg->got_offset, info);
4496 code = mono_arch_get_throw_exception (&info, TRUE);
4497 emit_trampoline (acfg, acfg->got_offset, info);
4498 code = mono_arch_get_rethrow_exception (&info, TRUE);
4499 emit_trampoline (acfg, acfg->got_offset, info);
4500 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4501 emit_trampoline (acfg, acfg->got_offset, info);
4503 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4505 GSList *l = mono_arch_get_trampolines (TRUE);
4507 while (l) {
4508 MonoTrampInfo *info = l->data;
4510 emit_trampoline (acfg, acfg->got_offset, info);
4511 l = l->next;
4514 #endif
4516 for (i = 0; i < 128; ++i) {
4517 int offset;
4519 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4520 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4521 emit_trampoline (acfg, acfg->got_offset, info);
4523 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4524 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4525 emit_trampoline (acfg, acfg->got_offset, info);
4529 GSList *l;
4531 /* delegate_invoke_impl trampolines */
4532 l = mono_arch_get_delegate_invoke_impls ();
4533 while (l) {
4534 MonoTrampInfo *info = l->data;
4536 emit_trampoline (acfg, acfg->got_offset, info);
4537 l = l->next;
4541 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4543 /* Emit trampolines which are numerous */
4546 * These include the following:
4547 * - specific trampolines
4548 * - static rgctx invoke trampolines
4549 * - imt thunks
4550 * These trampolines have the same code, they are parameterized by GOT
4551 * slots.
4552 * They are defined in this file, in the arch_... routines instead of
4553 * in tramp-<ARCH>.c, since it is easier to do it this way.
4557 * When running in aot-only mode, we can't create specific trampolines at
4558 * runtime, so we create a few, and save them in the AOT file.
4559 * Normal trampolines embed their argument as a literal inside the
4560 * trampoline code, we can't do that here, so instead we embed an offset
4561 * which needs to be added to the trampoline address to get the address of
4562 * the GOT slot which contains the argument value.
4563 * The generated trampolines jump to the generic trampolines using another
4564 * GOT slot, which will be setup by the AOT loader to point to the
4565 * generic trampoline code of the given type.
4569 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4570 * each class).
4573 emit_section_change (acfg, ".text", 0);
4575 tramp_got_offset = acfg->got_offset;
4577 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4578 switch (ntype) {
4579 case MONO_AOT_TRAMP_SPECIFIC:
4580 sprintf (symbol, "specific_trampolines");
4581 break;
4582 case MONO_AOT_TRAMP_STATIC_RGCTX:
4583 sprintf (symbol, "static_rgctx_trampolines");
4584 break;
4585 case MONO_AOT_TRAMP_IMT_THUNK:
4586 sprintf (symbol, "imt_thunks");
4587 break;
4588 default:
4589 g_assert_not_reached ();
4592 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4593 emit_label (acfg, symbol);
4595 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4597 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4598 int tramp_size = 0;
4600 switch (ntype) {
4601 case MONO_AOT_TRAMP_SPECIFIC:
4602 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4603 tramp_got_offset += 2;
4604 break;
4605 case MONO_AOT_TRAMP_STATIC_RGCTX:
4606 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4607 tramp_got_offset += 2;
4608 break;
4609 case MONO_AOT_TRAMP_IMT_THUNK:
4610 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4611 tramp_got_offset += 1;
4612 break;
4613 default:
4614 g_assert_not_reached ();
4616 #ifdef __native_client_codegen__
4617 /* align to avoid 32-byte boundary crossings */
4618 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4619 #endif
4621 if (!acfg->trampoline_size [ntype]) {
4622 g_assert (tramp_size);
4623 acfg->trampoline_size [ntype] = tramp_size;
4628 /* Reserve some entries at the end of the GOT for our use */
4629 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4632 acfg->got_offset += acfg->num_trampoline_got_entries;
4635 static gboolean
4636 str_begins_with (const char *str1, const char *str2)
4638 int len = strlen (str2);
4639 return strncmp (str1, str2, len) == 0;
4642 static void
4643 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4645 gchar **args, **ptr;
4647 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4648 for (ptr = args; ptr && *ptr; ptr ++) {
4649 const char *arg = *ptr;
4651 if (str_begins_with (arg, "outfile=")) {
4652 opts->outfile = g_strdup (arg + strlen ("outfile="));
4653 } else if (str_begins_with (arg, "save-temps")) {
4654 opts->save_temps = TRUE;
4655 } else if (str_begins_with (arg, "keep-temps")) {
4656 opts->save_temps = TRUE;
4657 } else if (str_begins_with (arg, "write-symbols")) {
4658 opts->write_symbols = TRUE;
4659 } else if (str_begins_with (arg, "no-write-symbols")) {
4660 opts->write_symbols = FALSE;
4661 } else if (str_begins_with (arg, "metadata-only")) {
4662 opts->metadata_only = TRUE;
4663 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4664 opts->bind_to_runtime_version = TRUE;
4665 } else if (str_begins_with (arg, "full")) {
4666 opts->full_aot = TRUE;
4667 } else if (str_begins_with (arg, "threads=")) {
4668 opts->nthreads = atoi (arg + strlen ("threads="));
4669 } else if (str_begins_with (arg, "static")) {
4670 opts->static_link = TRUE;
4671 opts->no_dlsym = TRUE;
4672 } else if (str_begins_with (arg, "asmonly")) {
4673 opts->asm_only = TRUE;
4674 } else if (str_begins_with (arg, "asmwriter")) {
4675 opts->asm_writer = TRUE;
4676 } else if (str_begins_with (arg, "nodebug")) {
4677 opts->nodebug = TRUE;
4678 } else if (str_begins_with (arg, "ntrampolines=")) {
4679 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4680 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4681 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4682 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4683 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4684 } else if (str_begins_with (arg, "autoreg")) {
4685 opts->autoreg = TRUE;
4686 } else if (str_begins_with (arg, "tool-prefix=")) {
4687 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4688 } else if (str_begins_with (arg, "soft-debug")) {
4689 opts->soft_debug = TRUE;
4690 } else if (str_begins_with (arg, "direct-pinvoke")) {
4691 opts->direct_pinvoke = TRUE;
4692 } else if (str_begins_with (arg, "print-skipped")) {
4693 opts->print_skipped_methods = TRUE;
4694 } else if (str_begins_with (arg, "stats")) {
4695 opts->stats = TRUE;
4696 } else if (str_begins_with (arg, "mtriple=")) {
4697 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
4698 } else if (str_begins_with (arg, "llvm-path=")) {
4699 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
4700 } else {
4701 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4702 exit (1);
4706 g_strfreev (args);
4709 static void
4710 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4712 MonoMethod *method = (MonoMethod*)key;
4713 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4714 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4715 MonoAotCompile *acfg = user_data;
4717 new_ji->image = ji->image;
4718 new_ji->token = ji->token;
4719 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4722 static gboolean
4723 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4725 if (klass->type_token)
4726 return TRUE;
4727 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4728 return TRUE;
4729 if (klass->rank)
4730 return can_encode_class (acfg, klass->element_class);
4731 return FALSE;
4734 static gboolean
4735 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4737 switch (patch_info->type) {
4738 case MONO_PATCH_INFO_METHOD:
4739 case MONO_PATCH_INFO_METHODCONST: {
4740 MonoMethod *method = patch_info->data.method;
4742 if (method->wrapper_type) {
4743 switch (method->wrapper_type) {
4744 case MONO_WRAPPER_NONE:
4745 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4746 case MONO_WRAPPER_XDOMAIN_INVOKE:
4747 case MONO_WRAPPER_STFLD:
4748 case MONO_WRAPPER_LDFLD:
4749 case MONO_WRAPPER_LDFLDA:
4750 case MONO_WRAPPER_LDFLD_REMOTE:
4751 case MONO_WRAPPER_STFLD_REMOTE:
4752 case MONO_WRAPPER_STELEMREF:
4753 case MONO_WRAPPER_ISINST:
4754 case MONO_WRAPPER_PROXY_ISINST:
4755 case MONO_WRAPPER_ALLOC:
4756 case MONO_WRAPPER_REMOTING_INVOKE:
4757 case MONO_WRAPPER_UNKNOWN:
4758 case MONO_WRAPPER_WRITE_BARRIER:
4759 break;
4760 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4761 if (!strcmp (method->name, "ElementAddr"))
4762 return TRUE;
4763 else
4764 return FALSE;
4765 case MONO_WRAPPER_CASTCLASS:
4766 if (!strcmp (method->name, "__castclass_with_cache"))
4767 return TRUE;
4768 else if (!strcmp (method->name, "__isinst_with_cache"))
4769 return TRUE;
4770 else
4771 return FALSE;
4772 default:
4773 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4774 return FALSE;
4776 } else {
4777 if (!method->token) {
4778 /* The method is part of a constructed type like Int[,].Set (). */
4779 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4780 if (method->klass->rank)
4781 return TRUE;
4782 return FALSE;
4786 break;
4788 case MONO_PATCH_INFO_VTABLE:
4789 case MONO_PATCH_INFO_CLASS_INIT:
4790 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4791 case MONO_PATCH_INFO_CLASS:
4792 case MONO_PATCH_INFO_IID:
4793 case MONO_PATCH_INFO_ADJUSTED_IID:
4794 if (!can_encode_class (acfg, patch_info->data.klass)) {
4795 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4796 return FALSE;
4798 break;
4799 case MONO_PATCH_INFO_RGCTX_FETCH: {
4800 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4802 if (!can_encode_patch (acfg, entry->data))
4803 return FALSE;
4804 break;
4806 default:
4807 break;
4810 return TRUE;
4814 * compile_method:
4816 * AOT compile a given method.
4817 * This function might be called by multiple threads, so it must be thread-safe.
4819 static void
4820 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4822 MonoCompile *cfg;
4823 MonoJumpInfo *patch_info;
4824 gboolean skip;
4825 int index, depth;
4826 MonoMethod *wrapped;
4828 if (acfg->aot_opts.metadata_only)
4829 return;
4831 mono_acfg_lock (acfg);
4832 index = get_method_index (acfg, method);
4833 mono_acfg_unlock (acfg);
4835 /* fixme: maybe we can also precompile wrapper methods */
4836 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4837 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4838 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4839 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4840 return;
4843 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4844 return;
4846 wrapped = mono_marshal_method_from_wrapper (method);
4847 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4848 // FIXME: The wrapper should be generic too, but it is not
4849 return;
4851 InterlockedIncrement (&acfg->stats.mcount);
4853 #if 0
4854 if (method->is_generic || method->klass->generic_container) {
4855 InterlockedIncrement (&acfg->stats.genericcount);
4856 return;
4858 #endif
4860 //acfg->aot_opts.print_skipped_methods = TRUE;
4863 * Since these methods are the only ones which are compiled with
4864 * AOT support, and they are not used by runtime startup/shutdown code,
4865 * the runtime will not see AOT methods during AOT compilation,so it
4866 * does not need to support them by creating a fake GOT etc.
4868 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4869 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4870 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4871 InterlockedIncrement (&acfg->stats.genericcount);
4872 return;
4874 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4875 //printf ("E: %s\n", mono_method_full_name (method, TRUE));
4876 /* Let the exception happen at runtime */
4877 return;
4880 if (cfg->disable_aot) {
4881 if (acfg->aot_opts.print_skipped_methods)
4882 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4883 InterlockedIncrement (&acfg->stats.ocount);
4884 mono_destroy_compile (cfg);
4885 return;
4888 /* Nullify patches which need no aot processing */
4889 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4890 switch (patch_info->type) {
4891 case MONO_PATCH_INFO_LABEL:
4892 case MONO_PATCH_INFO_BB:
4893 patch_info->type = MONO_PATCH_INFO_NONE;
4894 break;
4895 default:
4896 break;
4900 /* Collect method->token associations from the cfg */
4901 mono_acfg_lock (acfg);
4902 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4903 mono_acfg_unlock (acfg);
4906 * Check for absolute addresses.
4908 skip = FALSE;
4909 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4910 switch (patch_info->type) {
4911 case MONO_PATCH_INFO_ABS:
4912 /* unable to handle this */
4913 skip = TRUE;
4914 break;
4915 default:
4916 break;
4920 if (skip) {
4921 if (acfg->aot_opts.print_skipped_methods)
4922 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4923 InterlockedIncrement (&acfg->stats.abscount);
4924 mono_destroy_compile (cfg);
4925 return;
4928 /* Lock for the rest of the code */
4929 mono_acfg_lock (acfg);
4932 * Check for methods/klasses we can't encode.
4934 skip = FALSE;
4935 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4936 if (!can_encode_patch (acfg, patch_info))
4937 skip = TRUE;
4940 if (skip) {
4941 if (acfg->aot_opts.print_skipped_methods)
4942 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4943 acfg->stats.ocount++;
4944 mono_destroy_compile (cfg);
4945 mono_acfg_unlock (acfg);
4946 return;
4949 /* Adds generic instances referenced by this method */
4951 * The depth is used to avoid infinite loops when generic virtual recursion is
4952 * encountered.
4954 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4955 if (depth < 32) {
4956 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4957 switch (patch_info->type) {
4958 case MONO_PATCH_INFO_METHOD: {
4959 MonoMethod *m = patch_info->data.method;
4960 if (m->is_inflated) {
4961 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4962 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4963 !method_has_type_vars (m)) {
4964 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4965 if (acfg->aot_opts.full_aot)
4966 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4967 } else {
4968 add_extra_method_with_depth (acfg, m, depth + 1);
4969 add_types_from_method_header (acfg, m);
4972 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4974 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4975 add_extra_method_with_depth (acfg, m, depth + 1);
4976 break;
4978 case MONO_PATCH_INFO_VTABLE: {
4979 MonoClass *klass = patch_info->data.klass;
4981 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4982 add_generic_class_with_depth (acfg, klass, depth + 5);
4983 break;
4985 case MONO_PATCH_INFO_SFLDA: {
4986 MonoClass *klass = patch_info->data.field->parent;
4988 /* The .cctor needs to run at runtime. */
4989 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
4990 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
4991 break;
4993 default:
4994 break;
4999 /* Determine whenever the method has GOT slots */
5000 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5001 switch (patch_info->type) {
5002 case MONO_PATCH_INFO_GOT_OFFSET:
5003 case MONO_PATCH_INFO_NONE:
5004 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5005 break;
5006 case MONO_PATCH_INFO_IMAGE:
5007 /* The assembly is stored in GOT slot 0 */
5008 if (patch_info->data.image != acfg->image)
5009 cfg->has_got_slots = TRUE;
5010 break;
5011 default:
5012 if (!is_plt_patch (patch_info))
5013 cfg->has_got_slots = TRUE;
5014 break;
5018 if (!cfg->has_got_slots)
5019 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5022 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5024 /* Make a copy of the patch info which is in the mempool */
5026 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5028 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5029 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5031 if (!patches)
5032 patches = new_patch_info;
5033 else
5034 patches_end->next = new_patch_info;
5035 patches_end = new_patch_info;
5037 cfg->patch_info = patches;
5039 /* Make a copy of the unwind info */
5041 GSList *l, *unwind_ops;
5042 MonoUnwindOp *op;
5044 unwind_ops = NULL;
5045 for (l = cfg->unwind_ops; l; l = l->next) {
5046 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5047 memcpy (op, l->data, sizeof (MonoUnwindOp));
5048 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5050 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5052 /* Make a copy of the argument/local info */
5054 MonoInst **args, **locals;
5055 MonoMethodSignature *sig;
5056 MonoMethodHeader *header;
5057 int i;
5059 sig = mono_method_signature (method);
5060 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5061 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5062 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5063 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5065 cfg->args = args;
5067 header = mono_method_get_header (method);
5068 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5069 for (i = 0; i < header->num_locals; ++i) {
5070 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5071 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5073 cfg->locals = locals;
5076 /* Free some fields used by cfg to conserve memory */
5077 mono_mempool_destroy (cfg->mempool);
5078 cfg->mempool = NULL;
5079 g_free (cfg->varinfo);
5080 cfg->varinfo = NULL;
5081 g_free (cfg->vars);
5082 cfg->vars = NULL;
5083 if (cfg->rs) {
5084 mono_regstate_free (cfg->rs);
5085 cfg->rs = NULL;
5088 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5090 while (index >= acfg->cfgs_size) {
5091 MonoCompile **new_cfgs;
5092 int new_size;
5094 new_size = acfg->cfgs_size * 2;
5095 new_cfgs = g_new0 (MonoCompile*, new_size);
5096 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5097 g_free (acfg->cfgs);
5098 acfg->cfgs = new_cfgs;
5099 acfg->cfgs_size = new_size;
5101 acfg->cfgs [index] = cfg;
5103 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5106 if (cfg->orig_method->wrapper_type)
5107 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5110 mono_acfg_unlock (acfg);
5112 InterlockedIncrement (&acfg->stats.ccount);
5115 static void
5116 compile_thread_main (gpointer *user_data)
5118 MonoDomain *domain = user_data [0];
5119 MonoAotCompile *acfg = user_data [1];
5120 GPtrArray *methods = user_data [2];
5121 int i;
5123 mono_thread_attach (domain);
5125 for (i = 0; i < methods->len; ++i)
5126 compile_method (acfg, g_ptr_array_index (methods, i));
5129 static void
5130 load_profile_files (MonoAotCompile *acfg)
5132 FILE *infile;
5133 char *tmp;
5134 int file_index, res, method_index, i;
5135 char ver [256];
5136 guint32 token;
5137 GList *unordered, *l;
5138 gboolean found;
5140 file_index = 0;
5141 while (TRUE) {
5142 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5144 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5145 g_free (tmp);
5146 break;
5149 infile = fopen (tmp, "r");
5150 g_assert (infile);
5152 printf ("Using profile data file '%s'\n", tmp);
5153 g_free (tmp);
5155 file_index ++;
5157 res = fscanf (infile, "%32s\n", ver);
5158 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5159 printf ("Profile file has wrong version or invalid.\n");
5160 fclose (infile);
5161 continue;
5164 while (TRUE) {
5165 char name [1024];
5166 MonoMethodDesc *desc;
5167 MonoMethod *method;
5169 if (fgets (name, 1023, infile) == NULL)
5170 break;
5172 /* Kill the newline */
5173 if (strlen (name) > 0)
5174 name [strlen (name) - 1] = '\0';
5176 desc = mono_method_desc_new (name, TRUE);
5178 method = mono_method_desc_search_in_image (desc, acfg->image);
5180 if (method && mono_method_get_token (method)) {
5181 token = mono_method_get_token (method);
5182 method_index = mono_metadata_token_index (token) - 1;
5184 found = FALSE;
5185 for (i = 0; i < acfg->method_order->len; ++i) {
5186 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5187 found = TRUE;
5188 break;
5191 if (!found)
5192 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5193 } else {
5194 //printf ("No method found matching '%s'.\n", name);
5197 fclose (infile);
5200 /* Add missing methods */
5201 unordered = NULL;
5202 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5203 found = FALSE;
5204 for (i = 0; i < acfg->method_order->len; ++i) {
5205 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5206 found = TRUE;
5207 break;
5210 if (!found)
5211 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5213 unordered = g_list_reverse (unordered);
5214 for (l = unordered; l; l = l->next)
5215 g_ptr_array_add (acfg->method_order, l->data);
5218 /* Used by the LLVM backend */
5219 guint32
5220 mono_aot_get_got_offset (MonoJumpInfo *ji)
5222 return get_got_offset (llvm_acfg, ji);
5225 char*
5226 mono_aot_get_method_name (MonoCompile *cfg)
5228 if (llvm_acfg->aot_opts.static_link)
5229 /* Include the assembly name too to avoid duplicate symbol errors */
5230 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5231 else
5232 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5235 char*
5236 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5238 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5239 MonoPltEntry *plt_entry;
5241 ji->type = type;
5242 ji->data.target = data;
5244 if (!can_encode_patch (llvm_acfg, ji))
5245 return NULL;
5247 plt_entry = get_plt_entry (llvm_acfg, ji);
5248 plt_entry->llvm_used = TRUE;
5250 #if defined(__APPLE__)
5251 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5252 #else
5253 return g_strdup_printf (plt_entry->llvm_symbol);
5254 #endif
5257 MonoJumpInfo*
5258 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5260 MonoJumpInfo *res;
5262 mono_acfg_lock (llvm_acfg);
5263 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5264 mono_acfg_unlock (llvm_acfg);
5266 return res;
5269 #ifdef ENABLE_LLVM
5272 * emit_llvm_file:
5274 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5275 * tools.
5277 static void
5278 emit_llvm_file (MonoAotCompile *acfg)
5280 char *command, *opts;
5281 int i;
5282 MonoJumpInfo *patch_info;
5285 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5286 * to it.
5289 /* Compute the final size of the got */
5290 for (i = 0; i < acfg->nmethods; ++i) {
5291 if (acfg->cfgs [i]) {
5292 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5293 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5294 if (!is_plt_patch (patch_info))
5295 get_got_offset (acfg, patch_info);
5296 else
5297 get_plt_entry (acfg, patch_info);
5303 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5305 if (acfg->aot_opts.full_aot) {
5306 int ntype;
5309 * Need to add the got entries used by the trampolines.
5310 * This is only a conservative approximation.
5312 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5313 /* For the generic + rgctx trampolines */
5314 acfg->final_got_size += 200;
5315 /* For the specific trampolines */
5316 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5317 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5322 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5325 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5326 * a lot of time, and doesn't seem to save much space.
5327 * The following optimizations cannot be enabled:
5328 * - 'tailcallelim'
5329 * - 'jump-threading' changes our blockaddress references to int constants.
5330 * - 'basiccg' fails because it contains:
5331 * if (CS && !isa<IntrinsicInst>(II)) {
5332 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
5333 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
5334 * The opt list below was produced by taking the output of:
5335 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5336 * then removing tailcallelim + the global opts, and adding a second gvn.
5338 opts = g_strdup ("-instcombine -simplifycfg");
5339 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
5340 #if 1
5341 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5342 printf ("Executing opt: %s\n", command);
5343 if (system (command) != 0) {
5344 exit (1);
5346 #endif
5347 g_free (opts);
5349 if (!acfg->llc_args)
5350 acfg->llc_args = g_string_new ("");
5352 /* Verbose asm slows down llc greatly */
5353 g_string_append (acfg->llc_args, " -asm-verbose=false");
5355 if (acfg->aot_opts.mtriple)
5356 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5358 if (llvm_acfg->aot_opts.static_link)
5359 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5360 else
5361 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5362 unlink (acfg->tmpfname);
5364 command = g_strdup_printf ("%sllc %s -unwind-tables -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname);
5366 printf ("Executing llc: %s\n", command);
5368 if (system (command) != 0) {
5369 exit (1);
5372 #endif
5374 static void
5375 emit_code (MonoAotCompile *acfg)
5377 int oindex, i;
5378 char symbol [256];
5379 char end_symbol [256];
5381 #if defined(TARGET_POWERPC64)
5382 sprintf (symbol, ".Lgot_addr");
5383 emit_section_change (acfg, ".text", 0);
5384 emit_alignment (acfg, 8);
5385 emit_label (acfg, symbol);
5386 emit_pointer (acfg, acfg->got_symbol);
5387 #endif
5390 * This global symbol is used to compute the address of each method using the
5391 * code_offsets array. It is also used to compute the memory ranges occupied by
5392 * AOT code, so it must be equal to the address of the first emitted method.
5394 sprintf (symbol, "methods");
5395 emit_section_change (acfg, ".text", 0);
5396 emit_alignment (acfg, 8);
5397 if (acfg->llvm) {
5398 for (i = 0; i < acfg->nmethods; ++i) {
5399 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5400 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5401 break;
5404 if (i == acfg->nmethods)
5405 /* No LLVM compiled methods */
5406 emit_label (acfg, symbol);
5407 } else {
5408 emit_label (acfg, symbol);
5412 * Emit some padding so the local symbol for the first method doesn't have the
5413 * same address as 'methods'.
5415 #if defined(__default_codegen__)
5416 emit_zero_bytes (acfg, 16);
5417 #elif defined(__native_client_codegen__)
5419 const int kPaddingSize = 16;
5420 guint8 pad_buffer[kPaddingSize];
5421 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5422 emit_bytes (acfg, pad_buffer, kPaddingSize);
5424 #endif
5426 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5427 MonoCompile *cfg;
5428 MonoMethod *method;
5430 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5432 cfg = acfg->cfgs [i];
5434 if (!cfg)
5435 continue;
5437 method = cfg->orig_method;
5439 /* Emit unbox trampoline */
5440 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5441 if (!method->wrapper_type && !method->is_inflated) {
5442 g_assert (method->token);
5443 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
5444 } else {
5445 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
5448 emit_section_change (acfg, ".text", 0);
5449 #ifdef __native_client_codegen__
5450 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5451 #endif
5452 emit_global (acfg, symbol, TRUE);
5454 if (acfg->thumb_mixed && cfg->compile_llvm)
5455 fprintf (acfg->fp, "\n.thumb_func\n");
5457 emit_label (acfg, symbol);
5459 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
5462 if (cfg->compile_llvm)
5463 acfg->stats.llvm_count ++;
5464 else
5465 emit_method_code (acfg, cfg);
5468 sprintf (symbol, "methods_end");
5469 emit_section_change (acfg, ".text", 0);
5470 emit_alignment (acfg, 8);
5471 emit_label (acfg, symbol);
5474 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
5475 * from optimizing them away, since it doesn't see that code_offsets references them.
5476 * JITted methods don't need this since they are referenced using assembler local
5477 * symbols.
5478 * FIXME: This is why write-symbols doesn't work on OSX ?
5480 if (acfg->llvm && acfg->need_no_dead_strip) {
5481 fprintf (acfg->fp, "\n");
5482 for (i = 0; i < acfg->nmethods; ++i) {
5483 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
5484 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
5488 sprintf (symbol, "code_offsets");
5489 emit_section_change (acfg, RODATA_SECT, 1);
5490 emit_alignment (acfg, 8);
5491 emit_label (acfg, symbol);
5493 acfg->stats.offsets_size += acfg->nmethods * 4;
5495 sprintf (end_symbol, "methods");
5496 for (i = 0; i < acfg->nmethods; ++i) {
5497 if (acfg->cfgs [i]) {
5498 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5499 } else {
5500 emit_int32 (acfg, 0xffffffff);
5503 emit_line (acfg);
5506 static void
5507 emit_info (MonoAotCompile *acfg)
5509 int oindex, i;
5510 char symbol [256];
5511 gint32 *offsets;
5513 offsets = g_new0 (gint32, acfg->nmethods);
5515 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5516 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5518 if (acfg->cfgs [i]) {
5519 emit_method_info (acfg, acfg->cfgs [i]);
5520 offsets [i] = acfg->cfgs [i]->method_info_offset;
5521 } else {
5522 offsets [i] = 0;
5526 sprintf (symbol, "method_info_offsets");
5527 emit_section_change (acfg, RODATA_SECT, 1);
5528 emit_alignment (acfg, 8);
5529 emit_label (acfg, symbol);
5531 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5533 g_free (offsets);
5536 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5538 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5539 #define mix(a,b,c) { \
5540 a -= c; a ^= rot(c, 4); c += b; \
5541 b -= a; b ^= rot(a, 6); a += c; \
5542 c -= b; c ^= rot(b, 8); b += a; \
5543 a -= c; a ^= rot(c,16); c += b; \
5544 b -= a; b ^= rot(a,19); a += c; \
5545 c -= b; c ^= rot(b, 4); b += a; \
5547 #define final(a,b,c) { \
5548 c ^= b; c -= rot(b,14); \
5549 a ^= c; a -= rot(c,11); \
5550 b ^= a; b -= rot(a,25); \
5551 c ^= b; c -= rot(b,16); \
5552 a ^= c; a -= rot(c,4); \
5553 b ^= a; b -= rot(a,14); \
5554 c ^= b; c -= rot(b,24); \
5557 static guint
5558 mono_aot_type_hash (MonoType *t1)
5560 guint hash = t1->type;
5562 hash |= t1->byref << 6; /* do not collide with t1->type values */
5563 switch (t1->type) {
5564 case MONO_TYPE_VALUETYPE:
5565 case MONO_TYPE_CLASS:
5566 case MONO_TYPE_SZARRAY:
5567 /* check if the distribution is good enough */
5568 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5569 case MONO_TYPE_PTR:
5570 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5571 case MONO_TYPE_ARRAY:
5572 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5573 case MONO_TYPE_GENERICINST:
5574 return ((hash << 5) - hash) ^ 0;
5576 return hash;
5580 * mono_aot_method_hash:
5582 * Return a hash code for methods which only depends on metadata.
5584 guint32
5585 mono_aot_method_hash (MonoMethod *method)
5587 MonoMethodSignature *sig;
5588 MonoClass *klass;
5589 int i, hindex;
5590 int hashes_count;
5591 guint32 *hashes_start, *hashes;
5592 guint32 a, b, c;
5593 MonoGenericInst *ginst = NULL;
5595 /* Similar to the hash in mono_method_get_imt_slot () */
5597 sig = mono_method_signature (method);
5599 if (method->is_inflated)
5600 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5602 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5603 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5604 hashes = hashes_start;
5606 /* Some wrappers are assigned to random classes */
5607 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5608 klass = method->klass;
5609 else
5610 klass = mono_defaults.object_class;
5612 if (!method->wrapper_type) {
5613 char *full_name = mono_type_full_name (&klass->byval_arg);
5615 hashes [0] = mono_metadata_str_hash (full_name);
5616 hashes [1] = 0;
5617 g_free (full_name);
5618 } else {
5619 hashes [0] = mono_metadata_str_hash (klass->name);
5620 hashes [1] = mono_metadata_str_hash (klass->name_space);
5622 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5623 /* The method name includes a stringified pointer */
5624 hashes [2] = 0;
5625 else
5626 hashes [2] = mono_metadata_str_hash (method->name);
5627 hashes [3] = method->wrapper_type;
5628 hashes [4] = mono_aot_type_hash (sig->ret);
5629 hindex = 5;
5630 for (i = 0; i < sig->param_count; i++) {
5631 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5633 if (ginst) {
5634 for (i = 0; i < ginst->type_argc; ++i)
5635 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5637 g_assert (hindex == hashes_count);
5639 /* Setup internal state */
5640 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5642 /* Handle most of the hashes */
5643 while (hashes_count > 3) {
5644 a += hashes [0];
5645 b += hashes [1];
5646 c += hashes [2];
5647 mix (a,b,c);
5648 hashes_count -= 3;
5649 hashes += 3;
5652 /* Handle the last 3 hashes (all the case statements fall through) */
5653 switch (hashes_count) {
5654 case 3 : c += hashes [2];
5655 case 2 : b += hashes [1];
5656 case 1 : a += hashes [0];
5657 final (a,b,c);
5658 case 0: /* nothing left to add */
5659 break;
5662 free (hashes_start);
5664 return c;
5666 #undef rot
5667 #undef mix
5668 #undef final
5671 * mono_aot_wrapper_name:
5673 * Return a string which uniqely identifies the given wrapper method.
5675 char*
5676 mono_aot_wrapper_name (MonoMethod *method)
5678 char *name, *tmpsig, *klass_desc;
5680 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5682 switch (method->wrapper_type) {
5683 case MONO_WRAPPER_RUNTIME_INVOKE:
5684 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5685 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5686 else
5687 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5688 break;
5689 default:
5690 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5691 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5692 g_free (klass_desc);
5693 break;
5696 g_free (tmpsig);
5698 return name;
5702 * mono_aot_get_array_helper_from_wrapper;
5704 * Get the helper method in Array called by an array wrapper method.
5706 MonoMethod*
5707 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5709 MonoMethod *m;
5710 const char *prefix;
5711 MonoGenericContext ctx;
5712 MonoType *args [16];
5713 char *mname, *iname, *s, *s2, *helper_name = NULL;
5715 prefix = "System.Collections.Generic";
5716 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5717 s2 = strstr (s, "`1.");
5718 g_assert (s2);
5719 s2 [0] = '\0';
5720 iname = s;
5721 mname = s2 + 3;
5723 //printf ("X: %s %s\n", iname, mname);
5725 if (!strcmp (iname, "IList"))
5726 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5727 else
5728 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5729 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5730 g_assert (m);
5731 g_free (helper_name);
5732 g_free (s);
5734 if (m->is_generic) {
5735 memset (&ctx, 0, sizeof (ctx));
5736 args [0] = &method->klass->element_class->byval_arg;
5737 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5738 m = mono_class_inflate_generic_method (m, &ctx);
5741 return m;
5744 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5746 typedef struct HashEntry {
5747 guint32 key, value, index;
5748 struct HashEntry *next;
5749 } HashEntry;
5752 * emit_extra_methods:
5754 * Emit methods which are not in the METHOD table, like wrappers.
5756 static void
5757 emit_extra_methods (MonoAotCompile *acfg)
5759 int i, table_size, buf_size;
5760 char symbol [256];
5761 guint8 *p, *buf;
5762 guint32 *info_offsets;
5763 guint32 hash;
5764 GPtrArray *table;
5765 HashEntry *entry, *new_entry;
5766 int nmethods, max_chain_length;
5767 int *chain_lengths;
5769 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5771 /* Emit method info */
5772 nmethods = 0;
5773 for (i = 0; i < acfg->extra_methods->len; ++i) {
5774 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5775 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5776 char *name;
5778 if (!cfg)
5779 continue;
5781 buf_size = 10240;
5782 p = buf = g_malloc (buf_size);
5784 nmethods ++;
5786 method = cfg->method_to_register;
5788 name = NULL;
5789 if (method->wrapper_type) {
5790 gboolean encode_ref = FALSE;
5793 * We encode some wrappers using their name, since encoding them
5794 * directly would be difficult. This works because at runtime, we only need to
5795 * check whenever a method ref matches an existing MonoMethod. The downside is
5796 * that the method names are large, so we use the binary encoding if possible.
5798 switch (method->wrapper_type) {
5799 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5800 case MONO_WRAPPER_SYNCHRONIZED:
5801 encode_ref = TRUE;
5802 break;
5803 case MONO_WRAPPER_MANAGED_TO_NATIVE:
5804 /* Skip JIT icall wrappers */
5805 if (!strstr (method->name, "__icall_wrapper"))
5806 encode_ref = TRUE;
5807 break;
5808 case MONO_WRAPPER_UNKNOWN:
5809 if (!strcmp (method->name, "PtrToStructure") || !strcmp (method->name, "StructureToPtr"))
5810 encode_ref = TRUE;
5811 break;
5812 case MONO_WRAPPER_RUNTIME_INVOKE:
5813 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5814 /* Direct wrapper, encode normally */
5815 encode_ref = TRUE;
5816 break;
5817 default:
5818 break;
5821 if (!encode_ref)
5822 name = mono_aot_wrapper_name (method);
5825 if (name) {
5826 encode_value (1, p, &p);
5827 encode_value (method->wrapper_type, p, &p);
5828 strcpy ((char*)p, name);
5829 p += strlen (name ) + 1;
5830 g_free (name);
5831 } else {
5832 encode_value (0, p, &p);
5833 encode_method_ref (acfg, method, p, &p);
5836 g_assert ((p - buf) < buf_size);
5838 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5839 g_free (buf);
5843 * Construct a chained hash table for mapping indexes in extra_method_info to
5844 * method indexes.
5846 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5847 table = g_ptr_array_sized_new (table_size);
5848 for (i = 0; i < table_size; ++i)
5849 g_ptr_array_add (table, NULL);
5850 chain_lengths = g_new0 (int, table_size);
5851 max_chain_length = 0;
5852 for (i = 0; i < acfg->extra_methods->len; ++i) {
5853 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5854 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5855 guint32 key, value;
5857 if (!cfg)
5858 continue;
5860 key = info_offsets [i];
5861 value = get_method_index (acfg, method);
5863 hash = mono_aot_method_hash (method) % table_size;
5865 chain_lengths [hash] ++;
5866 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5868 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5869 new_entry->key = key;
5870 new_entry->value = value;
5872 entry = g_ptr_array_index (table, hash);
5873 if (entry == NULL) {
5874 new_entry->index = hash;
5875 g_ptr_array_index (table, hash) = new_entry;
5876 } else {
5877 while (entry->next)
5878 entry = entry->next;
5880 entry->next = new_entry;
5881 new_entry->index = table->len;
5882 g_ptr_array_add (table, new_entry);
5886 //printf ("MAX: %d\n", max_chain_length);
5888 /* Emit the table */
5889 sprintf (symbol, "extra_method_table");
5890 emit_section_change (acfg, RODATA_SECT, 0);
5891 emit_alignment (acfg, 8);
5892 emit_label (acfg, symbol);
5894 emit_int32 (acfg, table_size);
5895 for (i = 0; i < table->len; ++i) {
5896 HashEntry *entry = g_ptr_array_index (table, i);
5898 if (entry == NULL) {
5899 emit_int32 (acfg, 0);
5900 emit_int32 (acfg, 0);
5901 emit_int32 (acfg, 0);
5902 } else {
5903 //g_assert (entry->key > 0);
5904 emit_int32 (acfg, entry->key);
5905 emit_int32 (acfg, entry->value);
5906 if (entry->next)
5907 emit_int32 (acfg, entry->next->index);
5908 else
5909 emit_int32 (acfg, 0);
5914 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5915 * This is used by mono_aot_find_jit_info ().
5917 sprintf (symbol, "extra_method_info_offsets");
5918 emit_section_change (acfg, RODATA_SECT, 0);
5919 emit_alignment (acfg, 8);
5920 emit_label (acfg, symbol);
5922 emit_int32 (acfg, acfg->extra_methods->len);
5923 for (i = 0; i < acfg->extra_methods->len; ++i) {
5924 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5926 emit_int32 (acfg, get_method_index (acfg, method));
5927 emit_int32 (acfg, info_offsets [i]);
5931 static void
5932 emit_exception_info (MonoAotCompile *acfg)
5934 int i;
5935 char symbol [256];
5936 gint32 *offsets;
5938 offsets = g_new0 (gint32, acfg->nmethods);
5939 for (i = 0; i < acfg->nmethods; ++i) {
5940 if (acfg->cfgs [i]) {
5941 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5942 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5943 } else {
5944 offsets [i] = 0;
5948 sprintf (symbol, "ex_info_offsets");
5949 emit_section_change (acfg, RODATA_SECT, 1);
5950 emit_alignment (acfg, 8);
5951 emit_label (acfg, symbol);
5953 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5954 g_free (offsets);
5957 static void
5958 emit_unwind_info (MonoAotCompile *acfg)
5960 int i;
5961 char symbol [128];
5964 * The unwind info contains a lot of duplicates so we emit each unique
5965 * entry once, and only store the offset from the start of the table in the
5966 * exception info.
5969 sprintf (symbol, "unwind_info");
5970 emit_section_change (acfg, RODATA_SECT, 1);
5971 emit_alignment (acfg, 8);
5972 emit_label (acfg, symbol);
5974 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5975 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5976 guint8 *unwind_info;
5977 guint32 unwind_info_len;
5978 guint8 buf [16];
5979 guint8 *p;
5981 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5983 p = buf;
5984 encode_value (unwind_info_len, p, &p);
5985 emit_bytes (acfg, buf, p - buf);
5986 emit_bytes (acfg, unwind_info, unwind_info_len);
5988 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5992 static void
5993 emit_class_info (MonoAotCompile *acfg)
5995 int i;
5996 char symbol [256];
5997 gint32 *offsets;
5999 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6000 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6001 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6003 sprintf (symbol, "class_info_offsets");
6004 emit_section_change (acfg, RODATA_SECT, 1);
6005 emit_alignment (acfg, 8);
6006 emit_label (acfg, symbol);
6008 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6009 g_free (offsets);
6012 typedef struct ClassNameTableEntry {
6013 guint32 token, index;
6014 struct ClassNameTableEntry *next;
6015 } ClassNameTableEntry;
6017 static void
6018 emit_class_name_table (MonoAotCompile *acfg)
6020 int i, table_size;
6021 guint32 token, hash;
6022 MonoClass *klass;
6023 GPtrArray *table;
6024 char *full_name;
6025 char symbol [256];
6026 ClassNameTableEntry *entry, *new_entry;
6029 * Construct a chained hash table for mapping class names to typedef tokens.
6031 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6032 table = g_ptr_array_sized_new (table_size);
6033 for (i = 0; i < table_size; ++i)
6034 g_ptr_array_add (table, NULL);
6035 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6036 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6037 klass = mono_class_get (acfg->image, token);
6038 if (!klass) {
6039 mono_loader_clear_error ();
6040 continue;
6042 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6043 hash = mono_metadata_str_hash (full_name) % table_size;
6044 g_free (full_name);
6046 /* FIXME: Allocate from the mempool */
6047 new_entry = g_new0 (ClassNameTableEntry, 1);
6048 new_entry->token = token;
6050 entry = g_ptr_array_index (table, hash);
6051 if (entry == NULL) {
6052 new_entry->index = hash;
6053 g_ptr_array_index (table, hash) = new_entry;
6054 } else {
6055 while (entry->next)
6056 entry = entry->next;
6058 entry->next = new_entry;
6059 new_entry->index = table->len;
6060 g_ptr_array_add (table, new_entry);
6064 /* Emit the table */
6065 sprintf (symbol, "class_name_table");
6066 emit_section_change (acfg, RODATA_SECT, 0);
6067 emit_alignment (acfg, 8);
6068 emit_label (acfg, symbol);
6070 /* FIXME: Optimize memory usage */
6071 g_assert (table_size < 65000);
6072 emit_int16 (acfg, table_size);
6073 g_assert (table->len < 65000);
6074 for (i = 0; i < table->len; ++i) {
6075 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6077 if (entry == NULL) {
6078 emit_int16 (acfg, 0);
6079 emit_int16 (acfg, 0);
6080 } else {
6081 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6082 if (entry->next)
6083 emit_int16 (acfg, entry->next->index);
6084 else
6085 emit_int16 (acfg, 0);
6090 static void
6091 emit_image_table (MonoAotCompile *acfg)
6093 int i;
6094 char symbol [256];
6097 * The image table is small but referenced in a lot of places.
6098 * So we emit it at once, and reference its elements by an index.
6101 sprintf (symbol, "image_table");
6102 emit_section_change (acfg, RODATA_SECT, 1);
6103 emit_alignment (acfg, 8);
6104 emit_label (acfg, symbol);
6106 emit_int32 (acfg, acfg->image_table->len);
6107 for (i = 0; i < acfg->image_table->len; i++) {
6108 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6109 MonoAssemblyName *aname = &image->assembly->aname;
6111 /* FIXME: Support multi-module assemblies */
6112 g_assert (image->assembly->image == image);
6114 emit_string (acfg, image->assembly_name);
6115 emit_string (acfg, image->guid);
6116 emit_string (acfg, aname->culture ? aname->culture : "");
6117 emit_string (acfg, (const char*)aname->public_key_token);
6119 emit_alignment (acfg, 8);
6120 emit_int32 (acfg, aname->flags);
6121 emit_int32 (acfg, aname->major);
6122 emit_int32 (acfg, aname->minor);
6123 emit_int32 (acfg, aname->build);
6124 emit_int32 (acfg, aname->revision);
6128 static void
6129 emit_got_info (MonoAotCompile *acfg)
6131 char symbol [256];
6132 int i, first_plt_got_patch, buf_size;
6133 guint8 *p, *buf;
6134 guint32 *got_info_offsets;
6136 /* Add the patches needed by the PLT to the GOT */
6137 acfg->plt_got_offset_base = acfg->got_offset;
6138 first_plt_got_patch = acfg->got_patches->len;
6139 for (i = 1; i < acfg->plt_offset; ++i) {
6140 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6142 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6145 acfg->got_offset += acfg->plt_offset;
6148 * FIXME:
6149 * - optimize offsets table.
6150 * - reduce number of exported symbols.
6151 * - emit info for a klass only once.
6152 * - determine when a method uses a GOT slot which is guaranteed to be already
6153 * initialized.
6154 * - clean up and document the code.
6155 * - use String.Empty in class libs.
6158 /* Encode info required to decode shared GOT entries */
6159 buf_size = acfg->got_patches->len * 128;
6160 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6161 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6162 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6163 /* Unused */
6164 if (acfg->plt_offset)
6165 acfg->plt_got_info_offsets [0] = 0;
6166 for (i = 0; i < acfg->got_patches->len; ++i) {
6167 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6169 p = buf;
6171 encode_value (ji->type, p, &p);
6172 encode_patch (acfg, ji, p, &p);
6174 g_assert (p - buf <= buf_size);
6175 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6177 if (i >= first_plt_got_patch)
6178 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6179 acfg->stats.got_info_size += p - buf;
6182 /* Emit got_info_offsets table */
6183 sprintf (symbol, "got_info_offsets");
6184 emit_section_change (acfg, RODATA_SECT, 1);
6185 emit_alignment (acfg, 8);
6186 emit_label (acfg, symbol);
6188 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6189 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6192 static void
6193 emit_got (MonoAotCompile *acfg)
6195 char symbol [256];
6197 if (!acfg->llvm) {
6198 /* Don't make GOT global so accesses to it don't need relocations */
6199 sprintf (symbol, "%s", acfg->got_symbol);
6200 emit_section_change (acfg, ".bss", 0);
6201 emit_alignment (acfg, 8);
6202 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6203 emit_label (acfg, symbol);
6204 if (acfg->got_offset > 0)
6205 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6207 sprintf (symbol, "got_end");
6208 emit_label (acfg, symbol);
6212 typedef struct GlobalsTableEntry {
6213 guint32 value, index;
6214 struct GlobalsTableEntry *next;
6215 } GlobalsTableEntry;
6217 static void
6218 emit_globals (MonoAotCompile *acfg)
6220 int i, table_size;
6221 guint32 hash;
6222 GPtrArray *table;
6223 char symbol [256];
6224 GlobalsTableEntry *entry, *new_entry;
6226 if (!acfg->aot_opts.static_link)
6227 return;
6230 * When static linking, we emit a table containing our globals.
6234 * Construct a chained hash table for mapping global names to their index in
6235 * the globals table.
6237 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6238 table = g_ptr_array_sized_new (table_size);
6239 for (i = 0; i < table_size; ++i)
6240 g_ptr_array_add (table, NULL);
6241 for (i = 0; i < acfg->globals->len; ++i) {
6242 char *name = g_ptr_array_index (acfg->globals, i);
6244 hash = mono_metadata_str_hash (name) % table_size;
6246 /* FIXME: Allocate from the mempool */
6247 new_entry = g_new0 (GlobalsTableEntry, 1);
6248 new_entry->value = i;
6250 entry = g_ptr_array_index (table, hash);
6251 if (entry == NULL) {
6252 new_entry->index = hash;
6253 g_ptr_array_index (table, hash) = new_entry;
6254 } else {
6255 while (entry->next)
6256 entry = entry->next;
6258 entry->next = new_entry;
6259 new_entry->index = table->len;
6260 g_ptr_array_add (table, new_entry);
6264 /* Emit the table */
6265 sprintf (symbol, ".Lglobals_hash");
6266 emit_section_change (acfg, RODATA_SECT, 0);
6267 emit_alignment (acfg, 8);
6268 emit_label (acfg, symbol);
6270 /* FIXME: Optimize memory usage */
6271 g_assert (table_size < 65000);
6272 emit_int16 (acfg, table_size);
6273 for (i = 0; i < table->len; ++i) {
6274 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6276 if (entry == NULL) {
6277 emit_int16 (acfg, 0);
6278 emit_int16 (acfg, 0);
6279 } else {
6280 emit_int16 (acfg, entry->value + 1);
6281 if (entry->next)
6282 emit_int16 (acfg, entry->next->index);
6283 else
6284 emit_int16 (acfg, 0);
6288 /* Emit the names */
6289 for (i = 0; i < acfg->globals->len; ++i) {
6290 char *name = g_ptr_array_index (acfg->globals, i);
6292 sprintf (symbol, "name_%d", i);
6293 emit_section_change (acfg, RODATA_SECT, 1);
6294 emit_label (acfg, symbol);
6295 emit_string (acfg, name);
6298 /* Emit the globals table */
6299 sprintf (symbol, "globals");
6300 emit_section_change (acfg, ".data", 0);
6301 /* This is not a global, since it is accessed by the init function */
6302 emit_alignment (acfg, 8);
6303 emit_label (acfg, symbol);
6305 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6306 emit_pointer (acfg, symbol);
6308 for (i = 0; i < acfg->globals->len; ++i) {
6309 char *name = g_ptr_array_index (acfg->globals, i);
6311 sprintf (symbol, "name_%d", i);
6312 emit_pointer (acfg, symbol);
6314 sprintf (symbol, "%s", name);
6315 emit_pointer (acfg, symbol);
6317 /* Null terminate the table */
6318 emit_int32 (acfg, 0);
6319 emit_int32 (acfg, 0);
6322 static void
6323 emit_autoreg (MonoAotCompile *acfg)
6325 char *symbol;
6328 * Emit a function into the .ctor section which will be called by the ELF
6329 * loader to register this module with the runtime.
6331 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6332 return;
6334 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6336 arch_emit_autoreg (acfg, symbol);
6338 g_free (symbol);
6341 static void
6342 emit_mem_end (MonoAotCompile *acfg)
6344 char symbol [128];
6346 sprintf (symbol, "mem_end");
6347 emit_section_change (acfg, ".text", 1);
6348 emit_alignment (acfg, 8);
6349 emit_label (acfg, symbol);
6353 * Emit a structure containing all the information not stored elsewhere.
6355 static void
6356 emit_file_info (MonoAotCompile *acfg)
6358 char symbol [256];
6359 int i;
6360 int gc_name_offset;
6361 const char *gc_name;
6362 char *build_info;
6364 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6366 if (acfg->aot_opts.bind_to_runtime_version) {
6367 build_info = mono_get_runtime_build_info ();
6368 emit_string_symbol (acfg, "runtime_version", build_info);
6369 g_free (build_info);
6370 } else {
6371 emit_string_symbol (acfg, "runtime_version", "");
6374 /* Emit a string holding the assembly name */
6375 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6378 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6379 * in another.
6381 gc_name = mono_gc_get_gc_name ();
6382 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6384 sprintf (symbol, "mono_aot_file_info");
6385 emit_section_change (acfg, ".data", 0);
6386 emit_alignment (acfg, 8);
6387 emit_label (acfg, symbol);
6388 if (!acfg->aot_opts.static_link)
6389 emit_global (acfg, symbol, FALSE);
6391 /* The data emitted here must match MonoAotFileInfo. */
6393 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6394 emit_int32 (acfg, 0);
6397 * We emit pointers to our data structures instead of emitting global symbols which
6398 * point to them, to reduce the number of globals, and because using globals leads to
6399 * various problems (i.e. arm/thumb).
6401 emit_pointer (acfg, acfg->got_symbol);
6402 emit_pointer (acfg, "methods");
6403 if (acfg->llvm) {
6405 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6407 emit_pointer (acfg, "mono_eh_frame");
6408 } else {
6409 emit_pointer (acfg, NULL);
6411 emit_pointer (acfg, "blob");
6412 emit_pointer (acfg, "class_name_table");
6413 emit_pointer (acfg, "class_info_offsets");
6414 emit_pointer (acfg, "method_info_offsets");
6415 emit_pointer (acfg, "ex_info_offsets");
6416 emit_pointer (acfg, "code_offsets");
6417 emit_pointer (acfg, "extra_method_info_offsets");
6418 emit_pointer (acfg, "extra_method_table");
6419 emit_pointer (acfg, "got_info_offsets");
6420 emit_pointer (acfg, "methods_end");
6421 emit_pointer (acfg, "unwind_info");
6422 emit_pointer (acfg, "mem_end");
6423 emit_pointer (acfg, "image_table");
6424 emit_pointer (acfg, "plt");
6425 emit_pointer (acfg, "plt_end");
6426 emit_pointer (acfg, "assembly_guid");
6427 emit_pointer (acfg, "runtime_version");
6428 if (acfg->num_trampoline_got_entries) {
6429 emit_pointer (acfg, "specific_trampolines");
6430 emit_pointer (acfg, "static_rgctx_trampolines");
6431 emit_pointer (acfg, "imt_thunks");
6432 } else {
6433 emit_pointer (acfg, NULL);
6434 emit_pointer (acfg, NULL);
6435 emit_pointer (acfg, NULL);
6437 if (acfg->thumb_mixed) {
6438 emit_pointer (acfg, "thumb_end");
6439 } else {
6440 emit_pointer (acfg, NULL);
6442 if (acfg->aot_opts.static_link) {
6443 emit_pointer (acfg, "globals");
6444 } else {
6445 emit_pointer (acfg, NULL);
6447 emit_pointer (acfg, "assembly_name");
6449 emit_int32 (acfg, acfg->plt_got_offset_base);
6450 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6451 emit_int32 (acfg, acfg->plt_offset);
6452 emit_int32 (acfg, acfg->nmethods);
6453 emit_int32 (acfg, acfg->flags);
6454 emit_int32 (acfg, acfg->opts);
6455 emit_int32 (acfg, gc_name_offset);
6457 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6458 emit_int32 (acfg, acfg->num_trampolines [i]);
6459 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6460 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6461 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6462 emit_int32 (acfg, acfg->trampoline_size [i]);
6464 #if defined (TARGET_ARM) && defined (__APPLE__)
6466 MonoType t;
6467 int align = 0;
6469 t.type = MONO_TYPE_R8;
6470 mono_type_size (&t, &align);
6472 emit_int32 (acfg, align);
6474 t.type = MONO_TYPE_I8;
6475 mono_type_size (&t, &align);
6477 emit_int32 (acfg, align);
6479 #else
6480 emit_int32 (acfg, __alignof__ (double));
6481 emit_int32 (acfg, __alignof__ (gint64));
6482 #endif
6484 if (acfg->aot_opts.static_link) {
6485 char *p;
6488 * Emit a global symbol which can be passed by an embedding app to
6489 * mono_aot_register_module (). The symbol points to a pointer to the the file info
6490 * structure.
6492 #if defined(__APPLE__) && !defined(__native_client_codegen__)
6493 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6494 #else
6495 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6496 #endif
6498 /* Get rid of characters which cannot occur in symbols */
6499 p = symbol;
6500 for (p = symbol; *p; ++p) {
6501 if (!(isalnum (*p) || *p == '_'))
6502 *p = '_';
6504 acfg->static_linking_symbol = g_strdup (symbol);
6505 emit_global_inner (acfg, symbol, FALSE);
6506 emit_label (acfg, symbol);
6507 emit_pointer (acfg, "mono_aot_file_info");
6511 static void
6512 emit_blob (MonoAotCompile *acfg)
6514 char symbol [128];
6516 sprintf (symbol, "blob");
6517 emit_section_change (acfg, RODATA_SECT, 1);
6518 emit_alignment (acfg, 8);
6519 emit_label (acfg, symbol);
6521 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6524 static void
6525 emit_dwarf_info (MonoAotCompile *acfg)
6527 #ifdef EMIT_DWARF_INFO
6528 int i;
6529 char symbol [128], symbol2 [128];
6531 /* DIEs for methods */
6532 for (i = 0; i < acfg->nmethods; ++i) {
6533 MonoCompile *cfg = acfg->cfgs [i];
6535 if (!cfg)
6536 continue;
6538 // FIXME: LLVM doesn't define .Lme_...
6539 if (cfg->compile_llvm)
6540 continue;
6542 sprintf (symbol, "%s", cfg->asm_symbol);
6543 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6545 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
6547 #endif
6550 static void
6551 collect_methods (MonoAotCompile *acfg)
6553 int i;
6554 MonoImage *image = acfg->image;
6556 /* Collect methods */
6557 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6558 MonoMethod *method;
6559 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6561 method = mono_get_method (acfg->image, token, NULL);
6563 if (!method) {
6564 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
6565 exit (1);
6568 /* Load all methods eagerly to skip the slower lazy loading code */
6569 mono_class_setup_methods (method->klass);
6571 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6572 /* Compile the wrapper instead */
6573 /* We do this here instead of add_wrappers () because it is easy to do it here */
6574 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6575 method = wrapper;
6578 /* FIXME: Some mscorlib methods don't have debug info */
6580 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
6581 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6582 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6583 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
6584 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
6585 if (!mono_debug_lookup_method (method)) {
6586 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
6587 exit (1);
6593 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6594 add_method_with_index (acfg, method, i, FALSE);
6595 acfg->method_index ++;
6598 add_generic_instances (acfg);
6600 if (acfg->aot_opts.full_aot)
6601 add_wrappers (acfg);
6604 static void
6605 compile_methods (MonoAotCompile *acfg)
6607 int i, methods_len;
6609 if (acfg->aot_opts.nthreads > 0) {
6610 GPtrArray *frag;
6611 int len, j;
6612 GPtrArray *threads;
6613 HANDLE handle;
6614 gpointer *user_data;
6615 MonoMethod **methods;
6617 methods_len = acfg->methods->len;
6619 len = acfg->methods->len / acfg->aot_opts.nthreads;
6620 g_assert (len > 0);
6622 * Partition the list of methods into fragments, and hand it to threads to
6623 * process.
6625 threads = g_ptr_array_new ();
6626 /* Make a copy since acfg->methods is modified by compile_method () */
6627 methods = g_new0 (MonoMethod*, methods_len);
6628 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6629 for (i = 0; i < methods_len; ++i)
6630 methods [i] = g_ptr_array_index (acfg->methods, i);
6631 i = 0;
6632 while (i < methods_len) {
6633 frag = g_ptr_array_new ();
6634 for (j = 0; j < len; ++j) {
6635 if (i < methods_len) {
6636 g_ptr_array_add (frag, methods [i]);
6637 i ++;
6641 user_data = g_new0 (gpointer, 3);
6642 user_data [0] = mono_domain_get ();
6643 user_data [1] = acfg;
6644 user_data [2] = frag;
6646 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6647 g_ptr_array_add (threads, handle);
6649 g_free (methods);
6651 for (i = 0; i < threads->len; ++i) {
6652 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6654 } else {
6655 methods_len = 0;
6658 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6659 for (i = methods_len; i < acfg->methods->len; ++i) {
6660 /* This can new methods to acfg->methods */
6661 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6665 static int
6666 compile_asm (MonoAotCompile *acfg)
6668 char *command, *objfile;
6669 char *outfile_name, *tmp_outfile_name;
6670 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6672 #if defined(TARGET_AMD64)
6673 #define AS_OPTIONS "--64"
6674 #elif defined(TARGET_POWERPC64)
6675 #define AS_OPTIONS "-a64 -mppc64"
6676 #define LD_OPTIONS "-m elf64ppc"
6677 #elif defined(sparc) && SIZEOF_VOID_P == 8
6678 #define AS_OPTIONS "-xarch=v9"
6679 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6680 #define AS_OPTIONS "-arch i386 -W"
6681 #else
6682 #define AS_OPTIONS ""
6683 #endif
6685 #ifdef __native_client_codegen__
6686 #if defined(TARGET_AMD64)
6687 #define AS_NAME "nacl64-as"
6688 #else
6689 #define AS_NAME "nacl-as"
6690 #endif
6691 #else
6692 #define AS_NAME "as"
6693 #endif
6695 #ifndef LD_OPTIONS
6696 #define LD_OPTIONS ""
6697 #endif
6699 #define EH_LD_OPTIONS ""
6701 if (acfg->aot_opts.asm_only) {
6702 printf ("Output file: '%s'.\n", acfg->tmpfname);
6703 if (acfg->aot_opts.static_link)
6704 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6705 return 0;
6708 if (acfg->aot_opts.static_link) {
6709 if (acfg->aot_opts.outfile)
6710 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6711 else
6712 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6713 } else {
6714 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6716 command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
6717 printf ("Executing the native assembler: %s\n", command);
6718 if (system (command) != 0) {
6719 g_free (command);
6720 g_free (objfile);
6721 return 1;
6724 g_free (command);
6726 if (acfg->aot_opts.static_link) {
6727 printf ("Output file: '%s'.\n", objfile);
6728 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6729 g_free (objfile);
6730 return 0;
6733 if (acfg->aot_opts.outfile)
6734 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6735 else
6736 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6738 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6740 #if defined(sparc)
6741 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6742 #elif defined(__ppc__) && defined(__APPLE__)
6743 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6744 #elif defined(HOST_WIN32)
6745 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6746 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6747 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6748 #else
6749 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6750 #endif
6751 printf ("Executing the native linker: %s\n", command);
6752 if (system (command) != 0) {
6753 g_free (tmp_outfile_name);
6754 g_free (outfile_name);
6755 g_free (command);
6756 g_free (objfile);
6757 return 1;
6760 g_free (command);
6761 unlink (objfile);
6762 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6763 printf ("Stripping the binary: %s\n", com);
6764 system (com);
6765 g_free (com);*/
6767 #if defined(TARGET_ARM) && !defined(__APPLE__)
6769 * gas generates 'mapping symbols' each time code and data is mixed, which
6770 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6772 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6773 printf ("Stripping the binary: %s\n", command);
6774 if (system (command) != 0) {
6775 g_free (tmp_outfile_name);
6776 g_free (outfile_name);
6777 g_free (command);
6778 g_free (objfile);
6779 return 1;
6781 #endif
6783 rename (tmp_outfile_name, outfile_name);
6785 g_free (tmp_outfile_name);
6786 g_free (outfile_name);
6787 g_free (objfile);
6789 if (acfg->aot_opts.save_temps)
6790 printf ("Retained input file.\n");
6791 else
6792 unlink (acfg->tmpfname);
6794 return 0;
6797 static MonoAotCompile*
6798 acfg_create (MonoAssembly *ass, guint32 opts)
6800 MonoImage *image = ass->image;
6801 MonoAotCompile *acfg;
6802 int i;
6804 acfg = g_new0 (MonoAotCompile, 1);
6805 acfg->methods = g_ptr_array_new ();
6806 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6807 acfg->method_depth = g_hash_table_new (NULL, NULL);
6808 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6809 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6810 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6811 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6812 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6813 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6814 acfg->got_patches = g_ptr_array_new ();
6815 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6816 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6817 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6818 acfg->image_hash = g_hash_table_new (NULL, NULL);
6819 acfg->image_table = g_ptr_array_new ();
6820 acfg->globals = g_ptr_array_new ();
6821 acfg->image = image;
6822 acfg->opts = opts;
6823 acfg->mempool = mono_mempool_new ();
6824 acfg->extra_methods = g_ptr_array_new ();
6825 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6826 acfg->unwind_ops = g_ptr_array_new ();
6827 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6828 acfg->method_order = g_ptr_array_new ();
6829 InitializeCriticalSection (&acfg->mutex);
6831 return acfg;
6834 static void
6835 acfg_free (MonoAotCompile *acfg)
6837 int i;
6839 img_writer_destroy (acfg->w);
6840 for (i = 0; i < acfg->nmethods; ++i)
6841 if (acfg->cfgs [i])
6842 g_free (acfg->cfgs [i]);
6843 g_free (acfg->cfgs);
6844 g_free (acfg->static_linking_symbol);
6845 g_free (acfg->got_symbol);
6846 g_free (acfg->plt_symbol);
6847 g_ptr_array_free (acfg->methods, TRUE);
6848 g_ptr_array_free (acfg->got_patches, TRUE);
6849 g_ptr_array_free (acfg->image_table, TRUE);
6850 g_ptr_array_free (acfg->globals, TRUE);
6851 g_ptr_array_free (acfg->unwind_ops, TRUE);
6852 g_hash_table_destroy (acfg->method_indexes);
6853 g_hash_table_destroy (acfg->method_depth);
6854 g_hash_table_destroy (acfg->plt_offset_to_entry);
6855 g_hash_table_destroy (acfg->patch_to_plt_entry);
6856 g_hash_table_destroy (acfg->patch_to_got_offset);
6857 g_hash_table_destroy (acfg->method_to_cfg);
6858 g_hash_table_destroy (acfg->token_info_hash);
6859 g_hash_table_destroy (acfg->method_to_pinvoke_import);
6860 g_hash_table_destroy (acfg->image_hash);
6861 g_hash_table_destroy (acfg->unwind_info_offsets);
6862 g_hash_table_destroy (acfg->method_label_hash);
6863 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6864 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6865 g_free (acfg->patch_to_got_offset_by_type);
6866 mono_mempool_destroy (acfg->mempool);
6867 g_free (acfg);
6871 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6873 MonoImage *image = ass->image;
6874 int i, res;
6875 MonoAotCompile *acfg;
6876 char *outfile_name, *tmp_outfile_name, *p;
6877 TV_DECLARE (atv);
6878 TV_DECLARE (btv);
6880 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6882 acfg = acfg_create (ass, opts);
6884 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6885 acfg->aot_opts.write_symbols = TRUE;
6886 acfg->aot_opts.ntrampolines = 1024;
6887 acfg->aot_opts.nrgctx_trampolines = 1024;
6888 acfg->aot_opts.nimt_trampolines = 128;
6889 acfg->aot_opts.llvm_path = g_strdup ("");
6891 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6893 if (acfg->aot_opts.static_link)
6894 acfg->aot_opts.autoreg = TRUE;
6896 //acfg->aot_opts.print_skipped_methods = TRUE;
6898 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6899 if (acfg->aot_opts.full_aot) {
6900 printf ("--aot=full is not supported on this platform.\n");
6901 return 1;
6903 #endif
6905 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
6906 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
6907 exit (1);
6910 if (acfg->aot_opts.static_link)
6911 acfg->aot_opts.asm_writer = TRUE;
6913 if (acfg->aot_opts.soft_debug) {
6914 MonoDebugOptions *opt = mini_get_debug_options ();
6916 opt->mdb_optimizations = TRUE;
6917 opt->gen_seq_points = TRUE;
6919 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6920 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6921 return 1;
6923 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6926 if (mono_use_llvm) {
6927 acfg->llvm = TRUE;
6928 acfg->aot_opts.asm_writer = TRUE;
6929 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6931 if (acfg->aot_opts.soft_debug) {
6932 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
6933 exit (1);
6937 if (acfg->aot_opts.full_aot)
6938 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6940 load_profile_files (acfg);
6942 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6943 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6944 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6945 #endif
6946 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6948 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6950 arch_init (acfg);
6952 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6953 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6954 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
6956 /* Get rid of characters which cannot occur in symbols */
6957 for (p = acfg->got_symbol_base; *p; ++p) {
6958 if (!(isalnum (*p) || *p == '_'))
6959 *p = '_';
6961 for (p = acfg->plt_symbol; *p; ++p) {
6962 if (!(isalnum (*p) || *p == '_'))
6963 *p = '_';
6965 for (p = acfg->assembly_name_sym; *p; ++p) {
6966 if (!(isalnum (*p) || *p == '_'))
6967 *p = '_';
6970 acfg->method_index = 1;
6972 collect_methods (acfg);
6974 acfg->cfgs_size = acfg->methods->len + 32;
6975 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6977 /* PLT offset 0 is reserved for the PLT trampoline */
6978 acfg->plt_offset = 1;
6980 #ifdef ENABLE_LLVM
6981 if (acfg->llvm) {
6982 llvm_acfg = acfg;
6983 mono_llvm_create_aot_module (acfg->got_symbol_base);
6985 #endif
6987 /* GOT offset 0 is reserved for the address of the current assembly */
6989 MonoJumpInfo *ji;
6991 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6992 ji->type = MONO_PATCH_INFO_IMAGE;
6993 ji->data.image = acfg->image;
6995 get_got_offset (acfg, ji);
6997 /* Slot 1 is reserved for the mscorlib got addr */
6998 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6999 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
7000 get_got_offset (acfg, ji);
7002 /* This is very common */
7003 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7004 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
7005 get_got_offset (acfg, ji);
7008 TV_GETTIME (atv);
7010 compile_methods (acfg);
7012 TV_GETTIME (btv);
7014 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7016 TV_GETTIME (atv);
7018 #ifdef ENABLE_LLVM
7019 if (acfg->llvm) {
7020 if (acfg->aot_opts.asm_only) {
7021 if (acfg->aot_opts.outfile)
7022 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7023 else
7024 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7025 } else {
7026 acfg->tmpfname = g_strdup ("temp.s");
7029 emit_llvm_file (acfg);
7031 #endif
7033 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7034 if (acfg->aot_opts.outfile)
7035 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7036 else
7037 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7040 * Can't use g_file_open_tmp () as it will be deleted at exit, and
7041 * it might be in another file system so the rename () won't work.
7043 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7045 acfg->fp = fopen (tmp_outfile_name, "w");
7046 if (!acfg->fp) {
7047 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7048 return 1;
7051 acfg->w = img_writer_create (acfg->fp, TRUE);
7052 acfg->use_bin_writer = TRUE;
7053 } else {
7054 if (acfg->llvm) {
7055 /* Append to the .s file created by llvm */
7056 /* FIXME: Use multiple files instead */
7057 acfg->fp = fopen (acfg->tmpfname, "a+");
7058 } else {
7059 if (acfg->aot_opts.asm_only) {
7060 if (acfg->aot_opts.outfile)
7061 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7062 else
7063 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7064 acfg->fp = fopen (acfg->tmpfname, "w+");
7065 } else {
7066 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7067 acfg->fp = fdopen (i, "w+");
7069 if (acfg->fp == 0) {
7070 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
7071 return 1;
7074 acfg->w = img_writer_create (acfg->fp, FALSE);
7076 tmp_outfile_name = NULL;
7077 outfile_name = NULL;
7080 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7082 /* Compute symbols for methods */
7083 for (i = 0; i < acfg->nmethods; ++i) {
7084 if (acfg->cfgs [i]) {
7085 MonoCompile *cfg = acfg->cfgs [i];
7086 int method_index = get_method_index (acfg, cfg->orig_method);
7088 if (COMPILE_LLVM (cfg))
7089 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7090 else
7091 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7095 if (!acfg->aot_opts.nodebug)
7096 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7098 img_writer_emit_start (acfg->w);
7100 if (acfg->dwarf)
7101 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7103 if (acfg->thumb_mixed) {
7104 char symbol [256];
7106 * This global symbol marks the end of THUMB code, and the beginning of ARM
7107 * code generated by our JIT.
7109 sprintf (symbol, "thumb_end");
7110 emit_section_change (acfg, ".text", 0);
7111 emit_label (acfg, symbol);
7112 emit_zero_bytes (acfg, 16);
7114 fprintf (acfg->fp, ".arm\n");
7117 emit_code (acfg);
7119 emit_info (acfg);
7121 emit_extra_methods (acfg);
7123 emit_trampolines (acfg);
7125 emit_class_name_table (acfg);
7127 emit_got_info (acfg);
7129 emit_exception_info (acfg);
7131 emit_unwind_info (acfg);
7133 emit_class_info (acfg);
7135 emit_plt (acfg);
7137 emit_image_table (acfg);
7139 emit_got (acfg);
7141 emit_file_info (acfg);
7143 emit_blob (acfg);
7145 emit_globals (acfg);
7147 emit_autoreg (acfg);
7149 if (acfg->dwarf) {
7150 emit_dwarf_info (acfg);
7151 mono_dwarf_writer_close (acfg->dwarf);
7154 emit_mem_end (acfg);
7156 if (acfg->need_pt_gnu_stack) {
7157 /* This is required so the .so doesn't have an executable stack */
7158 /* The bin writer already emits this */
7159 if (!acfg->use_bin_writer)
7160 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7163 TV_GETTIME (btv);
7165 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7167 if (acfg->llvm)
7168 g_assert (acfg->got_offset <= acfg->final_got_size);
7170 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
7172 TV_GETTIME (atv);
7173 res = img_writer_emit_writeout (acfg->w);
7174 if (res != 0) {
7175 acfg_free (acfg);
7176 return res;
7178 if (acfg->use_bin_writer) {
7179 int err = rename (tmp_outfile_name, outfile_name);
7181 if (err) {
7182 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7183 return 1;
7185 } else {
7186 res = compile_asm (acfg);
7187 if (res != 0) {
7188 acfg_free (acfg);
7189 return res;
7192 TV_GETTIME (btv);
7193 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7195 printf ("Compiled %d out of %d methods (%d%%)\n", acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100);
7196 if (acfg->stats.genericcount)
7197 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7198 if (acfg->stats.abscount)
7199 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7200 if (acfg->stats.lmfcount)
7201 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7202 if (acfg->stats.ocount)
7203 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7204 if (acfg->llvm)
7205 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7206 printf ("Methods without GOT slots: %d (%d%%)\n", acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100);
7207 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7209 if (acfg->aot_opts.stats) {
7210 int i;
7212 printf ("GOT slot distribution:\n");
7213 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7214 if (acfg->stats.got_slot_types [i])
7215 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
7218 printf ("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);
7220 acfg_free (acfg);
7222 return 0;
7225 #else
7227 /* AOT disabled */
7230 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7232 return 0;
7235 #endif