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