2009-08-25 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_R1, ARMREG_PC, 8);
883         ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_R1);
884         /* Load branch addr + branch */
885         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
886         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_R1);
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 (mono_marshal_method_from_wrapper (method) != method) {
1359                                 /* Direct wrapper, encode it normally */
1360                         } else {
1361                                 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1362                         }
1363                         g_free (tmpsig);
1364                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1365                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1366                         name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1367                         g_free (tmpsig);
1368                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1369                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1370                         name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1371                         g_free (tmpsig);
1372                 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1373                         char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1374                         name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1375                         g_free (tmpsig);
1376                 }
1377         }
1378
1379         if (name) {
1380                 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1381                 strcpy ((char*)p, name);
1382                 p += strlen (name) + 1;
1383                 g_free (name);
1384         } else if (method->wrapper_type) {
1385                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1386
1387                 encode_value (method->wrapper_type, p, &p);
1388
1389                 switch (method->wrapper_type) {
1390                 case MONO_WRAPPER_REMOTING_INVOKE:
1391                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1392                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1393                         MonoMethod *m;
1394
1395                         m = mono_marshal_method_from_wrapper (method);
1396                         g_assert (m);
1397                         encode_method_ref (acfg, m, p, &p);
1398                         break;
1399                 }
1400                 case MONO_WRAPPER_PROXY_ISINST:
1401                 case MONO_WRAPPER_LDFLD:
1402                 case MONO_WRAPPER_LDFLDA:
1403                 case MONO_WRAPPER_STFLD:
1404                 case MONO_WRAPPER_ISINST: {
1405                         MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1406                         encode_klass_ref (acfg, proxy_class, p, &p);
1407                         break;
1408                 }
1409                 case MONO_WRAPPER_LDFLD_REMOTE:
1410                 case MONO_WRAPPER_STFLD_REMOTE:
1411                         break;
1412                 case MONO_WRAPPER_ALLOC: {
1413                         int alloc_type = mono_gc_get_managed_allocator_type (method);
1414                         g_assert (alloc_type != -1);
1415                         encode_value (alloc_type, p, &p);
1416                         break;
1417                 }
1418                 case MONO_WRAPPER_STELEMREF:
1419                         break;
1420                 case MONO_WRAPPER_UNKNOWN:
1421                         if (strcmp (method->name, "FastMonitorEnter") == 0)
1422                                 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1423                         else if (strcmp (method->name, "FastMonitorExit") == 0)
1424                                 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1425                         else
1426                                 g_assert_not_reached ();
1427                         break;
1428                 case MONO_WRAPPER_SYNCHRONIZED:
1429                 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1430                 case MONO_WRAPPER_RUNTIME_INVOKE: {
1431                         MonoMethod *m;
1432
1433                         m = mono_marshal_method_from_wrapper (method);
1434                         g_assert (m);
1435                         g_assert (m != method);
1436                         encode_method_ref (acfg, m, p, &p);
1437                         break;
1438                 }
1439                 default:
1440                         g_assert_not_reached ();
1441                 }
1442         } else if (mono_method_signature (method)->is_inflated) {
1443                 /* 
1444                  * This is a generic method, find the original token which referenced it and
1445                  * encode that.
1446                  * Obtain the token from information recorded by the JIT.
1447                  */
1448                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1449                 if (ji) {
1450                         image_index = get_image_index (acfg, ji->image);
1451                         g_assert (image_index < MAX_IMAGE_INDEX);
1452                         token = ji->token;
1453
1454                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1455                         encode_value (image_index, p, &p);
1456                         encode_value (token, p, &p);
1457                 } else {
1458                         MonoMethod *declaring;
1459                         MonoGenericContext *context = mono_method_get_context (method);
1460
1461                         g_assert (method->is_inflated);
1462                         declaring = ((MonoMethodInflated*)method)->declaring;
1463
1464                         /*
1465                          * This might be a non-generic method of a generic instance, which 
1466                          * doesn't have a token since the reference is generated by the JIT 
1467                          * like Nullable:Box/Unbox, or by generic sharing.
1468                          */
1469
1470                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1471                         /* Encode the klass */
1472                         encode_klass_ref (acfg, method->klass, p, &p);
1473                         /* Encode the method */
1474                         image_index = get_image_index (acfg, method->klass->image);
1475                         g_assert (image_index < MAX_IMAGE_INDEX);
1476                         g_assert (declaring->token);
1477                         token = declaring->token;
1478                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1479                         encode_value (image_index, p, &p);
1480                         encode_value (token, p, &p);
1481                         encode_generic_context (acfg, context, p, &p);
1482                 }
1483         } else if (token == 0) {
1484                 /* This might be a method of a constructed type like int[,].Set */
1485                 /* Obtain the token from information recorded by the JIT */
1486                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1487                 if (ji) {
1488                         image_index = get_image_index (acfg, ji->image);
1489                         g_assert (image_index < MAX_IMAGE_INDEX);
1490                         token = ji->token;
1491
1492                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1493                         encode_value (image_index, p, &p);
1494                         encode_value (token, p, &p);
1495                 } else {
1496                         /* Array methods */
1497                         g_assert (method->klass->rank);
1498
1499                         /* Encode directly */
1500                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1501                         encode_klass_ref (acfg, method->klass, p, &p);
1502                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1503                                 encode_value (0, p, &p);
1504                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1505                                 encode_value (1, p, &p);
1506                         else if (!strcmp (method->name, "Get"))
1507                                 encode_value (2, p, &p);
1508                         else if (!strcmp (method->name, "Address"))
1509                                 encode_value (3, p, &p);
1510                         else if (!strcmp (method->name, "Set"))
1511                                 encode_value (4, p, &p);
1512                         else
1513                                 g_assert_not_reached ();
1514                 }
1515         } else {
1516                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1517                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1518         }
1519         *endbuf = p;
1520 }
1521
1522 static gint
1523 compare_patches (gconstpointer a, gconstpointer b)
1524 {
1525         int i, j;
1526
1527         i = (*(MonoJumpInfo**)a)->ip.i;
1528         j = (*(MonoJumpInfo**)b)->ip.i;
1529
1530         if (i < j)
1531                 return -1;
1532         else
1533                 if (i > j)
1534                         return 1;
1535         else
1536                 return 0;
1537 }
1538
1539 /*
1540  * is_plt_patch:
1541  *
1542  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
1543  * PLT entry.
1544  */
1545 static inline gboolean
1546 is_plt_patch (MonoJumpInfo *patch_info)
1547 {
1548         switch (patch_info->type) {
1549         case MONO_PATCH_INFO_METHOD:
1550         case MONO_PATCH_INFO_INTERNAL_METHOD:
1551         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1552         case MONO_PATCH_INFO_ICALL_ADDR:
1553         case MONO_PATCH_INFO_CLASS_INIT:
1554         case MONO_PATCH_INFO_RGCTX_FETCH:
1555         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1556         case MONO_PATCH_INFO_MONITOR_ENTER:
1557         case MONO_PATCH_INFO_MONITOR_EXIT:
1558                 return TRUE;
1559         default:
1560                 return FALSE;
1561         }
1562 }
1563
1564 static int
1565 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1566 {
1567         int res = -1;
1568
1569         if (is_plt_patch (patch_info)) {
1570                 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1571
1572                 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1573                         /* 
1574                          * Allocate a separate PLT slot for each such patch, since some plt
1575                          * entries will refer to the method itself, and some will refer to
1576                          * wrapper.
1577                          */
1578                         idx = 0;
1579                 }
1580
1581                 if (idx) {
1582                         res = idx;
1583                 } else {
1584                         MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1585
1586                         res = acfg->plt_offset;
1587                         g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1588                         g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1589                         acfg->plt_offset ++;
1590                 }
1591         }
1592
1593         return res;
1594 }
1595
1596 /**
1597  * get_got_offset:
1598  *
1599  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
1600  * JI could be found if it exists, otherwise allocates a new one.
1601  */
1602 static guint32
1603 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1604 {
1605         guint32 got_offset;
1606
1607         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset, ji));
1608         if (got_offset)
1609                 return got_offset - 1;
1610
1611         got_offset = acfg->got_offset;
1612         acfg->got_offset ++;
1613
1614         acfg->stats.got_slots ++;
1615         acfg->stats.got_slot_types [ji->type] ++;
1616
1617         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1618         g_ptr_array_add (acfg->got_patches, ji);
1619
1620         return got_offset;
1621 }
1622
1623 /* Add a method to the list of methods which need to be emitted */
1624 static void
1625 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1626 {
1627         g_assert (method);
1628         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1629                 g_ptr_array_add (acfg->methods, method);
1630                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1631                 acfg->nmethods = acfg->methods->len + 1;
1632         }
1633
1634         if (method->wrapper_type || extra)
1635                 g_ptr_array_add (acfg->extra_methods, method);
1636 }
1637
1638 static guint32
1639 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1640 {
1641         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1642         
1643         g_assert (index);
1644
1645         return index - 1;
1646 }
1647
1648 static int
1649 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra)
1650 {
1651         int index;
1652
1653         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1654         if (index)
1655                 return index - 1;
1656
1657         index = acfg->method_index;
1658         add_method_with_index (acfg, method, index, extra);
1659
1660         /* FIXME: Fix quadratic behavior */
1661         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1662
1663         acfg->method_index ++;
1664
1665         return index;
1666 }
1667
1668 static int
1669 add_method (MonoAotCompile *acfg, MonoMethod *method)
1670 {
1671         return add_method_full (acfg, method, FALSE);
1672 }
1673
1674 static void
1675 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1676 {
1677         add_method_full (acfg, method, TRUE);
1678 }
1679
1680 static void
1681 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1682 {
1683         MonoAotCompile *acfg = user_data;
1684         MonoJitICallInfo *callinfo = value;
1685         MonoMethod *wrapper;
1686         char *name;
1687
1688         if (!callinfo->sig)
1689                 return;
1690
1691         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1692         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1693         g_free (name);
1694
1695         add_method (acfg, wrapper);
1696 }
1697
1698 static MonoMethod*
1699 get_runtime_invoke_sig (MonoMethodSignature *sig)
1700 {
1701         MonoMethodBuilder *mb;
1702         MonoMethod *m;
1703
1704         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1705         m = mono_mb_create_method (mb, sig, 16);
1706         return mono_marshal_get_runtime_invoke (m, FALSE);
1707 }
1708
1709 static void
1710 add_wrappers (MonoAotCompile *acfg)
1711 {
1712         MonoMethod *method, *m;
1713         int i, j;
1714         MonoMethodSignature *sig, *csig;
1715         guint32 token;
1716
1717         /* 
1718          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1719          * so there is only one wrapper of a given type, or inlining their contents into their
1720          * callers.
1721          */
1722
1723         /* 
1724          * FIXME: This depends on the fact that different wrappers have different 
1725          * names.
1726          */
1727
1728         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1729                 MonoMethod *method;
1730                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1731                 gboolean skip = FALSE;
1732
1733                 method = mono_get_method (acfg->image, token, NULL);
1734
1735                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1736                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1737                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1738                         skip = TRUE;
1739
1740                 if (method->is_generic || method->klass->generic_container)
1741                         skip = TRUE;
1742
1743                 /* Skip methods which can not be handled by get_runtime_invoke () */
1744                 sig = mono_method_signature (method);
1745                 if ((sig->ret->type == MONO_TYPE_PTR) ||
1746                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1747                         skip = TRUE;
1748
1749                 for (j = 0; j < sig->param_count; j++) {
1750                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1751                                 skip = TRUE;
1752                 }
1753
1754                 if (!skip)
1755                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1756         }
1757
1758         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1759 #ifdef MONO_ARCH_HAVE_TLS_GET
1760                 MonoMethodDesc *desc;
1761                 MonoMethod *orig_method;
1762                 int nallocators;
1763 #endif
1764
1765                 /* Runtime invoke wrappers */
1766
1767                 /* void runtime-invoke () [.cctor] */
1768                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1769                 csig->ret = &mono_defaults.void_class->byval_arg;
1770                 add_method (acfg, get_runtime_invoke_sig (csig));
1771
1772                 /* void runtime-invoke () [Finalize] */
1773                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1774                 csig->hasthis = 1;
1775                 csig->ret = &mono_defaults.void_class->byval_arg;
1776                 add_method (acfg, get_runtime_invoke_sig (csig));
1777
1778                 /* void runtime-invoke (string) [exception ctor] */
1779                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1780                 csig->hasthis = 1;
1781                 csig->ret = &mono_defaults.void_class->byval_arg;
1782                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1783                 add_method (acfg, get_runtime_invoke_sig (csig));
1784
1785                 /* void runtime-invoke (string, string) [exception ctor] */
1786                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1787                 csig->hasthis = 1;
1788                 csig->ret = &mono_defaults.void_class->byval_arg;
1789                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1790                 csig->params [1] = &mono_defaults.string_class->byval_arg;
1791                 add_method (acfg, get_runtime_invoke_sig (csig));
1792
1793                 /* string runtime-invoke () [Exception.ToString ()] */
1794                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1795                 csig->hasthis = 1;
1796                 csig->ret = &mono_defaults.string_class->byval_arg;
1797                 add_method (acfg, get_runtime_invoke_sig (csig));
1798
1799                 /* void runtime-invoke (string, Exception) [exception ctor] */
1800                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1801                 csig->hasthis = 1;
1802                 csig->ret = &mono_defaults.void_class->byval_arg;
1803                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1804                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1805                 add_method (acfg, get_runtime_invoke_sig (csig));
1806
1807                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1808                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1809                 csig->hasthis = 1;
1810                 csig->ret = &(mono_class_from_name (
1811                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1812                 csig->params [0] = &mono_defaults.string_class->byval_arg;
1813                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1814                 add_method (acfg, get_runtime_invoke_sig (csig));
1815
1816                 /* runtime-invoke used by finalizers */
1817                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1818
1819                 /* JIT icall wrappers */
1820                 /* FIXME: locking */
1821                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1822
1823                 /* stelemref */
1824                 add_method (acfg, mono_marshal_get_stelemref ());
1825
1826 #ifdef MONO_ARCH_HAVE_TLS_GET
1827                 /* Managed Allocators */
1828                 nallocators = mono_gc_get_managed_allocator_types ();
1829                 for (i = 0; i < nallocators; ++i) {
1830                         m = mono_gc_get_managed_allocator_by_type (i);
1831                         if (m)
1832                                 add_method (acfg, m);
1833                 }
1834
1835                 /* Monitor Enter/Exit */
1836                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1837                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1838                 g_assert (orig_method);
1839                 mono_method_desc_free (desc);
1840                 method = mono_monitor_get_fast_path (orig_method);
1841                 if (method)
1842                         add_method (acfg, method);
1843
1844                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1845                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1846                 g_assert (orig_method);
1847                 mono_method_desc_free (desc);
1848                 method = mono_monitor_get_fast_path (orig_method);
1849                 if (method)
1850                         add_method (acfg, method);
1851 #endif
1852         }
1853
1854         /* 
1855          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
1856          * we use the original method instead at runtime.
1857          * Since full-aot doesn't support remoting, this is not a problem.
1858          */
1859 #if 0
1860         /* remoting-invoke wrappers */
1861         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1862                 MonoMethodSignature *sig;
1863                 
1864                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1865                 method = mono_get_method (acfg->image, token, NULL);
1866
1867                 sig = mono_method_signature (method);
1868
1869                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1870                         m = mono_marshal_get_remoting_invoke_with_check (method);
1871
1872                         add_method (acfg, m);
1873                 }
1874         }
1875 #endif
1876
1877         /* delegate-invoke wrappers */
1878         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1879                 MonoClass *klass;
1880                 
1881                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1882                 klass = mono_class_get (acfg->image, token);
1883
1884                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1885                         method = mono_get_delegate_invoke (klass);
1886
1887                         m = mono_marshal_get_delegate_invoke (method, NULL);
1888
1889                         add_method (acfg, m);
1890
1891                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1892                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1893
1894                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1895                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1896                 }
1897         }
1898
1899         /* Synchronized wrappers */
1900         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1901                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1902                 method = mono_get_method (acfg->image, token, NULL);
1903
1904                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1905                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1906         }
1907
1908         /* pinvoke wrappers */
1909         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1910                 MonoMethod *method;
1911                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1912
1913                 method = mono_get_method (acfg->image, token, NULL);
1914
1915                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1916                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1917                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1918                 }
1919         }
1920
1921         /* StructureToPtr/PtrToStructure wrappers */
1922         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1923                 MonoClass *klass;
1924                 
1925                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1926                 klass = mono_class_get (acfg->image, token);
1927
1928                 if (klass->valuetype && !klass->generic_container && ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)) {
1929                         gboolean can_marshal = TRUE;
1930                         gpointer iter = NULL;
1931                         MonoClassField *field;
1932
1933                         /* Only allow a few field types to avoid asserts in the marshalling code */
1934                         while ((field = mono_class_get_fields (klass, &iter))) {
1935                                 switch (field->type->type) {
1936                                 case MONO_TYPE_I4:
1937                                 case MONO_TYPE_U4:
1938                                 case MONO_TYPE_I1:
1939                                 case MONO_TYPE_U1:
1940                                 case MONO_TYPE_BOOLEAN:
1941                                 case MONO_TYPE_I2:
1942                                 case MONO_TYPE_U2:
1943                                 case MONO_TYPE_CHAR:
1944                                 case MONO_TYPE_I8:
1945                                 case MONO_TYPE_U8:
1946                                 case MONO_TYPE_PTR:
1947                                 case MONO_TYPE_R4:
1948                                 case MONO_TYPE_R8:
1949                                         break;
1950                                 default:
1951                                         can_marshal = FALSE;
1952                                         break;
1953                                 }
1954                         }
1955
1956                         if (can_marshal) {
1957                                 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
1958                                 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
1959                         }
1960                 }
1961         }
1962 }
1963
1964 static gboolean
1965 has_type_vars (MonoClass *klass)
1966 {
1967         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1968                 return TRUE;
1969         if (klass->rank)
1970                 return has_type_vars (klass->element_class);
1971         if (klass->generic_class) {
1972                 MonoGenericContext *context = &klass->generic_class->context;
1973                 if (context->class_inst) {
1974                         int i;
1975
1976                         for (i = 0; i < context->class_inst->type_argc; ++i)
1977                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1978                                         return TRUE;
1979                 }
1980         }
1981         return FALSE;
1982 }
1983
1984 static gboolean
1985 method_has_type_vars (MonoMethod *method)
1986 {
1987         if (has_type_vars (method->klass))
1988                 return TRUE;
1989
1990         if (method->is_inflated) {
1991                 MonoGenericContext *context = mono_method_get_context (method);
1992                 if (context->method_inst) {
1993                         int i;
1994
1995                         for (i = 0; i < context->method_inst->type_argc; ++i)
1996                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
1997                                         return TRUE;
1998                 }
1999         }
2000         return FALSE;
2001 }
2002
2003 /*
2004  * add_generic_class:
2005  *
2006  *   Add all methods of a generic class.
2007  */
2008 static void
2009 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2010 {
2011         MonoMethod *method;
2012         gpointer iter;
2013
2014         mono_class_init (klass);
2015
2016         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2017                 return;
2018
2019         if (has_type_vars (klass))
2020                 return;
2021
2022         if (!klass->generic_class && !klass->rank)
2023                 return;
2024
2025         iter = NULL;
2026         while ((method = mono_class_get_methods (klass, &iter))) {
2027                 if (mono_method_is_generic_sharable_impl (method, FALSE))
2028                         /* Already added */
2029                         continue;
2030
2031                 if (method->is_generic)
2032                         /* FIXME: */
2033                         continue;
2034
2035                 /*
2036                  * FIXME: Instances which are referenced by these methods are not added,
2037                  * for example Array.Resize<int> for List<int>.Add ().
2038                  */
2039                 add_extra_method (acfg, method);
2040         }
2041
2042         if (klass->delegate) {
2043                 method = mono_get_delegate_invoke (klass);
2044
2045                 method = mono_marshal_get_delegate_invoke (method, NULL);
2046
2047                 add_method (acfg, method);
2048         }
2049
2050         /* 
2051          * For ICollection<T>, where T is a vtype, add instances of the helper methods
2052          * in Array, since a T[] could be cast to ICollection<T>.
2053          */
2054         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2055                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1")) &&
2056                 MONO_TYPE_ISSTRUCT (klass->generic_class->context.class_inst->type_argv [0])) {
2057                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2058                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2059                 gpointer iter;
2060                 char *name_prefix;
2061
2062                 if (!strcmp (klass->name, "IEnumerator`1"))
2063                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2064                 else
2065                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2066
2067                 /* Add the T[]/InternalEnumerator class */
2068                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2069                         MonoClass *nclass;
2070
2071                         iter = NULL;
2072                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2073                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2074                                         break;
2075                         }
2076                         g_assert (nclass);
2077                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2078                         add_generic_class (acfg, nclass);
2079                 }
2080
2081                 iter = NULL;
2082                 while ((method = mono_class_get_methods (array_class, &iter))) {
2083                         if (strstr (method->name, name_prefix))
2084                                 add_extra_method (acfg, method);
2085                 }
2086
2087                 g_free (name_prefix);
2088         }
2089 }
2090
2091 static void
2092 add_array_wrappers (MonoAotCompile *acfg, MonoClass *klass)
2093 {
2094         int i;
2095
2096         mono_class_setup_methods (klass);
2097         for (i = 0; i < klass->method.count; ++i) {
2098                 if (klass->methods [i]->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED)
2099                         add_extra_method (acfg, klass->methods [i]);
2100         }
2101 }
2102
2103 /*
2104  * add_generic_instances:
2105  *
2106  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
2107  */
2108 static void
2109 add_generic_instances (MonoAotCompile *acfg)
2110 {
2111         int i;
2112         guint32 token;
2113         MonoMethod *method;
2114         MonoMethodHeader *header;
2115         MonoMethodSignature *sig;
2116         MonoGenericContext *context;
2117
2118         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2119                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2120                 method = mono_get_method (acfg->image, token, NULL);
2121
2122                 context = mono_method_get_context (method);
2123                 if (context && ((context->class_inst && context->class_inst->is_open) ||
2124                                                 (context->method_inst && context->method_inst->is_open)))
2125                         continue;
2126
2127                 if (method->klass->image != acfg->image)
2128                         continue;
2129
2130                 if (mono_method_is_generic_sharable_impl (method, FALSE))
2131                         /* Already added */
2132                         continue;
2133
2134                 add_extra_method (acfg, method);
2135         }
2136
2137         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2138                 MonoClass *klass;
2139
2140                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2141
2142                 klass = mono_class_get (acfg->image, token);
2143                 if (!klass || klass->rank)
2144                         continue;
2145
2146                 add_generic_class (acfg, klass);
2147         }
2148
2149         /* Add types of args/locals */
2150         for (i = 0; i < acfg->methods->len; ++i) {
2151                 int j;
2152
2153                 method = g_ptr_array_index (acfg->methods, i);
2154
2155                 sig = mono_method_signature (method);
2156
2157                 if (sig) {
2158                         for (j = 0; j < sig->param_count; ++j)
2159                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2160                                         add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2161                 }
2162
2163                 header = mono_method_get_header (method);
2164
2165                 if (header) {
2166                         for (j = 0; j < header->num_locals; ++j)
2167                                 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2168                                         add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2169                 }
2170         }
2171
2172         if (acfg->image == mono_defaults.corlib) {
2173                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2174                 MonoClass *klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2175
2176                 if (klass) {
2177                         MonoGenericContext ctx;
2178                         MonoType *args [16];
2179
2180                         memset (&ctx, 0, sizeof (ctx));
2181
2182                         args [0] = &mono_defaults.byte_class->byval_arg;
2183                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2184                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2185
2186                         args [0] = &mono_defaults.sbyte_class->byval_arg;
2187                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2188                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2189
2190                         args [0] = &mono_defaults.int16_class->byval_arg;
2191                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2192                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2193
2194                         args [0] = &mono_defaults.uint16_class->byval_arg;
2195                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2196                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2197
2198                         args [0] = &mono_defaults.int32_class->byval_arg;
2199                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2200                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2201
2202                         args [0] = &mono_defaults.uint32_class->byval_arg;
2203                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2204                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2205
2206                         args [0] = &mono_defaults.int64_class->byval_arg;
2207                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2208                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2209
2210                         args [0] = &mono_defaults.uint64_class->byval_arg;
2211                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2212                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2213                 }
2214
2215                 /* Add GenericEqualityComparer<T> instances for primitive types */
2216                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2217
2218                 if (klass) {
2219                         MonoGenericContext ctx;
2220                         MonoType *args [16];
2221
2222                         memset (&ctx, 0, sizeof (ctx));
2223
2224                         args [0] = &mono_defaults.byte_class->byval_arg;
2225                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2226                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2227
2228                         args [0] = &mono_defaults.sbyte_class->byval_arg;
2229                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2230                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2231
2232                         args [0] = &mono_defaults.int16_class->byval_arg;
2233                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2234                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2235
2236                         args [0] = &mono_defaults.uint16_class->byval_arg;
2237                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2238                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2239
2240                         args [0] = &mono_defaults.int32_class->byval_arg;
2241                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2242                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2243
2244                         args [0] = &mono_defaults.uint32_class->byval_arg;
2245                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2246                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2247
2248                         args [0] = &mono_defaults.int64_class->byval_arg;
2249                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2250                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2251
2252                         args [0] = &mono_defaults.uint64_class->byval_arg;
2253                         ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2254                         add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2255                 }
2256
2257                 /* Emit the array wrapper methods for arrays of primitive types */
2258                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.byte_class, 1));
2259                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.sbyte_class, 1));
2260                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int16_class, 1));
2261                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.uint16_class, 1));
2262                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int32_class, 1));
2263                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.uint32_class, 1));
2264                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.int64_class, 1));
2265                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.single_class, 1));
2266                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.double_class, 1));
2267                 /* These are not handled by generic sharing */
2268                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.object_class, 1));
2269                 add_array_wrappers (acfg, mono_array_class_get (mono_defaults.string_class, 1));
2270
2271                 /* Add instances of Array.GetGenericValueImpl */
2272                 {
2273                         MonoGenericContext ctx;
2274                         MonoType *args [16];
2275                         MonoMethod *method;
2276
2277                         memset (&ctx, 0, sizeof (ctx));
2278
2279                         /* 
2280                          * managed-to-native wrappers are not shared, so have to generate 
2281                          * these for ref types too.
2282                          */
2283                         klass = mono_array_class_get (mono_defaults.int_class, 1)->parent;
2284                         method = mono_class_get_method_from_name (klass, "GetGenericValueImpl", 2);
2285
2286                         if (method) {
2287                                 /* String */
2288                                 args [0] = &mono_defaults.string_class->byval_arg;
2289                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2290                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (method, &ctx), TRUE, TRUE));
2291                         }
2292                 }
2293         }
2294 }
2295
2296 /*
2297  * is_direct_callable:
2298  *
2299  *   Return whenever the method identified by JI is directly callable without 
2300  * going through the PLT.
2301  */
2302 static gboolean
2303 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2304 {
2305         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2306                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2307                 if (callee_cfg) {
2308                         gboolean direct_callable = TRUE;
2309
2310                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2311                                 direct_callable = FALSE;
2312                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2313                                 // FIXME: Maybe call the wrapper directly ?
2314                                 direct_callable = FALSE;
2315
2316                         if (direct_callable)
2317                                 return TRUE;
2318                 }
2319         }
2320
2321         return FALSE;
2322 }
2323
2324 /*
2325  * emit_and_reloc_code:
2326  *
2327  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2328  * is true, calls are made through the GOT too. This is used for emitting trampolines
2329  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2330  * since trampolines are needed to make PTL work.
2331  */
2332 static void
2333 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2334 {
2335         int i, pindex, start_index, method_index;
2336         GPtrArray *patches;
2337         MonoJumpInfo *patch_info;
2338         MonoMethodHeader *header;
2339         gboolean skip, direct_call;
2340         guint32 got_slot;
2341         char direct_call_target [128];
2342
2343         if (method) {
2344                 header = mono_method_get_header (method);
2345
2346                 method_index = get_method_index (acfg, method);
2347         }
2348
2349         /* Collect and sort relocations */
2350         patches = g_ptr_array_new ();
2351         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2352                 g_ptr_array_add (patches, patch_info);
2353         g_ptr_array_sort (patches, compare_patches);
2354
2355         start_index = 0;
2356         for (i = 0; i < code_len; i++) {
2357                 patch_info = NULL;
2358                 for (pindex = start_index; pindex < patches->len; ++pindex) {
2359                         patch_info = g_ptr_array_index (patches, pindex);
2360                         if (patch_info->ip.i >= i)
2361                                 break;
2362                 }
2363
2364 #ifdef MONO_ARCH_AOT_SUPPORTED
2365                 skip = FALSE;
2366                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2367                         start_index = pindex;
2368
2369                         switch (patch_info->type) {
2370                         case MONO_PATCH_INFO_NONE:
2371                                 break;
2372                         case MONO_PATCH_INFO_GOT_OFFSET: {
2373                                 int code_size;
2374  
2375                                 arch_emit_got_offset (acfg, code + i, &code_size);
2376                                 i += code_size - 1;
2377                                 skip = TRUE;
2378                                 patch_info->type = MONO_PATCH_INFO_NONE;
2379                                 break;
2380                         }
2381                         default: {
2382                                 /*
2383                                  * If this patch is a call, try emitting a direct call instead of
2384                                  * through a PLT entry. This is possible if the called method is in
2385                                  * the same assembly and requires no initialization.
2386                                  */
2387                                 direct_call = FALSE;
2388                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2389                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2390                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2391                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2392                                                 direct_call = TRUE;
2393                                                 sprintf (direct_call_target, "%sm_%x", acfg->temp_prefix, get_method_index (acfg, callee_cfg->orig_method));
2394                                                 patch_info->type = MONO_PATCH_INFO_NONE;
2395                                                 acfg->stats.direct_calls ++;
2396                                         }
2397
2398                                         acfg->stats.all_calls ++;
2399                                 }
2400
2401                                 if (!got_only && !direct_call) {
2402                                         int plt_offset = get_plt_offset (acfg, patch_info);
2403                                         if (plt_offset != -1) {
2404                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2405                                                 direct_call = TRUE;
2406                                                 sprintf (direct_call_target, "%sp_%d", acfg->temp_prefix, plt_offset);
2407                 
2408                                                 /* Nullify the patch */
2409                                                 patch_info->type = MONO_PATCH_INFO_NONE;
2410                                         }
2411                                 }
2412
2413                                 if (direct_call) {
2414                                         int call_size;
2415
2416                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
2417                                         i += call_size - 1;
2418                                 } else {
2419                                         int code_size;
2420
2421                                         got_slot = get_got_offset (acfg, patch_info);
2422
2423                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2424                                         i += code_size - 1;
2425                                 }
2426                                 skip = TRUE;
2427                         }
2428                         }
2429                 }
2430 #endif /* MONO_ARCH_AOT_SUPPORTED */
2431
2432                 if (!skip) {
2433                         /* Find next patch */
2434                         patch_info = NULL;
2435                         for (pindex = start_index; pindex < patches->len; ++pindex) {
2436                                 patch_info = g_ptr_array_index (patches, pindex);
2437                                 if (patch_info->ip.i >= i)
2438                                         break;
2439                         }
2440
2441                         /* Try to emit multiple bytes at once */
2442                         if (pindex < patches->len && patch_info->ip.i > i) {
2443                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2444                                 i = patch_info->ip.i - 1;
2445                         } else {
2446                                 emit_bytes (acfg, code + i, 1);
2447                         }
2448                 }
2449         }
2450 }
2451
2452 /*
2453  * sanitize_symbol:
2454  *
2455  *   Modify SYMBOL so it only includes characters permissible in symbols.
2456  */
2457 static void
2458 sanitize_symbol (char *symbol)
2459 {
2460         int i, len = strlen (symbol);
2461
2462         for (i = 0; i < len; ++i)
2463                 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2464                         symbol [i] = '_';
2465 }
2466
2467 static char*
2468 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2469 {
2470         char *name1, *name2, *cached;
2471         int i, j, len, count;
2472                 
2473         name1 = mono_method_full_name (method, TRUE);
2474         len = strlen (name1);
2475         name2 = malloc (strlen (prefix) + len + 16);
2476         memcpy (name2, prefix, strlen (prefix));
2477         j = strlen (prefix);
2478         for (i = 0; i < len; ++i) {
2479                 if (isalnum (name1 [i])) {
2480                         name2 [j ++] = name1 [i];
2481                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2482                         i += 2;
2483                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2484                         name2 [j ++] = '_';
2485                         i++;
2486                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2487                 } else
2488                         name2 [j ++] = '_';
2489         }
2490         name2 [j] = '\0';
2491
2492         g_free (name1);
2493
2494         count = 0;
2495         while (g_hash_table_lookup (cache, name2)) {
2496                 sprintf (name2 + j, "_%d", count);
2497                 count ++;
2498         }
2499
2500         cached = g_strdup (name2);
2501         g_hash_table_insert (cache, cached, cached);
2502
2503         return name2;
2504 }
2505
2506 static void
2507 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2508 {
2509         MonoMethod *method;
2510         int method_index;
2511         guint8 *code;
2512         char *debug_sym = NULL;
2513         char symbol [128];
2514         int func_alignment = AOT_FUNC_ALIGNMENT;
2515         MonoMethodHeader *header;
2516
2517         method = cfg->orig_method;
2518         code = cfg->native_code;
2519         header = mono_method_get_header (method);
2520
2521         method_index = get_method_index (acfg, method);
2522
2523         /* Emit unbox trampoline */
2524         if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2525                 char call_target [256];
2526
2527                 if (!method->wrapper_type && !method->is_inflated) {
2528                         g_assert (method->token);
2529                         sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2530                 } else {
2531                         sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2532                 }
2533
2534                 emit_section_change (acfg, ".text", 0);
2535                 emit_global (acfg, symbol, TRUE);
2536                 emit_label (acfg, symbol);
2537
2538                 sprintf (call_target, "%sm_%x", acfg->temp_prefix, method_index);
2539
2540                 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2541         }
2542
2543         /* Make the labels local */
2544         sprintf (symbol, "%sm_%x", acfg->temp_prefix, method_index);
2545
2546         emit_alignment (acfg, func_alignment);
2547         emit_label (acfg, symbol);
2548
2549         if (acfg->aot_opts.write_symbols) {
2550                 /* 
2551                  * Write a C style symbol for every method, this has two uses:
2552                  * - it works on platforms where the dwarf debugging info is not
2553                  *   yet supported.
2554                  * - it allows the setting of breakpoints of aot-ed methods.
2555                  */
2556                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
2557
2558                 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2559                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
2560                 emit_label (acfg, debug_sym);
2561         }
2562
2563         if (cfg->verbose_level > 0)
2564                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2565
2566         acfg->stats.code_size += cfg->code_len;
2567
2568         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2569
2570         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2571
2572         emit_line (acfg);
2573
2574         if (acfg->aot_opts.write_symbols) {
2575                 emit_symbol_size (acfg, debug_sym, ".");
2576                 g_free (debug_sym);
2577         }
2578
2579         sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2580         emit_label (acfg, symbol);
2581 }
2582
2583 /**
2584  * encode_patch:
2585  *
2586  *  Encode PATCH_INFO into its disk representation.
2587  */
2588 static void
2589 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2590 {
2591         guint8 *p = buf;
2592
2593         switch (patch_info->type) {
2594         case MONO_PATCH_INFO_NONE:
2595                 break;
2596         case MONO_PATCH_INFO_IMAGE:
2597                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2598                 break;
2599         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
2600                 break;
2601         case MONO_PATCH_INFO_METHOD_REL:
2602                 encode_value ((gint)patch_info->data.offset, p, &p);
2603                 break;
2604         case MONO_PATCH_INFO_SWITCH: {
2605                 gpointer *table = (gpointer *)patch_info->data.table->table;
2606                 int k;
2607
2608                 encode_value (patch_info->data.table->table_size, p, &p);
2609                 for (k = 0; k < patch_info->data.table->table_size; k++)
2610                         encode_value ((int)(gssize)table [k], p, &p);
2611                 break;
2612         }
2613         case MONO_PATCH_INFO_METHODCONST:
2614         case MONO_PATCH_INFO_METHOD:
2615         case MONO_PATCH_INFO_METHOD_JUMP:
2616         case MONO_PATCH_INFO_ICALL_ADDR:
2617         case MONO_PATCH_INFO_METHOD_RGCTX:
2618                 encode_method_ref (acfg, patch_info->data.method, p, &p);
2619                 break;
2620         case MONO_PATCH_INFO_INTERNAL_METHOD:
2621         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2622                 guint32 len = strlen (patch_info->data.name);
2623
2624                 encode_value (len, p, &p);
2625
2626                 memcpy (p, patch_info->data.name, len);
2627                 p += len;
2628                 *p++ = '\0';
2629                 break;
2630         }
2631         case MONO_PATCH_INFO_LDSTR: {
2632                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2633                 guint32 token = patch_info->data.token->token;
2634                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2635                 encode_value (image_index, p, &p);
2636                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2637                 break;
2638         }
2639         case MONO_PATCH_INFO_RVA:
2640         case MONO_PATCH_INFO_DECLSEC:
2641         case MONO_PATCH_INFO_LDTOKEN:
2642         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2643                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2644                 encode_value (patch_info->data.token->token, p, &p);
2645                 encode_value (patch_info->data.token->has_context, p, &p);
2646                 if (patch_info->data.token->has_context)
2647                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2648                 break;
2649         case MONO_PATCH_INFO_EXC_NAME: {
2650                 MonoClass *ex_class;
2651
2652                 ex_class =
2653                         mono_class_from_name (mono_defaults.exception_class->image,
2654                                                                   "System", patch_info->data.target);
2655                 g_assert (ex_class);
2656                 encode_klass_ref (acfg, ex_class, p, &p);
2657                 break;
2658         }
2659         case MONO_PATCH_INFO_R4:
2660                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2661                 break;
2662         case MONO_PATCH_INFO_R8:
2663                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2664                 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2665                 break;
2666         case MONO_PATCH_INFO_VTABLE:
2667         case MONO_PATCH_INFO_CLASS:
2668         case MONO_PATCH_INFO_IID:
2669         case MONO_PATCH_INFO_ADJUSTED_IID:
2670                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2671                 break;
2672         case MONO_PATCH_INFO_CLASS_INIT:
2673         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2674                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2675                 break;
2676         case MONO_PATCH_INFO_FIELD:
2677         case MONO_PATCH_INFO_SFLDA:
2678                 encode_field_info (acfg, patch_info->data.field, p, &p);
2679                 break;
2680         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2681                 break;
2682         case MONO_PATCH_INFO_RGCTX_FETCH: {
2683                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2684
2685                 encode_method_ref (acfg, entry->method, p, &p);
2686                 encode_value (entry->in_mrgctx, p, &p);
2687                 encode_value (entry->info_type, p, &p);
2688                 encode_value (entry->data->type, p, &p);
2689                 encode_patch (acfg, entry->data, p, &p);
2690                 break;
2691         }
2692         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2693         case MONO_PATCH_INFO_MONITOR_ENTER:
2694         case MONO_PATCH_INFO_MONITOR_EXIT:
2695                 break;
2696         default:
2697                 g_warning ("unable to handle jump info %d", patch_info->type);
2698                 g_assert_not_reached ();
2699         }
2700
2701         *endbuf = p;
2702 }
2703
2704 static void
2705 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2706 {
2707         guint8 *p = buf;
2708         guint32 pindex, offset;
2709         MonoJumpInfo *patch_info;
2710
2711         encode_value (n_patches, p, &p);
2712
2713         for (pindex = 0; pindex < patches->len; ++pindex) {
2714                 patch_info = g_ptr_array_index (patches, pindex);
2715
2716                 if (patch_info->type == MONO_PATCH_INFO_NONE)
2717                         /* Nothing to do */
2718                         continue;
2719
2720                 offset = get_got_offset (acfg, patch_info);
2721                 encode_value (offset, p, &p);
2722         }
2723
2724         *endbuf = p;
2725 }
2726
2727 static void
2728 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2729 {
2730         MonoMethod *method;
2731         GList *l;
2732         int pindex, buf_size, n_patches;
2733         guint8 *code;
2734         char symbol [128];
2735         GPtrArray *patches;
2736         MonoJumpInfo *patch_info;
2737         MonoMethodHeader *header;
2738         guint32 method_index;
2739         guint8 *p, *buf;
2740         guint32 first_got_offset;
2741
2742         method = cfg->orig_method;
2743         code = cfg->native_code;
2744         header = mono_method_get_header (method);
2745
2746         method_index = get_method_index (acfg, method);
2747
2748         /* Make the labels local */
2749         sprintf (symbol, "%sm_%x_p", acfg->temp_prefix, method_index);
2750
2751         /* Sort relocations */
2752         patches = g_ptr_array_new ();
2753         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2754                 g_ptr_array_add (patches, patch_info);
2755         g_ptr_array_sort (patches, compare_patches);
2756
2757         first_got_offset = acfg->cfgs [method_index]->got_offset;
2758
2759         /**********************/
2760         /* Encode method info */
2761         /**********************/
2762
2763         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2764         p = buf = g_malloc (buf_size);
2765
2766         if (mono_class_get_cctor (method->klass))
2767                 encode_klass_ref (acfg, method->klass, p, &p);
2768         else
2769                 /* Not needed when loading the method */
2770                 encode_value (0, p, &p);
2771
2772         /* String table */
2773         if (cfg->opt & MONO_OPT_SHARED) {
2774                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2775                 for (l = cfg->ldstr_list; l; l = l->next) {
2776                         encode_value ((long)l->data, p, &p);
2777                 }
2778         }
2779         else
2780                 /* Used only in shared mode */
2781                 g_assert (!cfg->ldstr_list);
2782
2783         n_patches = 0;
2784         for (pindex = 0; pindex < patches->len; ++pindex) {
2785                 patch_info = g_ptr_array_index (patches, pindex);
2786                 
2787                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2788                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
2789                         patch_info->type = MONO_PATCH_INFO_NONE;
2790                         /* Nothing to do */
2791                         continue;
2792                 }
2793
2794                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2795                         /* Stored in a GOT slot initialized at module load time */
2796                         patch_info->type = MONO_PATCH_INFO_NONE;
2797                         continue;
2798                 }
2799
2800                 if (is_plt_patch (patch_info)) {
2801                         /* Calls are made through the PLT */
2802                         patch_info->type = MONO_PATCH_INFO_NONE;
2803                         continue;
2804                 }
2805
2806                 n_patches ++;
2807         }
2808
2809         if (n_patches)
2810                 g_assert (cfg->has_got_slots);
2811
2812         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2813
2814         acfg->stats.info_size += p - buf;
2815
2816         /* Emit method info */
2817
2818         emit_label (acfg, symbol);
2819
2820         g_assert (p - buf < buf_size);
2821         emit_bytes (acfg, buf, p - buf);
2822         g_free (buf);
2823 }
2824
2825 static guint32
2826 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2827 {
2828         guint32 cache_index;
2829         guint32 offset;
2830
2831         /* Reuse the unwind module to canonize and store unwind info entries */
2832         cache_index = mono_cache_unwind_info (encoded, encoded_len);
2833
2834         /* Use +/- 1 to distinguish 0s from missing entries */
2835         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2836         if (offset)
2837                 return offset - 1;
2838         else {
2839                 guint8 buf [16];
2840                 guint8 *p;
2841
2842                 /* 
2843                  * It would be easier to use assembler symbols, but the caller needs an
2844                  * offset now.
2845                  */
2846                 offset = acfg->unwind_info_offset;
2847                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2848                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2849
2850                 p = buf;
2851                 encode_value (encoded_len, p, &p);
2852
2853                 acfg->unwind_info_offset += encoded_len + (p - buf);
2854                 return offset;
2855         }
2856 }
2857
2858 static void
2859 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2860 {
2861         MonoMethod *method;
2862         int k, buf_size, method_index;
2863         guint32 debug_info_size;
2864         guint8 *code;
2865         char symbol [128];
2866         MonoMethodHeader *header;
2867         guint8 *p, *buf, *debug_info;
2868         MonoJitInfo *jinfo = cfg->jit_info;
2869         guint32 flags;
2870         gboolean use_unwind_ops = FALSE;
2871
2872         method = cfg->orig_method;
2873         code = cfg->native_code;
2874         header = mono_method_get_header (method);
2875
2876         method_index = get_method_index (acfg, method);
2877
2878         /* Make the labels local */
2879         sprintf (symbol, "%se_%x_p", acfg->temp_prefix, method_index);
2880
2881         if (!acfg->aot_opts.nodebug) {
2882                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2883         } else {
2884                 debug_info = NULL;
2885                 debug_info_size = 0;
2886         }
2887
2888         buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2889         p = buf = g_malloc (buf_size);
2890
2891 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2892         use_unwind_ops = cfg->unwind_ops != NULL;
2893 #endif
2894
2895         flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0);
2896
2897         encode_value (jinfo->code_size, p, &p);
2898         encode_value (flags, p, &p);
2899
2900         if (use_unwind_ops) {
2901                 guint32 encoded_len;
2902                 guint8 *encoded;
2903
2904                 /* 
2905                  * This is a duplicate of the data in the .debug_frame section, but that
2906                  * section cannot be accessed using the dl interface.
2907                  */
2908                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2909                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
2910                 g_free (encoded);
2911         } else {
2912                 encode_value (jinfo->used_regs, p, &p);
2913         }
2914
2915         /* Exception table */
2916         if (jinfo->num_clauses)
2917                 encode_value (jinfo->num_clauses, p, &p);
2918
2919         for (k = 0; k < jinfo->num_clauses; ++k) {
2920                 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2921
2922                 encode_value (ei->exvar_offset, p, &p);
2923
2924                 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2925                         encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2926                 else {
2927                         if (ei->data.catch_class) {
2928                                 encode_value (1, p, &p);
2929                                 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
2930                         } else {
2931                                 encode_value (0, p, &p);
2932                         }
2933                 }
2934
2935                 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2936                 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2937                 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2938         }
2939
2940         if (jinfo->has_generic_jit_info) {
2941                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2942
2943                 encode_value (gi->has_this ? 1 : 0, p, &p);
2944                 encode_value (gi->this_reg, p, &p);
2945                 encode_value (gi->this_offset, p, &p);
2946
2947                 /* 
2948                  * Need to encode jinfo->method too, since it is not equal to 'method'
2949                  * when using generic sharing.
2950                  */
2951                 encode_method_ref (acfg, jinfo->method, p, &p);
2952         }
2953
2954         g_assert (debug_info_size < buf_size);
2955
2956         encode_value (debug_info_size, p, &p);
2957         if (debug_info_size) {
2958                 memcpy (p, debug_info, debug_info_size);
2959                 p += debug_info_size;
2960                 g_free (debug_info);
2961         }
2962
2963         acfg->stats.ex_info_size += p - buf;
2964
2965         /* Emit info */
2966
2967         emit_label (acfg, symbol);
2968
2969         g_assert (p - buf < buf_size);
2970         emit_bytes (acfg, buf, p - buf);
2971         g_free (buf);
2972 }
2973
2974 static void
2975 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2976 {
2977         MonoClass *klass = mono_class_get (acfg->image, token);
2978         guint8 *p, *buf;
2979         int i, buf_size;
2980         char symbol [128];
2981         gboolean no_special_static, cant_encode;
2982         gpointer iter = NULL;
2983
2984         buf_size = 10240 + (klass->vtable_size * 16);
2985         p = buf = g_malloc (buf_size);
2986
2987         g_assert (klass);
2988
2989         mono_class_init (klass);
2990
2991         mono_class_get_nested_types (klass, &iter);
2992         g_assert (klass->nested_classes_inited);
2993
2994         mono_class_setup_vtable (klass);
2995
2996         /* 
2997          * Emit all the information which is required for creating vtables so
2998          * the runtime does not need to create the MonoMethod structures which
2999          * take up a lot of space.
3000          */
3001
3002         no_special_static = !mono_class_has_special_static_fields (klass);
3003
3004         /* Check whenever we have enough info to encode the vtable */
3005         cant_encode = FALSE;
3006         for (i = 0; i < klass->vtable_size; ++i) {
3007                 MonoMethod *cm = klass->vtable [i];
3008
3009                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3010                         cant_encode = TRUE;
3011         }
3012
3013         if (klass->generic_container || cant_encode) {
3014                 encode_value (-1, p, &p);
3015         } else {
3016                 encode_value (klass->vtable_size, p, &p);
3017                 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);
3018                 if (klass->has_cctor)
3019                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3020                 if (klass->has_finalize)
3021                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3022  
3023                 encode_value (klass->instance_size, p, &p);
3024                 encode_value (mono_class_data_size (klass), p, &p);
3025                 encode_value (klass->packing_size, p, &p);
3026                 encode_value (klass->min_align, p, &p);
3027
3028                 for (i = 0; i < klass->vtable_size; ++i) {
3029                         MonoMethod *cm = klass->vtable [i];
3030
3031                         if (cm)
3032                                 encode_method_ref (acfg, cm, p, &p);
3033                         else
3034                                 encode_value (0, p, &p);
3035                 }
3036         }
3037
3038         acfg->stats.class_info_size += p - buf;
3039
3040         /* Emit the info */
3041         sprintf (symbol, "%sK_I_%x", acfg->temp_prefix, token - MONO_TOKEN_TYPE_DEF - 1);
3042         emit_label (acfg, symbol);
3043
3044         g_assert (p - buf < buf_size);
3045         emit_bytes (acfg, buf, p - buf);
3046         g_free (buf);
3047 }
3048
3049 /*
3050  * Calls made from AOTed code are routed through a table of jumps similar to the
3051  * ELF PLT (Program Linkage Table). The differences are the following:
3052  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3053  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3054  *   jumps. This means the jumps need to be patched when the address of the callee is
3055  *   known. Initially the PLT entries jump to code which transfers control to the
3056  *   AOT runtime through the first PLT entry.
3057  */
3058 static void
3059 emit_plt (MonoAotCompile *acfg)
3060 {
3061         char symbol [128];
3062         int i;
3063         GHashTable *cache;
3064
3065         cache = g_hash_table_new (g_str_hash, g_str_equal);
3066
3067         emit_line (acfg);
3068         sprintf (symbol, "plt");
3069
3070         emit_section_change (acfg, ".text", 0);
3071         emit_global (acfg, symbol, TRUE);
3072 #ifdef TARGET_X86
3073         /* This section will be made read-write by the AOT loader */
3074         emit_alignment (acfg, mono_pagesize ());
3075 #else
3076         emit_alignment (acfg, 16);
3077 #endif
3078         emit_label (acfg, symbol);
3079         emit_label (acfg, acfg->plt_symbol);
3080
3081         for (i = 0; i < acfg->plt_offset; ++i) {
3082                 char label [128];
3083                 char *debug_sym = NULL;
3084
3085                 sprintf (label, "%sp_%d", acfg->temp_prefix, i);
3086                 emit_label (acfg, label);
3087
3088                 if (acfg->aot_opts.write_symbols) {
3089                         MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3090                         char *debug_sym = NULL;
3091
3092                         if (ji) {
3093                                 switch (ji->type) {
3094                                 case MONO_PATCH_INFO_METHOD:
3095                                         debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3096                                         break;
3097                                 case MONO_PATCH_INFO_INTERNAL_METHOD:
3098                                         debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3099                                         break;
3100                                 case MONO_PATCH_INFO_CLASS_INIT:
3101                                         debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3102                                         sanitize_symbol (debug_sym);
3103                                         break;
3104                                 case MONO_PATCH_INFO_RGCTX_FETCH:
3105                                         debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3106                                         break;
3107                                 case MONO_PATCH_INFO_ICALL_ADDR: {
3108                                         char *s = get_debug_sym (ji->data.method, "", cache);
3109                                         
3110                                         debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3111                                         g_free (s);
3112                                         break;
3113                                 }
3114                                 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3115                                         debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3116                                         break;
3117                                 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3118                                         debug_sym = g_strdup_printf ("plt__generic_class_init");
3119                                         break;
3120                                 default:
3121                                         break;
3122                                 }
3123
3124                                 if (debug_sym) {
3125                                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3126                                         emit_label (acfg, debug_sym);
3127                                 }
3128                         }
3129                 }
3130
3131                 /* 
3132                  * The first plt entry is used to transfer code to the AOT loader. 
3133                  */
3134                 arch_emit_plt_entry (acfg, i);
3135
3136                 if (debug_sym) {
3137                         emit_symbol_size (acfg, debug_sym, ".");
3138                         g_free (debug_sym);
3139                 }
3140         }
3141
3142         emit_symbol_size (acfg, acfg->plt_symbol, ".");
3143
3144         sprintf (symbol, "plt_end");
3145         emit_global (acfg, symbol, TRUE);
3146         emit_label (acfg, symbol);
3147
3148         g_hash_table_destroy (cache);
3149 }
3150
3151 static G_GNUC_UNUSED void
3152 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code, 
3153                                  guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3154 {
3155         char start_symbol [256];
3156         char symbol [256];
3157         guint32 buf_size;
3158         MonoJumpInfo *patch_info;
3159         guint8 *buf, *p;
3160         GPtrArray *patches;
3161
3162         /* Emit code */
3163
3164         sprintf (start_symbol, "%s", name);
3165
3166         emit_section_change (acfg, ".text", 0);
3167         emit_global (acfg, start_symbol, TRUE);
3168         emit_alignment (acfg, 16);
3169         emit_label (acfg, start_symbol);
3170
3171         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3172         emit_label (acfg, symbol);
3173
3174         /* 
3175          * The code should access everything through the GOT, so we pass
3176          * TRUE here.
3177          */
3178         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3179
3180         emit_symbol_size (acfg, start_symbol, ".");
3181
3182         /* Emit info */
3183
3184         /* Sort relocations */
3185         patches = g_ptr_array_new ();
3186         for (patch_info = ji; patch_info; patch_info = patch_info->next)
3187                 if (patch_info->type != MONO_PATCH_INFO_NONE)
3188                         g_ptr_array_add (patches, patch_info);
3189         g_ptr_array_sort (patches, compare_patches);
3190
3191         buf_size = patches->len * 128 + 128;
3192         buf = g_malloc (buf_size);
3193         p = buf;
3194
3195         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3196         g_assert (p - buf < buf_size);
3197
3198         sprintf (symbol, "%s_p", name);
3199
3200         emit_section_change (acfg, ".text", 0);
3201         emit_global (acfg, symbol, FALSE);
3202         emit_label (acfg, symbol);
3203                 
3204         emit_bytes (acfg, buf, p - buf);
3205
3206         /* Emit debug info */
3207         if (unwind_ops) {
3208                 char symbol2 [256];
3209
3210                 sprintf (symbol, "%s", name);
3211                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3212
3213                 if (acfg->dwarf)
3214                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3215         }
3216 }
3217
3218 static void
3219 emit_trampolines (MonoAotCompile *acfg)
3220 {
3221         char symbol [256];
3222         int i, tramp_got_offset;
3223         MonoAotTrampoline ntype;
3224 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3225         int tramp_type;
3226         guint32 code_size;
3227         MonoJumpInfo *ji;
3228         guint8 *code;
3229         GSList *unwind_ops;
3230 #endif
3231
3232         if (!acfg->aot_opts.full_aot)
3233                 return;
3234         
3235         g_assert (acfg->image->assembly);
3236
3237         /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3238         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3239 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3240                 /*
3241                  * Emit the generic trampolines.
3242                  *
3243                  * We could save some code by treating the generic trampolines as a wrapper
3244                  * method, but that approach has its own complexities, so we choose the simpler
3245                  * method.
3246                  */
3247                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3248                         code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3249
3250                         /* Emit trampoline code */
3251
3252                         sprintf (symbol, "generic_trampoline_%d", tramp_type);
3253
3254                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3255                 }
3256
3257                 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3258                 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3259 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3260                 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3261                 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3262                 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3263                 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3264 #endif
3265
3266                 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3267                 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3268
3269                 /* Emit the exception related code pieces */
3270                 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3271                 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3272                 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3273                 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3274                 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3275                 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3276                 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3277                 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3278                 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3279                 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3280                 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3281                 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3282
3283 #if defined(TARGET_AMD64)
3284                 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3285                 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3286 #endif
3287
3288                 for (i = 0; i < 128; ++i) {
3289                         int offset;
3290
3291                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3292                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3293                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3294                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3295
3296                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3297                         code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3298                         sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3299                         emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3300                 }
3301
3302                 {
3303                         GSList *l;
3304
3305                         /* delegate_invoke_impl trampolines */
3306                         l = mono_arch_get_delegate_invoke_impls ();
3307                         while (l) {
3308                                 MonoAotTrampInfo *info = l->data;
3309
3310                                 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3311                                 l = l->next;
3312                         }
3313                 }
3314
3315 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3316
3317                 /* Emit trampolines which are numerous */
3318
3319                 /*
3320                  * These include the following:
3321                  * - specific trampolines
3322                  * - static rgctx invoke trampolines
3323                  * - imt thunks
3324                  * These trampolines have the same code, they are parameterized by GOT 
3325                  * slots. 
3326                  * They are defined in this file, in the arch_... routines instead of
3327                  * in tramp-<ARCH>.c, since it is easier to do it this way.
3328                  */
3329
3330                 /*
3331                  * When running in aot-only mode, we can't create specific trampolines at 
3332                  * runtime, so we create a few, and save them in the AOT file. 
3333                  * Normal trampolines embed their argument as a literal inside the 
3334                  * trampoline code, we can't do that here, so instead we embed an offset
3335                  * which needs to be added to the trampoline address to get the address of
3336                  * the GOT slot which contains the argument value.
3337                  * The generated trampolines jump to the generic trampolines using another
3338                  * GOT slot, which will be setup by the AOT loader to point to the 
3339                  * generic trampoline code of the given type.
3340                  */
3341
3342                 /*
3343                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3344                  * each class).
3345                  */
3346
3347                 emit_section_change (acfg, ".text", 0);
3348
3349                 tramp_got_offset = acfg->got_offset;
3350
3351                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3352                         switch (ntype) {
3353                         case MONO_AOT_TRAMP_SPECIFIC:
3354                                 sprintf (symbol, "specific_trampolines");
3355                                 break;
3356                         case MONO_AOT_TRAMP_STATIC_RGCTX:
3357                                 sprintf (symbol, "static_rgctx_trampolines");
3358                                 break;
3359                         case MONO_AOT_TRAMP_IMT_THUNK:
3360                                 sprintf (symbol, "imt_thunks");
3361                                 break;
3362                         default:
3363                                 g_assert_not_reached ();
3364                         }
3365
3366                         emit_global (acfg, symbol, TRUE);
3367                         emit_alignment (acfg, 16);
3368                         emit_label (acfg, symbol);
3369
3370                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3371
3372                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3373                                 int tramp_size = 0;
3374
3375                                 switch (ntype) {
3376                                 case MONO_AOT_TRAMP_SPECIFIC:
3377                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3378                                         tramp_got_offset += 2;
3379                                 break;
3380                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
3381                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
3382                                         tramp_got_offset += 2;
3383                                         break;
3384                                 case MONO_AOT_TRAMP_IMT_THUNK:
3385                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3386                                         tramp_got_offset += 1;
3387                                         break;
3388                                 default:
3389                                         g_assert_not_reached ();
3390                                 }
3391
3392                                 if (!acfg->trampoline_size [ntype]) {
3393                                         g_assert (tramp_size);
3394                                         acfg->trampoline_size [ntype] = tramp_size;
3395                                 }
3396                         }
3397                 }
3398
3399                 /* Reserve some entries at the end of the GOT for our use */
3400                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3401         }
3402
3403         acfg->got_offset += acfg->num_trampoline_got_entries;
3404 }
3405
3406 static gboolean
3407 str_begins_with (const char *str1, const char *str2)
3408 {
3409         int len = strlen (str2);
3410         return strncmp (str1, str2, len) == 0;
3411 }
3412
3413 static void
3414 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3415 {
3416         gchar **args, **ptr;
3417
3418         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3419         for (ptr = args; ptr && *ptr; ptr ++) {
3420                 const char *arg = *ptr;
3421
3422                 if (str_begins_with (arg, "outfile=")) {
3423                         opts->outfile = g_strdup (arg + strlen ("outfile="));
3424                 } else if (str_begins_with (arg, "save-temps")) {
3425                         opts->save_temps = TRUE;
3426                 } else if (str_begins_with (arg, "keep-temps")) {
3427                         opts->save_temps = TRUE;
3428                 } else if (str_begins_with (arg, "write-symbols")) {
3429                         opts->write_symbols = TRUE;
3430                 } else if (str_begins_with (arg, "metadata-only")) {
3431                         opts->metadata_only = TRUE;
3432                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3433                         opts->bind_to_runtime_version = TRUE;
3434                 } else if (str_begins_with (arg, "full")) {
3435                         opts->full_aot = TRUE;
3436                 } else if (str_begins_with (arg, "threads=")) {
3437                         opts->nthreads = atoi (arg + strlen ("threads="));
3438                 } else if (str_begins_with (arg, "static")) {
3439                         opts->static_link = TRUE;
3440                         opts->no_dlsym = TRUE;
3441                 } else if (str_begins_with (arg, "asmonly")) {
3442                         opts->asm_only = TRUE;
3443                 } else if (str_begins_with (arg, "asmwriter")) {
3444                         opts->asm_writer = TRUE;
3445                 } else if (str_begins_with (arg, "nodebug")) {
3446                         opts->nodebug = TRUE;
3447                 } else if (str_begins_with (arg, "ntrampolines=")) {
3448                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3449                 } else if (str_begins_with (arg, "tool-prefix=")) {
3450                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
3451                 } else {
3452                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3453                         exit (1);
3454                 }
3455         }
3456
3457         g_strfreev (args);
3458 }
3459
3460 static void
3461 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3462 {
3463         MonoMethod *method = (MonoMethod*)key;
3464         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3465         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3466         MonoAotCompile *acfg = user_data;
3467
3468         new_ji->image = ji->image;
3469         new_ji->token = ji->token;
3470         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3471 }
3472
3473 static gboolean
3474 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
3475 {
3476         if (klass->type_token)
3477                 return TRUE;
3478         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3479                 return TRUE;
3480         if (klass->rank)
3481                 return can_encode_class (acfg, klass->element_class);
3482         return FALSE;
3483 }
3484
3485 static gboolean
3486 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3487 {
3488         switch (patch_info->type) {
3489         case MONO_PATCH_INFO_METHOD:
3490         case MONO_PATCH_INFO_METHODCONST: {
3491                 MonoMethod *method = patch_info->data.method;
3492
3493                 if (method->wrapper_type) {
3494                         switch (method->wrapper_type) {
3495                         case MONO_WRAPPER_NONE:
3496                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3497                         case MONO_WRAPPER_XDOMAIN_INVOKE:
3498                         case MONO_WRAPPER_STFLD:
3499                         case MONO_WRAPPER_LDFLD:
3500                         case MONO_WRAPPER_LDFLDA:
3501                         case MONO_WRAPPER_LDFLD_REMOTE:
3502                         case MONO_WRAPPER_STFLD_REMOTE:
3503                         case MONO_WRAPPER_STELEMREF:
3504                         case MONO_WRAPPER_ISINST:
3505                         case MONO_WRAPPER_PROXY_ISINST:
3506                         case MONO_WRAPPER_ALLOC:
3507                         case MONO_WRAPPER_REMOTING_INVOKE:
3508                         case MONO_WRAPPER_UNKNOWN:
3509                                 break;
3510                         default:
3511                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3512                                 return FALSE;
3513                         }
3514                 } else {
3515                         if (!method->token) {
3516                                 /* The method is part of a constructed type like Int[,].Set (). */
3517                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
3518                                         if (method->klass->rank)
3519                                                 return TRUE;
3520                                         return FALSE;
3521                                 }
3522                         }
3523                 }
3524                 break;
3525         }
3526         case MONO_PATCH_INFO_VTABLE:
3527         case MONO_PATCH_INFO_CLASS_INIT:
3528         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3529         case MONO_PATCH_INFO_CLASS:
3530         case MONO_PATCH_INFO_IID:
3531         case MONO_PATCH_INFO_ADJUSTED_IID:
3532                 if (!can_encode_class (acfg, patch_info->data.klass)) {
3533                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3534                         return FALSE;
3535                 }
3536                 break;
3537         case MONO_PATCH_INFO_RGCTX_FETCH: {
3538                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3539
3540                 if (!can_encode_patch (acfg, entry->data))
3541                         return FALSE;
3542                 break;
3543         }
3544         default:
3545                 break;
3546         }
3547
3548         return TRUE;
3549 }
3550
3551 static void
3552 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3553
3554 /*
3555  * compile_method:
3556  *
3557  *   AOT compile a given method.
3558  * This function might be called by multiple threads, so it must be thread-safe.
3559  */
3560 static void
3561 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3562 {
3563         MonoCompile *cfg;
3564         MonoJumpInfo *patch_info;
3565         gboolean skip;
3566         int index;
3567         MonoMethod *wrapped;
3568
3569         if (acfg->aot_opts.metadata_only)
3570                 return;
3571
3572         mono_acfg_lock (acfg);
3573         index = get_method_index (acfg, method);
3574         mono_acfg_unlock (acfg);
3575
3576         /* fixme: maybe we can also precompile wrapper methods */
3577         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3578                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3579                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3580                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3581                 return;
3582         }
3583
3584         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3585                 return;
3586
3587         wrapped = mono_marshal_method_from_wrapper (method);
3588         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3589                 // FIXME: The wrapper should be generic too, but it is not
3590                 return;
3591
3592         InterlockedIncrement (&acfg->stats.mcount);
3593
3594 #if 0
3595         if (method->is_generic || method->klass->generic_container) {
3596                 InterlockedIncrement (&acfg->stats.genericcount);
3597                 return;
3598         }
3599 #endif
3600
3601         //acfg->aot_opts.print_skipped_methods = TRUE;
3602
3603         /*
3604          * Since these methods are the only ones which are compiled with
3605          * AOT support, and they are not used by runtime startup/shutdown code,
3606          * the runtime will not see AOT methods during AOT compilation,so it
3607          * does not need to support them by creating a fake GOT etc.
3608          */
3609         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3610         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3611                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3612                 InterlockedIncrement (&acfg->stats.genericcount);
3613                 return;
3614         }
3615         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3616                 /* Let the exception happen at runtime */
3617                 return;
3618         }
3619
3620         if (cfg->disable_aot) {
3621                 if (acfg->aot_opts.print_skipped_methods)
3622                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3623                 InterlockedIncrement (&acfg->stats.ocount);
3624                 mono_destroy_compile (cfg);
3625                 return;
3626         }
3627
3628         /* Nullify patches which need no aot processing */
3629         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3630                 switch (patch_info->type) {
3631                 case MONO_PATCH_INFO_LABEL:
3632                 case MONO_PATCH_INFO_BB:
3633                         patch_info->type = MONO_PATCH_INFO_NONE;
3634                         break;
3635                 default:
3636                         break;
3637                 }
3638         }
3639
3640         /* Collect method->token associations from the cfg */
3641         mono_acfg_lock (acfg);
3642         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3643         mono_acfg_unlock (acfg);
3644
3645         /*
3646          * Check for absolute addresses.
3647          */
3648         skip = FALSE;
3649         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3650                 switch (patch_info->type) {
3651                 case MONO_PATCH_INFO_ABS:
3652                         /* unable to handle this */
3653                         skip = TRUE;    
3654                         break;
3655                 default:
3656                         break;
3657                 }
3658         }
3659
3660         if (skip) {
3661                 if (acfg->aot_opts.print_skipped_methods)
3662                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3663                 InterlockedIncrement (&acfg->stats.abscount);
3664                 mono_destroy_compile (cfg);
3665                 return;
3666         }
3667
3668         /* Lock for the rest of the code */
3669         mono_acfg_lock (acfg);
3670
3671         /*
3672          * Check for methods/klasses we can't encode.
3673          */
3674         skip = FALSE;
3675         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3676                 if (!can_encode_patch (acfg, patch_info))
3677                         skip = TRUE;
3678         }
3679
3680         if (skip) {
3681                 if (acfg->aot_opts.print_skipped_methods)
3682                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3683                 acfg->stats.ocount++;
3684                 mono_destroy_compile (cfg);
3685                 mono_acfg_unlock (acfg);
3686                 return;
3687         }
3688
3689         /* Adds generic instances referenced by this method */
3690         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3691                 switch (patch_info->type) {
3692                 case MONO_PATCH_INFO_METHOD: {
3693                         MonoMethod *m = patch_info->data.method;
3694                         if (m->is_inflated) {
3695                                 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3696                                           mono_method_is_generic_sharable_impl (m, FALSE)) &&
3697                                         !method_has_type_vars (m)) {
3698                                         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3699                                                 if (acfg->aot_opts.full_aot)
3700                                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
3701                                         } else {
3702                                                 add_extra_method (acfg, m);
3703                                         }
3704                                 }
3705                                 add_generic_class (acfg, m->klass);
3706                         }
3707                         break;
3708                 }
3709                 case MONO_PATCH_INFO_VTABLE: {
3710                         MonoClass *klass = patch_info->data.klass;
3711
3712                         if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
3713                                 add_generic_class (acfg, klass);
3714                         break;
3715                 }
3716                 default:
3717                         break;
3718                 }
3719         }
3720
3721         /* Determine whenever the method has GOT slots */
3722         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3723                 switch (patch_info->type) {
3724                 case MONO_PATCH_INFO_GOT_OFFSET:
3725                 case MONO_PATCH_INFO_NONE:
3726                         break;
3727                 case MONO_PATCH_INFO_IMAGE:
3728                         /* The assembly is stored in GOT slot 0 */
3729                         if (patch_info->data.image != acfg->image)
3730                                 cfg->has_got_slots = TRUE;
3731                         break;
3732                 default:
3733                         if (!is_plt_patch (patch_info))
3734                                 cfg->has_got_slots = TRUE;
3735                         break;
3736                 }
3737         }
3738
3739         if (!cfg->has_got_slots)
3740                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3741
3742         /* Make a copy of the patch info which is in the mempool */
3743         {
3744                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3745
3746                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3747                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3748
3749                         if (!patches)
3750                                 patches = new_patch_info;
3751                         else
3752                                 patches_end->next = new_patch_info;
3753                         patches_end = new_patch_info;
3754                 }
3755                 cfg->patch_info = patches;
3756         }
3757         /* Make a copy of the unwind info */
3758         {
3759                 GSList *l, *unwind_ops;
3760                 MonoUnwindOp *op;
3761
3762                 unwind_ops = NULL;
3763                 for (l = cfg->unwind_ops; l; l = l->next) {
3764                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3765                         memcpy (op, l->data, sizeof (MonoUnwindOp));
3766                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3767                 }
3768                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3769         }
3770         /* Make a copy of the argument/local info */
3771         {
3772                 MonoInst **args, **locals;
3773                 MonoMethodSignature *sig;
3774                 MonoMethodHeader *header;
3775                 int i;
3776                 
3777                 sig = mono_method_signature (method);
3778                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3779                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3780                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3781                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3782                 }
3783                 cfg->args = args;
3784
3785                 header = mono_method_get_header (method);
3786                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3787                 for (i = 0; i < header->num_locals; ++i) {
3788                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3789                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3790                 }
3791                 cfg->locals = locals;
3792         }
3793
3794         /* Free some fields used by cfg to conserve memory */
3795         mono_mempool_destroy (cfg->mempool);
3796         cfg->mempool = NULL;
3797         g_free (cfg->varinfo);
3798         cfg->varinfo = NULL;
3799         g_free (cfg->vars);
3800         cfg->vars = NULL;
3801         if (cfg->rs) {
3802                 mono_regstate_free (cfg->rs);
3803                 cfg->rs = NULL;
3804         }
3805
3806         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
3807
3808         while (index >= acfg->cfgs_size) {
3809                 MonoCompile **new_cfgs;
3810                 int new_size;
3811
3812                 new_size = acfg->cfgs_size * 2;
3813                 new_cfgs = g_new0 (MonoCompile*, new_size);
3814                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3815                 g_free (acfg->cfgs);
3816                 acfg->cfgs = new_cfgs;
3817                 acfg->cfgs_size = new_size;
3818         }
3819         acfg->cfgs [index] = cfg;
3820
3821         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3822
3823         /*
3824         if (cfg->orig_method->wrapper_type)
3825                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3826         */
3827
3828         mono_acfg_unlock (acfg);
3829
3830         InterlockedIncrement (&acfg->stats.ccount);
3831 }
3832  
3833 static void
3834 compile_thread_main (gpointer *user_data)
3835 {
3836         MonoDomain *domain = user_data [0];
3837         MonoAotCompile *acfg = user_data [1];
3838         GPtrArray *methods = user_data [2];
3839         int i;
3840
3841         mono_thread_attach (domain);
3842
3843         for (i = 0; i < methods->len; ++i)
3844                 compile_method (acfg, g_ptr_array_index (methods, i));
3845 }
3846
3847 static void
3848 load_profile_files (MonoAotCompile *acfg)
3849 {
3850         FILE *infile;
3851         char *tmp;
3852         int file_index, res, method_index, i;
3853         char ver [256];
3854         guint32 token;
3855         GList *unordered;
3856
3857         file_index = 0;
3858         while (TRUE) {
3859                 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);
3860
3861                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3862                         g_free (tmp);
3863                         break;
3864                 }
3865
3866                 infile = fopen (tmp, "r");
3867                 g_assert (infile);
3868
3869                 printf ("Using profile data file '%s'\n", tmp);
3870                 g_free (tmp);
3871
3872                 file_index ++;
3873
3874                 res = fscanf (infile, "%32s\n", ver);
3875                 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3876                         printf ("Profile file has wrong version or invalid.\n");
3877                         fclose (infile);
3878                         continue;
3879                 }
3880
3881                 while (TRUE) {
3882                         res = fscanf (infile, "%d\n", &token);
3883                         if (res < 1)
3884                                 break;
3885
3886                         method_index = mono_metadata_token_index (token) - 1;
3887
3888                         if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3889                                 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3890                 }
3891                 fclose (infile);
3892         }
3893
3894         /* Add missing methods */
3895         unordered = NULL;
3896         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3897                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3898                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3899         }
3900         unordered = g_list_reverse (unordered);
3901         if (acfg->method_order)
3902                 g_list_last (acfg->method_order)->next = unordered;
3903         else
3904                 acfg->method_order = unordered;
3905 }
3906
3907 static void
3908 emit_code (MonoAotCompile *acfg)
3909 {
3910         int i;
3911         char symbol [256];
3912         GList *l;
3913
3914 #if defined(TARGET_POWERPC64)
3915         sprintf (symbol, ".Lgot_addr");
3916         emit_section_change (acfg, ".text", 0);
3917         emit_alignment (acfg, 8);
3918         emit_label (acfg, symbol);
3919         emit_pointer (acfg, acfg->got_symbol);
3920 #endif
3921
3922         sprintf (symbol, "methods");
3923         emit_section_change (acfg, ".text", 0);
3924         emit_global (acfg, symbol, TRUE);
3925         emit_alignment (acfg, 8);
3926         emit_label (acfg, symbol);
3927
3928         /* 
3929          * Emit some padding so the local symbol for the first method doesn't have the
3930          * same address as 'methods'.
3931          */
3932         emit_zero_bytes (acfg, 16);
3933
3934         for (l = acfg->method_order; l != NULL; l = l->next) {
3935                 i = GPOINTER_TO_UINT (l->data);
3936
3937                 if (acfg->cfgs [i])
3938                         emit_method_code (acfg, acfg->cfgs [i]);
3939         }
3940
3941         sprintf (symbol, "methods_end");
3942         emit_section_change (acfg, ".text", 0);
3943         emit_global (acfg, symbol, FALSE);
3944         emit_alignment (acfg, 8);
3945         emit_label (acfg, symbol);
3946
3947         sprintf (symbol, "method_offsets");
3948         emit_section_change (acfg, ".text", 1);
3949         emit_global (acfg, symbol, FALSE);
3950         emit_alignment (acfg, 8);
3951         emit_label (acfg, symbol);
3952
3953         for (i = 0; i < acfg->nmethods; ++i) {
3954                 if (acfg->cfgs [i]) {
3955                         sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
3956                         emit_symbol_diff (acfg, symbol, "methods", 0);
3957                 } else {
3958                         emit_int32 (acfg, 0xffffffff);
3959                 }
3960         }
3961         emit_line (acfg);
3962 }
3963
3964 static void
3965 emit_info (MonoAotCompile *acfg)
3966 {
3967         int i;
3968         char symbol [256];
3969         GList *l;
3970
3971         /* Emit method info */
3972         sprintf (symbol, "method_info");
3973         emit_section_change (acfg, ".text", 1);
3974         emit_global (acfg, symbol, FALSE);
3975         emit_alignment (acfg, 8);
3976         emit_label (acfg, symbol);
3977
3978         /* To reduce size of generated assembly code */
3979         sprintf (symbol, "mi");
3980         emit_label (acfg, symbol);
3981
3982         for (l = acfg->method_order; l != NULL; l = l->next) {
3983                 i = GPOINTER_TO_UINT (l->data);
3984
3985                 if (acfg->cfgs [i])
3986                         emit_method_info (acfg, acfg->cfgs [i]);
3987         }
3988
3989         sprintf (symbol, "method_info_offsets");
3990         emit_section_change (acfg, ".text", 1);
3991         emit_global (acfg, symbol, FALSE);
3992         emit_alignment (acfg, 8);
3993         emit_label (acfg, symbol);
3994
3995         for (i = 0; i < acfg->nmethods; ++i) {
3996                 if (acfg->cfgs [i]) {
3997                         sprintf (symbol, "%sm_%x_p", acfg->temp_prefix, i);
3998                         emit_symbol_diff (acfg, symbol, "mi", 0);
3999                 } else {
4000                         emit_int32 (acfg, 0);
4001                 }
4002         }
4003         emit_line (acfg);
4004 }
4005
4006 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4007
4008 /*
4009  * mono_aot_str_hash:
4010  *
4011  * Hash function for strings which we use to hash strings for things which are
4012  * saved in the AOT image, since g_str_hash () can change.
4013  */
4014 guint
4015 mono_aot_str_hash (gconstpointer v1)
4016 {
4017         /* Same as g_str_hash () in glib */
4018         char *p = (char *) v1;
4019         guint hash = *p;
4020
4021         while (*p++) {
4022                 if (*p)
4023                         hash = (hash << 5) - hash + *p;
4024         }
4025
4026         return hash;
4027
4028
4029 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4030 #define mix(a,b,c) { \
4031         a -= c;  a ^= rot(c, 4);  c += b; \
4032         b -= a;  b ^= rot(a, 6);  a += c; \
4033         c -= b;  c ^= rot(b, 8);  b += a; \
4034         a -= c;  a ^= rot(c,16);  c += b; \
4035         b -= a;  b ^= rot(a,19);  a += c; \
4036         c -= b;  c ^= rot(b, 4);  b += a; \
4037 }
4038 #define final(a,b,c) { \
4039         c ^= b; c -= rot(b,14); \
4040         a ^= c; a -= rot(c,11); \
4041         b ^= a; b -= rot(a,25); \
4042         c ^= b; c -= rot(b,16); \
4043         a ^= c; a -= rot(c,4);  \
4044         b ^= a; b -= rot(a,14); \
4045         c ^= b; c -= rot(b,24); \
4046 }
4047
4048 static guint
4049 mono_aot_type_hash (MonoType *t1)
4050 {
4051         guint hash = t1->type;
4052
4053         hash |= t1->byref << 6; /* do not collide with t1->type values */
4054         switch (t1->type) {
4055         case MONO_TYPE_VALUETYPE:
4056         case MONO_TYPE_CLASS:
4057         case MONO_TYPE_SZARRAY:
4058                 /* check if the distribution is good enough */
4059                 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
4060         case MONO_TYPE_PTR:
4061                 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
4062         case MONO_TYPE_ARRAY:
4063                 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
4064         case MONO_TYPE_GENERICINST:
4065                 return ((hash << 5) - hash) ^ 0;
4066         }
4067         return hash;
4068 }
4069
4070 /*
4071  * mono_aot_method_hash:
4072  *
4073  *   Return a hash code for methods which only depends on metadata.
4074  */
4075 guint32
4076 mono_aot_method_hash (MonoMethod *method)
4077 {
4078         MonoMethodSignature *sig;
4079         MonoClass *klass;
4080         int i;
4081         int hashes_count;
4082         guint32 *hashes_start, *hashes;
4083         guint32 a, b, c;
4084
4085         /* Similar to the hash in mono_method_get_imt_slot () */
4086
4087         sig = mono_method_signature (method);
4088
4089         hashes_count = sig->param_count + 5;
4090         hashes_start = malloc (hashes_count * sizeof (guint32));
4091         hashes = hashes_start;
4092
4093         /* Some wrappers are assigned to random classes */
4094         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4095                 klass = method->klass;
4096         else
4097                 klass = mono_defaults.object_class;
4098
4099         if (!method->wrapper_type) {
4100                 char *full_name = mono_type_full_name (&klass->byval_arg);
4101
4102                 hashes [0] = mono_aot_str_hash (full_name);
4103                 hashes [1] = 0;
4104                 g_free (full_name);
4105         } else {
4106                 hashes [0] = mono_aot_str_hash (klass->name);
4107                 hashes [1] = mono_aot_str_hash (klass->name_space);
4108         }
4109         hashes [2] = mono_aot_str_hash (method->name);
4110         hashes [3] = method->wrapper_type;
4111         hashes [4] = mono_aot_type_hash (sig->ret);
4112         for (i = 0; i < sig->param_count; i++) {
4113                 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4114         }
4115         
4116         /* Setup internal state */
4117         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4118
4119         /* Handle most of the hashes */
4120         while (hashes_count > 3) {
4121                 a += hashes [0];
4122                 b += hashes [1];
4123                 c += hashes [2];
4124                 mix (a,b,c);
4125                 hashes_count -= 3;
4126                 hashes += 3;
4127         }
4128
4129         /* Handle the last 3 hashes (all the case statements fall through) */
4130         switch (hashes_count) { 
4131         case 3 : c += hashes [2];
4132         case 2 : b += hashes [1];
4133         case 1 : a += hashes [0];
4134                 final (a,b,c);
4135         case 0: /* nothing left to add */
4136                 break;
4137         }
4138         
4139         free (hashes_start);
4140         
4141         return c;
4142 }
4143 #undef rot
4144 #undef mix
4145 #undef final
4146
4147 /*
4148  * mono_aot_wrapper_name:
4149  *
4150  *   Return a string which uniqely identifies the given wrapper method.
4151  */
4152 char*
4153 mono_aot_wrapper_name (MonoMethod *method)
4154 {
4155         char *name, *tmpsig, *klass_desc;
4156
4157         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4158
4159         switch (method->wrapper_type) {
4160         case MONO_WRAPPER_RUNTIME_INVOKE:
4161         case MONO_WRAPPER_DELEGATE_INVOKE:
4162         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
4163         case MONO_WRAPPER_DELEGATE_END_INVOKE:
4164                 /* This is a hack to work around the fact that runtime invoke wrappers get assigned to some random class */
4165                 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4166                 break;
4167         default:
4168                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4169
4170                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4171                 break;
4172         }
4173
4174         g_free (tmpsig);
4175
4176         return name;
4177 }
4178
4179 /*
4180  * mono_aot_tramp_info_create:
4181  *
4182  *   Create a MonoAotTrampInfo structure from the arguments.
4183  */
4184 MonoAotTrampInfo*
4185 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4186 {
4187         MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4188
4189         info->name = (char*)name;
4190         info->code = code;
4191         info->code_size = code_size;
4192
4193         return info;
4194 }
4195
4196 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4197
4198 typedef struct HashEntry {
4199     guint32 key, value, index;
4200         struct HashEntry *next;
4201 } HashEntry;
4202
4203 /*
4204  * emit_extra_methods:
4205  *
4206  * Emit methods which are not in the METHOD table, like wrappers.
4207  */
4208 static void
4209 emit_extra_methods (MonoAotCompile *acfg)
4210 {
4211         int i, table_size, buf_size;
4212         char symbol [256];
4213         guint8 *p, *buf;
4214         guint32 *info_offsets;
4215         guint32 hash;
4216         GPtrArray *table;
4217         HashEntry *entry, *new_entry;
4218         int nmethods, max_chain_length;
4219         int *chain_lengths;
4220
4221         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4222
4223         buf_size = acfg->extra_methods->len * 256 + 256;
4224         p = buf = g_malloc (buf_size);
4225
4226         /* Encode method info */
4227         nmethods = 0;
4228         /* So offsets are > 0 */
4229         *p = 0;
4230         p++;
4231         for (i = 0; i < acfg->extra_methods->len; ++i) {
4232                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4233                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4234                 char *name;
4235
4236                 if (!cfg)
4237                         continue;
4238
4239                 nmethods ++;
4240                 info_offsets [i] = p - buf;
4241
4242                 name = NULL;
4243                 if (method->wrapper_type) {
4244                         /* 
4245                          * We encode some wrappers using their name, since encoding them
4246                          * directly would be difficult. This also avoids creating the wrapper
4247                          * methods at runtime, since they are not needed anyway.
4248                          */
4249                         switch (method->wrapper_type) {
4250                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4251                         case MONO_WRAPPER_SYNCHRONIZED:
4252                                 /* encode_method_ref () can handle these */
4253                                 break;
4254                         case MONO_WRAPPER_RUNTIME_INVOKE:
4255                                 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
4256                                         /* Direct wrapper, encode normally */
4257                                         break;
4258                                 /* Fall through */
4259                         default:
4260                                 name = mono_aot_wrapper_name (method);
4261                                 break;
4262                         }
4263                 }
4264
4265                 if (name) {
4266                         encode_value (1, p, &p);
4267                         encode_value (method->wrapper_type, p, &p);
4268                         strcpy ((char*)p, name);
4269                         p += strlen (name ) + 1;
4270                         g_free (name);
4271                 } else {
4272                         encode_value (0, p, &p);
4273                         encode_method_ref (acfg, method, p, &p);
4274                 }
4275
4276                 g_assert ((p - buf) < buf_size);
4277         }
4278
4279         g_assert ((p - buf) < buf_size);
4280
4281         /* Emit method info */
4282         sprintf (symbol, "extra_method_info");
4283         emit_section_change (acfg, ".text", 1);
4284         emit_global (acfg, symbol, FALSE);
4285         emit_alignment (acfg, 8);
4286         emit_label (acfg, symbol);
4287
4288         emit_bytes (acfg, buf, p - buf);
4289
4290         emit_line (acfg);
4291
4292         /*
4293          * Construct a chained hash table for mapping indexes in extra_method_info to
4294          * method indexes.
4295          */
4296         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4297         table = g_ptr_array_sized_new (table_size);
4298         for (i = 0; i < table_size; ++i)
4299                 g_ptr_array_add (table, NULL);
4300         chain_lengths = g_new0 (int, table_size);
4301         max_chain_length = 0;
4302         for (i = 0; i < acfg->extra_methods->len; ++i) {
4303                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4304                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4305                 guint32 key, value;
4306
4307                 if (!cfg)
4308                         continue;
4309
4310                 key = info_offsets [i];
4311                 value = get_method_index (acfg, method);
4312
4313                 hash = mono_aot_method_hash (method) % table_size;
4314
4315                 chain_lengths [hash] ++;
4316                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
4317
4318                 /* FIXME: Allocate from the mempool */
4319                 new_entry = g_new0 (HashEntry, 1);
4320                 new_entry->key = key;
4321                 new_entry->value = value;
4322
4323                 entry = g_ptr_array_index (table, hash);
4324                 if (entry == NULL) {
4325                         new_entry->index = hash;
4326                         g_ptr_array_index (table, hash) = new_entry;
4327                 } else {
4328                         while (entry->next)
4329                                 entry = entry->next;
4330                         
4331                         entry->next = new_entry;
4332                         new_entry->index = table->len;
4333                         g_ptr_array_add (table, new_entry);
4334                 }
4335         }
4336
4337         //printf ("MAX: %d\n", max_chain_length);
4338
4339         /* Emit the table */
4340         sprintf (symbol, "extra_method_table");
4341         emit_section_change (acfg, ".text", 0);
4342         emit_global (acfg, symbol, FALSE);
4343         emit_alignment (acfg, 8);
4344         emit_label (acfg, symbol);
4345
4346         g_assert (table_size < 65000);
4347         emit_int32 (acfg, table_size);
4348         g_assert (table->len < 65000);
4349         for (i = 0; i < table->len; ++i) {
4350                 HashEntry *entry = g_ptr_array_index (table, i);
4351
4352                 if (entry == NULL) {
4353                         emit_int32 (acfg, 0);
4354                         emit_int32 (acfg, 0);
4355                         emit_int32 (acfg, 0);
4356                 } else {
4357                         g_assert (entry->key > 0);
4358                         emit_int32 (acfg, entry->key);
4359                         emit_int32 (acfg, entry->value);
4360                         if (entry->next)
4361                                 emit_int32 (acfg, entry->next->index);
4362                         else
4363                                 emit_int32 (acfg, 0);
4364                 }
4365         }
4366
4367         /* 
4368          * Emit a table reverse mapping method indexes to their index in extra_method_info.
4369          * This is used by mono_aot_find_jit_info ().
4370          */
4371         sprintf (symbol, "extra_method_info_offsets");
4372         emit_section_change (acfg, ".text", 0);
4373         emit_global (acfg, symbol, FALSE);
4374         emit_alignment (acfg, 8);
4375         emit_label (acfg, symbol);
4376
4377         emit_int32 (acfg, acfg->extra_methods->len);
4378         for (i = 0; i < acfg->extra_methods->len; ++i) {
4379                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4380
4381                 emit_int32 (acfg, get_method_index (acfg, method));
4382                 emit_int32 (acfg, info_offsets [i]);
4383         }
4384 }       
4385
4386 static void
4387 emit_method_order (MonoAotCompile *acfg)
4388 {
4389         int i, index, len;
4390         char symbol [256];
4391         GList *l;
4392
4393         sprintf (symbol, "method_order");
4394         emit_section_change (acfg, ".text", 1);
4395         emit_global (acfg, symbol, FALSE);
4396         emit_alignment (acfg, 8);
4397         emit_label (acfg, symbol);
4398
4399         /* First emit an index table */
4400         index = 0;
4401         len = 0;
4402         for (l = acfg->method_order; l != NULL; l = l->next) {
4403                 i = GPOINTER_TO_UINT (l->data);
4404
4405                 if (acfg->cfgs [i]) {
4406                         if ((index % 1024) == 0) {
4407                                 emit_int32 (acfg, i);
4408                         }
4409
4410                         index ++;
4411                 }
4412
4413                 len ++;
4414         }
4415         emit_int32 (acfg, 0xffffff);
4416
4417         /* Then emit the whole method order */
4418         for (l = acfg->method_order; l != NULL; l = l->next) {
4419                 i = GPOINTER_TO_UINT (l->data);
4420
4421                 if (acfg->cfgs [i]) {
4422                         emit_int32 (acfg, i);
4423                 }
4424         }       
4425         emit_line (acfg);
4426
4427         sprintf (symbol, "method_order_end");
4428         emit_section_change (acfg, ".text", 1);
4429         emit_global (acfg, symbol, FALSE);
4430         emit_label (acfg, symbol);
4431 }
4432
4433 static void
4434 emit_exception_info (MonoAotCompile *acfg)
4435 {
4436         int i;
4437         char symbol [256];
4438
4439         sprintf (symbol, "ex_info");
4440         emit_section_change (acfg, ".text", 1);
4441         emit_global (acfg, symbol, FALSE);
4442         emit_alignment (acfg, 8);
4443         emit_label (acfg, symbol);
4444
4445         /* To reduce size of generated assembly */
4446         sprintf (symbol, "ex");
4447         emit_label (acfg, symbol);
4448
4449         for (i = 0; i < acfg->nmethods; ++i) {
4450                 if (acfg->cfgs [i])
4451                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
4452         }
4453
4454         sprintf (symbol, "ex_info_offsets");
4455         emit_section_change (acfg, ".text", 1);
4456         emit_global (acfg, symbol, FALSE);
4457         emit_alignment (acfg, 8);
4458         emit_label (acfg, symbol);
4459
4460         for (i = 0; i < acfg->nmethods; ++i) {
4461                 if (acfg->cfgs [i]) {
4462                         sprintf (symbol, "%se_%x_p", acfg->temp_prefix, i);
4463                         emit_symbol_diff (acfg, symbol, "ex", 0);
4464                 } else {
4465                         emit_int32 (acfg, 0);
4466                 }
4467         }
4468         emit_line (acfg);
4469 }
4470
4471 static void
4472 emit_unwind_info (MonoAotCompile *acfg)
4473 {
4474         int i;
4475         char symbol [128];
4476
4477         /* 
4478          * The unwind info contains a lot of duplicates so we emit each unique
4479          * entry once, and only store the offset from the start of the table in the
4480          * exception info.
4481          */
4482
4483         sprintf (symbol, "unwind_info");
4484         emit_section_change (acfg, ".text", 1);
4485         emit_alignment (acfg, 8);
4486         emit_label (acfg, symbol);
4487         emit_global (acfg, symbol, FALSE);
4488
4489         for (i = 0; i < acfg->unwind_ops->len; ++i) {
4490                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
4491                 guint8 *unwind_info;
4492                 guint32 unwind_info_len;
4493                 guint8 buf [16];
4494                 guint8 *p;
4495
4496                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
4497
4498                 p = buf;
4499                 encode_value (unwind_info_len, p, &p);
4500                 emit_bytes (acfg, buf, p - buf);
4501                 emit_bytes (acfg, unwind_info, unwind_info_len);
4502
4503                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
4504         }
4505 }
4506
4507 static void
4508 emit_class_info (MonoAotCompile *acfg)
4509 {
4510         int i;
4511         char symbol [256];
4512
4513         sprintf (symbol, "class_info");
4514         emit_section_change (acfg, ".text", 1);
4515         emit_global (acfg, symbol, FALSE);
4516         emit_alignment (acfg, 8);
4517         emit_label (acfg, symbol);
4518
4519         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4520                 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4521
4522         sprintf (symbol, "class_info_offsets");
4523         emit_section_change (acfg, ".text", 1);
4524         emit_global (acfg, symbol, FALSE);
4525         emit_alignment (acfg, 8);
4526         emit_label (acfg, symbol);
4527
4528         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4529                 sprintf (symbol, "%sK_I_%x", acfg->temp_prefix, i);
4530                 emit_symbol_diff (acfg, symbol, "class_info", 0);
4531         }
4532         emit_line (acfg);
4533 }
4534
4535 typedef struct ClassNameTableEntry {
4536         guint32 token, index;
4537         struct ClassNameTableEntry *next;
4538 } ClassNameTableEntry;
4539
4540 static void
4541 emit_class_name_table (MonoAotCompile *acfg)
4542 {
4543         int i, table_size;
4544         guint32 token, hash;
4545         MonoClass *klass;
4546         GPtrArray *table;
4547         char *full_name;
4548         char symbol [256];
4549         ClassNameTableEntry *entry, *new_entry;
4550
4551         /*
4552          * Construct a chained hash table for mapping class names to typedef tokens.
4553          */
4554         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4555         table = g_ptr_array_sized_new (table_size);
4556         for (i = 0; i < table_size; ++i)
4557                 g_ptr_array_add (table, NULL);
4558         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4559                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4560                 klass = mono_class_get (acfg->image, token);
4561                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4562                 hash = mono_aot_str_hash (full_name) % table_size;
4563                 g_free (full_name);
4564
4565                 /* FIXME: Allocate from the mempool */
4566                 new_entry = g_new0 (ClassNameTableEntry, 1);
4567                 new_entry->token = token;
4568
4569                 entry = g_ptr_array_index (table, hash);
4570                 if (entry == NULL) {
4571                         new_entry->index = hash;
4572                         g_ptr_array_index (table, hash) = new_entry;
4573                 } else {
4574                         while (entry->next)
4575                                 entry = entry->next;
4576                         
4577                         entry->next = new_entry;
4578                         new_entry->index = table->len;
4579                         g_ptr_array_add (table, new_entry);
4580                 }
4581         }
4582
4583         /* Emit the table */
4584         sprintf (symbol, "class_name_table");
4585         emit_section_change (acfg, ".text", 0);
4586         emit_global (acfg, symbol, FALSE);
4587         emit_alignment (acfg, 8);
4588         emit_label (acfg, symbol);
4589
4590         /* FIXME: Optimize memory usage */
4591         g_assert (table_size < 65000);
4592         emit_int16 (acfg, table_size);
4593         g_assert (table->len < 65000);
4594         for (i = 0; i < table->len; ++i) {
4595                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4596
4597                 if (entry == NULL) {
4598                         emit_int16 (acfg, 0);
4599                         emit_int16 (acfg, 0);
4600                 } else {
4601                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
4602                         if (entry->next)
4603                                 emit_int16 (acfg, entry->next->index);
4604                         else
4605                                 emit_int16 (acfg, 0);
4606                 }
4607         }
4608 }
4609
4610 static void
4611 emit_image_table (MonoAotCompile *acfg)
4612 {
4613         int i;
4614         char symbol [256];
4615
4616         /*
4617          * The image table is small but referenced in a lot of places.
4618          * So we emit it at once, and reference its elements by an index.
4619          */
4620
4621         sprintf (symbol, "mono_image_table");
4622         emit_section_change (acfg, ".text", 1);
4623         emit_global (acfg, symbol, FALSE);
4624         emit_alignment (acfg, 8);
4625         emit_label (acfg, symbol);
4626
4627         emit_int32 (acfg, acfg->image_table->len);
4628         for (i = 0; i < acfg->image_table->len; i++) {
4629                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4630                 MonoAssemblyName *aname = &image->assembly->aname;
4631
4632                 /* FIXME: Support multi-module assemblies */
4633                 g_assert (image->assembly->image == image);
4634
4635                 emit_string (acfg, image->assembly_name);
4636                 emit_string (acfg, image->guid);
4637                 emit_string (acfg, aname->culture ? aname->culture : "");
4638                 emit_string (acfg, (const char*)aname->public_key_token);
4639
4640                 emit_alignment (acfg, 8);
4641                 emit_int32 (acfg, aname->flags);
4642                 emit_int32 (acfg, aname->major);
4643                 emit_int32 (acfg, aname->minor);
4644                 emit_int32 (acfg, aname->build);
4645                 emit_int32 (acfg, aname->revision);
4646         }
4647 }
4648
4649 static void
4650 emit_got_info (MonoAotCompile *acfg)
4651 {
4652         char symbol [256];
4653         int i, first_plt_got_patch, buf_size;
4654         guint8 *p, *buf;
4655         guint32 *got_info_offsets;
4656
4657         /* Add the patches needed by the PLT to the GOT */
4658         acfg->plt_got_offset_base = acfg->got_offset;
4659         first_plt_got_patch = acfg->got_patches->len;
4660         for (i = 1; i < acfg->plt_offset; ++i) {
4661                 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4662
4663                 g_ptr_array_add (acfg->got_patches, patch_info);
4664         }
4665
4666         acfg->got_offset += acfg->plt_offset;
4667
4668         /**
4669          * FIXME: 
4670          * - optimize offsets table.
4671          * - reduce number of exported symbols.
4672          * - emit info for a klass only once.
4673          * - determine when a method uses a GOT slot which is guaranteed to be already 
4674          *   initialized.
4675          * - clean up and document the code.
4676          * - use String.Empty in class libs.
4677          */
4678
4679         /* Encode info required to decode shared GOT entries */
4680         buf_size = acfg->got_patches->len * 64;
4681         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4682         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
4683         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4684         /* Unused */
4685         if (acfg->plt_offset)
4686                 acfg->plt_got_info_offsets [0] = 0;
4687         for (i = 0; i < acfg->got_patches->len; ++i) {
4688                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
4689
4690                 got_info_offsets [i] = p - buf;
4691                 if (i >= first_plt_got_patch)
4692                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4693                 encode_value (ji->type, p, &p);
4694                 encode_patch (acfg, ji, p, &p);
4695         }
4696
4697         g_assert (p - buf <= buf_size);
4698
4699         acfg->stats.got_info_size = p - buf;
4700
4701         /* Emit got_info table */
4702         sprintf (symbol, "got_info");
4703         emit_section_change (acfg, ".text", 1);
4704         emit_global (acfg, symbol, FALSE);
4705         emit_alignment (acfg, 8);
4706         emit_label (acfg, symbol);
4707
4708         emit_bytes (acfg, buf, p - buf);
4709
4710         /* Emit got_info_offsets table */
4711         sprintf (symbol, "got_info_offsets");
4712         emit_section_change (acfg, ".text", 1);
4713         emit_global (acfg, symbol, FALSE);
4714         emit_alignment (acfg, 8);
4715         emit_label (acfg, symbol);
4716
4717         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
4718         for (i = 0; i < first_plt_got_patch; ++i)
4719                 emit_int32 (acfg, got_info_offsets [i]);
4720
4721         acfg->stats.got_info_offsets_size = acfg->got_patches->len * 4;
4722 }
4723
4724 static void
4725 emit_got (MonoAotCompile *acfg)
4726 {
4727         char symbol [256];
4728
4729         /* Don't make GOT global so accesses to it don't need relocations */
4730         sprintf (symbol, "%s", acfg->got_symbol);
4731         emit_section_change (acfg, ".bss", 0);
4732         emit_alignment (acfg, 8);
4733         emit_local_symbol (acfg, symbol, "got_end", FALSE);
4734         emit_label (acfg, symbol);
4735         if (acfg->got_offset > 0)
4736                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4737
4738         sprintf (symbol, "got_end");
4739         emit_label (acfg, symbol);
4740
4741         sprintf (symbol, "mono_aot_got_addr");
4742         emit_section_change (acfg, ".data", 0);
4743         emit_global (acfg, symbol, FALSE);
4744         emit_alignment (acfg, 8);
4745         emit_label (acfg, symbol);
4746         emit_pointer (acfg, acfg->got_symbol);
4747 }
4748
4749 static void
4750 emit_globals (MonoAotCompile *acfg)
4751 {
4752         char *opts_str;
4753         char *build_info;
4754
4755         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4756
4757         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4758
4759         opts_str = g_strdup_printf ("%d", acfg->opts);
4760         emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4761         g_free (opts_str);
4762
4763         emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4764
4765         if (acfg->aot_opts.bind_to_runtime_version) {
4766                 build_info = mono_get_runtime_build_info ();
4767                 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4768                 g_free (build_info);
4769         } else {
4770                 emit_string_symbol (acfg, "mono_runtime_version", "");
4771         }
4772
4773         /* 
4774          * When static linking, we emit a global which will point to the symbol table.
4775          */
4776         if (acfg->aot_opts.static_link) {
4777                 int i;
4778                 char symbol [256];
4779                 char *p;
4780
4781                 /* Emit a string holding the assembly name */
4782                 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4783
4784                 /* Emit the names */
4785                 for (i = 0; i < acfg->globals->len; ++i) {
4786                         char *name = g_ptr_array_index (acfg->globals, i);
4787
4788                         sprintf (symbol, "name_%d", i);
4789                         emit_section_change (acfg, ".text", 1);
4790                         emit_label (acfg, symbol);
4791                         emit_string (acfg, name);
4792                 }
4793
4794                 /* Emit the globals table */
4795                 sprintf (symbol, "globals");
4796                 emit_section_change (acfg, ".data", 0);
4797                 /* This is not a global, since it is accessed by the init function */
4798                 emit_alignment (acfg, 8);
4799                 emit_label (acfg, symbol);
4800
4801                 for (i = 0; i < acfg->globals->len; ++i) {
4802                         char *name = g_ptr_array_index (acfg->globals, i);
4803
4804                         sprintf (symbol, "name_%d", i);
4805                         emit_pointer (acfg, symbol);
4806
4807                         sprintf (symbol, "%s", name);
4808                         emit_pointer (acfg, symbol);
4809                 }
4810                 /* Null terminate the table */
4811                 emit_int32 (acfg, 0);
4812                 emit_int32 (acfg, 0);
4813
4814                 /* 
4815                  * Emit a global symbol which can be passed by an embedding app to
4816                  * mono_aot_register_module ().
4817                  */
4818 #if defined(__MACH__)
4819                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4820 #else
4821                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4822 #endif
4823
4824                 /* Get rid of characters which cannot occur in symbols */
4825                 p = symbol;
4826                 for (p = symbol; *p; ++p) {
4827                         if (!(isalnum (*p) || *p == '_'))
4828                                 *p = '_';
4829                 }
4830                 acfg->static_linking_symbol = g_strdup (symbol);
4831                 emit_global_inner (acfg, symbol, FALSE);
4832                 emit_alignment (acfg, 8);
4833                 emit_label (acfg, symbol);
4834                 emit_pointer (acfg, "globals");
4835         }
4836 }
4837
4838 static void
4839 emit_mem_end (MonoAotCompile *acfg)
4840 {
4841         char symbol [128];
4842
4843         sprintf (symbol, "mem_end");
4844         emit_section_change (acfg, ".text", 1);
4845         emit_global (acfg, symbol, FALSE);
4846         emit_alignment (acfg, 8);
4847         emit_label (acfg, symbol);
4848 }
4849
4850 /*
4851  * Emit a structure containing all the information not stored elsewhere.
4852  */
4853 static void
4854 emit_file_info (MonoAotCompile *acfg)
4855 {
4856         char symbol [128];
4857         int i;
4858
4859         sprintf (symbol, "mono_aot_file_info");
4860         emit_section_change (acfg, ".data", 0);
4861         emit_alignment (acfg, 8);
4862         emit_label (acfg, symbol);
4863         emit_global (acfg, symbol, FALSE);
4864
4865         /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
4866         emit_int32 (acfg, acfg->plt_got_offset_base);
4867         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4868         emit_int32 (acfg, acfg->plt_offset);
4869         emit_int32 (acfg, acfg->nmethods);
4870
4871         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4872                 emit_int32 (acfg, acfg->num_trampolines [i]);
4873         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4874                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
4875         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4876                 emit_int32 (acfg, acfg->trampoline_size [i]);
4877 }
4878
4879 static void
4880 emit_dwarf_info (MonoAotCompile *acfg)
4881 {
4882 #ifdef EMIT_DWARF_INFO
4883         int i;
4884         char symbol [128], symbol2 [128];
4885
4886         /* DIEs for methods */
4887         for (i = 0; i < acfg->nmethods; ++i) {
4888                 MonoCompile *cfg = acfg->cfgs [i];
4889
4890                 if (!cfg)
4891                         continue;
4892
4893                 sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
4894                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
4895
4896                 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 ()));
4897         }
4898 #endif
4899 }
4900
4901 static void
4902 collect_methods (MonoAotCompile *acfg)
4903 {
4904         int i;
4905         MonoImage *image = acfg->image;
4906
4907         /* Collect methods */
4908         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4909                 MonoMethod *method;
4910                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4911
4912                 method = mono_get_method (acfg->image, token, NULL);
4913
4914                 if (!method) {
4915                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4916                         exit (1);
4917                 }
4918                         
4919                 /* Load all methods eagerly to skip the slower lazy loading code */
4920                 mono_class_setup_methods (method->klass);
4921
4922                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4923                         /* Compile the wrapper instead */
4924                         /* We do this here instead of add_wrappers () because it is easy to do it here */
4925                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4926                         method = wrapper;
4927                 }
4928
4929                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4930                 add_method_with_index (acfg, method, i, FALSE);
4931                 acfg->method_index ++;
4932         }
4933
4934         add_generic_instances (acfg);
4935
4936         if (acfg->aot_opts.full_aot)
4937                 add_wrappers (acfg);
4938 }
4939
4940 static void
4941 compile_methods (MonoAotCompile *acfg)
4942 {
4943         int i, methods_len;
4944
4945         if (acfg->aot_opts.nthreads > 0) {
4946                 GPtrArray *frag;
4947                 int len, j;
4948                 GPtrArray *threads;
4949                 HANDLE handle;
4950                 gpointer *user_data;
4951                 MonoMethod **methods;
4952
4953                 methods_len = acfg->methods->len;
4954
4955                 len = acfg->methods->len / acfg->aot_opts.nthreads;
4956                 g_assert (len > 0);
4957                 /* 
4958                  * Partition the list of methods into fragments, and hand it to threads to
4959                  * process.
4960                  */
4961                 threads = g_ptr_array_new ();
4962                 /* Make a copy since acfg->methods is modified by compile_method () */
4963                 methods = g_new0 (MonoMethod*, methods_len);
4964                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4965                 for (i = 0; i < methods_len; ++i)
4966                         methods [i] = g_ptr_array_index (acfg->methods, i);
4967                 i = 0;
4968                 while (i < methods_len) {
4969                         frag = g_ptr_array_new ();
4970                         for (j = 0; j < len; ++j) {
4971                                 if (i < methods_len) {
4972                                         g_ptr_array_add (frag, methods [i]);
4973                                         i ++;
4974                                 }
4975                         }
4976
4977                         user_data = g_new0 (gpointer, 3);
4978                         user_data [0] = mono_domain_get ();
4979                         user_data [1] = acfg;
4980                         user_data [2] = frag;
4981                         
4982                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4983                         g_ptr_array_add (threads, handle);
4984                 }
4985                 g_free (methods);
4986
4987                 for (i = 0; i < threads->len; ++i) {
4988                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4989                 }
4990         } else {
4991                 methods_len = 0;
4992         }
4993
4994         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4995         for (i = methods_len; i < acfg->methods->len; ++i) {
4996                 /* This can new methods to acfg->methods */
4997                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4998         }
4999 }
5000
5001 static int
5002 compile_asm (MonoAotCompile *acfg)
5003 {
5004         char *command, *objfile;
5005         char *outfile_name, *tmp_outfile_name;
5006         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5007
5008 #if defined(TARGET_AMD64)
5009 #define AS_OPTIONS "--64"
5010 #elif defined(TARGET_POWERPC64)
5011 #define AS_OPTIONS "-a64 -mppc64"
5012 #define LD_OPTIONS "-m elf64ppc"
5013 #elif defined(sparc) && SIZEOF_VOID_P == 8
5014 #define AS_OPTIONS "-xarch=v9"
5015 #else
5016 #define AS_OPTIONS ""
5017 #endif
5018
5019 #ifndef LD_OPTIONS
5020 #define LD_OPTIONS ""
5021 #endif
5022
5023         if (acfg->aot_opts.asm_only) {
5024                 printf ("Output file: '%s'.\n", acfg->tmpfname);
5025                 if (acfg->aot_opts.static_link)
5026                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5027                 return 0;
5028         }
5029
5030         if (acfg->aot_opts.static_link) {
5031                 if (acfg->aot_opts.outfile)
5032                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5033                 else
5034                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
5035         } else {
5036                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5037         }
5038         command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5039         printf ("Executing the native assembler: %s\n", command);
5040         if (system (command) != 0) {
5041                 g_free (command);
5042                 g_free (objfile);
5043                 return 1;
5044         }
5045
5046         g_free (command);
5047
5048         if (acfg->aot_opts.static_link) {
5049                 printf ("Output file: '%s'.\n", objfile);
5050                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5051                 g_free (objfile);
5052                 return 0;
5053         }
5054
5055         if (acfg->aot_opts.outfile)
5056                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5057         else
5058                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5059
5060         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5061
5062 #if defined(sparc)
5063         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5064 #elif defined(__ppc__) && defined(__MACH__)
5065         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5066 #elif defined(PLATFORM_WIN32)
5067         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5068 #else
5069         command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5070 #endif
5071         printf ("Executing the native linker: %s\n", command);
5072         if (system (command) != 0) {
5073                 g_free (tmp_outfile_name);
5074                 g_free (outfile_name);
5075                 g_free (command);
5076                 g_free (objfile);
5077                 return 1;
5078         }
5079
5080         g_free (command);
5081         unlink (objfile);
5082         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5083         printf ("Stripping the binary: %s\n", com);
5084         system (com);
5085         g_free (com);*/
5086
5087 #if defined(TARGET_ARM) && !defined(__MACH__)
5088         /* 
5089          * gas generates 'mapping symbols' each time code and data is mixed, which 
5090          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5091          */
5092         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5093         printf ("Stripping the binary: %s\n", command);
5094         if (system (command) != 0) {
5095                 g_free (tmp_outfile_name);
5096                 g_free (outfile_name);
5097                 g_free (command);
5098                 g_free (objfile);
5099                 return 1;
5100         }
5101 #endif
5102
5103         rename (tmp_outfile_name, outfile_name);
5104
5105         g_free (tmp_outfile_name);
5106         g_free (outfile_name);
5107         g_free (objfile);
5108
5109         if (acfg->aot_opts.save_temps)
5110                 printf ("Retained input file.\n");
5111         else
5112                 unlink (acfg->tmpfname);
5113
5114         return 0;
5115 }
5116
5117 static MonoAotCompile*
5118 acfg_create (MonoAssembly *ass, guint32 opts)
5119 {
5120         MonoImage *image = ass->image;
5121         MonoAotCompile *acfg;
5122
5123         acfg = g_new0 (MonoAotCompile, 1);
5124         acfg->methods = g_ptr_array_new ();
5125         acfg->method_indexes = g_hash_table_new (NULL, NULL);
5126         acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5127         acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5128         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5129         acfg->got_patches = g_ptr_array_new ();
5130         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5131         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5132         acfg->image_hash = g_hash_table_new (NULL, NULL);
5133         acfg->image_table = g_ptr_array_new ();
5134         acfg->globals = g_ptr_array_new ();
5135         acfg->image = image;
5136         acfg->opts = opts;
5137         acfg->mempool = mono_mempool_new ();
5138         acfg->extra_methods = g_ptr_array_new ();
5139         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5140         acfg->unwind_ops = g_ptr_array_new ();
5141         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5142         InitializeCriticalSection (&acfg->mutex);
5143
5144         return acfg;
5145 }
5146
5147 static void
5148 acfg_free (MonoAotCompile *acfg)
5149 {
5150         int i;
5151
5152         img_writer_destroy (acfg->w);
5153         for (i = 0; i < acfg->nmethods; ++i)
5154                 if (acfg->cfgs [i])
5155                         g_free (acfg->cfgs [i]);
5156         g_free (acfg->cfgs);
5157         g_free (acfg->static_linking_symbol);
5158         g_free (acfg->got_symbol);
5159         g_free (acfg->plt_symbol);
5160         g_ptr_array_free (acfg->methods, TRUE);
5161         g_ptr_array_free (acfg->got_patches, TRUE);
5162         g_ptr_array_free (acfg->image_table, TRUE);
5163         g_ptr_array_free (acfg->globals, TRUE);
5164         g_ptr_array_free (acfg->unwind_ops, TRUE);
5165         g_hash_table_destroy (acfg->method_indexes);
5166         g_hash_table_destroy (acfg->plt_offset_to_patch);
5167         g_hash_table_destroy (acfg->patch_to_plt_offset);
5168         g_hash_table_destroy (acfg->patch_to_got_offset);
5169         g_hash_table_destroy (acfg->method_to_cfg);
5170         g_hash_table_destroy (acfg->token_info_hash);
5171         g_hash_table_destroy (acfg->image_hash);
5172         g_hash_table_destroy (acfg->unwind_info_offsets);
5173         g_hash_table_destroy (acfg->method_label_hash);
5174         mono_mempool_destroy (acfg->mempool);
5175         g_free (acfg);
5176 }
5177
5178 int
5179 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5180 {
5181         MonoImage *image = ass->image;
5182         int res;
5183         MonoAotCompile *acfg;
5184         char *outfile_name, *tmp_outfile_name, *p;
5185         TV_DECLARE (atv);
5186         TV_DECLARE (btv);
5187
5188         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5189
5190         acfg = acfg_create (ass, opts);
5191
5192         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5193         acfg->aot_opts.write_symbols = TRUE;
5194         acfg->aot_opts.ntrampolines = 1024;
5195
5196         mono_aot_parse_options (aot_options, &acfg->aot_opts);
5197
5198         //acfg->aot_opts.print_skipped_methods = TRUE;
5199
5200 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5201         if (acfg->aot_opts.full_aot) {
5202                 printf ("--aot=full is not supported on this platform.\n");
5203                 return 1;
5204         }
5205 #endif
5206
5207         if (acfg->aot_opts.static_link)
5208                 acfg->aot_opts.asm_writer = TRUE;
5209
5210         load_profile_files (acfg);
5211
5212         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
5213 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
5214         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
5215 #endif
5216         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
5217
5218         acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
5219         acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
5220
5221         /* Get rid of characters which cannot occur in symbols */
5222         for (p = acfg->got_symbol; *p; ++p) {
5223                 if (!(isalnum (*p) || *p == '_'))
5224                         *p = '_';
5225         }
5226         for (p = acfg->plt_symbol; *p; ++p) {
5227                 if (!(isalnum (*p) || *p == '_'))
5228                         *p = '_';
5229         }
5230
5231         acfg->method_index = 1;
5232
5233         collect_methods (acfg);
5234
5235         acfg->cfgs_size = acfg->methods->len + 32;
5236         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5237
5238         /* PLT offset 0 is reserved for the PLT trampoline */
5239         acfg->plt_offset = 1;
5240
5241         /* GOT offset 0 is reserved for the address of the current assembly */
5242         {
5243                 MonoJumpInfo *ji;
5244
5245                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5246                 ji->type = MONO_PATCH_INFO_IMAGE;
5247                 ji->data.image = acfg->image;
5248
5249                 get_got_offset (acfg, ji);
5250
5251                 /* Slot 1 is reserved for the mscorlib got addr */
5252                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5253                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
5254                 get_got_offset (acfg, ji);
5255         }
5256
5257         TV_GETTIME (atv);
5258
5259         compile_methods (acfg);
5260
5261         TV_GETTIME (btv);
5262
5263         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
5264
5265         TV_GETTIME (atv);
5266
5267         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
5268                 if (acfg->aot_opts.outfile)
5269                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5270                 else
5271                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5272
5273                 /* 
5274                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
5275                  * it might be in another file system so the rename () won't work.
5276                  */
5277                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5278
5279                 acfg->fp = fopen (tmp_outfile_name, "w");
5280                 if (!acfg->fp) {
5281                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
5282                         return 1;
5283                 }
5284
5285                 acfg->w = img_writer_create (acfg->fp, TRUE);
5286                 acfg->use_bin_writer = TRUE;
5287         } else {
5288                 if (acfg->aot_opts.asm_only) {
5289                         if (acfg->aot_opts.outfile)
5290                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5291                         else
5292                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
5293                         acfg->fp = fopen (acfg->tmpfname, "w+");
5294                 } else {
5295                         int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
5296                         acfg->fp = fdopen (i, "w+");
5297                 }
5298                 g_assert (acfg->fp);
5299
5300                 acfg->w = img_writer_create (acfg->fp, FALSE);
5301                 
5302                 tmp_outfile_name = NULL;
5303                 outfile_name = NULL;
5304         }
5305
5306         acfg->temp_prefix = img_writer_get_temp_label_prefix (acfg->w);
5307
5308         if (!acfg->aot_opts.nodebug)
5309                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, FALSE);
5310
5311         img_writer_emit_start (acfg->w);
5312
5313         if (acfg->dwarf)
5314                 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
5315
5316         emit_code (acfg);
5317
5318         emit_info (acfg);
5319
5320         emit_extra_methods (acfg);
5321
5322         emit_method_order (acfg);
5323
5324         emit_trampolines (acfg);
5325
5326         emit_class_name_table (acfg);
5327
5328         emit_got_info (acfg);
5329
5330         emit_exception_info (acfg);
5331
5332         emit_unwind_info (acfg);
5333
5334         emit_class_info (acfg);
5335
5336         emit_plt (acfg);
5337
5338         emit_image_table (acfg);
5339
5340         emit_got (acfg);
5341
5342         emit_file_info (acfg);
5343
5344         emit_globals (acfg);
5345
5346         if (acfg->dwarf) {
5347                 emit_dwarf_info (acfg);
5348                 mono_dwarf_writer_close (acfg->dwarf);
5349         }
5350
5351         emit_mem_end (acfg);
5352
5353         TV_GETTIME (btv);
5354
5355         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
5356
5357         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)));
5358
5359         TV_GETTIME (atv);
5360         res = img_writer_emit_writeout (acfg->w);
5361         if (res != 0) {
5362                 acfg_free (acfg);
5363                 return res;
5364         }
5365         if (acfg->use_bin_writer) {
5366                 int err = rename (tmp_outfile_name, outfile_name);
5367
5368                 if (err) {
5369                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
5370                         return 1;
5371                 }
5372         } else {
5373                 res = compile_asm (acfg);
5374                 if (res != 0) {
5375                         acfg_free (acfg);
5376                         return res;
5377                 }
5378         }
5379         TV_GETTIME (btv);
5380         acfg->stats.link_time = TV_ELAPSED (atv, btv);
5381
5382         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);
5383         if (acfg->stats.genericcount)
5384                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
5385         if (acfg->stats.abscount)
5386                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
5387         if (acfg->stats.lmfcount)
5388                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
5389         if (acfg->stats.ocount)
5390                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
5391         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);
5392         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
5393
5394         /*
5395         printf ("GOT slot distribution:\n");
5396         for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
5397                 if (acfg->stats.got_slot_types [i])
5398                         printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
5399         */
5400
5401         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);
5402
5403         acfg_free (acfg);
5404         
5405         return 0;
5406 }
5407  
5408 /*
5409  * Support for emitting debug info for JITted code.
5410  *
5411  *   This works as follows:
5412  * - the runtime writes out an xdb.s file containing DWARF debug info.
5413  * - the user calls a gdb macro
5414  * - the macro compiles and loads this shared library using add-symbol-file.
5415  *
5416  * This is based on the xdebug functionality in the Kaffe Java VM.
5417  * 
5418  * We emit assembly code instead of using the ELF writer, so we can emit debug info
5419  * incrementally as each method is JITted, and the debugger doesn't have to call
5420  * into the runtime to emit the shared library, which would cause all kinds of
5421  * complications, like threading issues, and the fact that the ELF writer's
5422  * emit_writeout () function cannot be called more than once.
5423  */
5424
5425 /* The recommended gdb macro is: */
5426 /*
5427   define xdb
5428   shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
5429   add-symbol-file xdb.so 0
5430   end
5431 */
5432
5433 static MonoDwarfWriter *xdebug_writer;
5434 static FILE *xdebug_fp;
5435
5436 void
5437 mono_xdebug_init (void)
5438 {
5439         FILE *il_file;
5440         MonoImageWriter *w;
5441
5442         unlink ("xdb.s");
5443         xdebug_fp = fopen ("xdb.s", "w");
5444
5445         w = img_writer_create (xdebug_fp, FALSE);
5446
5447         img_writer_emit_start (w);
5448
5449         /* This file will contain the IL code for methods which don't have debug info */
5450         il_file = fopen ("xdb.il", "w");
5451
5452         xdebug_writer = mono_dwarf_writer_create (w, il_file, TRUE);
5453
5454         /* Emit something so the file has a text segment */
5455         img_writer_emit_section_change (w, ".text", 0);
5456         img_writer_emit_string (w, "");
5457
5458         mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
5459 }
5460
5461 /*
5462  * mono_save_xdebug_info:
5463  *
5464  *   Emit debugging info for METHOD into an assembly file which can be assembled
5465  * and loaded into gdb to provide debugging info for JITted code.
5466  * LOCKING: Acquires the loader lock.
5467  */
5468 void
5469 mono_save_xdebug_info (MonoCompile *cfg)
5470 {
5471         if (!xdebug_writer)
5472                 return;
5473
5474         mono_loader_lock ();
5475         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 ()));
5476         fflush (xdebug_fp);
5477         mono_loader_unlock ();
5478 }
5479
5480 /*
5481  * mono_save_trampoline_xdebug_info:
5482  *
5483  *   Same as mono_save_xdebug_info, but for trampolines.
5484  * LOCKING: Acquires the loader lock.
5485  */
5486 void
5487 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
5488 {
5489         if (!xdebug_writer)
5490                 return;
5491
5492         mono_loader_lock ();
5493         mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
5494         fflush (xdebug_fp);
5495         mono_loader_unlock ();
5496 }
5497
5498 #else
5499
5500 /* AOT disabled */
5501
5502 int
5503 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5504 {
5505         return 0;
5506 }
5507
5508 void
5509 mono_xdebug_init (void)
5510 {
5511 }
5512
5513 void
5514 mono_save_xdebug_info (MonoCompile *cfg)
5515 {
5516 }
5517
5518 void
5519 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
5520 {
5521 }
5522
5523 #endif