2009-10-06 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / aot-compiler.c
1 /*
2  * aot-compiler.c: mono Ahead of Time compiler
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Zoltan Varga (vargaz@gmail.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 /* Remaining AOT-only work:
12  * - optimize the trampolines, generate more code in the arch files.
13  * - make things more consistent with how elf works, for example, use ELF 
14  *   relocations.
15  * Remaining generics sharing work:
16  * - optimize the size of the data which is encoded.
17  * - optimize the runtime loading of data:
18  *   - the trampoline code calls mono_jit_info_table_find () to find the rgctx, 
19  *     which loads the debugging+exception handling info for the method. This is a 
20  *     huge waste of time and code, since the rgctx structure is currently empty.
21  *   - every shared method has a MonoGenericJitInfo structure which is only really
22  *     used for handling catch clauses with open types, not a very common use case.
23  */
24
25 #include "config.h"
26 #include <sys/types.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #ifdef HAVE_STDINT_H
31 #include <stdint.h>
32 #endif
33 #include <fcntl.h>
34 #include <ctype.h>
35 #include <string.h>
36 #ifndef PLATFORM_WIN32
37 #include <sys/time.h>
38 #else
39 #include <winsock2.h>
40 #include <windows.h>
41 #endif
42
43 #include <errno.h>
44 #include <sys/stat.h>
45
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
64
65 #include "mini.h"
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
68
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
70
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
74
75 #ifdef PLATFORM_WIN32
76 #define SHARED_EXT ".dll"
77 #elif defined(__ppc__) && defined(__MACH__)
78 #define SHARED_EXT ".dylib"
79 #else
80 #define SHARED_EXT ".so"
81 #endif
82
83 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
84 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
85 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
86
87 typedef struct MonoAotOptions {
88         char *outfile;
89         gboolean save_temps;
90         gboolean write_symbols;
91         gboolean metadata_only;
92         gboolean bind_to_runtime_version;
93         gboolean full_aot;
94         gboolean no_dlsym;
95         gboolean static_link;
96         gboolean asm_only;
97         gboolean asm_writer;
98         gboolean nodebug;
99         int nthreads;
100         int ntrampolines;
101         gboolean print_skipped_methods;
102         char *tool_prefix;
103 } MonoAotOptions;
104
105 typedef struct MonoAotStats {
106         int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
107         int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
108         int methods_without_got_slots, direct_calls, all_calls;
109         int got_slots;
110         int got_slot_types [MONO_PATCH_INFO_NONE];
111         int jit_time, gen_time, link_time;
112 } MonoAotStats;
113
114 typedef struct MonoAotCompile {
115         MonoImage *image;
116         GPtrArray *methods;
117         GHashTable *method_indexes;
118         MonoCompile **cfgs;
119         int cfgs_size;
120         GHashTable *patch_to_plt_offset;
121         GHashTable *plt_offset_to_patch;
122         GHashTable *patch_to_got_offset;
123         GPtrArray *got_patches;
124         GHashTable *image_hash;
125         GHashTable *method_to_cfg;
126         GHashTable *token_info_hash;
127         GPtrArray *extra_methods;
128         GPtrArray *image_table;
129         GPtrArray *globals;
130         GList *method_order;
131         guint32 *plt_got_info_offsets;
132         guint32 got_offset, plt_offset, plt_got_offset_base;
133         /* Number of GOT entries reserved for trampolines */
134         guint32 num_trampoline_got_entries;
135
136         guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
137         guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
138         guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
139
140         MonoAotOptions aot_opts;
141         guint32 nmethods;
142         guint32 opts;
143         MonoMemPool *mempool;
144         MonoAotStats stats;
145         int method_index;
146         char *static_linking_symbol;
147         CRITICAL_SECTION mutex;
148         gboolean use_bin_writer;
149         MonoImageWriter *w;
150         MonoDwarfWriter *dwarf;
151         FILE *fp;
152         char *tmpfname;
153         GSList *cie_program;
154         GHashTable *unwind_info_offsets;
155         GPtrArray *unwind_ops;
156         guint32 unwind_info_offset;
157         char *got_symbol;
158         char *plt_symbol;
159         GHashTable *method_label_hash;
160         const char *temp_prefix;
161         guint32 label_generator;
162 } MonoAotCompile;
163
164 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
165 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
166
167 #ifdef HAVE_ARRAY_ELEM_INIT
168 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
169 #define MSGSTRFIELD1(line) str##line
170 static const struct msgstr_t {
171 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
172 #include "patch-info.h"
173 #undef PATCH_INFO
174 } opstr = {
175 #define PATCH_INFO(a,b) b,
176 #include "patch-info.h"
177 #undef PATCH_INFO
178 };
179 static const gint16 opidx [] = {
180 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
181 #include "patch-info.h"
182 #undef PATCH_INFO
183 };
184
185 static G_GNUC_UNUSED const char*
186 get_patch_name (int info)
187 {
188         return (const char*)&opstr + opidx [info];
189 }
190
191 #else
192 #define PATCH_INFO(a,b) b,
193 static const char* const
194 patch_types [MONO_PATCH_INFO_NUM + 1] = {
195 #include "patch-info.h"
196         NULL
197 };
198
199 static G_GNUC_UNUSED const char*
200 get_patch_name (int info)
201 {
202         return patch_types [info];
203 }
204
205 #endif
206
207 /* Wrappers around the image writer functions */
208
209 static inline void
210 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
211 {
212         img_writer_emit_section_change (acfg->w, section_name, subsection_index);
213 }
214
215 static inline void
216 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
217 {
218         img_writer_emit_push_section (acfg->w, section_name, subsection);
219 }
220
221 static inline void
222 emit_pop_section (MonoAotCompile *acfg)
223 {
224         img_writer_emit_pop_section (acfg->w);
225 }
226
227 static inline void
228 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
229
230         img_writer_emit_local_symbol (acfg->w, name, end_label, func); 
231 }
232
233 static inline void
234 emit_label (MonoAotCompile *acfg, const char *name) 
235
236         img_writer_emit_label (acfg->w, name); 
237 }
238
239 static inline void
240 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
241
242         img_writer_emit_bytes (acfg->w, buf, size); 
243 }
244
245 static inline void
246 emit_string (MonoAotCompile *acfg, const char *value) 
247
248         img_writer_emit_string (acfg->w, value); 
249 }
250
251 static inline void
252 emit_line (MonoAotCompile *acfg) 
253
254         img_writer_emit_line (acfg->w); 
255 }
256
257 static inline void
258 emit_alignment (MonoAotCompile *acfg, int size) 
259
260         img_writer_emit_alignment (acfg->w, size); 
261 }
262
263 static inline void
264 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target) 
265
266         img_writer_emit_pointer_unaligned (acfg->w, target); 
267 }
268
269 static inline void
270 emit_pointer (MonoAotCompile *acfg, const char *target) 
271
272         img_writer_emit_pointer (acfg->w, target); 
273 }
274
275 static inline void
276 emit_int16 (MonoAotCompile *acfg, int value) 
277
278         img_writer_emit_int16 (acfg->w, value); 
279 }
280
281 static inline void
282 emit_int32 (MonoAotCompile *acfg, int value) 
283
284         img_writer_emit_int32 (acfg->w, value); 
285 }
286
287 static inline void
288 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
289
290         img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
291 }
292
293 static inline void
294 emit_zero_bytes (MonoAotCompile *acfg, int num) 
295
296         img_writer_emit_zero_bytes (acfg->w, num); 
297 }
298
299 static inline void
300 emit_byte (MonoAotCompile *acfg, guint8 val) 
301
302         img_writer_emit_byte (acfg->w, val); 
303 }
304
305 static G_GNUC_UNUSED void
306 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
307 {
308         img_writer_emit_global (acfg->w, name, func);
309 }
310
311 static void
312 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
313 {
314         if (acfg->aot_opts.no_dlsym) {
315                 g_ptr_array_add (acfg->globals, g_strdup (name));
316                 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
317         } else {
318                 img_writer_emit_global (acfg->w, name, func);
319         }
320 }
321
322 static void
323 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
324 {
325         img_writer_emit_symbol_size (acfg->w, name, end_label);
326 }
327
328 static void
329 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
330 {
331         img_writer_emit_section_change (acfg->w, ".text", 1);
332         emit_global (acfg, name, FALSE);
333         img_writer_emit_label (acfg->w, name);
334         img_writer_emit_string (acfg->w, value);
335 }
336
337 static G_GNUC_UNUSED void
338 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
339 {
340         do {
341                 guint8 b = value & 0x7f;
342                 value >>= 7;
343                 if (value != 0) /* more bytes to come */
344                         b |= 0x80;
345                 emit_byte (acfg, b);
346         } while (value);
347 }
348
349 static G_GNUC_UNUSED void
350 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
351 {
352         gboolean more = 1;
353         gboolean negative = (value < 0);
354         guint32 size = 64;
355         guint8 byte;
356
357         while (more) {
358                 byte = value & 0x7f;
359                 value >>= 7;
360                 /* the following is unnecessary if the
361                  * implementation of >>= uses an arithmetic rather
362                  * than logical shift for a signed left operand
363                  */
364                 if (negative)
365                         /* sign extend */
366                         value |= - ((gint64)1 <<(size - 7));
367                 /* sign bit of byte is second high order bit (0x40) */
368                 if ((value == 0 && !(byte & 0x40)) ||
369                         (value == -1 && (byte & 0x40)))
370                         more = 0;
371                 else
372                         byte |= 0x80;
373                 emit_byte (acfg, byte);
374         }
375 }
376
377 static G_GNUC_UNUSED void
378 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
379 {
380         guint8 *p = buf;
381
382         do {
383                 guint8 b = value & 0x7f;
384                 value >>= 7;
385                 if (value != 0) /* more bytes to come */
386                         b |= 0x80;
387                 *p ++ = b;
388         } while (value);
389
390         *endbuf = p;
391 }
392
393 static G_GNUC_UNUSED void
394 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
395 {
396         gboolean more = 1;
397         gboolean negative = (value < 0);
398         guint32 size = 32;
399         guint8 byte;
400         guint8 *p = buf;
401
402         while (more) {
403                 byte = value & 0x7f;
404                 value >>= 7;
405                 /* the following is unnecessary if the
406                  * implementation of >>= uses an arithmetic rather
407                  * than logical shift for a signed left operand
408                  */
409                 if (negative)
410                         /* sign extend */
411                         value |= - (1 <<(size - 7));
412                 /* sign bit of byte is second high order bit (0x40) */
413                 if ((value == 0 && !(byte & 0x40)) ||
414                         (value == -1 && (byte & 0x40)))
415                         more = 0;
416                 else
417                         byte |= 0x80;
418                 *p ++= byte;
419         }
420
421         *endbuf = p;
422 }
423
424 /* ARCHITECTURE SPECIFIC CODE */
425
426 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
427 #define EMIT_DWARF_INFO 1
428 #endif
429
430 #if defined(TARGET_ARM)
431 #define AOT_FUNC_ALIGNMENT 4
432 #else
433 #define AOT_FUNC_ALIGNMENT 16
434 #endif
435  
436 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
437 #define PPC_LD_OP "ld"
438 #define PPC_LDX_OP "ldx"
439 #else
440 #define PPC_LD_OP "lwz"
441 #define PPC_LDX_OP "lwzx"
442 #endif
443
444 /*
445  * arch_emit_direct_call:
446  *
447  *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
448  * calling code.
449  */
450 static void
451 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
452 {
453 #if defined(TARGET_X86) || defined(TARGET_AMD64)
454         /* Need to make sure this is exactly 5 bytes long */
455         emit_byte (acfg, '\xe8');
456         emit_symbol_diff (acfg, target, ".", -4);
457         *call_size = 5;
458 #elif defined(TARGET_ARM)
459         if (acfg->use_bin_writer) {
460                 guint8 buf [4];
461                 guint8 *code;
462
463                 code = buf;
464                 ARM_BL (code, 0);
465
466                 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
467                 emit_bytes (acfg, buf, 4);
468         } else {
469                 img_writer_emit_unset_mode (acfg->w);
470                 fprintf (acfg->fp, "bl %s\n", target);
471         }
472         *call_size = 4;
473 #elif defined(TARGET_POWERPC)
474         if (acfg->use_bin_writer) {
475                 g_assert_not_reached ();
476         } else {
477                 img_writer_emit_unset_mode (acfg->w);
478                 fprintf (acfg->fp, "bl %s\n", target);
479                 *call_size = 4;
480         }
481 #else
482         g_assert_not_reached ();
483 #endif
484 }
485
486 /*
487  * PPC32 design:
488  * - we use an approach similar to the x86 abi: reserve a register (r30) to hold 
489  *   the GOT pointer.
490  * - The full-aot trampolines need access to the GOT of mscorlib, so we store
491  *   in in the 2. slot of every GOT, and require every method to place the GOT
492  *   address in r30, even when it doesn't access the GOT otherwise. This way,
493  *   the trampolines can compute the mscorlib GOT address by loading 4(r30).
494  */
495
496 /*
497  * PPC64 design:
498  * PPC64 uses function descriptors which greatly complicate all code, since
499  * these are used very inconsistently in the runtime. Some functions like 
500  * mono_compile_method () return ftn descriptors, while others like the
501  * trampoline creation functions do not.
502  * We assume that all GOT slots contain function descriptors, and create 
503  * descriptors in aot-runtime.c when needed.
504  * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
505  * from function descriptors, we could do the same, but it would require 
506  * rewriting all the ppc/aot code to handle function descriptors properly.
507  * So instead, we use the same approach as on PPC32.
508  * This is a horrible mess, but fixing it would probably lead to an even bigger
509  * one.
510  */
511
512 #ifdef MONO_ARCH_AOT_SUPPORTED
513 /*
514  * arch_emit_got_offset:
515  *
516  *   The memory pointed to by CODE should hold native code for computing the GOT
517  * address. Emit this code while patching it with the offset between code and
518  * the GOT. CODE_SIZE is set to the number of bytes emitted.
519  */
520 static void
521 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
522 {
523 #if defined(TARGET_POWERPC64)
524         g_assert (!acfg->use_bin_writer);
525         img_writer_emit_unset_mode (acfg->w);
526         /* 
527          * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
528          * unsupported relocations. So we store the got address into the .Lgot_addr
529          * symbol which is in the text segment, compute its address, and load it.
530          */
531         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
532         fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
533         fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
534         fprintf (acfg->fp, "add 30, 30, 0\n");
535         fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
536         acfg->label_generator ++;
537         *code_size = 16;
538 #elif defined(TARGET_POWERPC)
539         g_assert (!acfg->use_bin_writer);
540         img_writer_emit_unset_mode (acfg->w);
541         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
542         fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
543         fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
544         acfg->label_generator ++;
545         *code_size = 8;
546 #else
547         guint32 offset = mono_arch_get_patch_offset (code);
548         emit_bytes (acfg, code, offset);
549         emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
550
551         *code_size = offset + 4;
552 #endif
553 }
554
555 /*
556  * arch_emit_got_access:
557  *
558  *   The memory pointed to by CODE should hold native code for loading a GOT
559  * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
560  * CODE_SIZE is set to the number of bytes emitted.
561  */
562 static void
563 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
564 {
565         /* Emit beginning of instruction */
566         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
567
568         /* Emit the offset */
569 #ifdef TARGET_AMD64
570         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
571         *code_size = mono_arch_get_patch_offset (code) + 4;
572 #elif defined(TARGET_X86)
573         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
574         *code_size = mono_arch_get_patch_offset (code) + 4;
575 #elif defined(TARGET_ARM)
576         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
577         *code_size = mono_arch_get_patch_offset (code) + 4;
578 #elif defined(TARGET_POWERPC)
579         {
580                 guint8 buf [32];
581                 guint8 *code;
582
583                 code = buf;
584                 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
585                 g_assert (code - buf == 8);
586                 emit_bytes (acfg, buf, code - buf);
587                 *code_size = code - buf;
588         }
589 #else
590         g_assert_not_reached ();
591 #endif
592 }
593
594 #endif
595
596 /*
597  * arch_emit_plt_entry:
598  *
599  *   Emit code for the PLT entry with index INDEX.
600  */
601 static void
602 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
603 {
604 #if defined(TARGET_X86)
605                 if (index == 0) {
606                         /* It is filled up during loading by the AOT loader. */
607                         emit_zero_bytes (acfg, 16);
608                 } else {
609                         /* Need to make sure this is 9 bytes long */
610                         emit_byte (acfg, '\xe9');
611                         emit_symbol_diff (acfg, acfg->plt_symbol, ".", -4);
612                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
613                 }
614 #elif defined(TARGET_AMD64)
615                 /*
616                  * We can't emit jumps because they are 32 bits only so they can't be patched.
617                  * So we make indirect calls through GOT entries which are patched by the AOT 
618                  * loader to point to .Lpd entries. 
619                  * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
620                  */
621                 /* jmpq *<offset>(%rip) */
622                 emit_byte (acfg, '\xff');
623                 emit_byte (acfg, '\x25');
624                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
625                 /* Used by mono_aot_get_plt_info_offset */
626                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
627 #elif defined(TARGET_ARM)
628                 guint8 buf [256];
629                 guint8 *code;
630
631                 /* FIXME:
632                  * - optimize OP_AOTCONST implementation
633                  * - optimize the PLT entries
634                  * - optimize SWITCH AOT implementation
635                  * - implement IMT support
636                  */
637                 code = buf;
638                 if (acfg->use_bin_writer && FALSE) {
639                         /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
640                         /* We only emit 1 relocation since we implement it ourselves anyway */
641                         img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
642                         /* FIXME: A 2 instruction encoding is sufficient in most cases */
643                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
644                         ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
645                         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
646                         emit_bytes (acfg, buf, code - buf);
647                         /* Used by mono_aot_get_plt_info_offset */
648                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
649                 } else {
650                         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
651                         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
652                         emit_bytes (acfg, buf, code - buf);
653                         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
654                         /* Used by mono_aot_get_plt_info_offset */
655                         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
656                 }
657                 /* 
658                  * The plt_got_info_offset is computed automatically by 
659                  * mono_aot_get_plt_info_offset (), so no need to save it here.
660                  */
661 #elif defined(TARGET_POWERPC)
662                 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
663
664                 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
665                 g_assert (!acfg->use_bin_writer);
666                 img_writer_emit_unset_mode (acfg->w);
667                 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
668                 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
669                 fprintf (acfg->fp, "add 11, 11, 30\n");
670                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
671 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
672                 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
673                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
674 #endif
675                 fprintf (acfg->fp, "mtctr 11\n");
676                 fprintf (acfg->fp, "bctr\n");
677                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
678 #else
679                 g_assert_not_reached ();
680 #endif
681 }
682
683 /*
684  * arch_emit_specific_trampoline:
685  *
686  *   Emit code for a specific trampoline. OFFSET is the offset of the first of
687  * two GOT slots which contain the generic trampoline address and the trampoline
688  * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
689  */
690 static void
691 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
692 {
693         /*
694          * The trampolines created here are variations of the specific 
695          * trampolines created in mono_arch_create_specific_trampoline (). The 
696          * differences are:
697          * - the generic trampoline address is taken from a got slot.
698          * - the offset of the got slot where the trampoline argument is stored
699          *   is embedded in the instruction stream, and the generic trampoline
700          *   can load the argument by loading the offset, adding it to the
701          *   address of the trampoline to get the address of the got slot, and
702          *   loading the argument from there.
703          * - all the trampolines should be of the same length.
704          */
705 #if defined(TARGET_AMD64)
706         /* This should be exactly 16 bytes long */
707         *tramp_size = 16;
708         /* call *<offset>(%rip) */
709         emit_byte (acfg, '\x41');
710         emit_byte (acfg, '\xff');
711         emit_byte (acfg, '\x15');
712         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
713         /* This should be relative to the start of the trampoline */
714         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
715         emit_zero_bytes (acfg, 5);
716 #elif defined(TARGET_ARM)
717         guint8 buf [128];
718         guint8 *code;
719
720         /* This should be exactly 20 bytes long */
721         *tramp_size = 20;
722         code = buf;
723         ARM_PUSH (code, 0x5fff);
724         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
725         /* Load the value from the GOT */
726         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
727         /* Branch to it */
728         ARM_BLX_REG (code, ARMREG_R1);
729
730         g_assert (code - buf == 16);
731
732         /* Emit it */
733         emit_bytes (acfg, buf, code - buf);
734         /* 
735          * Only one offset is needed, since the second one would be equal to the
736          * first one.
737          */
738         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
739         //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
740 #elif defined(TARGET_POWERPC)
741         guint8 buf [128];
742         guint8 *code;
743
744         *tramp_size = 4;
745         code = buf;
746
747         g_assert (!acfg->use_bin_writer);
748
749         /*
750          * PPC has no ip relative addressing, so we need to compute the address
751          * of the mscorlib got. That is slow and complex, so instead, we store it
752          * in the second got slot of every aot image. The caller already computed
753          * the address of its got and placed it into r30.
754          */
755         img_writer_emit_unset_mode (acfg->w);
756         /* Load mscorlib got address */
757         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
758         /* Load generic trampoline address */
759         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
760         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
761         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
762 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
763         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
764 #endif
765         fprintf (acfg->fp, "mtctr 11\n");
766         /* Load trampoline argument */
767         /* On ppc, we pass it normally to the generic trampoline */
768         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
769         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
770         fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
771         /* Branch to generic trampoline */
772         fprintf (acfg->fp, "bctr\n");
773
774 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
775         *tramp_size = 10 * 4;
776 #else
777         *tramp_size = 9 * 4;
778 #endif
779 #else
780         g_assert_not_reached ();
781 #endif
782 }
783
784 /*
785  * arch_emit_unbox_trampoline:
786  *
787  *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
788  * CALL_TARGET is the symbol pointing to the native code of METHOD.
789  */
790 static void
791 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
792 {
793 #if defined(TARGET_AMD64)
794         guint8 buf [32];
795         guint8 *code;
796         int this_reg;
797
798         this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
799         code = buf;
800         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
801
802         emit_bytes (acfg, buf, code - buf);
803         /* jump <method> */
804         emit_byte (acfg, '\xe9');
805         emit_symbol_diff (acfg, call_target, ".", -4);
806 #elif defined(TARGET_ARM)
807         guint8 buf [128];
808         guint8 *code;
809         int this_pos = 0;
810
811         code = buf;
812
813         if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
814                 this_pos = 1;
815
816         ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
817
818         emit_bytes (acfg, buf, code - buf);
819         /* jump to method */
820         if (acfg->use_bin_writer) {
821                 guint8 buf [4];
822                 guint8 *code;
823
824                 code = buf;
825                 ARM_B (code, 0);
826
827                 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
828                 emit_bytes (acfg, buf, 4);
829         } else {
830                 fprintf (acfg->fp, "\n\tb %s\n", call_target);
831         }
832 #elif defined(TARGET_POWERPC)
833         int this_pos = 3;
834
835         if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
836                 this_pos = 4;
837
838         g_assert (!acfg->use_bin_writer);
839
840         fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
841         fprintf (acfg->fp, "\n\tb %s\n", call_target);
842 #else
843         g_assert_not_reached ();
844 #endif
845 }
846
847 /*
848  * arch_emit_static_rgctx_trampoline:
849  *
850  *   Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
851  * two GOT slots which contain the rgctx argument, and the method to jump to.
852  * TRAMP_SIZE is set to the size of the emitted trampoline.
853  * These kinds of trampolines cannot be enumerated statically, since there could
854  * be one trampoline per method instantiation, so we emit the same code for all
855  * trampolines, and parameterize them using two GOT slots.
856  */
857 static void
858 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
859 {
860 #if defined(TARGET_AMD64)
861         /* This should be exactly 13 bytes long */
862         *tramp_size = 13;
863
864         /* mov <OFFSET>(%rip), %r10 */
865         emit_byte (acfg, '\x4d');
866         emit_byte (acfg, '\x8b');
867         emit_byte (acfg, '\x15');
868         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
869
870         /* jmp *<offset>(%rip) */
871         emit_byte (acfg, '\xff');
872         emit_byte (acfg, '\x25');
873         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
874 #elif defined(TARGET_ARM)
875         guint8 buf [128];
876         guint8 *code;
877
878         /* This should be exactly 24 bytes long */
879         *tramp_size = 24;
880         code = buf;
881         /* Load rgctx value */
882         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
883         ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
884         /* Load branch addr + branch */
885         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
886         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
887
888         g_assert (code - buf == 16);
889
890         /* Emit it */
891         emit_bytes (acfg, buf, code - buf);
892         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
893         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
894 #elif defined(TARGET_POWERPC)
895         guint8 buf [128];
896         guint8 *code;
897
898         *tramp_size = 4;
899         code = buf;
900
901         g_assert (!acfg->use_bin_writer);
902
903         /*
904          * PPC has no ip relative addressing, so we need to compute the address
905          * of the mscorlib got. That is slow and complex, so instead, we store it
906          * in the second got slot of every aot image. The caller already computed
907          * the address of its got and placed it into r30.
908          */
909         img_writer_emit_unset_mode (acfg->w);
910         /* Load mscorlib got address */
911         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
912         /* Load rgctx */
913         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
914         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
915         fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
916         /* Load target address */
917         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
918         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
919         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
920 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
921         fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
922         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
923 #endif
924         fprintf (acfg->fp, "mtctr 11\n");
925         /* Branch to the target address */
926         fprintf (acfg->fp, "bctr\n");
927
928 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
929         *tramp_size = 11 * 4;
930 #else
931         *tramp_size = 9 * 4;
932 #endif
933
934 #else
935         g_assert_not_reached ();
936 #endif
937 }       
938
939 /*
940  * arch_emit_imt_thunk:
941  *
942  *   Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
943  * points to an array of pointer pairs. The pairs of the form [key, ptr], where
944  * key is the IMT key, and ptr holds the address of a memory location holding
945  * the address to branch to if the IMT arg matches the key. The array is 
946  * terminated by a pair whose key is NULL, and whose ptr is the address of the 
947  * fail_tramp.
948  * TRAMP_SIZE is set to the size of the emitted trampoline.
949  */
950 static void
951 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
952 {
953 #if defined(TARGET_AMD64)
954         guint8 *buf, *code;
955         guint8 *labels [3];
956
957         code = buf = g_malloc (256);
958
959         /* FIXME: Optimize this, i.e. use binary search etc. */
960         /* Maybe move the body into a separate function (slower, but much smaller) */
961
962         /* R10 is a free register */
963
964         labels [0] = code;
965         amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
966         labels [1] = code;
967         amd64_branch8 (code, X86_CC_Z, FALSE, 0);
968
969         /* Check key */
970         amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
971         labels [2] = code;
972         amd64_branch8 (code, X86_CC_Z, FALSE, 0);
973
974         /* Loop footer */
975         amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
976         amd64_jump_code (code, labels [0]);
977
978         /* Match */
979         mono_amd64_patch (labels [2], code);
980         amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
981         amd64_jump_membase (code, AMD64_R10, 0);
982
983         /* No match */
984         /* FIXME: */
985         mono_amd64_patch (labels [1], code);
986         x86_breakpoint (code);
987
988         /* mov <OFFSET>(%rip), %r10 */
989         emit_byte (acfg, '\x4d');
990         emit_byte (acfg, '\x8b');
991         emit_byte (acfg, '\x15');
992         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
993
994         emit_bytes (acfg, buf, code - buf);
995         
996         *tramp_size = code - buf + 7;
997 #elif defined(TARGET_ARM)
998         guint8 buf [128];
999         guint8 *code, *code2, *labels [16];
1000
1001         code = buf;
1002
1003         /* The IMT method is in v5 */
1004
1005         /* Need at least two free registers, plus a slot for storing the pc */
1006         ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1007         labels [0] = code;
1008         /* Load the parameter from the GOT */
1009         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1010         ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1011
1012         labels [1] = code;
1013         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1014         ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1015         labels [2] = code;
1016         ARM_B_COND (code, ARMCOND_EQ, 0);
1017
1018         /* End-of-loop check */
1019         ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1020         labels [3] = code;
1021         ARM_B_COND (code, ARMCOND_EQ, 0);
1022
1023         /* Loop footer */
1024         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1025         labels [4] = code;
1026         ARM_B (code, 0);
1027         arm_patch (labels [4], labels [1]);
1028
1029         /* Match */
1030         arm_patch (labels [2], code);
1031         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1032         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1033         /* Save it to the third stack slot */
1034         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1035         /* Restore the registers and branch */
1036         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1037
1038         /* No match */
1039         arm_patch (labels [3], code);
1040         ARM_DBRK (code);
1041
1042         /* Fixup offset */
1043         code2 = labels [0];
1044         ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1045
1046         emit_bytes (acfg, buf, code - buf);
1047         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1048
1049         *tramp_size = code - buf + 4;
1050 #elif defined(TARGET_POWERPC)
1051         guint8 buf [128];
1052         guint8 *code, *labels [16];
1053
1054         code = buf;
1055
1056         /* Load the mscorlib got address */
1057         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1058         /* Load the parameter from the GOT */
1059         ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1060         ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1061
1062         /* Load and check key */
1063         labels [1] = code;
1064         ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1065         ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1066         labels [2] = code;
1067         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1068
1069         /* End-of-loop check */
1070         ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1071         labels [3] = code;
1072         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1073
1074         /* Loop footer */
1075         ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1076         labels [4] = code;
1077         ppc_b (code, 0);
1078         mono_ppc_patch (labels [4], labels [1]);
1079
1080         /* Match */
1081         mono_ppc_patch (labels [2], code);
1082         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1083         /* r11 now contains the value of the vtable slot */
1084         /* this is not a function descriptor on ppc64 */
1085         ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1086         ppc_mtctr (code, ppc_r11);
1087         ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1088
1089         /* Fail */
1090         mono_ppc_patch (labels [3], code);
1091         /* FIXME: */
1092         ppc_break (code);
1093
1094         *tramp_size = code - buf;
1095
1096         emit_bytes (acfg, buf, code - buf);
1097 #else
1098         g_assert_not_reached ();
1099 #endif
1100 }
1101
1102 /*
1103  * arch_get_cie_program:
1104  *
1105  *   Get the unwind bytecode for the DWARF CIE.
1106  */
1107 static GSList*
1108 arch_get_cie_program (void)
1109 {
1110 #ifdef TARGET_AMD64
1111         GSList *l = NULL;
1112
1113         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
1114         mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
1115
1116         return l;
1117 #elif defined(TARGET_POWERPC)
1118         GSList *l = NULL;
1119
1120         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, ppc_r1, 0);
1121
1122         return l;
1123 #else
1124         return NULL;
1125 #endif
1126 }
1127
1128 /* END OF ARCH SPECIFIC CODE */
1129
1130 static guint32
1131 mono_get_field_token (MonoClassField *field) 
1132 {
1133         MonoClass *klass = field->parent;
1134         int i;
1135
1136         for (i = 0; i < klass->field.count; ++i) {
1137                 if (field == &klass->fields [i])
1138                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1139         }
1140
1141         g_assert_not_reached ();
1142         return 0;
1143 }
1144
1145 static inline void
1146 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1147 {
1148         guint8 *p = buf;
1149
1150         //printf ("ENCODE: %d 0x%x.\n", value, value);
1151
1152         /* 
1153          * Same encoding as the one used in the metadata, extended to handle values
1154          * greater than 0x1fffffff.
1155          */
1156         if ((value >= 0) && (value <= 127))
1157                 *p++ = value;
1158         else if ((value >= 0) && (value <= 16383)) {
1159                 p [0] = 0x80 | (value >> 8);
1160                 p [1] = value & 0xff;
1161                 p += 2;
1162         } else if ((value >= 0) && (value <= 0x1fffffff)) {
1163                 p [0] = (value >> 24) | 0xc0;
1164                 p [1] = (value >> 16) & 0xff;
1165                 p [2] = (value >> 8) & 0xff;
1166                 p [3] = value & 0xff;
1167                 p += 4;
1168         }
1169         else {
1170                 p [0] = 0xff;
1171                 p [1] = (value >> 24) & 0xff;
1172                 p [2] = (value >> 16) & 0xff;
1173                 p [3] = (value >> 8) & 0xff;
1174                 p [4] = value & 0xff;
1175                 p += 5;
1176         }
1177         if (endbuf)
1178                 *endbuf = p;
1179 }
1180
1181 static guint32
1182 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1183 {
1184         guint32 index;
1185
1186         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1187         if (index)
1188                 return index - 1;
1189         else {
1190                 index = g_hash_table_size (cfg->image_hash);
1191                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1192                 g_ptr_array_add (cfg->image_table, image);
1193                 return index;
1194         }
1195 }
1196
1197 static guint32
1198 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1199 {
1200         int i;
1201         MonoClass *k = NULL;
1202
1203         /* FIXME: Search referenced images as well */
1204         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1205                 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1206                 if (k == klass)
1207                         break;
1208         }
1209
1210         if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1211                 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1212         else
1213                 return 0;
1214 }
1215
1216 static void
1217 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1218
1219 /*
1220  * encode_klass_ref:
1221  *
1222  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
1223  * standard metadata encoding.
1224  */
1225 static void
1226 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1227 {
1228         guint8 *p = buf;
1229
1230         if (klass->generic_class) {
1231                 guint32 token;
1232                 g_assert (klass->type_token);
1233
1234                 /* Find a typespec for a class if possible */
1235                 token = find_typespec_for_class (acfg, klass);
1236                 if (token) {
1237                         encode_value (token, p, &p);
1238                         encode_value (get_image_index (acfg, acfg->image), p, &p);
1239                 } else {
1240                         MonoClass *gclass = klass->generic_class->container_class;
1241                         MonoGenericInst *inst = klass->generic_class->context.class_inst;
1242                         int i;
1243
1244                         /* Encode it ourselves */
1245                         /* Marker */
1246                         encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1247                         encode_value (MONO_TYPE_GENERICINST, p, &p);
1248                         encode_klass_ref (acfg, gclass, p, &p);
1249                         encode_value (inst->type_argc, p, &p);
1250                         for (i = 0; i < inst->type_argc; ++i)
1251                                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1252                 }
1253         } else if (klass->type_token) {
1254                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1255                 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1256                 encode_value (get_image_index (acfg, klass->image), p, &p);
1257         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1258                 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1259                 g_assert (container);
1260
1261                 /* Marker */
1262                 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1263                 encode_value (klass->byval_arg.type, p, &p);
1264
1265                 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1266                 
1267                 encode_value (container->is_method, p, &p);
1268                 if (container->is_method)
1269                         encode_method_ref (acfg, container->owner.method, p, &p);
1270                 else
1271                         encode_klass_ref (acfg, container->owner.klass, p, &p);
1272         } else {
1273                 /* Array class */
1274                 g_assert (klass->rank > 0);
1275                 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1276                 encode_value (get_image_index (acfg, klass->image), p, &p);
1277                 encode_value (klass->rank, p, &p);
1278                 encode_klass_ref (acfg, klass->element_class, p, &p);
1279         }
1280         *endbuf = p;
1281 }
1282
1283 static void
1284 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1285 {
1286         guint32 token = mono_get_field_token (field);
1287         guint8 *p = buf;
1288
1289         encode_klass_ref (cfg, field->parent, p, &p);
1290         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1291         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1292         *endbuf = p;
1293 }
1294
1295 static void
1296 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1297 {
1298         guint8 *p = buf;
1299         int i;
1300         MonoGenericInst *inst;
1301
1302         /* Encode the context */
1303         inst = context->class_inst;
1304         encode_value (inst ? 1 : 0, p, &p);
1305         if (inst) {
1306                 encode_value (inst->type_argc, p, &p);
1307                 for (i = 0; i < inst->type_argc; ++i)
1308                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1309         }
1310         inst = context->method_inst;
1311         encode_value (inst ? 1 : 0, p, &p);
1312         if (inst) {
1313                 encode_value (inst->type_argc, p, &p);
1314                 for (i = 0; i < inst->type_argc; ++i)
1315                         encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1316         }
1317
1318         *endbuf = p;
1319 }
1320
1321 #define MAX_IMAGE_INDEX 250
1322
1323 static void
1324 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1325 {
1326         guint32 image_index = get_image_index (acfg, method->klass->image);
1327         guint32 token = method->token;
1328         MonoJumpInfoToken *ji;
1329         guint8 *p = buf;
1330         char *name;
1331
1332         /*
1333          * The encoding for most methods is as follows:
1334          * - image index encoded as a leb128
1335          * - token index encoded as a leb128
1336          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1337          * types of method encodings.
1338          */
1339
1340         g_assert (image_index < MONO_AOT_METHODREF_MIN);
1341
1342         /* Mark methods which can't use aot trampolines because they need the further 
1343          * processing in mono_magic_trampoline () which requires a MonoMethod*.
1344          */
1345         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1346                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1347                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1348
1349         /* 
1350          * Some wrapper methods are shared using their signature, encode their 
1351          * stringified signature instead.
1352          * FIXME: Optimize disk usage
1353          */
1354         name = NULL;
1355         if (method->wrapper_type) {
1356                 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1357                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1358                         if (strcmp (method->name, "runtime_invoke_dynamic")) {
1359                                 name = mono_aot_wrapper_name (method);
1360                         } else if (mono_marshal_method_from_wrapper (method) != method) {
1361                                 /* Direct wrapper, encode it normally */
1362                         } else {
1363                                 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1364                         }
1365                         g_free (tmpsig);
1366                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1367                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1368                         name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1369                         g_free (tmpsig);
1370                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1371                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1372                         name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1373                         g_free (tmpsig);
1374                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1375                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1376                         name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1377                         g_free (tmpsig);
1378                 }
1379         }
1380
1381         if (name) {
1382                 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1383                 strcpy ((char*)p, name);
1384                 p += strlen (name) + 1;
1385                 g_free (name);
1386         } else if (method->wrapper_type) {
1387                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1388
1389                 encode_value (method->wrapper_type, p, &p);
1390
1391                 switch (method->wrapper_type) {
1392                 case MONO_WRAPPER_REMOTING_INVOKE:
1393                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1394                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1395                         MonoMethod *m;
1396
1397                         m = mono_marshal_method_from_wrapper (method);
1398                         g_assert (m);
1399                         encode_method_ref (acfg, m, p, &p);
1400                         break;
1401                 }
1402                 case MONO_WRAPPER_PROXY_ISINST:
1403                 case MONO_WRAPPER_LDFLD:
1404                 case MONO_WRAPPER_LDFLDA:
1405                 case MONO_WRAPPER_STFLD:
1406                 case MONO_WRAPPER_ISINST: {
1407                         MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1408                         encode_klass_ref (acfg, proxy_class, p, &p);
1409                         break;
1410                 }
1411                 case MONO_WRAPPER_LDFLD_REMOTE:
1412                 case MONO_WRAPPER_STFLD_REMOTE:
1413                         break;
1414                 case MONO_WRAPPER_ALLOC: {
1415                         int alloc_type = mono_gc_get_managed_allocator_type (method);
1416                         g_assert (alloc_type != -1);
1417                         encode_value (alloc_type, p, &p);
1418                         break;
1419                 }
1420                 case MONO_WRAPPER_STELEMREF:
1421                         break;
1422                 case MONO_WRAPPER_UNKNOWN:
1423                         if (strcmp (method->name, "FastMonitorEnter") == 0)
1424                                 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1425                         else if (strcmp (method->name, "FastMonitorExit") == 0)
1426                                 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1427                         else
1428                                 g_assert_not_reached ();
1429                         break;
1430                 case MONO_WRAPPER_SYNCHRONIZED:
1431                 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1432                 case MONO_WRAPPER_RUNTIME_INVOKE: {
1433                         MonoMethod *m;
1434
1435                         m = mono_marshal_method_from_wrapper (method);
1436                         g_assert (m);
1437                         g_assert (m != method);
1438                         encode_method_ref (acfg, m, p, &p);
1439                         break;
1440                 }
1441                 default:
1442                         g_assert_not_reached ();
1443                 }
1444         } else if (mono_method_signature (method)->is_inflated) {
1445                 /* 
1446                  * This is a generic method, find the original token which referenced it and
1447                  * encode that.
1448                  * Obtain the token from information recorded by the JIT.
1449                  */
1450                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1451                 if (ji) {
1452                         image_index = get_image_index (acfg, ji->image);
1453                         g_assert (image_index < MAX_IMAGE_INDEX);
1454                         token = ji->token;
1455
1456                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1457                         encode_value (image_index, p, &p);
1458                         encode_value (token, p, &p);
1459                 } else {
1460                         MonoMethod *declaring;
1461                         MonoGenericContext *context = mono_method_get_context (method);
1462
1463                         g_assert (method->is_inflated);
1464                         declaring = ((MonoMethodInflated*)method)->declaring;
1465
1466                         /*
1467                          * This might be a non-generic method of a generic instance, which 
1468                          * doesn't have a token since the reference is generated by the JIT 
1469                          * like Nullable:Box/Unbox, or by generic sharing.
1470                          */
1471
1472                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1473                         /* Encode the klass */
1474                         encode_klass_ref (acfg, method->klass, p, &p);
1475                         /* Encode the method */
1476                         image_index = get_image_index (acfg, method->klass->image);
1477                         g_assert (image_index < MAX_IMAGE_INDEX);
1478                         g_assert (declaring->token);
1479                         token = declaring->token;
1480                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1481                         encode_value (image_index, p, &p);
1482                         encode_value (token, p, &p);
1483                         encode_generic_context (acfg, context, p, &p);
1484                 }
1485         } else if (token == 0) {
1486                 /* This might be a method of a constructed type like int[,].Set */
1487                 /* Obtain the token from information recorded by the JIT */
1488                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1489                 if (ji) {
1490                         image_index = get_image_index (acfg, ji->image);
1491                         g_assert (image_index < MAX_IMAGE_INDEX);
1492                         token = ji->token;
1493
1494                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1495                         encode_value (image_index, p, &p);
1496                         encode_value (token, p, &p);
1497                 } else {
1498                         /* Array methods */
1499                         g_assert (method->klass->rank);
1500
1501                         /* Encode directly */
1502                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1503                         encode_klass_ref (acfg, method->klass, p, &p);
1504                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1505                                 encode_value (0, p, &p);
1506                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1507                                 encode_value (1, p, &p);
1508                         else if (!strcmp (method->name, "Get"))
1509                                 encode_value (2, p, &p);
1510                         else if (!strcmp (method->name, "Address"))
1511                                 encode_value (3, p, &p);
1512                         else if (!strcmp (method->name, "Set"))
1513                                 encode_value (4, p, &p);
1514                         else
1515                                 g_assert_not_reached ();
1516                 }
1517         } else {
1518                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1519                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1520         }
1521         *endbuf = p;
1522 }
1523
1524 static gint
1525 compare_patches (gconstpointer a, gconstpointer b)
1526 {
1527         int i, j;
1528
1529         i = (*(MonoJumpInfo**)a)->ip.i;
1530         j = (*(MonoJumpInfo**)b)->ip.i;
1531
1532         if (i < j)
1533                 return -1;
1534         else
1535                 if (i > j)
1536                         return 1;
1537         else
1538                 return 0;
1539 }
1540
1541 /*
1542  * is_plt_patch:
1543  *
1544  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
1545  * PLT entry.
1546  */
1547 static inline gboolean
1548 is_plt_patch (MonoJumpInfo *patch_info)
1549 {
1550         switch (patch_info->type) {
1551         case MONO_PATCH_INFO_METHOD:
1552         case MONO_PATCH_INFO_INTERNAL_METHOD:
1553         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1554         case MONO_PATCH_INFO_ICALL_ADDR:
1555         case MONO_PATCH_INFO_CLASS_INIT:
1556         case MONO_PATCH_INFO_RGCTX_FETCH:
1557         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1558         case MONO_PATCH_INFO_MONITOR_ENTER:
1559         case MONO_PATCH_INFO_MONITOR_EXIT:
1560                 return TRUE;
1561         default:
1562                 return FALSE;
1563         }
1564 }
1565
1566 static int
1567 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1568 {
1569         int res = -1;
1570
1571         if (is_plt_patch (patch_info)) {
1572                 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1573
1574                 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1575                         /* 
1576                          * Allocate a separate PLT slot for each such patch, since some plt
1577                          * entries will refer to the method itself, and some will refer to
1578                          * wrapper.
1579                          */
1580                         idx = 0;
1581                 }
1582
1583                 if (idx) {
1584                         res = idx;
1585                 } else {
1586                         MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1587
1588                         res = acfg->plt_offset;
1589                         g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1590                         g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1591                         acfg->plt_offset ++;
1592                 }
1593         }
1594
1595         return res;
1596 }
1597
1598 /**
1599  * get_got_offset:
1600  *
1601  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
1602  * JI could be found if it exists, otherwise allocates a new one.
1603  */
1604 static guint32
1605 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1606 {
1607         guint32 got_offset;
1608
1609         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset, ji));
1610         if (got_offset)
1611                 return got_offset - 1;
1612
1613         got_offset = acfg->got_offset;
1614         acfg->got_offset ++;
1615
1616         acfg->stats.got_slots ++;
1617         acfg->stats.got_slot_types [ji->type] ++;
1618
1619         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1620         g_ptr_array_add (acfg->got_patches, ji);
1621
1622         return got_offset;
1623 }
1624
1625 /* Add a method to the list of methods which need to be emitted */
1626 static void
1627 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1628 {
1629         g_assert (method);
1630         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1631                 g_ptr_array_add (acfg->methods, method);
1632                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1633                 acfg->nmethods = acfg->methods->len + 1;
1634         }
1635
1636         if (method->wrapper_type || extra)
1637                 g_ptr_array_add (acfg->extra_methods, method);
1638 }
1639
1640 static guint32
1641 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1642 {
1643         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1644         
1645         g_assert (index);
1646
1647         return index - 1;
1648 }
1649
1650 static int
1651 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra)
1652 {
1653         int index;
1654
1655         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1656         if (index)
1657                 return index - 1;
1658
1659         index = acfg->method_index;
1660         add_method_with_index (acfg, method, index, extra);
1661
1662         /* FIXME: Fix quadratic behavior */
1663         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1664
1665         acfg->method_index ++;
1666
1667         return index;
1668 }
1669
1670 static int
1671 add_method (MonoAotCompile *acfg, MonoMethod *method)
1672 {
1673         return add_method_full (acfg, method, FALSE);
1674 }
1675
1676 static void
1677 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1678 {
1679         add_method_full (acfg, method, TRUE);
1680 }
1681
1682 static void
1683 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1684 {
1685         MonoAotCompile *acfg = user_data;
1686         MonoJitICallInfo *callinfo = value;
1687         MonoMethod *wrapper;
1688         char *name;
1689
1690         if (!callinfo->sig)
1691                 return;
1692
1693         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1694         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1695         g_free (name);
1696
1697         add_method (acfg, wrapper);
1698 }
1699
1700 static MonoMethod*
1701 get_runtime_invoke_sig (MonoMethodSignature *sig)
1702 {
1703         MonoMethodBuilder *mb;
1704         MonoMethod *m;
1705
1706         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1707         m = mono_mb_create_method (mb, sig, 16);
1708         return mono_marshal_get_runtime_invoke (m, FALSE);
1709 }
1710
1711 static gboolean
1712 can_marshal_struct (MonoClass *klass)
1713 {
1714         MonoClassField *field;
1715         gboolean can_marshal = TRUE;
1716         gpointer iter = NULL;
1717
1718         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1719                 return FALSE;
1720
1721         /* Only allow a few field types to avoid asserts in the marshalling code */
1722         while ((field = mono_class_get_fields (klass, &iter))) {
1723                 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1724                         continue;
1725
1726                 switch (field->type->type) {
1727                 case MONO_TYPE_I4:
1728                 case MONO_TYPE_U4:
1729                 case MONO_TYPE_I1:
1730                 case MONO_TYPE_U1:
1731                 case MONO_TYPE_BOOLEAN:
1732                 case MONO_TYPE_I2:
1733                 case MONO_TYPE_U2:
1734                 case MONO_TYPE_CHAR:
1735                 case MONO_TYPE_I8:
1736                 case MONO_TYPE_U8:
1737                 case MONO_TYPE_I:
1738                 case MONO_TYPE_U:
1739                 case MONO_TYPE_PTR:
1740                 case MONO_TYPE_R4:
1741                 case MONO_TYPE_R8:
1742                 case MONO_TYPE_STRING:
1743                         break;
1744                 case MONO_TYPE_VALUETYPE:
1745                         if (!can_marshal_struct (mono_class_from_mono_type (field->type)))
1746                                 can_marshal = FALSE;
1747                         break;
1748                 default:
1749                         can_marshal = FALSE;
1750                         break;
1751                 }
1752         }
1753
1754         return can_marshal;
1755 }
1756
1757 static void
1758 add_wrappers (MonoAotCompile *acfg)
1759 {
1760         MonoMethod *method, *m;
1761         int i, j;
1762         MonoMethodSignature *sig, *csig;
1763         guint32 token;
1764
1765         /* 
1766          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1767          * so there is only one wrapper of a given type, or inlining their contents into their
1768          * callers.
1769          */
1770
1771         /* 
1772          * FIXME: This depends on the fact that different wrappers have different 
1773          * names.
1774          */
1775
1776         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1777                 MonoMethod *method;
1778                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1779                 gboolean skip = FALSE;
1780
1781                 method = mono_get_method (acfg->image, token, NULL);
1782
1783                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1784                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1785                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1786                         skip = TRUE;
1787
1788                 if (method->is_generic || method->klass->generic_container)
1789                         skip = TRUE;
1790
1791                 /* Skip methods which can not be handled by get_runtime_invoke () */
1792                 sig = mono_method_signature (method);
1793                 if ((sig->ret->type == MONO_TYPE_PTR) ||
1794                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1795                         skip = TRUE;
1796
1797                 for (j = 0; j < sig->param_count; j++) {
1798                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1799                                 skip = TRUE;
1800                 }
1801
1802 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
1803                 if (!method->klass->contextbound) {
1804                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
1805
1806                         if (info) {
1807                                 /* Supported by the dynamic runtime-invoke wrapper */
1808                                 skip = TRUE;
1809                                 g_free (info);
1810                         }
1811                 }
1812 #endif
1813
1814                 if (!skip) {
1815                         //printf ("%s\n", mono_method_full_name (method, TRUE));
1816                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1817                 }
1818         }
1819
1820         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1821 #ifdef MONO_ARCH_HAVE_TLS_GET
1822                 MonoMethodDesc *desc;
1823                 MonoMethod *orig_method;
1824                 int nallocators;
1825 #endif
1826
1827                 /* Runtime invoke wrappers */
1828
1829                 /* void runtime-invoke () [.cctor] */
1830                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1831                 csig->ret = &mono_defaults.void_class->byval_arg;
1832                 add_method (acfg, get_runtime_invoke_sig (csig));
1833
1834                 /* void runtime-invoke () [Finalize] */
1835                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1836                 csig->hasthis = 1;
1837                 csig->ret = &mono_defaults.void_class->byval_arg;
1838                 add_method (acfg, get_runtime_invoke_sig (csig));
1839
1840                 /* void runtime-invoke (string) [exception ctor] */
1841                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1842                 csig->hasthis = 1;
1843                 csig->ret = &mono_defaults.void_class->byval_arg;
1844                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1845                 add_method (acfg, get_runtime_invoke_sig (csig));
1846
1847                 /* void runtime-invoke (string, string) [exception ctor] */
1848                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1849                 csig->hasthis = 1;
1850                 csig->ret = &mono_defaults.void_class->byval_arg;
1851                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1852                 csig->params [1] = &mono_defaults.string_class->byval_arg;
1853                 add_method (acfg, get_runtime_invoke_sig (csig));
1854
1855                 /* string runtime-invoke () [Exception.ToString ()] */
1856                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1857                 csig->hasthis = 1;
1858                 csig->ret = &mono_defaults.string_class->byval_arg;
1859                 add_method (acfg, get_runtime_invoke_sig (csig));
1860
1861                 /* void runtime-invoke (string, Exception) [exception ctor] */
1862                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1863                 csig->hasthis = 1;
1864                 csig->ret = &mono_defaults.void_class->byval_arg;
1865                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1866                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1867                 add_method (acfg, get_runtime_invoke_sig (csig));
1868
1869                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1870                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1871                 csig->hasthis = 1;
1872                 csig->ret = &(mono_class_from_name (
1873                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1874                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1875                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1876                 add_method (acfg, get_runtime_invoke_sig (csig));
1877
1878                 /* runtime-invoke used by finalizers */
1879                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1880
1881                 /* This is used by mono_runtime_capture_context () */
1882                 method = mono_get_context_capture_method ();
1883                 if (method)
1884                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1885
1886 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
1887                 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
1888 #endif
1889
1890                 /* JIT icall wrappers */
1891                 /* FIXME: locking */
1892                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1893
1894                 /* stelemref */
1895                 add_method (acfg, mono_marshal_get_stelemref ());
1896
1897 #ifdef MONO_ARCH_HAVE_TLS_GET
1898                 /* Managed Allocators */
1899                 nallocators = mono_gc_get_managed_allocator_types ();
1900                 for (i = 0; i < nallocators; ++i) {
1901                         m = mono_gc_get_managed_allocator_by_type (i);
1902                         if (m)
1903                                 add_method (acfg, m);
1904                 }
1905
1906                 /* Monitor Enter/Exit */
1907                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1908                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1909                 g_assert (orig_method);
1910                 mono_method_desc_free (desc);
1911                 method = mono_monitor_get_fast_path (orig_method);
1912                 if (method)
1913                         add_method (acfg, method);
1914
1915                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1916                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1917                 g_assert (orig_method);
1918                 mono_method_desc_free (desc);
1919                 method = mono_monitor_get_fast_path (orig_method);
1920                 if (method)
1921                         add_method (acfg, method);
1922 #endif
1923         }
1924
1925         /* 
1926          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
1927          * we use the original method instead at runtime.
1928          * Since full-aot doesn't support remoting, this is not a problem.
1929          */
1930 #if 0
1931         /* remoting-invoke wrappers */
1932         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1933                 MonoMethodSignature *sig;
1934                 
1935                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1936                 method = mono_get_method (acfg->image, token, NULL);
1937
1938                 sig = mono_method_signature (method);
1939
1940                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1941                         m = mono_marshal_get_remoting_invoke_with_check (method);
1942
1943                         add_method (acfg, m);
1944                 }
1945         }
1946 #endif
1947
1948         /* delegate-invoke wrappers */
1949         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1950                 MonoClass *klass;
1951                 
1952                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1953                 klass = mono_class_get (acfg->image, token);
1954
1955                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1956                         method = mono_get_delegate_invoke (klass);
1957
1958                         m = mono_marshal_get_delegate_invoke (method, NULL);
1959
1960                         add_method (acfg, m);
1961
1962                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1963                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1964
1965                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1966                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1967                 }
1968         }
1969
1970         /* Synchronized wrappers */
1971         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1972                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1973                 method = mono_get_method (acfg->image, token, NULL);
1974
1975                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1976                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1977         }
1978
1979         /* pinvoke wrappers */
1980         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1981                 MonoMethod *method;
1982                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1983
1984                 method = mono_get_method (acfg->image, token, NULL);
1985
1986                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1987                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1988                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1989                 }
1990         }
1991
1992         /* StructureToPtr/PtrToStructure wrappers */
1993         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1994                 MonoClass *klass;
1995                 
1996                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1997                 klass = mono_class_get (acfg->image, token);
1998
1999                 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2000                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2001                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2002                 }
2003         }
2004 }
2005
2006 static gboolean
2007 has_type_vars (MonoClass *klass)
2008 {
2009         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2010                 return TRUE;
2011         if (klass->rank)
2012                 return has_type_vars (klass->element_class);
2013         if (klass->generic_class) {
2014                 MonoGenericContext *context = &klass->generic_class->context;
2015                 if (context->class_inst) {
2016                         int i;
2017
2018                         for (i = 0; i < context->class_inst->type_argc; ++i)
2019                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2020                                         return TRUE;
2021                 }
2022         }
2023         return FALSE;
2024 }
2025
2026 static gboolean
2027 method_has_type_vars (MonoMethod *method)
2028 {
2029         if (has_type_vars (method->klass))
2030                 return TRUE;
2031
2032         if (method->is_inflated) {
2033                 MonoGenericContext *context = mono_method_get_context (method);
2034                 if (context->method_inst) {
2035                         int i;
2036
2037                         for (i = 0; i < context->method_inst->type_argc; ++i)
2038                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2039                                         return TRUE;
2040                 }
2041         }
2042         return FALSE;
2043 }
2044
2045 /*
2046  * add_generic_class:
2047  *
2048  *   Add all methods of a generic class.
2049  */
2050 static void
2051 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2052 {
2053         MonoMethod *method;
2054         gpointer iter;
2055
2056         mono_class_init (klass);
2057
2058         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2059                 return;
2060
2061         if (has_type_vars (klass))
2062                 return;
2063
2064         if (!klass->generic_class && !klass->rank)
2065                 return;
2066
2067         iter = NULL;
2068         while ((method = mono_class_get_methods (klass, &iter))) {
2069                 if (mono_method_is_generic_sharable_impl (method, FALSE))
2070                         /* Already added */
2071                         continue;
2072
2073                 if (method->is_generic)
2074                         /* FIXME: */
2075                         continue;
2076
2077                 /*
2078                  * FIXME: Instances which are referenced by these methods are not added,
2079                  * for example Array.Resize<int> for List<int>.Add ().
2080                  */
2081                 add_extra_method (acfg, method);
2082         }
2083
2084         if (klass->delegate) {
2085                 method = mono_get_delegate_invoke (klass);
2086
2087                 method = mono_marshal_get_delegate_invoke (method, NULL);
2088
2089                 add_method (acfg, method);
2090         }
2091
2092         /* 
2093          * For ICollection<T>, add instances of the helper methods
2094          * in Array, since a T[] could be cast to ICollection<T>.
2095          */
2096         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2097                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2098                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2099                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2100                 gpointer iter;
2101                 char *name_prefix;
2102
2103                 if (!strcmp (klass->name, "IEnumerator`1"))
2104                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2105                 else
2106                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2107
2108                 /* Add the T[]/InternalEnumerator class */
2109                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2110                         MonoClass *nclass;
2111
2112                         iter = NULL;
2113                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2114                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2115                                         break;
2116                         }
2117                         g_assert (nclass);
2118                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2119                         add_generic_class (acfg, nclass);
2120                 }
2121
2122                 iter = NULL;
2123                 while ((method = mono_class_get_methods (array_class, &iter))) {
2124                         if (strstr (method->name, name_prefix))
2125                                 add_extra_method (acfg, method);
2126                 }
2127
2128                 g_free (name_prefix);
2129
2130                 /* 
2131                  * Add instance of Array.GetGenericValueImpl, which is called by the
2132                  * array helper methods.
2133                  * managed-to-native wrappers are not shared, so have to generate 
2134                  * these for ref types too.
2135                  */
2136                 if (acfg->aot_opts.full_aot) {
2137                         MonoGenericContext ctx;
2138                         MonoType *args [16];
2139                         static MonoMethod *get_method;
2140
2141                         if (get_method == NULL) {
2142                                 MonoClass *array_klass = mono_array_class_get (mono_defaults.int_class, 1)->parent;
2143                                 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2144                         }
2145
2146                         if (get_method) {
2147                                 memset (&ctx, 0, sizeof (ctx));
2148                                 args [0] = &tclass->byval_arg;
2149                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2150                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2151                         }
2152                 }
2153         }
2154
2155         /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2156         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2157                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2158                 MonoClass *icomparable, *gcomparer;
2159                 MonoGenericContext ctx;
2160                 MonoType *args [16];
2161
2162                 memset (&ctx, 0, sizeof (ctx));
2163
2164                 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2165                 g_assert (icomparable);
2166                 args [0] = &tclass->byval_arg;
2167                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2168
2169                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2170                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2171                         g_assert (gcomparer);
2172                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2173                 }
2174         }
2175 }
2176
2177 static void
2178 add_array_wrappers (MonoAotCompile *acfg, MonoClass *klass)
2179 {
2180         int i;
2181
2182         mono_class_setup_methods (klass);
2183         for (i = 0; i < klass->method.count; ++i) {
2184                 if (klass->methods [i]->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED)
2185                         add_extra_method (acfg, klass->methods [i]);
2186         }
2187 }
2188
2189 /*
2190  * add_generic_instances:
2191  *
2192  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
2193  */
2194 static void
2195 add_generic_instances (MonoAotCompile *acfg)
2196 {
2197         int i;
2198         guint32 token;
2199         MonoMethod *method;
2200         MonoMethodHeader *header;
2201         MonoMethodSignature *sig;
2202         MonoGenericContext *context;
2203
2204         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2205                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2206                 method = mono_get_method (acfg->image, token, NULL);
2207
2208                 context = mono_method_get_context (method);
2209                 if (context && ((context->class_inst && context->class_inst->is_open) ||
2210                                                 (context->method_inst && context->method_inst->is_open)))
2211                         continue;
2212
2213                 if (method->klass->image != acfg->image)
2214                         continue;
2215
2216                 if (mono_method_is_generic_sharable_impl (method, FALSE))
2217                         /* Already added */
2218                         continue;
2219
2220                 add_extra_method (acfg, method);
2221         }
2222
2223         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2224                 MonoClass *klass;
2225
2226                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2227
2228                 klass = mono_class_get (acfg->image, token);
2229                 if (!klass || klass->rank)
2230                         continue;
2231
2232                 add_generic_class (acfg, klass);
2233         }
2234
2235         /* Add types of args/locals */
2236         for (i = 0; i < acfg->methods->len; ++i) {
2237                 int j;
2238
2239                 method = g_ptr_array_index (acfg->methods, i);
2240
2241                 sig = mono_method_signature (method);
2242
2243                 if (sig) {
2244                         for (j = 0; j < sig->param_count; ++j)
2245                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2246                                         add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2247                 }
2248
2249                 header = mono_method_get_header (method);
2250
2251                 if (header) {
2252                         for (j = 0; j < header->num_locals; ++j)
2253                                 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2254                                         add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2255                 }
2256         }
2257
2258         if (acfg->image == mono_defaults.corlib) {
2259                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2260                 MonoClass *klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2261
2262                 if (klass) {
2263                         MonoGenericContext ctx;
2264                         MonoType *args [16];
2265
2266                         memset (&ctx, 0, sizeof (ctx));
2267
2268                         args [0] = &mono_defaults.byte_class->byval_arg;
2269                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2270                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2271
2272                         args [0] = &mono_defaults.sbyte_class->byval_arg;
2273                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2274                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2275
2276                         args [0] = &mono_defaults.int16_class->byval_arg;
2277                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2278                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2279
2280                         args [0] = &mono_defaults.uint16_class->byval_arg;
2281                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2282                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2283
2284                         args [0] = &mono_defaults.int32_class->byval_arg;
2285                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2286                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2287
2288                         args [0] = &mono_defaults.uint32_class->byval_arg;
2289                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2290                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2291
2292                         args [0] = &mono_defaults.int64_class->byval_arg;
2293                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2294                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2295
2296                         args [0] = &mono_defaults.uint64_class->byval_arg;
2297                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2298                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2299                 }
2300
2301                 /* Add GenericEqualityComparer<T> instances for primitive types */
2302                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2303
2304                 if (klass) {
2305                         MonoGenericContext ctx;
2306                         MonoType *args [16];
2307
2308                         memset (&ctx, 0, sizeof (ctx));
2309
2310                         args [0] = &mono_defaults.byte_class->byval_arg;
2311                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2312                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2313
2314                         args [0] = &mono_defaults.sbyte_class->byval_arg;
2315                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2316                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2317
2318                         args [0] = &mono_defaults.int16_class->byval_arg;
2319                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2320                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2321
2322                         args [0] = &mono_defaults.uint16_class->byval_arg;
2323                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2324                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2325
2326                         args [0] = &mono_defaults.int32_class->byval_arg;
2327                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2328                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2329
2330                         args [0] = &mono_defaults.uint32_class->byval_arg;
2331                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2332                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2333
2334                         args [0] = &mono_defaults.int64_class->byval_arg;
2335                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2336                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2337
2338                         args [0] = &mono_defaults.uint64_class->byval_arg;
2339                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2340                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2341
2342                         args [0] = &mono_defaults.char_class->byval_arg;
2343                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2344                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2345
2346                         args [0] = &mono_defaults.boolean_class->byval_arg;
2347                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2348                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2349
2350                         args [0] = &mono_defaults.single_class->byval_arg;
2351                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2352                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2353
2354                         args [0] = &mono_defaults.double_class->byval_arg;
2355                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2356                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2357
2358                 }
2359
2360                 /* Emit the array wrapper methods for arrays of primitive types */
2361                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.byte_class, 1));
2362                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.sbyte_class, 1));
2363                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int16_class, 1));
2364                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.uint16_class, 1));
2365                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int32_class, 1));
2366                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.uint32_class, 1));
2367                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int64_class, 1));
2368                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.single_class, 1));
2369                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.double_class, 1));
2370                 /* These are not handled by generic sharing */
2371                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.object_class, 1));
2372                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.string_class, 1));
2373
2374                 /* Add instances of Array.GetGenericValueImpl */
2375                 {
2376                         MonoGenericContext ctx;
2377                         MonoType *args [16];
2378                         MonoMethod *method;
2379
2380                         memset (&ctx, 0, sizeof (ctx));
2381
2382                         /* 
2383                          * managed-to-native wrappers are not shared, so have to generate 
2384                          * these for ref types too.
2385                          */
2386                         klass = mono_array_class_get (mono_defaults.int_class, 1)->parent;
2387                         method = mono_class_get_method_from_name (klass, "GetGenericValueImpl", 2);
2388
2389                         if (method) {
2390                                 /* String */
2391                                 args [0] = &mono_defaults.string_class->byval_arg;
2392                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2393                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (method, &ctx), TRUE, TRUE));
2394                         }
2395                 }
2396         }
2397 }
2398
2399 /*
2400  * is_direct_callable:
2401  *
2402  *   Return whenever the method identified by JI is directly callable without 
2403  * going through the PLT.
2404  */
2405 static gboolean
2406 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2407 {
2408         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2409                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2410                 if (callee_cfg) {
2411                         gboolean direct_callable = TRUE;
2412
2413                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2414                                 direct_callable = FALSE;
2415                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2416                                 // FIXME: Maybe call the wrapper directly ?
2417                                 direct_callable = FALSE;
2418
2419                         if (direct_callable)
2420                                 return TRUE;
2421                 }
2422         }
2423
2424         return FALSE;
2425 }
2426
2427 /*
2428  * emit_and_reloc_code:
2429  *
2430  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2431  * is true, calls are made through the GOT too. This is used for emitting trampolines
2432  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2433  * since trampolines are needed to make PTL work.
2434  */
2435 static void
2436 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2437 {
2438         int i, pindex, start_index, method_index;
2439         GPtrArray *patches;
2440         MonoJumpInfo *patch_info;
2441         MonoMethodHeader *header;
2442         gboolean skip, direct_call;
2443         guint32 got_slot;
2444         char direct_call_target [128];
2445
2446         if (method) {
2447                 header = mono_method_get_header (method);
2448
2449                 method_index = get_method_index (acfg, method);
2450         }
2451
2452         /* Collect and sort relocations */
2453         patches = g_ptr_array_new ();
2454         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2455                 g_ptr_array_add (patches, patch_info);
2456         g_ptr_array_sort (patches, compare_patches);
2457
2458         start_index = 0;
2459         for (i = 0; i < code_len; i++) {
2460                 patch_info = NULL;
2461                 for (pindex = start_index; pindex < patches->len; ++pindex) {
2462                         patch_info = g_ptr_array_index (patches, pindex);
2463                         if (patch_info->ip.i >= i)
2464                                 break;
2465                 }
2466
2467 #ifdef MONO_ARCH_AOT_SUPPORTED
2468                 skip = FALSE;
2469                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2470                         start_index = pindex;
2471
2472                         switch (patch_info->type) {
2473                         case MONO_PATCH_INFO_NONE:
2474                                 break;
2475                         case MONO_PATCH_INFO_GOT_OFFSET: {
2476                                 int code_size;
2477  
2478                                 arch_emit_got_offset (acfg, code + i, &code_size);
2479                                 i += code_size - 1;
2480                                 skip = TRUE;
2481                                 patch_info->type = MONO_PATCH_INFO_NONE;
2482                                 break;
2483                         }
2484                         default: {
2485                                 /*
2486                                  * If this patch is a call, try emitting a direct call instead of
2487                                  * through a PLT entry. This is possible if the called method is in
2488                                  * the same assembly and requires no initialization.
2489                                  */
2490                                 direct_call = FALSE;
2491                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2492                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2493                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2494                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2495                                                 direct_call = TRUE;
2496                                                 sprintf (direct_call_target, "%sm_%x", acfg->temp_prefix, get_method_index (acfg, callee_cfg->orig_method));
2497                                                 patch_info->type = MONO_PATCH_INFO_NONE;
2498                                                 acfg->stats.direct_calls ++;
2499                                         }
2500
2501                                         acfg->stats.all_calls ++;
2502                                 }
2503
2504                                 if (!got_only && !direct_call) {
2505                                         int plt_offset = get_plt_offset (acfg, patch_info);
2506                                         if (plt_offset != -1) {
2507                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2508                                                 direct_call = TRUE;
2509                                                 sprintf (direct_call_target, "%sp_%d", acfg->temp_prefix, plt_offset);
2510                 
2511                                                 /* Nullify the patch */
2512                                                 patch_info->type = MONO_PATCH_INFO_NONE;
2513                                         }
2514                                 }
2515
2516                                 if (direct_call) {
2517                                         int call_size;
2518
2519                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
2520                                         i += call_size - 1;
2521                                 } else {
2522                                         int code_size;
2523
2524                                         got_slot = get_got_offset (acfg, patch_info);
2525
2526                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2527                                         i += code_size - 1;
2528                                 }
2529                                 skip = TRUE;
2530                         }
2531                         }
2532                 }
2533 #endif /* MONO_ARCH_AOT_SUPPORTED */
2534
2535                 if (!skip) {
2536                         /* Find next patch */
2537                         patch_info = NULL;
2538                         for (pindex = start_index; pindex < patches->len; ++pindex) {
2539                                 patch_info = g_ptr_array_index (patches, pindex);
2540                                 if (patch_info->ip.i >= i)
2541                                         break;
2542                         }
2543
2544                         /* Try to emit multiple bytes at once */
2545                         if (pindex < patches->len && patch_info->ip.i > i) {
2546                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2547                                 i = patch_info->ip.i - 1;
2548                         } else {
2549                                 emit_bytes (acfg, code + i, 1);
2550                         }
2551                 }
2552         }
2553 }
2554
2555 /*
2556  * sanitize_symbol:
2557  *
2558  *   Modify SYMBOL so it only includes characters permissible in symbols.
2559  */
2560 static void
2561 sanitize_symbol (char *symbol)
2562 {
2563         int i, len = strlen (symbol);
2564
2565         for (i = 0; i < len; ++i)
2566                 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2567                         symbol [i] = '_';
2568 }
2569
2570 static char*
2571 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2572 {
2573         char *name1, *name2, *cached;
2574         int i, j, len, count;
2575                 
2576         name1 = mono_method_full_name (method, TRUE);
2577         len = strlen (name1);
2578         name2 = malloc (strlen (prefix) + len + 16);
2579         memcpy (name2, prefix, strlen (prefix));
2580         j = strlen (prefix);
2581         for (i = 0; i < len; ++i) {
2582                 if (isalnum (name1 [i])) {
2583                         name2 [j ++] = name1 [i];
2584                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2585                         i += 2;
2586                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2587                         name2 [j ++] = '_';
2588                         i++;
2589                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2590                 } else
2591                         name2 [j ++] = '_';
2592         }
2593         name2 [j] = '\0';
2594
2595         g_free (name1);
2596
2597         count = 0;
2598         while (g_hash_table_lookup (cache, name2)) {
2599                 sprintf (name2 + j, "_%d", count);
2600                 count ++;
2601         }
2602
2603         cached = g_strdup (name2);
2604         g_hash_table_insert (cache, cached, cached);
2605
2606         return name2;
2607 }
2608
2609 static void
2610 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2611 {
2612         MonoMethod *method;
2613         int method_index;
2614         guint8 *code;
2615         char *debug_sym = NULL;
2616         char symbol [128];
2617         int func_alignment = AOT_FUNC_ALIGNMENT;
2618         MonoMethodHeader *header;
2619
2620         method = cfg->orig_method;
2621         code = cfg->native_code;
2622         header = mono_method_get_header (method);
2623
2624         method_index = get_method_index (acfg, method);
2625
2626         /* Emit unbox trampoline */
2627         if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2628                 char call_target [256];
2629
2630                 if (!method->wrapper_type && !method->is_inflated) {
2631                         g_assert (method->token);
2632                         sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2633                 } else {
2634                         sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2635                 }
2636
2637                 emit_section_change (acfg, ".text", 0);
2638                 emit_global (acfg, symbol, TRUE);
2639                 emit_label (acfg, symbol);
2640
2641                 sprintf (call_target, "%sm_%x", acfg->temp_prefix, method_index);
2642
2643                 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2644         }
2645
2646         /* Make the labels local */
2647         sprintf (symbol, "%sm_%x", acfg->temp_prefix, method_index);
2648
2649         emit_alignment (acfg, func_alignment);
2650         emit_label (acfg, symbol);
2651
2652         if (acfg->aot_opts.write_symbols) {
2653                 /* 
2654                  * Write a C style symbol for every method, this has two uses:
2655                  * - it works on platforms where the dwarf debugging info is not
2656                  *   yet supported.
2657                  * - it allows the setting of breakpoints of aot-ed methods.
2658                  */
2659                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
2660
2661                 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2662                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
2663                 emit_label (acfg, debug_sym);
2664         }
2665
2666         if (cfg->verbose_level > 0)
2667                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2668
2669         acfg->stats.code_size += cfg->code_len;
2670
2671         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2672
2673         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2674
2675         emit_line (acfg);
2676
2677         if (acfg->aot_opts.write_symbols) {
2678                 emit_symbol_size (acfg, debug_sym, ".");
2679                 g_free (debug_sym);
2680         }
2681
2682         sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2683         emit_label (acfg, symbol);
2684 }
2685
2686 /**
2687  * encode_patch:
2688  *
2689  *  Encode PATCH_INFO into its disk representation.
2690  */
2691 static void
2692 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2693 {
2694         guint8 *p = buf;
2695
2696         switch (patch_info->type) {
2697         case MONO_PATCH_INFO_NONE:
2698                 break;
2699         case MONO_PATCH_INFO_IMAGE:
2700                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2701                 break;
2702         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
2703                 break;
2704         case MONO_PATCH_INFO_METHOD_REL:
2705                 encode_value ((gint)patch_info->data.offset, p, &p);
2706                 break;
2707         case MONO_PATCH_INFO_SWITCH: {
2708                 gpointer *table = (gpointer *)patch_info->data.table->table;
2709                 int k;
2710
2711                 encode_value (patch_info->data.table->table_size, p, &p);
2712                 for (k = 0; k < patch_info->data.table->table_size; k++)
2713                         encode_value ((int)(gssize)table [k], p, &p);
2714                 break;
2715         }
2716         case MONO_PATCH_INFO_METHODCONST:
2717         case MONO_PATCH_INFO_METHOD:
2718         case MONO_PATCH_INFO_METHOD_JUMP:
2719         case MONO_PATCH_INFO_ICALL_ADDR:
2720         case MONO_PATCH_INFO_METHOD_RGCTX:
2721                 encode_method_ref (acfg, patch_info->data.method, p, &p);
2722                 break;
2723         case MONO_PATCH_INFO_INTERNAL_METHOD:
2724         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2725                 guint32 len = strlen (patch_info->data.name);
2726
2727                 encode_value (len, p, &p);
2728
2729                 memcpy (p, patch_info->data.name, len);
2730                 p += len;
2731                 *p++ = '\0';
2732                 break;
2733         }
2734         case MONO_PATCH_INFO_LDSTR: {
2735                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2736                 guint32 token = patch_info->data.token->token;
2737                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2738                 encode_value (image_index, p, &p);
2739                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2740                 break;
2741         }
2742         case MONO_PATCH_INFO_RVA:
2743         case MONO_PATCH_INFO_DECLSEC:
2744         case MONO_PATCH_INFO_LDTOKEN:
2745         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2746                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2747                 encode_value (patch_info->data.token->token, p, &p);
2748                 encode_value (patch_info->data.token->has_context, p, &p);
2749                 if (patch_info->data.token->has_context)
2750                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2751                 break;
2752         case MONO_PATCH_INFO_EXC_NAME: {
2753                 MonoClass *ex_class;
2754
2755                 ex_class =
2756                         mono_class_from_name (mono_defaults.exception_class->image,
2757                                                                   "System", patch_info->data.target);
2758                 g_assert (ex_class);
2759                 encode_klass_ref (acfg, ex_class, p, &p);
2760                 break;
2761         }
2762         case MONO_PATCH_INFO_R4:
2763                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2764                 break;
2765         case MONO_PATCH_INFO_R8:
2766                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2767                 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2768                 break;
2769         case MONO_PATCH_INFO_VTABLE:
2770         case MONO_PATCH_INFO_CLASS:
2771         case MONO_PATCH_INFO_IID:
2772         case MONO_PATCH_INFO_ADJUSTED_IID:
2773                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2774                 break;
2775         case MONO_PATCH_INFO_CLASS_INIT:
2776         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2777                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2778                 break;
2779         case MONO_PATCH_INFO_FIELD:
2780         case MONO_PATCH_INFO_SFLDA:
2781                 encode_field_info (acfg, patch_info->data.field, p, &p);
2782                 break;
2783         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2784                 break;
2785         case MONO_PATCH_INFO_RGCTX_FETCH: {
2786                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2787
2788                 encode_method_ref (acfg, entry->method, p, &p);
2789                 encode_value (entry->in_mrgctx, p, &p);
2790                 encode_value (entry->info_type, p, &p);
2791                 encode_value (entry->data->type, p, &p);
2792                 encode_patch (acfg, entry->data, p, &p);
2793                 break;
2794         }
2795         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2796         case MONO_PATCH_INFO_MONITOR_ENTER:
2797         case MONO_PATCH_INFO_MONITOR_EXIT:
2798                 break;
2799         default:
2800                 g_warning ("unable to handle jump info %d", patch_info->type);
2801                 g_assert_not_reached ();
2802         }
2803
2804         *endbuf = p;
2805 }
2806
2807 static void
2808 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2809 {
2810         guint8 *p = buf;
2811         guint32 pindex, offset;
2812         MonoJumpInfo *patch_info;
2813
2814         encode_value (n_patches, p, &p);
2815
2816         for (pindex = 0; pindex < patches->len; ++pindex) {
2817                 patch_info = g_ptr_array_index (patches, pindex);
2818
2819                 if (patch_info->type == MONO_PATCH_INFO_NONE)
2820                         /* Nothing to do */
2821                         continue;
2822
2823                 offset = get_got_offset (acfg, patch_info);
2824                 encode_value (offset, p, &p);
2825         }
2826
2827         *endbuf = p;
2828 }
2829
2830 static void
2831 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2832 {
2833         MonoMethod *method;
2834         GList *l;
2835         int pindex, buf_size, n_patches;
2836         guint8 *code;
2837         char symbol [128];
2838         GPtrArray *patches;
2839         MonoJumpInfo *patch_info;
2840         MonoMethodHeader *header;
2841         guint32 method_index;
2842         guint8 *p, *buf;
2843         guint32 first_got_offset;
2844
2845         method = cfg->orig_method;
2846         code = cfg->native_code;
2847         header = mono_method_get_header (method);
2848
2849         method_index = get_method_index (acfg, method);
2850
2851         /* Make the labels local */
2852         sprintf (symbol, "%sm_%x_p", acfg->temp_prefix, method_index);
2853
2854         /* Sort relocations */
2855         patches = g_ptr_array_new ();
2856         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2857                 g_ptr_array_add (patches, patch_info);
2858         g_ptr_array_sort (patches, compare_patches);
2859
2860         first_got_offset = acfg->cfgs [method_index]->got_offset;
2861
2862         /**********************/
2863         /* Encode method info */
2864         /**********************/
2865
2866         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2867         p = buf = g_malloc (buf_size);
2868
2869         if (mono_class_get_cctor (method->klass))
2870                 encode_klass_ref (acfg, method->klass, p, &p);
2871         else
2872                 /* Not needed when loading the method */
2873                 encode_value (0, p, &p);
2874
2875         /* String table */
2876         if (cfg->opt & MONO_OPT_SHARED) {
2877                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2878                 for (l = cfg->ldstr_list; l; l = l->next) {
2879                         encode_value ((long)l->data, p, &p);
2880                 }
2881         }
2882         else
2883                 /* Used only in shared mode */
2884                 g_assert (!cfg->ldstr_list);
2885
2886         n_patches = 0;
2887         for (pindex = 0; pindex < patches->len; ++pindex) {
2888                 patch_info = g_ptr_array_index (patches, pindex);
2889                 
2890                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2891                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
2892                         patch_info->type = MONO_PATCH_INFO_NONE;
2893                         /* Nothing to do */
2894                         continue;
2895                 }
2896
2897                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2898                         /* Stored in a GOT slot initialized at module load time */
2899                         patch_info->type = MONO_PATCH_INFO_NONE;
2900                         continue;
2901                 }
2902
2903                 if (is_plt_patch (patch_info)) {
2904                         /* Calls are made through the PLT */
2905                         patch_info->type = MONO_PATCH_INFO_NONE;
2906                         continue;
2907                 }
2908
2909                 n_patches ++;
2910         }
2911
2912         if (n_patches)
2913                 g_assert (cfg->has_got_slots);
2914
2915         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2916
2917         acfg->stats.info_size += p - buf;
2918
2919         /* Emit method info */
2920
2921         emit_label (acfg, symbol);
2922
2923         g_assert (p - buf < buf_size);
2924         emit_bytes (acfg, buf, p - buf);
2925         g_free (buf);
2926 }
2927
2928 static guint32
2929 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2930 {
2931         guint32 cache_index;
2932         guint32 offset;
2933
2934         /* Reuse the unwind module to canonize and store unwind info entries */
2935         cache_index = mono_cache_unwind_info (encoded, encoded_len);
2936
2937         /* Use +/- 1 to distinguish 0s from missing entries */
2938         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2939         if (offset)
2940                 return offset - 1;
2941         else {
2942                 guint8 buf [16];
2943                 guint8 *p;
2944
2945                 /* 
2946                  * It would be easier to use assembler symbols, but the caller needs an
2947                  * offset now.
2948                  */
2949                 offset = acfg->unwind_info_offset;
2950                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2951                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2952
2953                 p = buf;
2954                 encode_value (encoded_len, p, &p);
2955
2956                 acfg->unwind_info_offset += encoded_len + (p - buf);
2957                 return offset;
2958         }
2959 }
2960
2961 static void
2962 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2963 {
2964         MonoMethod *method;
2965         int k, buf_size, method_index;
2966         guint32 debug_info_size;
2967         guint8 *code;
2968         char symbol [128];
2969         MonoMethodHeader *header;
2970         guint8 *p, *buf, *debug_info;
2971         MonoJitInfo *jinfo = cfg->jit_info;
2972         guint32 flags;
2973         gboolean use_unwind_ops = FALSE;
2974
2975         method = cfg->orig_method;
2976         code = cfg->native_code;
2977         header = mono_method_get_header (method);
2978
2979         method_index = get_method_index (acfg, method);
2980
2981         /* Make the labels local */
2982         sprintf (symbol, "%se_%x_p", acfg->temp_prefix, method_index);
2983
2984         if (!acfg->aot_opts.nodebug) {
2985                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2986         } else {
2987                 debug_info = NULL;
2988                 debug_info_size = 0;
2989         }
2990
2991         buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2992         p = buf = g_malloc (buf_size);
2993
2994 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2995         use_unwind_ops = cfg->unwind_ops != NULL;
2996 #endif
2997
2998         flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0);
2999
3000         encode_value (jinfo->code_size, p, &p);
3001         encode_value (flags, p, &p);
3002
3003         if (use_unwind_ops) {
3004                 guint32 encoded_len;
3005                 guint8 *encoded;
3006
3007                 /* 
3008                  * This is a duplicate of the data in the .debug_frame section, but that
3009                  * section cannot be accessed using the dl interface.
3010                  */
3011                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3012                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3013                 g_free (encoded);
3014         } else {
3015                 encode_value (jinfo->used_regs, p, &p);
3016         }
3017
3018         /* Exception table */
3019         if (jinfo->num_clauses)
3020                 encode_value (jinfo->num_clauses, p, &p);
3021
3022         for (k = 0; k < jinfo->num_clauses; ++k) {
3023                 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3024
3025                 encode_value (ei->flags, p, &p);
3026                 encode_value (ei->exvar_offset, p, &p);
3027
3028                 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
3029                         encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3030                 else {
3031                         if (ei->data.catch_class) {
3032                                 encode_value (1, p, &p);
3033                                 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3034                         } else {
3035                                 encode_value (0, p, &p);
3036                         }
3037                 }
3038
3039                 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3040                 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3041                 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3042         }
3043
3044         if (jinfo->has_generic_jit_info) {
3045                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3046
3047                 encode_value (gi->has_this ? 1 : 0, p, &p);
3048                 encode_value (gi->this_reg, p, &p);
3049                 encode_value (gi->this_offset, p, &p);
3050
3051                 /* 
3052                  * Need to encode jinfo->method too, since it is not equal to 'method'
3053                  * when using generic sharing.
3054                  */
3055                 encode_method_ref (acfg, jinfo->method, p, &p);
3056         }
3057
3058         g_assert (debug_info_size < buf_size);
3059
3060         encode_value (debug_info_size, p, &p);
3061         if (debug_info_size) {
3062                 memcpy (p, debug_info, debug_info_size);
3063                 p += debug_info_size;
3064                 g_free (debug_info);
3065         }
3066
3067         acfg->stats.ex_info_size += p - buf;
3068
3069         /* Emit info */
3070
3071         emit_label (acfg, symbol);
3072
3073         g_assert (p - buf < buf_size);
3074         emit_bytes (acfg, buf, p - buf);
3075         g_free (buf);
3076 }
3077
3078 static void
3079 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3080 {
3081         MonoClass *klass = mono_class_get (acfg->image, token);
3082         guint8 *p, *buf;
3083         int i, buf_size;
3084         char symbol [128];
3085         gboolean no_special_static, cant_encode;
3086         gpointer iter = NULL;
3087
3088         buf_size = 10240 + (klass->vtable_size * 16);
3089         p = buf = g_malloc (buf_size);
3090
3091         g_assert (klass);
3092
3093         mono_class_init (klass);
3094
3095         mono_class_get_nested_types (klass, &iter);
3096         g_assert (klass->nested_classes_inited);
3097
3098         mono_class_setup_vtable (klass);
3099
3100         /* 
3101          * Emit all the information which is required for creating vtables so
3102          * the runtime does not need to create the MonoMethod structures which
3103          * take up a lot of space.
3104          */
3105
3106         no_special_static = !mono_class_has_special_static_fields (klass);
3107
3108         /* Check whenever we have enough info to encode the vtable */
3109         cant_encode = FALSE;
3110         for (i = 0; i < klass->vtable_size; ++i) {
3111                 MonoMethod *cm = klass->vtable [i];
3112
3113                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3114                         cant_encode = TRUE;
3115         }
3116
3117         if (klass->generic_container || cant_encode) {
3118                 encode_value (-1, p, &p);
3119         } else {
3120                 encode_value (klass->vtable_size, p, &p);
3121                 encode_value ((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);
3122                 if (klass->has_cctor)
3123                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3124                 if (klass->has_finalize)
3125                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3126  
3127                 encode_value (klass->instance_size, p, &p);
3128                 encode_value (mono_class_data_size (klass), p, &p);
3129                 encode_value (klass->packing_size, p, &p);
3130                 encode_value (klass->min_align, p, &p);
3131
3132                 for (i = 0; i < klass->vtable_size; ++i) {
3133                         MonoMethod *cm = klass->vtable [i];
3134
3135                         if (cm)
3136                                 encode_method_ref (acfg, cm, p, &p);
3137                         else
3138                                 encode_value (0, p, &p);
3139                 }
3140         }
3141
3142         acfg->stats.class_info_size += p - buf;
3143
3144         /* Emit the info */
3145         sprintf (symbol, "%sK_I_%x", acfg->temp_prefix, token - MONO_TOKEN_TYPE_DEF - 1);
3146         emit_label (acfg, symbol);
3147
3148         g_assert (p - buf < buf_size);
3149         emit_bytes (acfg, buf, p - buf);
3150         g_free (buf);
3151 }
3152
3153 /*
3154  * Calls made from AOTed code are routed through a table of jumps similar to the
3155  * ELF PLT (Program Linkage Table). The differences are the following:
3156  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3157  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3158  *   jumps. This means the jumps need to be patched when the address of the callee is
3159  *   known. Initially the PLT entries jump to code which transfers control to the
3160  *   AOT runtime through the first PLT entry.
3161  */
3162 static void
3163 emit_plt (MonoAotCompile *acfg)
3164 {
3165         char symbol [128];
3166         int i;
3167         GHashTable *cache;
3168
3169         cache = g_hash_table_new (g_str_hash, g_str_equal);
3170
3171         emit_line (acfg);
3172         sprintf (symbol, "plt");
3173
3174         emit_section_change (acfg, ".text", 0);
3175         emit_global (acfg, symbol, TRUE);
3176 #ifdef TARGET_X86
3177         /* This section will be made read-write by the AOT loader */
3178         emit_alignment (acfg, mono_pagesize ());
3179 #else
3180         emit_alignment (acfg, 16);
3181 #endif
3182         emit_label (acfg, symbol);
3183         emit_label (acfg, acfg->plt_symbol);
3184
3185         for (i = 0; i < acfg->plt_offset; ++i) {
3186                 char label [128];
3187                 char *debug_sym = NULL;
3188
3189                 sprintf (label, "%sp_%d", acfg->temp_prefix, i);
3190                 emit_label (acfg, label);
3191
3192                 if (acfg->aot_opts.write_symbols) {
3193                         MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3194                         char *debug_sym = NULL;
3195
3196                         if (ji) {
3197                                 switch (ji->type) {
3198                                 case MONO_PATCH_INFO_METHOD:
3199                                         debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3200                                         break;
3201                                 case MONO_PATCH_INFO_INTERNAL_METHOD:
3202                                         debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3203                                         break;
3204                                 case MONO_PATCH_INFO_CLASS_INIT:
3205                                         debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3206                                         sanitize_symbol (debug_sym);
3207                                         break;
3208                                 case MONO_PATCH_INFO_RGCTX_FETCH:
3209                                         debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3210                                         break;
3211                                 case MONO_PATCH_INFO_ICALL_ADDR: {
3212                                         char *s = get_debug_sym (ji->data.method, "", cache);
3213                                         
3214                                         debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3215                                         g_free (s);
3216                                         break;
3217                                 }
3218                                 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3219                                         debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3220                                         break;
3221                                 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3222                                         debug_sym = g_strdup_printf ("plt__generic_class_init");
3223                                         break;
3224                                 default:
3225                                         break;
3226                                 }
3227
3228                                 if (debug_sym) {
3229                                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3230                                         emit_label (acfg, debug_sym);
3231                                 }
3232                         }
3233                 }
3234
3235                 /* 
3236                  * The first plt entry is used to transfer code to the AOT loader. 
3237                  */
3238                 arch_emit_plt_entry (acfg, i);
3239
3240                 if (debug_sym) {
3241                         emit_symbol_size (acfg, debug_sym, ".");
3242                         g_free (debug_sym);
3243                 }
3244         }
3245
3246         emit_symbol_size (acfg, acfg->plt_symbol, ".");
3247
3248         sprintf (symbol, "plt_end");
3249         emit_global (acfg, symbol, TRUE);
3250         emit_label (acfg, symbol);
3251
3252         g_hash_table_destroy (cache);
3253 }
3254
3255 static G_GNUC_UNUSED void
3256 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code, 
3257                                  guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3258 {
3259         char start_symbol [256];
3260         char symbol [256];
3261         guint32 buf_size;
3262         MonoJumpInfo *patch_info;
3263         guint8 *buf, *p;
3264         GPtrArray *patches;
3265
3266         /* Emit code */
3267
3268         sprintf (start_symbol, "%s", name);
3269
3270         emit_section_change (acfg, ".text", 0);
3271         emit_global (acfg, start_symbol, TRUE);
3272         emit_alignment (acfg, 16);
3273         emit_label (acfg, start_symbol);
3274
3275         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3276         emit_label (acfg, symbol);
3277
3278         /* 
3279          * The code should access everything through the GOT, so we pass
3280          * TRUE here.
3281          */
3282         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3283
3284         emit_symbol_size (acfg, start_symbol, ".");
3285
3286         /* Emit info */
3287
3288         /* Sort relocations */
3289         patches = g_ptr_array_new ();
3290         for (patch_info = ji; patch_info; patch_info = patch_info->next)
3291                 if (patch_info->type != MONO_PATCH_INFO_NONE)
3292                         g_ptr_array_add (patches, patch_info);
3293         g_ptr_array_sort (patches, compare_patches);
3294
3295         buf_size = patches->len * 128 + 128;
3296         buf = g_malloc (buf_size);
3297         p = buf;
3298
3299         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3300         g_assert (p - buf < buf_size);
3301
3302         sprintf (symbol, "%s_p", name);
3303
3304         emit_section_change (acfg, ".text", 0);
3305         emit_global (acfg, symbol, FALSE);
3306         emit_label (acfg, symbol);
3307                 
3308         emit_bytes (acfg, buf, p - buf);
3309
3310         /* Emit debug info */
3311         if (unwind_ops) {
3312                 char symbol2 [256];
3313
3314                 sprintf (symbol, "%s", name);
3315                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3316
3317                 if (acfg->dwarf)
3318                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3319         }
3320 }
3321
3322 static void
3323 emit_trampolines (MonoAotCompile *acfg)
3324 {
3325         char symbol [256];
3326         int i, tramp_got_offset;
3327         MonoAotTrampoline ntype;
3328 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3329         int tramp_type;
3330         guint32 code_size;
3331         MonoJumpInfo *ji;
3332         guint8 *code;
3333         GSList *unwind_ops;
3334 #endif
3335
3336         if (!acfg->aot_opts.full_aot)
3337                 return;
3338         
3339         g_assert (acfg->image->assembly);
3340
3341         /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3342         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3343 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3344                 /*
3345                  * Emit the generic trampolines.
3346                  *
3347                  * We could save some code by treating the generic trampolines as a wrapper
3348                  * method, but that approach has its own complexities, so we choose the simpler
3349                  * method.
3350                  */
3351                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3352                         code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3353
3354                         /* Emit trampoline code */
3355
3356                         sprintf (symbol, "generic_trampoline_%d", tramp_type);
3357
3358                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3359                 }
3360
3361                 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3362                 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3363 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3364                 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3365                 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3366                 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3367                 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3368 #endif
3369
3370                 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3371                 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3372
3373                 /* Emit the exception related code pieces */
3374                 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3375                 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3376                 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3377                 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3378                 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3379                 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3380                 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3381                 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3382                 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3383                 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3384                 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3385                 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3386
3387 #if defined(TARGET_AMD64)
3388                 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3389                 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3390 #endif
3391
3392                 for (i = 0; i < 128; ++i) {
3393                         int offset;
3394
3395                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3396                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3397                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3398                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3399
3400                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3401                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3402                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3403                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3404                 }
3405
3406                 {
3407                         GSList *l;
3408
3409                         /* delegate_invoke_impl trampolines */
3410                         l = mono_arch_get_delegate_invoke_impls ();
3411                         while (l) {
3412                                 MonoAotTrampInfo *info = l->data;
3413
3414                                 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3415                                 l = l->next;
3416                         }
3417                 }
3418
3419 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3420
3421                 /* Emit trampolines which are numerous */
3422
3423                 /*
3424                  * These include the following:
3425                  * - specific trampolines
3426                  * - static rgctx invoke trampolines
3427                  * - imt thunks
3428                  * These trampolines have the same code, they are parameterized by GOT 
3429                  * slots. 
3430                  * They are defined in this file, in the arch_... routines instead of
3431                  * in tramp-<ARCH>.c, since it is easier to do it this way.
3432                  */
3433
3434                 /*
3435                  * When running in aot-only mode, we can't create specific trampolines at 
3436                  * runtime, so we create a few, and save them in the AOT file. 
3437                  * Normal trampolines embed their argument as a literal inside the 
3438                  * trampoline code, we can't do that here, so instead we embed an offset
3439                  * which needs to be added to the trampoline address to get the address of
3440                  * the GOT slot which contains the argument value.
3441                  * The generated trampolines jump to the generic trampolines using another
3442                  * GOT slot, which will be setup by the AOT loader to point to the 
3443                  * generic trampoline code of the given type.
3444                  */
3445
3446                 /*
3447                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3448                  * each class).
3449                  */
3450
3451                 emit_section_change (acfg, ".text", 0);
3452
3453                 tramp_got_offset = acfg->got_offset;
3454
3455                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3456                         switch (ntype) {
3457                         case MONO_AOT_TRAMP_SPECIFIC:
3458                                 sprintf (symbol, "specific_trampolines");
3459                                 break;
3460                         case MONO_AOT_TRAMP_STATIC_RGCTX:
3461                                 sprintf (symbol, "static_rgctx_trampolines");
3462                                 break;
3463                         case MONO_AOT_TRAMP_IMT_THUNK:
3464                                 sprintf (symbol, "imt_thunks");
3465                                 break;
3466                         default:
3467                                 g_assert_not_reached ();
3468                         }
3469
3470                         emit_global (acfg, symbol, TRUE);
3471                         emit_alignment (acfg, 16);
3472                         emit_label (acfg, symbol);
3473
3474                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3475
3476                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3477                                 int tramp_size = 0;
3478
3479                                 switch (ntype) {
3480                                 case MONO_AOT_TRAMP_SPECIFIC:
3481                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3482                                         tramp_got_offset += 2;
3483                                 break;
3484                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
3485                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
3486                                         tramp_got_offset += 2;
3487                                         break;
3488                                 case MONO_AOT_TRAMP_IMT_THUNK:
3489                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3490                                         tramp_got_offset += 1;
3491                                         break;
3492                                 default:
3493                                         g_assert_not_reached ();
3494                                 }
3495
3496                                 if (!acfg->trampoline_size [ntype]) {
3497                                         g_assert (tramp_size);
3498                                         acfg->trampoline_size [ntype] = tramp_size;
3499                                 }
3500                         }
3501                 }
3502
3503                 /* Reserve some entries at the end of the GOT for our use */
3504                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3505         }
3506
3507         acfg->got_offset += acfg->num_trampoline_got_entries;
3508 }
3509
3510 static gboolean
3511 str_begins_with (const char *str1, const char *str2)
3512 {
3513         int len = strlen (str2);
3514         return strncmp (str1, str2, len) == 0;
3515 }
3516
3517 static void
3518 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3519 {
3520         gchar **args, **ptr;
3521
3522         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3523         for (ptr = args; ptr && *ptr; ptr ++) {
3524                 const char *arg = *ptr;
3525
3526                 if (str_begins_with (arg, "outfile=")) {
3527                         opts->outfile = g_strdup (arg + strlen ("outfile="));
3528                 } else if (str_begins_with (arg, "save-temps")) {
3529                         opts->save_temps = TRUE;
3530                 } else if (str_begins_with (arg, "keep-temps")) {
3531                         opts->save_temps = TRUE;
3532                 } else if (str_begins_with (arg, "write-symbols")) {
3533                         opts->write_symbols = TRUE;
3534                 } else if (str_begins_with (arg, "metadata-only")) {
3535                         opts->metadata_only = TRUE;
3536                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3537                         opts->bind_to_runtime_version = TRUE;
3538                 } else if (str_begins_with (arg, "full")) {
3539                         opts->full_aot = TRUE;
3540                 } else if (str_begins_with (arg, "threads=")) {
3541                         opts->nthreads = atoi (arg + strlen ("threads="));
3542                 } else if (str_begins_with (arg, "static")) {
3543                         opts->static_link = TRUE;
3544                         opts->no_dlsym = TRUE;
3545                 } else if (str_begins_with (arg, "asmonly")) {
3546                         opts->asm_only = TRUE;
3547                 } else if (str_begins_with (arg, "asmwriter")) {
3548                         opts->asm_writer = TRUE;
3549                 } else if (str_begins_with (arg, "nodebug")) {
3550                         opts->nodebug = TRUE;
3551                 } else if (str_begins_with (arg, "ntrampolines=")) {
3552                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3553                 } else if (str_begins_with (arg, "tool-prefix=")) {
3554                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
3555                 } else {
3556                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3557                         exit (1);
3558                 }
3559         }
3560
3561         g_strfreev (args);
3562 }
3563
3564 static void
3565 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3566 {
3567         MonoMethod *method = (MonoMethod*)key;
3568         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3569         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3570         MonoAotCompile *acfg = user_data;
3571
3572         new_ji->image = ji->image;
3573         new_ji->token = ji->token;
3574         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3575 }
3576
3577 static gboolean
3578 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
3579 {
3580         if (klass->type_token)
3581                 return TRUE;
3582         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3583                 return TRUE;
3584         if (klass->rank)
3585                 return can_encode_class (acfg, klass->element_class);
3586         return FALSE;
3587 }
3588
3589 static gboolean
3590 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3591 {
3592         switch (patch_info->type) {
3593         case MONO_PATCH_INFO_METHOD:
3594         case MONO_PATCH_INFO_METHODCONST: {
3595                 MonoMethod *method = patch_info->data.method;
3596
3597                 if (method->wrapper_type) {
3598                         switch (method->wrapper_type) {
3599                         case MONO_WRAPPER_NONE:
3600                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3601                         case MONO_WRAPPER_XDOMAIN_INVOKE:
3602                         case MONO_WRAPPER_STFLD:
3603                         case MONO_WRAPPER_LDFLD:
3604                         case MONO_WRAPPER_LDFLDA:
3605                         case MONO_WRAPPER_LDFLD_REMOTE:
3606                         case MONO_WRAPPER_STFLD_REMOTE:
3607                         case MONO_WRAPPER_STELEMREF:
3608                         case MONO_WRAPPER_ISINST:
3609                         case MONO_WRAPPER_PROXY_ISINST:
3610                         case MONO_WRAPPER_ALLOC:
3611                         case MONO_WRAPPER_REMOTING_INVOKE:
3612                         case MONO_WRAPPER_UNKNOWN:
3613                                 break;
3614                         default:
3615                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3616                                 return FALSE;
3617                         }
3618                 } else {
3619                         if (!method->token) {
3620                                 /* The method is part of a constructed type like Int[,].Set (). */
3621                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
3622                                         if (method->klass->rank)
3623                                                 return TRUE;
3624                                         return FALSE;
3625                                 }
3626                         }
3627                 }
3628                 break;
3629         }
3630         case MONO_PATCH_INFO_VTABLE:
3631         case MONO_PATCH_INFO_CLASS_INIT:
3632         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3633         case MONO_PATCH_INFO_CLASS:
3634         case MONO_PATCH_INFO_IID:
3635         case MONO_PATCH_INFO_ADJUSTED_IID:
3636                 if (!can_encode_class (acfg, patch_info->data.klass)) {
3637                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3638                         return FALSE;
3639                 }
3640                 break;
3641         case MONO_PATCH_INFO_RGCTX_FETCH: {
3642                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3643
3644                 if (!can_encode_patch (acfg, entry->data))
3645                         return FALSE;
3646                 break;
3647         }
3648         default:
3649                 break;
3650         }
3651
3652         return TRUE;
3653 }
3654
3655 static void
3656 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3657
3658 /*
3659  * compile_method:
3660  *
3661  *   AOT compile a given method.
3662  * This function might be called by multiple threads, so it must be thread-safe.
3663  */
3664 static void
3665 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3666 {
3667         MonoCompile *cfg;
3668         MonoJumpInfo *patch_info;
3669         gboolean skip;
3670         int index;
3671         MonoMethod *wrapped;
3672
3673         if (acfg->aot_opts.metadata_only)
3674                 return;
3675
3676         mono_acfg_lock (acfg);
3677         index = get_method_index (acfg, method);
3678         mono_acfg_unlock (acfg);
3679
3680         /* fixme: maybe we can also precompile wrapper methods */
3681         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3682                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3683                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3684                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3685                 return;
3686         }
3687
3688         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3689                 return;
3690
3691         wrapped = mono_marshal_method_from_wrapper (method);
3692         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3693                 // FIXME: The wrapper should be generic too, but it is not
3694                 return;
3695
3696         InterlockedIncrement (&acfg->stats.mcount);
3697
3698 #if 0
3699         if (method->is_generic || method->klass->generic_container) {
3700                 InterlockedIncrement (&acfg->stats.genericcount);
3701                 return;
3702         }
3703 #endif
3704
3705         //acfg->aot_opts.print_skipped_methods = TRUE;
3706
3707         /*
3708          * Since these methods are the only ones which are compiled with
3709          * AOT support, and they are not used by runtime startup/shutdown code,
3710          * the runtime will not see AOT methods during AOT compilation,so it
3711          * does not need to support them by creating a fake GOT etc.
3712          */
3713         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3714         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3715                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3716                 InterlockedIncrement (&acfg->stats.genericcount);
3717                 return;
3718         }
3719         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3720                 /* Let the exception happen at runtime */
3721                 return;
3722         }
3723
3724         if (cfg->disable_aot) {
3725                 if (acfg->aot_opts.print_skipped_methods)
3726                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3727                 InterlockedIncrement (&acfg->stats.ocount);
3728                 mono_destroy_compile (cfg);
3729                 return;
3730         }
3731
3732         /* Nullify patches which need no aot processing */
3733         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3734                 switch (patch_info->type) {
3735                 case MONO_PATCH_INFO_LABEL:
3736                 case MONO_PATCH_INFO_BB:
3737                         patch_info->type = MONO_PATCH_INFO_NONE;
3738                         break;
3739                 default:
3740                         break;
3741                 }
3742         }
3743
3744         /* Collect method->token associations from the cfg */
3745         mono_acfg_lock (acfg);
3746         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3747         mono_acfg_unlock (acfg);
3748
3749         /*
3750          * Check for absolute addresses.
3751          */
3752         skip = FALSE;
3753         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3754                 switch (patch_info->type) {
3755                 case MONO_PATCH_INFO_ABS:
3756                         /* unable to handle this */
3757                         skip = TRUE;    
3758                         break;
3759                 default:
3760                         break;
3761                 }
3762         }
3763
3764         if (skip) {
3765                 if (acfg->aot_opts.print_skipped_methods)
3766                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3767                 InterlockedIncrement (&acfg->stats.abscount);
3768                 mono_destroy_compile (cfg);
3769                 return;
3770         }
3771
3772         /* Lock for the rest of the code */
3773         mono_acfg_lock (acfg);
3774
3775         /*
3776          * Check for methods/klasses we can't encode.
3777          */
3778         skip = FALSE;
3779         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3780                 if (!can_encode_patch (acfg, patch_info))
3781                         skip = TRUE;
3782         }
3783
3784         if (skip) {
3785                 if (acfg->aot_opts.print_skipped_methods)
3786                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3787                 acfg->stats.ocount++;
3788                 mono_destroy_compile (cfg);
3789                 mono_acfg_unlock (acfg);
3790                 return;
3791         }
3792
3793         /* Adds generic instances referenced by this method */
3794         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3795                 switch (patch_info->type) {
3796                 case MONO_PATCH_INFO_METHOD: {
3797                         MonoMethod *m = patch_info->data.method;
3798                         if (m->is_inflated) {
3799                                 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3800                                           mono_method_is_generic_sharable_impl (m, FALSE)) &&
3801                                         !method_has_type_vars (m)) {
3802                                         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3803                                                 if (acfg->aot_opts.full_aot)
3804                                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
3805                                         } else {
3806                                                 add_extra_method (acfg, m);
3807                                         }
3808                                 }
3809                                 add_generic_class (acfg, m->klass);
3810                         }
3811                         break;
3812                 }
3813                 case MONO_PATCH_INFO_VTABLE: {
3814                         MonoClass *klass = patch_info->data.klass;
3815
3816                         if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
3817                                 add_generic_class (acfg, klass);
3818                         break;
3819                 }
3820                 default:
3821                         break;
3822                 }
3823         }
3824
3825         /* Determine whenever the method has GOT slots */
3826         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3827                 switch (patch_info->type) {
3828                 case MONO_PATCH_INFO_GOT_OFFSET:
3829                 case MONO_PATCH_INFO_NONE:
3830                         break;
3831                 case MONO_PATCH_INFO_IMAGE:
3832                         /* The assembly is stored in GOT slot 0 */
3833                         if (patch_info->data.image != acfg->image)
3834                                 cfg->has_got_slots = TRUE;
3835                         break;
3836                 default:
3837                         if (!is_plt_patch (patch_info))
3838                                 cfg->has_got_slots = TRUE;
3839                         break;
3840                 }
3841         }
3842
3843         if (!cfg->has_got_slots)
3844                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3845
3846         /* Make a copy of the patch info which is in the mempool */
3847         {
3848                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3849
3850                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3851                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3852
3853                         if (!patches)
3854                                 patches = new_patch_info;
3855                         else
3856                                 patches_end->next = new_patch_info;
3857                         patches_end = new_patch_info;
3858                 }
3859                 cfg->patch_info = patches;
3860         }
3861         /* Make a copy of the unwind info */
3862         {
3863                 GSList *l, *unwind_ops;
3864                 MonoUnwindOp *op;
3865
3866                 unwind_ops = NULL;
3867                 for (l = cfg->unwind_ops; l; l = l->next) {
3868                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3869                         memcpy (op, l->data, sizeof (MonoUnwindOp));
3870                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3871                 }
3872                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3873         }
3874         /* Make a copy of the argument/local info */
3875         {
3876                 MonoInst **args, **locals;
3877                 MonoMethodSignature *sig;
3878                 MonoMethodHeader *header;
3879                 int i;
3880                 
3881                 sig = mono_method_signature (method);
3882                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3883                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3884                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3885                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3886                 }
3887                 cfg->args = args;
3888
3889                 header = mono_method_get_header (method);
3890                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3891                 for (i = 0; i < header->num_locals; ++i) {
3892                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3893                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3894                 }
3895                 cfg->locals = locals;
3896         }
3897
3898         /* Free some fields used by cfg to conserve memory */
3899         mono_mempool_destroy (cfg->mempool);
3900         cfg->mempool = NULL;
3901         g_free (cfg->varinfo);
3902         cfg->varinfo = NULL;
3903         g_free (cfg->vars);
3904         cfg->vars = NULL;
3905         if (cfg->rs) {
3906                 mono_regstate_free (cfg->rs);
3907                 cfg->rs = NULL;
3908         }
3909
3910         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
3911
3912         while (index >= acfg->cfgs_size) {
3913                 MonoCompile **new_cfgs;
3914                 int new_size;
3915
3916                 new_size = acfg->cfgs_size * 2;
3917                 new_cfgs = g_new0 (MonoCompile*, new_size);
3918                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3919                 g_free (acfg->cfgs);
3920                 acfg->cfgs = new_cfgs;
3921                 acfg->cfgs_size = new_size;
3922         }
3923         acfg->cfgs [index] = cfg;
3924
3925         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3926
3927         /*
3928         if (cfg->orig_method->wrapper_type)
3929                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3930         */
3931
3932         mono_acfg_unlock (acfg);
3933
3934         InterlockedIncrement (&acfg->stats.ccount);
3935 }
3936  
3937 static void
3938 compile_thread_main (gpointer *user_data)
3939 {
3940         MonoDomain *domain = user_data [0];
3941         MonoAotCompile *acfg = user_data [1];
3942         GPtrArray *methods = user_data [2];
3943         int i;
3944
3945         mono_thread_attach (domain);
3946
3947         for (i = 0; i < methods->len; ++i)
3948                 compile_method (acfg, g_ptr_array_index (methods, i));
3949 }
3950
3951 static void
3952 load_profile_files (MonoAotCompile *acfg)
3953 {
3954         FILE *infile;
3955         char *tmp;
3956         int file_index, res, method_index, i;
3957         char ver [256];
3958         guint32 token;
3959         GList *unordered;
3960
3961         file_index = 0;
3962         while (TRUE) {
3963                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%s-%d", g_get_home_dir (), acfg->image->assembly_name, acfg->image->guid, file_index);
3964
3965                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3966                         g_free (tmp);
3967                         break;
3968                 }
3969
3970                 infile = fopen (tmp, "r");
3971                 g_assert (infile);
3972
3973                 printf ("Using profile data file '%s'\n", tmp);
3974                 g_free (tmp);
3975
3976                 file_index ++;
3977
3978                 res = fscanf (infile, "%32s\n", ver);
3979                 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3980                         printf ("Profile file has wrong version or invalid.\n");
3981                         fclose (infile);
3982                         continue;
3983                 }
3984
3985                 while (TRUE) {
3986                         res = fscanf (infile, "%d\n", &token);
3987                         if (res < 1)
3988                                 break;
3989
3990                         method_index = mono_metadata_token_index (token) - 1;
3991
3992                         if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3993                                 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3994                 }
3995                 fclose (infile);
3996         }
3997
3998         /* Add missing methods */
3999         unordered = NULL;
4000         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4001                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4002                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4003         }
4004         unordered = g_list_reverse (unordered);
4005         if (acfg->method_order)
4006                 g_list_last (acfg->method_order)->next = unordered;
4007         else
4008                 acfg->method_order = unordered;
4009 }
4010
4011 static void
4012 emit_code (MonoAotCompile *acfg)
4013 {
4014         int i;
4015         char symbol [256];
4016         GList *l;
4017
4018 #if defined(TARGET_POWERPC64)
4019         sprintf (symbol, ".Lgot_addr");
4020         emit_section_change (acfg, ".text", 0);
4021         emit_alignment (acfg, 8);
4022         emit_label (acfg, symbol);
4023         emit_pointer (acfg, acfg->got_symbol);
4024 #endif
4025
4026         sprintf (symbol, "methods");
4027         emit_section_change (acfg, ".text", 0);
4028         emit_global (acfg, symbol, TRUE);
4029         emit_alignment (acfg, 8);
4030         emit_label (acfg, symbol);
4031
4032         /* 
4033          * Emit some padding so the local symbol for the first method doesn't have the
4034          * same address as 'methods'.
4035          */
4036         emit_zero_bytes (acfg, 16);
4037
4038         for (l = acfg->method_order; l != NULL; l = l->next) {
4039                 i = GPOINTER_TO_UINT (l->data);
4040
4041                 if (acfg->cfgs [i])
4042                         emit_method_code (acfg, acfg->cfgs [i]);
4043         }
4044
4045         sprintf (symbol, "methods_end");
4046         emit_section_change (acfg, ".text", 0);
4047         emit_global (acfg, symbol, FALSE);
4048         emit_alignment (acfg, 8);
4049         emit_label (acfg, symbol);
4050
4051         sprintf (symbol, "method_offsets");
4052         emit_section_change (acfg, ".text", 1);
4053         emit_global (acfg, symbol, FALSE);
4054         emit_alignment (acfg, 8);
4055         emit_label (acfg, symbol);
4056
4057         for (i = 0; i < acfg->nmethods; ++i) {
4058                 if (acfg->cfgs [i]) {
4059                         sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
4060                         emit_symbol_diff (acfg, symbol, "methods", 0);
4061                 } else {
4062                         emit_int32 (acfg, 0xffffffff);
4063                 }
4064         }
4065         emit_line (acfg);
4066 }
4067
4068 static void
4069 emit_info (MonoAotCompile *acfg)
4070 {
4071         int i;
4072         char symbol [256];
4073         GList *l;
4074
4075         /* Emit method info */
4076         sprintf (symbol, "method_info");
4077         emit_section_change (acfg, ".text", 1);
4078         emit_global (acfg, symbol, FALSE);
4079         emit_alignment (acfg, 8);
4080         emit_label (acfg, symbol);
4081
4082         /* To reduce size of generated assembly code */
4083         sprintf (symbol, "mi");
4084         emit_label (acfg, symbol);
4085
4086         for (l = acfg->method_order; l != NULL; l = l->next) {
4087                 i = GPOINTER_TO_UINT (l->data);
4088
4089                 if (acfg->cfgs [i])
4090                         emit_method_info (acfg, acfg->cfgs [i]);
4091         }
4092
4093         sprintf (symbol, "method_info_offsets");
4094         emit_section_change (acfg, ".text", 1);
4095         emit_global (acfg, symbol, FALSE);
4096         emit_alignment (acfg, 8);
4097         emit_label (acfg, symbol);
4098
4099         for (i = 0; i < acfg->nmethods; ++i) {
4100                 if (acfg->cfgs [i]) {
4101                         sprintf (symbol, "%sm_%x_p", acfg->temp_prefix, i);
4102                         emit_symbol_diff (acfg, symbol, "mi", 0);
4103                 } else {
4104                         emit_int32 (acfg, 0);
4105                 }
4106         }
4107         emit_line (acfg);
4108 }
4109
4110 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4111
4112 /*
4113  * mono_aot_str_hash:
4114  *
4115  * Hash function for strings which we use to hash strings for things which are
4116  * saved in the AOT image, since g_str_hash () can change.
4117  */
4118 guint
4119 mono_aot_str_hash (gconstpointer v1)
4120 {
4121         /* Same as g_str_hash () in glib */
4122         char *p = (char *) v1;
4123         guint hash = *p;
4124
4125         while (*p++) {
4126                 if (*p)
4127                         hash = (hash << 5) - hash + *p;
4128         }
4129
4130         return hash;
4131
4132
4133 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4134 #define mix(a,b,c) { \
4135         a -= c;  a ^= rot(c, 4);  c += b; \
4136         b -= a;  b ^= rot(a, 6);  a += c; \
4137         c -= b;  c ^= rot(b, 8);  b += a; \
4138         a -= c;  a ^= rot(c,16);  c += b; \
4139         b -= a;  b ^= rot(a,19);  a += c; \
4140         c -= b;  c ^= rot(b, 4);  b += a; \
4141 }
4142 #define final(a,b,c) { \
4143         c ^= b; c -= rot(b,14); \
4144         a ^= c; a -= rot(c,11); \
4145         b ^= a; b -= rot(a,25); \
4146         c ^= b; c -= rot(b,16); \
4147         a ^= c; a -= rot(c,4);  \
4148         b ^= a; b -= rot(a,14); \
4149         c ^= b; c -= rot(b,24); \
4150 }
4151
4152 static guint
4153 mono_aot_type_hash (MonoType *t1)
4154 {
4155         guint hash = t1->type;
4156
4157         hash |= t1->byref << 6; /* do not collide with t1->type values */
4158         switch (t1->type) {
4159         case MONO_TYPE_VALUETYPE:
4160         case MONO_TYPE_CLASS:
4161         case MONO_TYPE_SZARRAY:
4162                 /* check if the distribution is good enough */
4163                 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
4164         case MONO_TYPE_PTR:
4165                 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
4166         case MONO_TYPE_ARRAY:
4167                 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
4168         case MONO_TYPE_GENERICINST:
4169                 return ((hash << 5) - hash) ^ 0;
4170         }
4171         return hash;
4172 }
4173
4174 /*
4175  * mono_aot_method_hash:
4176  *
4177  *   Return a hash code for methods which only depends on metadata.
4178  */
4179 guint32
4180 mono_aot_method_hash (MonoMethod *method)
4181 {
4182         MonoMethodSignature *sig;
4183         MonoClass *klass;
4184         int i;
4185         int hashes_count;
4186         guint32 *hashes_start, *hashes;
4187         guint32 a, b, c;
4188
4189         /* Similar to the hash in mono_method_get_imt_slot () */
4190
4191         sig = mono_method_signature (method);
4192
4193         hashes_count = sig->param_count + 5;
4194         hashes_start = malloc (hashes_count * sizeof (guint32));
4195         hashes = hashes_start;
4196
4197         /* Some wrappers are assigned to random classes */
4198         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4199                 klass = method->klass;
4200         else
4201                 klass = mono_defaults.object_class;
4202
4203         if (!method->wrapper_type) {
4204                 char *full_name = mono_type_full_name (&klass->byval_arg);
4205
4206                 hashes [0] = mono_aot_str_hash (full_name);
4207                 hashes [1] = 0;
4208                 g_free (full_name);
4209         } else {
4210                 hashes [0] = mono_aot_str_hash (klass->name);
4211                 hashes [1] = mono_aot_str_hash (klass->name_space);
4212         }
4213         hashes [2] = mono_aot_str_hash (method->name);
4214         hashes [3] = method->wrapper_type;
4215         hashes [4] = mono_aot_type_hash (sig->ret);
4216         for (i = 0; i < sig->param_count; i++) {
4217                 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4218         }
4219         
4220         /* Setup internal state */
4221         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4222
4223         /* Handle most of the hashes */
4224         while (hashes_count > 3) {
4225                 a += hashes [0];
4226                 b += hashes [1];
4227                 c += hashes [2];
4228                 mix (a,b,c);
4229                 hashes_count -= 3;
4230                 hashes += 3;
4231         }
4232
4233         /* Handle the last 3 hashes (all the case statements fall through) */
4234         switch (hashes_count) { 
4235         case 3 : c += hashes [2];
4236         case 2 : b += hashes [1];
4237         case 1 : a += hashes [0];
4238                 final (a,b,c);
4239         case 0: /* nothing left to add */
4240                 break;
4241         }
4242         
4243         free (hashes_start);
4244         
4245         return c;
4246 }
4247 #undef rot
4248 #undef mix
4249 #undef final
4250
4251 /*
4252  * mono_aot_wrapper_name:
4253  *
4254  *   Return a string which uniqely identifies the given wrapper method.
4255  */
4256 char*
4257 mono_aot_wrapper_name (MonoMethod *method)
4258 {
4259         char *name, *tmpsig, *klass_desc;
4260
4261         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4262
4263         switch (method->wrapper_type) {
4264         case MONO_WRAPPER_RUNTIME_INVOKE:
4265                 if (!strcmp (method->name, "runtime_invoke_dynamic"))
4266                         name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
4267                 else
4268                         name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4269                 break;
4270         case MONO_WRAPPER_DELEGATE_INVOKE:
4271         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
4272         case MONO_WRAPPER_DELEGATE_END_INVOKE:
4273                 /* This is a hack to work around the fact that these wrappers get assigned to some random class */
4274                 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4275                 break;
4276         default:
4277                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4278
4279                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4280                 break;
4281         }
4282
4283         g_free (tmpsig);
4284
4285         return name;
4286 }
4287
4288 /*
4289  * mono_aot_tramp_info_create:
4290  *
4291  *   Create a MonoAotTrampInfo structure from the arguments.
4292  */
4293 MonoAotTrampInfo*
4294 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4295 {
4296         MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4297
4298         info->name = (char*)name;
4299         info->code = code;
4300         info->code_size = code_size;
4301
4302         return info;
4303 }
4304
4305 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4306
4307 typedef struct HashEntry {
4308     guint32 key, value, index;
4309         struct HashEntry *next;
4310 } HashEntry;
4311
4312 /*
4313  * emit_extra_methods:
4314  *
4315  * Emit methods which are not in the METHOD table, like wrappers.
4316  */
4317 static void
4318 emit_extra_methods (MonoAotCompile *acfg)
4319 {
4320         int i, table_size, buf_size;
4321         char symbol [256];
4322         guint8 *p, *buf;
4323         guint32 *info_offsets;
4324         guint32 hash;
4325         GPtrArray *table;
4326         HashEntry *entry, *new_entry;
4327         int nmethods, max_chain_length;
4328         int *chain_lengths;
4329
4330         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4331
4332         buf_size = acfg->extra_methods->len * 256 + 256;
4333         p = buf = g_malloc (buf_size);
4334
4335         /* Encode method info */
4336         nmethods = 0;
4337         /* So offsets are > 0 */
4338         *p = 0;
4339         p++;
4340         for (i = 0; i < acfg->extra_methods->len; ++i) {
4341                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4342                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4343                 char *name;
4344
4345                 if (!cfg)
4346                         continue;
4347
4348                 nmethods ++;
4349                 info_offsets [i] = p - buf;
4350
4351                 name = NULL;
4352                 if (method->wrapper_type) {
4353                         /* 
4354                          * We encode some wrappers using their name, since encoding them
4355                          * directly would be difficult. This also avoids creating the wrapper
4356                          * methods at runtime, since they are not needed anyway.
4357                          */
4358                         switch (method->wrapper_type) {
4359                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4360                         case MONO_WRAPPER_SYNCHRONIZED:
4361                                 /* encode_method_ref () can handle these */
4362                                 break;
4363                         case MONO_WRAPPER_RUNTIME_INVOKE:
4364                                 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
4365                                         /* Direct wrapper, encode normally */
4366                                         break;
4367                                 /* Fall through */
4368                         default:
4369                                 name = mono_aot_wrapper_name (method);
4370                                 break;
4371                         }
4372                 }
4373
4374                 if (name) {
4375                         encode_value (1, p, &p);
4376                         encode_value (method->wrapper_type, p, &p);
4377                         strcpy ((char*)p, name);
4378                         p += strlen (name ) + 1;
4379                         g_free (name);
4380                 } else {
4381                         encode_value (0, p, &p);
4382                         encode_method_ref (acfg, method, p, &p);
4383                 }
4384
4385                 g_assert ((p - buf) < buf_size);
4386         }
4387
4388         g_assert ((p - buf) < buf_size);
4389
4390         /* Emit method info */
4391         sprintf (symbol, "extra_method_info");
4392         emit_section_change (acfg, ".text", 1);
4393         emit_global (acfg, symbol, FALSE);
4394         emit_alignment (acfg, 8);
4395         emit_label (acfg, symbol);
4396
4397         emit_bytes (acfg, buf, p - buf);
4398
4399         emit_line (acfg);
4400
4401         /*
4402          * Construct a chained hash table for mapping indexes in extra_method_info to
4403          * method indexes.
4404          */
4405         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4406         table = g_ptr_array_sized_new (table_size);
4407         for (i = 0; i < table_size; ++i)
4408                 g_ptr_array_add (table, NULL);
4409         chain_lengths = g_new0 (int, table_size);
4410         max_chain_length = 0;
4411         for (i = 0; i < acfg->extra_methods->len; ++i) {
4412                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4413                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4414                 guint32 key, value;
4415
4416                 if (!cfg)
4417                         continue;
4418
4419                 key = info_offsets [i];
4420                 value = get_method_index (acfg, method);
4421
4422                 hash = mono_aot_method_hash (method) % table_size;
4423
4424                 chain_lengths [hash] ++;
4425                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
4426
4427                 /* FIXME: Allocate from the mempool */
4428                 new_entry = g_new0 (HashEntry, 1);
4429                 new_entry->key = key;
4430                 new_entry->value = value;
4431
4432                 entry = g_ptr_array_index (table, hash);
4433                 if (entry == NULL) {
4434                         new_entry->index = hash;
4435                         g_ptr_array_index (table, hash) = new_entry;
4436                 } else {
4437                         while (entry->next)
4438                                 entry = entry->next;
4439                         
4440                         entry->next = new_entry;
4441                         new_entry->index = table->len;
4442                         g_ptr_array_add (table, new_entry);
4443                 }
4444         }
4445
4446         //printf ("MAX: %d\n", max_chain_length);
4447
4448         /* Emit the table */
4449         sprintf (symbol, "extra_method_table");
4450         emit_section_change (acfg, ".text", 0);
4451         emit_global (acfg, symbol, FALSE);
4452         emit_alignment (acfg, 8);
4453         emit_label (acfg, symbol);
4454
4455         g_assert (table_size < 65000);
4456         emit_int32 (acfg, table_size);
4457         g_assert (table->len < 65000);
4458         for (i = 0; i < table->len; ++i) {
4459                 HashEntry *entry = g_ptr_array_index (table, i);
4460
4461                 if (entry == NULL) {
4462                         emit_int32 (acfg, 0);
4463                         emit_int32 (acfg, 0);
4464                         emit_int32 (acfg, 0);
4465                 } else {
4466                         g_assert (entry->key > 0);
4467                         emit_int32 (acfg, entry->key);
4468                         emit_int32 (acfg, entry->value);
4469                         if (entry->next)
4470                                 emit_int32 (acfg, entry->next->index);
4471                         else
4472                                 emit_int32 (acfg, 0);
4473                 }
4474         }
4475
4476         /* 
4477          * Emit a table reverse mapping method indexes to their index in extra_method_info.
4478          * This is used by mono_aot_find_jit_info ().
4479          */
4480         sprintf (symbol, "extra_method_info_offsets");
4481         emit_section_change (acfg, ".text", 0);
4482         emit_global (acfg, symbol, FALSE);
4483         emit_alignment (acfg, 8);
4484         emit_label (acfg, symbol);
4485
4486         emit_int32 (acfg, acfg->extra_methods->len);
4487         for (i = 0; i < acfg->extra_methods->len; ++i) {
4488                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4489
4490                 emit_int32 (acfg, get_method_index (acfg, method));
4491                 emit_int32 (acfg, info_offsets [i]);
4492         }
4493 }       
4494
4495 static void
4496 emit_method_order (MonoAotCompile *acfg)
4497 {
4498         int i, index, len;
4499         char symbol [256];
4500         GList *l;
4501
4502         sprintf (symbol, "method_order");
4503         emit_section_change (acfg, ".text", 1);
4504         emit_global (acfg, symbol, FALSE);
4505         emit_alignment (acfg, 8);
4506         emit_label (acfg, symbol);
4507
4508         /* First emit an index table */
4509         index = 0;
4510         len = 0;
4511         for (l = acfg->method_order; l != NULL; l = l->next) {
4512                 i = GPOINTER_TO_UINT (l->data);
4513
4514                 if (acfg->cfgs [i]) {
4515                         if ((index % 1024) == 0) {
4516                                 emit_int32 (acfg, i);
4517                         }
4518
4519                         index ++;
4520                 }
4521
4522                 len ++;
4523         }
4524         emit_int32 (acfg, 0xffffff);
4525
4526         /* Then emit the whole method order */
4527         for (l = acfg->method_order; l != NULL; l = l->next) {
4528                 i = GPOINTER_TO_UINT (l->data);
4529
4530                 if (acfg->cfgs [i]) {
4531                         emit_int32 (acfg, i);
4532                 }
4533         }       
4534         emit_line (acfg);
4535
4536         sprintf (symbol, "method_order_end");
4537         emit_section_change (acfg, ".text", 1);
4538         emit_global (acfg, symbol, FALSE);
4539         emit_label (acfg, symbol);
4540 }
4541
4542 static void
4543 emit_exception_info (MonoAotCompile *acfg)
4544 {
4545         int i;
4546         char symbol [256];
4547
4548         sprintf (symbol, "ex_info");
4549         emit_section_change (acfg, ".text", 1);
4550         emit_global (acfg, symbol, FALSE);
4551         emit_alignment (acfg, 8);
4552         emit_label (acfg, symbol);
4553
4554         /* To reduce size of generated assembly */
4555         sprintf (symbol, "ex");
4556         emit_label (acfg, symbol);
4557
4558         for (i = 0; i < acfg->nmethods; ++i) {
4559                 if (acfg->cfgs [i])
4560                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
4561         }
4562
4563         sprintf (symbol, "ex_info_offsets");
4564         emit_section_change (acfg, ".text", 1);
4565         emit_global (acfg, symbol, FALSE);
4566         emit_alignment (acfg, 8);
4567         emit_label (acfg, symbol);
4568
4569         for (i = 0; i < acfg->nmethods; ++i) {
4570                 if (acfg->cfgs [i]) {
4571                         sprintf (symbol, "%se_%x_p", acfg->temp_prefix, i);
4572                         emit_symbol_diff (acfg, symbol, "ex", 0);
4573                 } else {
4574                         emit_int32 (acfg, 0);
4575                 }
4576         }
4577         emit_line (acfg);
4578 }
4579
4580 static void
4581 emit_unwind_info (MonoAotCompile *acfg)
4582 {
4583         int i;
4584         char symbol [128];
4585
4586         /* 
4587          * The unwind info contains a lot of duplicates so we emit each unique
4588          * entry once, and only store the offset from the start of the table in the
4589          * exception info.
4590          */
4591
4592         sprintf (symbol, "unwind_info");
4593         emit_section_change (acfg, ".text", 1);
4594         emit_alignment (acfg, 8);
4595         emit_label (acfg, symbol);
4596         emit_global (acfg, symbol, FALSE);
4597
4598         for (i = 0; i < acfg->unwind_ops->len; ++i) {
4599                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
4600                 guint8 *unwind_info;
4601                 guint32 unwind_info_len;
4602                 guint8 buf [16];
4603                 guint8 *p;
4604
4605                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
4606
4607                 p = buf;
4608                 encode_value (unwind_info_len, p, &p);
4609                 emit_bytes (acfg, buf, p - buf);
4610                 emit_bytes (acfg, unwind_info, unwind_info_len);
4611
4612                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
4613         }
4614 }
4615
4616 static void
4617 emit_class_info (MonoAotCompile *acfg)
4618 {
4619         int i;
4620         char symbol [256];
4621
4622         sprintf (symbol, "class_info");
4623         emit_section_change (acfg, ".text", 1);
4624         emit_global (acfg, symbol, FALSE);
4625         emit_alignment (acfg, 8);
4626         emit_label (acfg, symbol);
4627
4628         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4629                 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4630
4631         sprintf (symbol, "class_info_offsets");
4632         emit_section_change (acfg, ".text", 1);
4633         emit_global (acfg, symbol, FALSE);
4634         emit_alignment (acfg, 8);
4635         emit_label (acfg, symbol);
4636
4637         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4638                 sprintf (symbol, "%sK_I_%x", acfg->temp_prefix, i);
4639                 emit_symbol_diff (acfg, symbol, "class_info", 0);
4640         }
4641         emit_line (acfg);
4642 }
4643
4644 typedef struct ClassNameTableEntry {
4645         guint32 token, index;
4646         struct ClassNameTableEntry *next;
4647 } ClassNameTableEntry;
4648
4649 static void
4650 emit_class_name_table (MonoAotCompile *acfg)
4651 {
4652         int i, table_size;
4653         guint32 token, hash;
4654         MonoClass *klass;
4655         GPtrArray *table;
4656         char *full_name;
4657         char symbol [256];
4658         ClassNameTableEntry *entry, *new_entry;
4659
4660         /*
4661          * Construct a chained hash table for mapping class names to typedef tokens.
4662          */
4663         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4664         table = g_ptr_array_sized_new (table_size);
4665         for (i = 0; i < table_size; ++i)
4666                 g_ptr_array_add (table, NULL);
4667         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4668                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4669                 klass = mono_class_get (acfg->image, token);
4670                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4671                 hash = mono_aot_str_hash (full_name) % table_size;
4672                 g_free (full_name);
4673
4674                 /* FIXME: Allocate from the mempool */
4675                 new_entry = g_new0 (ClassNameTableEntry, 1);
4676                 new_entry->token = token;
4677
4678                 entry = g_ptr_array_index (table, hash);
4679                 if (entry == NULL) {
4680                         new_entry->index = hash;
4681                         g_ptr_array_index (table, hash) = new_entry;
4682                 } else {
4683                         while (entry->next)
4684                                 entry = entry->next;
4685                         
4686                         entry->next = new_entry;
4687                         new_entry->index = table->len;
4688                         g_ptr_array_add (table, new_entry);
4689                 }
4690         }
4691
4692         /* Emit the table */
4693         sprintf (symbol, "class_name_table");
4694         emit_section_change (acfg, ".text", 0);
4695         emit_global (acfg, symbol, FALSE);
4696         emit_alignment (acfg, 8);
4697         emit_label (acfg, symbol);
4698
4699         /* FIXME: Optimize memory usage */
4700         g_assert (table_size < 65000);
4701         emit_int16 (acfg, table_size);
4702         g_assert (table->len < 65000);
4703         for (i = 0; i < table->len; ++i) {
4704                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4705
4706                 if (entry == NULL) {
4707                         emit_int16 (acfg, 0);
4708                         emit_int16 (acfg, 0);
4709                 } else {
4710                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
4711                         if (entry->next)
4712                                 emit_int16 (acfg, entry->next->index);
4713                         else
4714                                 emit_int16 (acfg, 0);
4715                 }
4716         }
4717 }
4718
4719 static void
4720 emit_image_table (MonoAotCompile *acfg)
4721 {
4722         int i;
4723         char symbol [256];
4724
4725         /*
4726          * The image table is small but referenced in a lot of places.
4727          * So we emit it at once, and reference its elements by an index.
4728          */
4729
4730         sprintf (symbol, "mono_image_table");
4731         emit_section_change (acfg, ".text", 1);
4732         emit_global (acfg, symbol, FALSE);
4733         emit_alignment (acfg, 8);
4734         emit_label (acfg, symbol);
4735
4736         emit_int32 (acfg, acfg->image_table->len);
4737         for (i = 0; i < acfg->image_table->len; i++) {
4738                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4739                 MonoAssemblyName *aname = &image->assembly->aname;
4740
4741                 /* FIXME: Support multi-module assemblies */
4742                 g_assert (image->assembly->image == image);
4743
4744                 emit_string (acfg, image->assembly_name);
4745                 emit_string (acfg, image->guid);
4746                 emit_string (acfg, aname->culture ? aname->culture : "");
4747                 emit_string (acfg, (const char*)aname->public_key_token);
4748
4749                 emit_alignment (acfg, 8);
4750                 emit_int32 (acfg, aname->flags);
4751                 emit_int32 (acfg, aname->major);
4752                 emit_int32 (acfg, aname->minor);
4753                 emit_int32 (acfg, aname->build);
4754                 emit_int32 (acfg, aname->revision);
4755         }
4756 }
4757
4758 static void
4759 emit_got_info (MonoAotCompile *acfg)
4760 {
4761         char symbol [256];
4762         int i, first_plt_got_patch, buf_size;
4763         guint8 *p, *buf;
4764         guint32 *got_info_offsets;
4765
4766         /* Add the patches needed by the PLT to the GOT */
4767         acfg->plt_got_offset_base = acfg->got_offset;
4768         first_plt_got_patch = acfg->got_patches->len;
4769         for (i = 1; i < acfg->plt_offset; ++i) {
4770                 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4771
4772                 g_ptr_array_add (acfg->got_patches, patch_info);
4773         }
4774
4775         acfg->got_offset += acfg->plt_offset;
4776
4777         /**
4778          * FIXME: 
4779          * - optimize offsets table.
4780          * - reduce number of exported symbols.
4781          * - emit info for a klass only once.
4782          * - determine when a method uses a GOT slot which is guaranteed to be already 
4783          *   initialized.
4784          * - clean up and document the code.
4785          * - use String.Empty in class libs.
4786          */
4787
4788         /* Encode info required to decode shared GOT entries */
4789         buf_size = acfg->got_patches->len * 64;
4790         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4791         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
4792         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4793         /* Unused */
4794         if (acfg->plt_offset)
4795                 acfg->plt_got_info_offsets [0] = 0;
4796         for (i = 0; i < acfg->got_patches->len; ++i) {
4797                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
4798
4799                 got_info_offsets [i] = p - buf;
4800                 if (i >= first_plt_got_patch)
4801                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4802                 encode_value (ji->type, p, &p);
4803                 encode_patch (acfg, ji, p, &p);
4804         }
4805
4806         g_assert (p - buf <= buf_size);
4807
4808         acfg->stats.got_info_size = p - buf;
4809
4810         /* Emit got_info table */
4811         sprintf (symbol, "got_info");
4812         emit_section_change (acfg, ".text", 1);
4813         emit_global (acfg, symbol, FALSE);
4814         emit_alignment (acfg, 8);
4815         emit_label (acfg, symbol);
4816
4817         emit_bytes (acfg, buf, p - buf);
4818
4819         /* Emit got_info_offsets table */
4820         sprintf (symbol, "got_info_offsets");
4821         emit_section_change (acfg, ".text", 1);
4822         emit_global (acfg, symbol, FALSE);
4823         emit_alignment (acfg, 8);
4824         emit_label (acfg, symbol);
4825
4826         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
4827         for (i = 0; i < first_plt_got_patch; ++i)
4828                 emit_int32 (acfg, got_info_offsets [i]);
4829
4830         acfg->stats.got_info_offsets_size = acfg->got_patches->len * 4;
4831 }
4832
4833 static void
4834 emit_got (MonoAotCompile *acfg)
4835 {
4836         char symbol [256];
4837
4838         /* Don't make GOT global so accesses to it don't need relocations */
4839         sprintf (symbol, "%s", acfg->got_symbol);
4840         emit_section_change (acfg, ".bss", 0);
4841         emit_alignment (acfg, 8);
4842         emit_local_symbol (acfg, symbol, "got_end", FALSE);
4843         emit_label (acfg, symbol);
4844         if (acfg->got_offset > 0)
4845                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4846
4847         sprintf (symbol, "got_end");
4848         emit_label (acfg, symbol);
4849
4850         sprintf (symbol, "mono_aot_got_addr");
4851         emit_section_change (acfg, ".data", 0);
4852         emit_global (acfg, symbol, FALSE);
4853         emit_alignment (acfg, 8);
4854         emit_label (acfg, symbol);
4855         emit_pointer (acfg, acfg->got_symbol);
4856 }
4857
4858 static void
4859 emit_globals (MonoAotCompile *acfg)
4860 {
4861         char *opts_str;
4862         char *build_info;
4863
4864         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4865
4866         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4867
4868         opts_str = g_strdup_printf ("%d", acfg->opts);
4869         emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4870         g_free (opts_str);
4871
4872         emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4873
4874         if (acfg->aot_opts.bind_to_runtime_version) {
4875                 build_info = mono_get_runtime_build_info ();
4876                 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4877                 g_free (build_info);
4878         } else {
4879                 emit_string_symbol (acfg, "mono_runtime_version", "");
4880         }
4881
4882         /* 
4883          * When static linking, we emit a global which will point to the symbol table.
4884          */
4885         if (acfg->aot_opts.static_link) {
4886                 int i;
4887                 char symbol [256];
4888                 char *p;
4889
4890                 /* Emit a string holding the assembly name */
4891                 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4892
4893                 /* Emit the names */
4894                 for (i = 0; i < acfg->globals->len; ++i) {
4895                         char *name = g_ptr_array_index (acfg->globals, i);
4896
4897                         sprintf (symbol, "name_%d", i);
4898                         emit_section_change (acfg, ".text", 1);
4899                         emit_label (acfg, symbol);
4900                         emit_string (acfg, name);
4901                 }
4902
4903                 /* Emit the globals table */
4904                 sprintf (symbol, "globals");
4905                 emit_section_change (acfg, ".data", 0);
4906                 /* This is not a global, since it is accessed by the init function */
4907                 emit_alignment (acfg, 8);
4908                 emit_label (acfg, symbol);
4909
4910                 for (i = 0; i < acfg->globals->len; ++i) {
4911                         char *name = g_ptr_array_index (acfg->globals, i);
4912
4913                         sprintf (symbol, "name_%d", i);
4914                         emit_pointer (acfg, symbol);
4915
4916                         sprintf (symbol, "%s", name);
4917                         emit_pointer (acfg, symbol);
4918                 }
4919                 /* Null terminate the table */
4920                 emit_int32 (acfg, 0);
4921                 emit_int32 (acfg, 0);
4922
4923                 /* 
4924                  * Emit a global symbol which can be passed by an embedding app to
4925                  * mono_aot_register_module ().
4926                  */
4927 #if defined(__MACH__)
4928                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4929 #else
4930                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4931 #endif
4932
4933                 /* Get rid of characters which cannot occur in symbols */
4934                 p = symbol;
4935                 for (p = symbol; *p; ++p) {
4936                         if (!(isalnum (*p) || *p == '_'))
4937                                 *p = '_';
4938                 }
4939                 acfg->static_linking_symbol = g_strdup (symbol);
4940                 emit_global_inner (acfg, symbol, FALSE);
4941                 emit_alignment (acfg, 8);
4942                 emit_label (acfg, symbol);
4943                 emit_pointer (acfg, "globals");
4944         }
4945 }
4946
4947 static void
4948 emit_mem_end (MonoAotCompile *acfg)
4949 {
4950         char symbol [128];
4951
4952         sprintf (symbol, "mem_end");
4953         emit_section_change (acfg, ".text", 1);
4954         emit_global (acfg, symbol, FALSE);
4955         emit_alignment (acfg, 8);
4956         emit_label (acfg, symbol);
4957 }
4958
4959 /*
4960  * Emit a structure containing all the information not stored elsewhere.
4961  */
4962 static void
4963 emit_file_info (MonoAotCompile *acfg)
4964 {
4965         char symbol [128];
4966         int i;
4967
4968         sprintf (symbol, "mono_aot_file_info");
4969         emit_section_change (acfg, ".data", 0);
4970         emit_alignment (acfg, 8);
4971         emit_label (acfg, symbol);
4972         emit_global (acfg, symbol, FALSE);
4973
4974         /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
4975         emit_int32 (acfg, acfg->plt_got_offset_base);
4976         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4977         emit_int32 (acfg, acfg->plt_offset);
4978         emit_int32 (acfg, acfg->nmethods);
4979
4980         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4981                 emit_int32 (acfg, acfg->num_trampolines [i]);
4982         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4983                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
4984         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4985                 emit_int32 (acfg, acfg->trampoline_size [i]);
4986 }
4987
4988 static void
4989 emit_dwarf_info (MonoAotCompile *acfg)
4990 {
4991 #ifdef EMIT_DWARF_INFO
4992         int i;
4993         char symbol [128], symbol2 [128];
4994
4995         /* DIEs for methods */
4996         for (i = 0; i < acfg->nmethods; ++i) {
4997                 MonoCompile *cfg = acfg->cfgs [i];
4998
4999                 if (!cfg)
5000                         continue;
5001
5002                 sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
5003                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5004
5005                 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 ()));
5006         }
5007 #endif
5008 }
5009
5010 static void
5011 collect_methods (MonoAotCompile *acfg)
5012 {
5013         int i;
5014         MonoImage *image = acfg->image;
5015
5016         /* Collect methods */
5017         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5018                 MonoMethod *method;
5019                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5020
5021                 method = mono_get_method (acfg->image, token, NULL);
5022
5023                 if (!method) {
5024                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5025                         exit (1);
5026                 }
5027                         
5028                 /* Load all methods eagerly to skip the slower lazy loading code */
5029                 mono_class_setup_methods (method->klass);
5030
5031                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5032                         /* Compile the wrapper instead */
5033                         /* We do this here instead of add_wrappers () because it is easy to do it here */
5034                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5035                         method = wrapper;
5036                 }
5037
5038                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5039                 add_method_with_index (acfg, method, i, FALSE);
5040                 acfg->method_index ++;
5041         }
5042
5043         add_generic_instances (acfg);
5044
5045         if (acfg->aot_opts.full_aot)
5046                 add_wrappers (acfg);
5047 }
5048
5049 static void
5050 compile_methods (MonoAotCompile *acfg)
5051 {
5052         int i, methods_len;
5053
5054         if (acfg->aot_opts.nthreads > 0) {
5055                 GPtrArray *frag;
5056                 int len, j;
5057                 GPtrArray *threads;
5058                 HANDLE handle;
5059                 gpointer *user_data;
5060                 MonoMethod **methods;
5061
5062                 methods_len = acfg->methods->len;
5063
5064                 len = acfg->methods->len / acfg->aot_opts.nthreads;
5065                 g_assert (len > 0);
5066                 /* 
5067                  * Partition the list of methods into fragments, and hand it to threads to
5068                  * process.
5069                  */
5070                 threads = g_ptr_array_new ();
5071                 /* Make a copy since acfg->methods is modified by compile_method () */
5072                 methods = g_new0 (MonoMethod*, methods_len);
5073                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5074                 for (i = 0; i < methods_len; ++i)
5075                         methods [i] = g_ptr_array_index (acfg->methods, i);
5076                 i = 0;
5077                 while (i < methods_len) {
5078                         frag = g_ptr_array_new ();
5079                         for (j = 0; j < len; ++j) {
5080                                 if (i < methods_len) {
5081                                         g_ptr_array_add (frag, methods [i]);
5082                                         i ++;
5083                                 }
5084                         }
5085
5086                         user_data = g_new0 (gpointer, 3);
5087                         user_data [0] = mono_domain_get ();
5088                         user_data [1] = acfg;
5089                         user_data [2] = frag;
5090                         
5091                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5092                         g_ptr_array_add (threads, handle);
5093                 }
5094                 g_free (methods);
5095
5096                 for (i = 0; i < threads->len; ++i) {
5097                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5098                 }
5099         } else {
5100                 methods_len = 0;
5101         }
5102
5103         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5104         for (i = methods_len; i < acfg->methods->len; ++i) {
5105                 /* This can new methods to acfg->methods */
5106                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5107         }
5108 }
5109
5110 static int
5111 compile_asm (MonoAotCompile *acfg)
5112 {
5113         char *command, *objfile;
5114         char *outfile_name, *tmp_outfile_name;
5115         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5116
5117 #if defined(TARGET_AMD64)
5118 #define AS_OPTIONS "--64"
5119 #elif defined(TARGET_POWERPC64)
5120 #define AS_OPTIONS "-a64 -mppc64"
5121 #define LD_OPTIONS "-m elf64ppc"
5122 #elif defined(sparc) && SIZEOF_VOID_P == 8
5123 #define AS_OPTIONS "-xarch=v9"
5124 #else
5125 #define AS_OPTIONS ""
5126 #endif
5127
5128 #ifndef LD_OPTIONS
5129 #define LD_OPTIONS ""
5130 #endif
5131
5132         if (acfg->aot_opts.asm_only) {
5133                 printf ("Output file: '%s'.\n", acfg->tmpfname);
5134                 if (acfg->aot_opts.static_link)
5135                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5136                 return 0;
5137         }
5138
5139         if (acfg->aot_opts.static_link) {
5140                 if (acfg->aot_opts.outfile)
5141                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5142                 else
5143                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
5144         } else {
5145                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5146         }
5147         command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5148         printf ("Executing the native assembler: %s\n", command);
5149         if (system (command) != 0) {
5150                 g_free (command);
5151                 g_free (objfile);
5152                 return 1;
5153         }
5154
5155         g_free (command);
5156
5157         if (acfg->aot_opts.static_link) {
5158                 printf ("Output file: '%s'.\n", objfile);
5159                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5160                 g_free (objfile);
5161                 return 0;
5162         }
5163
5164         if (acfg->aot_opts.outfile)
5165                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5166         else
5167                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5168
5169         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5170
5171 #if defined(sparc)
5172         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5173 #elif defined(__ppc__) && defined(__MACH__)
5174         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5175 #elif defined(PLATFORM_WIN32)
5176         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5177 #else
5178         command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5179 #endif
5180         printf ("Executing the native linker: %s\n", command);
5181         if (system (command) != 0) {
5182                 g_free (tmp_outfile_name);
5183                 g_free (outfile_name);
5184                 g_free (command);
5185                 g_free (objfile);
5186                 return 1;
5187         }
5188
5189         g_free (command);
5190         unlink (objfile);
5191         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5192         printf ("Stripping the binary: %s\n", com);
5193         system (com);
5194         g_free (com);*/
5195
5196 #if defined(TARGET_ARM) && !defined(__MACH__)
5197         /* 
5198          * gas generates 'mapping symbols' each time code and data is mixed, which 
5199          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5200          */
5201         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5202         printf ("Stripping the binary: %s\n", command);
5203         if (system (command) != 0) {
5204                 g_free (tmp_outfile_name);
5205                 g_free (outfile_name);
5206                 g_free (command);
5207                 g_free (objfile);
5208                 return 1;
5209         }
5210 #endif
5211
5212         rename (tmp_outfile_name, outfile_name);
5213
5214         g_free (tmp_outfile_name);
5215         g_free (outfile_name);
5216         g_free (objfile);
5217
5218         if (acfg->aot_opts.save_temps)
5219                 printf ("Retained input file.\n");
5220         else
5221                 unlink (acfg->tmpfname);
5222
5223         return 0;
5224 }
5225
5226 static MonoAotCompile*
5227 acfg_create (MonoAssembly *ass, guint32 opts)
5228 {
5229         MonoImage *image = ass->image;
5230         MonoAotCompile *acfg;
5231
5232         acfg = g_new0 (MonoAotCompile, 1);
5233         acfg->methods = g_ptr_array_new ();
5234         acfg->method_indexes = g_hash_table_new (NULL, NULL);
5235         acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5236         acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5237         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5238         acfg->got_patches = g_ptr_array_new ();
5239         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5240         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5241         acfg->image_hash = g_hash_table_new (NULL, NULL);
5242         acfg->image_table = g_ptr_array_new ();
5243         acfg->globals = g_ptr_array_new ();
5244         acfg->image = image;
5245         acfg->opts = opts;
5246         acfg->mempool = mono_mempool_new ();
5247         acfg->extra_methods = g_ptr_array_new ();
5248         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5249         acfg->unwind_ops = g_ptr_array_new ();
5250         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5251         InitializeCriticalSection (&acfg->mutex);
5252
5253         return acfg;
5254 }
5255
5256 static void
5257 acfg_free (MonoAotCompile *acfg)
5258 {
5259         int i;
5260
5261         img_writer_destroy (acfg->w);
5262         for (i = 0; i < acfg->nmethods; ++i)
5263                 if (acfg->cfgs [i])
5264                         g_free (acfg->cfgs [i]);
5265         g_free (acfg->cfgs);
5266         g_free (acfg->static_linking_symbol);
5267         g_free (acfg->got_symbol);
5268         g_free (acfg->plt_symbol);
5269         g_ptr_array_free (acfg->methods, TRUE);
5270         g_ptr_array_free (acfg->got_patches, TRUE);
5271         g_ptr_array_free (acfg->image_table, TRUE);
5272         g_ptr_array_free (acfg->globals, TRUE);
5273         g_ptr_array_free (acfg->unwind_ops, TRUE);
5274         g_hash_table_destroy (acfg->method_indexes);
5275         g_hash_table_destroy (acfg->plt_offset_to_patch);
5276         g_hash_table_destroy (acfg->patch_to_plt_offset);
5277         g_hash_table_destroy (acfg->patch_to_got_offset);
5278         g_hash_table_destroy (acfg->method_to_cfg);
5279         g_hash_table_destroy (acfg->token_info_hash);
5280         g_hash_table_destroy (acfg->image_hash);
5281         g_hash_table_destroy (acfg->unwind_info_offsets);
5282         g_hash_table_destroy (acfg->method_label_hash);
5283         mono_mempool_destroy (acfg->mempool);
5284         g_free (acfg);
5285 }
5286
5287 int
5288 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5289 {
5290         MonoImage *image = ass->image;
5291         int res;
5292         MonoAotCompile *acfg;
5293         char *outfile_name, *tmp_outfile_name, *p;
5294         TV_DECLARE (atv);
5295         TV_DECLARE (btv);
5296
5297         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5298
5299         acfg = acfg_create (ass, opts);
5300
5301         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5302         acfg->aot_opts.write_symbols = TRUE;
5303         acfg->aot_opts.ntrampolines = 1024;
5304
5305         mono_aot_parse_options (aot_options, &acfg->aot_opts);
5306
5307         //acfg->aot_opts.print_skipped_methods = TRUE;
5308
5309 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5310         if (acfg->aot_opts.full_aot) {
5311                 printf ("--aot=full is not supported on this platform.\n");
5312                 return 1;
5313         }
5314 #endif
5315
5316         if (acfg->aot_opts.static_link)
5317                 acfg->aot_opts.asm_writer = TRUE;
5318
5319         load_profile_files (acfg);
5320
5321         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
5322 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
5323         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
5324 #endif
5325         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
5326
5327         acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
5328         acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
5329
5330         /* Get rid of characters which cannot occur in symbols */
5331         for (p = acfg->got_symbol; *p; ++p) {
5332                 if (!(isalnum (*p) || *p == '_'))
5333                         *p = '_';
5334         }
5335         for (p = acfg->plt_symbol; *p; ++p) {
5336                 if (!(isalnum (*p) || *p == '_'))
5337                         *p = '_';
5338         }
5339
5340         acfg->method_index = 1;
5341
5342         collect_methods (acfg);
5343
5344         acfg->cfgs_size = acfg->methods->len + 32;
5345         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5346
5347         /* PLT offset 0 is reserved for the PLT trampoline */
5348         acfg->plt_offset = 1;
5349
5350         /* GOT offset 0 is reserved for the address of the current assembly */
5351         {
5352                 MonoJumpInfo *ji;
5353
5354                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5355                 ji->type = MONO_PATCH_INFO_IMAGE;
5356                 ji->data.image = acfg->image;
5357
5358                 get_got_offset (acfg, ji);
5359
5360                 /* Slot 1 is reserved for the mscorlib got addr */
5361                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5362                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
5363                 get_got_offset (acfg, ji);
5364         }
5365
5366         TV_GETTIME (atv);
5367
5368         compile_methods (acfg);
5369
5370         TV_GETTIME (btv);
5371
5372         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
5373
5374         TV_GETTIME (atv);
5375
5376         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
5377                 if (acfg->aot_opts.outfile)
5378                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5379                 else
5380                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5381
5382                 /* 
5383                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
5384                  * it might be in another file system so the rename () won't work.
5385                  */
5386                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5387
5388                 acfg->fp = fopen (tmp_outfile_name, "w");
5389                 if (!acfg->fp) {
5390                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
5391                         return 1;
5392                 }
5393
5394                 acfg->w = img_writer_create (acfg->fp, TRUE);
5395                 acfg->use_bin_writer = TRUE;
5396         } else {
5397                 if (acfg->aot_opts.asm_only) {
5398                         if (acfg->aot_opts.outfile)
5399                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5400                         else
5401                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
5402                         acfg->fp = fopen (acfg->tmpfname, "w+");
5403                 } else {
5404                         int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
5405                         acfg->fp = fdopen (i, "w+");
5406                 }
5407                 g_assert (acfg->fp);
5408
5409                 acfg->w = img_writer_create (acfg->fp, FALSE);
5410                 
5411                 tmp_outfile_name = NULL;
5412                 outfile_name = NULL;
5413         }
5414
5415         acfg->temp_prefix = img_writer_get_temp_label_prefix (acfg->w);
5416
5417         if (!acfg->aot_opts.nodebug)
5418                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, FALSE);
5419
5420         img_writer_emit_start (acfg->w);
5421
5422         if (acfg->dwarf)
5423                 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
5424
5425         emit_code (acfg);
5426
5427         emit_info (acfg);
5428
5429         emit_extra_methods (acfg);
5430
5431         emit_method_order (acfg);
5432
5433         emit_trampolines (acfg);
5434
5435         emit_class_name_table (acfg);
5436
5437         emit_got_info (acfg);
5438
5439         emit_exception_info (acfg);
5440
5441         emit_unwind_info (acfg);
5442
5443         emit_class_info (acfg);
5444
5445         emit_plt (acfg);
5446
5447         emit_image_table (acfg);
5448
5449         emit_got (acfg);
5450
5451         emit_file_info (acfg);
5452
5453         emit_globals (acfg);
5454
5455         if (acfg->dwarf) {
5456                 emit_dwarf_info (acfg);
5457                 mono_dwarf_writer_close (acfg->dwarf);
5458         }
5459
5460         emit_mem_end (acfg);
5461
5462         TV_GETTIME (btv);
5463
5464         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
5465
5466         printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT Info Offsets: %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, acfg->stats.got_info_offsets_size, (int)(acfg->got_offset * sizeof (gpointer)), (int)(acfg->nmethods * 3 * sizeof (gpointer)));
5467
5468         TV_GETTIME (atv);
5469         res = img_writer_emit_writeout (acfg->w);
5470         if (res != 0) {
5471                 acfg_free (acfg);
5472                 return res;
5473         }
5474         if (acfg->use_bin_writer) {
5475                 int err = rename (tmp_outfile_name, outfile_name);
5476
5477                 if (err) {
5478                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
5479                         return 1;
5480                 }
5481         } else {
5482                 res = compile_asm (acfg);
5483                 if (res != 0) {
5484                         acfg_free (acfg);
5485                         return res;
5486                 }
5487         }
5488         TV_GETTIME (btv);
5489         acfg->stats.link_time = TV_ELAPSED (atv, btv);
5490
5491         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);
5492         if (acfg->stats.genericcount)
5493                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
5494         if (acfg->stats.abscount)
5495                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
5496         if (acfg->stats.lmfcount)
5497                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
5498         if (acfg->stats.ocount)
5499                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
5500         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);
5501         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
5502
5503         /*
5504         printf ("GOT slot distribution:\n");
5505         for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
5506                 if (acfg->stats.got_slot_types [i])
5507                         printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
5508         */
5509
5510         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);
5511
5512         acfg_free (acfg);
5513         
5514         return 0;
5515 }
5516  
5517 /*
5518  * Support for emitting debug info for JITted code.
5519  *
5520  *   This works as follows:
5521  * - the runtime writes out an xdb.s file containing DWARF debug info.
5522  * - the user calls a gdb macro
5523  * - the macro compiles and loads this shared library using add-symbol-file.
5524  *
5525  * This is based on the xdebug functionality in the Kaffe Java VM.
5526  * 
5527  * We emit assembly code instead of using the ELF writer, so we can emit debug info
5528  * incrementally as each method is JITted, and the debugger doesn't have to call
5529  * into the runtime to emit the shared library, which would cause all kinds of
5530  * complications, like threading issues, and the fact that the ELF writer's
5531  * emit_writeout () function cannot be called more than once.
5532  */
5533
5534 /* The recommended gdb macro is: */
5535 /*
5536   define xdb
5537   shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
5538   add-symbol-file xdb.so 0
5539   end
5540 */
5541
5542 static MonoDwarfWriter *xdebug_writer;
5543 static FILE *xdebug_fp;
5544
5545 void
5546 mono_xdebug_init (void)
5547 {
5548         FILE *il_file;
5549         MonoImageWriter *w;
5550
5551         unlink ("xdb.s");
5552         xdebug_fp = fopen ("xdb.s", "w");
5553
5554         w = img_writer_create (xdebug_fp, FALSE);
5555
5556         img_writer_emit_start (w);
5557
5558         /* This file will contain the IL code for methods which don't have debug info */
5559         il_file = fopen ("xdb.il", "w");
5560
5561         xdebug_writer = mono_dwarf_writer_create (w, il_file, TRUE);
5562
5563         /* Emit something so the file has a text segment */
5564         img_writer_emit_section_change (w, ".text", 0);
5565         img_writer_emit_string (w, "");
5566
5567         mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
5568 }
5569
5570 /*
5571  * mono_save_xdebug_info:
5572  *
5573  *   Emit debugging info for METHOD into an assembly file which can be assembled
5574  * and loaded into gdb to provide debugging info for JITted code.
5575  * LOCKING: Acquires the loader lock.
5576  */
5577 void
5578 mono_save_xdebug_info (MonoCompile *cfg)
5579 {
5580         if (!xdebug_writer)
5581                 return;
5582
5583         mono_loader_lock ();
5584         mono_dwarf_writer_emit_method (xdebug_writer, cfg, cfg->jit_info->method, NULL, NULL, 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 ()));
5585         fflush (xdebug_fp);
5586         mono_loader_unlock ();
5587 }
5588
5589 /*
5590  * mono_save_trampoline_xdebug_info:
5591  *
5592  *   Same as mono_save_xdebug_info, but for trampolines.
5593  * LOCKING: Acquires the loader lock.
5594  */
5595 void
5596 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
5597 {
5598         if (!xdebug_writer)
5599                 return;
5600
5601         mono_loader_lock ();
5602         mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
5603         fflush (xdebug_fp);
5604         mono_loader_unlock ();
5605 }
5606
5607 #else
5608
5609 /* AOT disabled */
5610
5611 int
5612 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5613 {
5614         return 0;
5615 }
5616
5617 void
5618 mono_xdebug_init (void)
5619 {
5620 }
5621
5622 void
5623 mono_save_xdebug_info (MonoCompile *cfg)
5624 {
5625 }
5626
5627 void
5628 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
5629 {
5630 }
5631
5632 #endif