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