Fix mono_mutex_trylock on Windows
[mono.git] / mono / mini / mini-llvm.c
1 /*
2  * mini-llvm.c: llvm "Backend" for the mono JIT
3  *
4  * Copyright 2009-2011 Novell Inc (http://www.novell.com)
5  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
6  */
7
8 #include "mini.h"
9 #include <mono/metadata/debug-helpers.h>
10 #include <mono/metadata/debug-mono-symfile.h>
11 #include <mono/metadata/mempool-internals.h>
12 #include <mono/utils/mono-tls.h>
13 #include <mono/utils/mono-dl.h>
14 #include <mono/utils/mono-time.h>
15 #include <mono/utils/freebsd-dwarf.h>
16
17 #ifndef __STDC_LIMIT_MACROS
18 #define __STDC_LIMIT_MACROS
19 #endif
20 #ifndef __STDC_CONSTANT_MACROS
21 #define __STDC_CONSTANT_MACROS
22 #endif
23
24 #include "llvm-c/Core.h"
25 #include "llvm-c/ExecutionEngine.h"
26 #include "llvm-c/BitWriter.h"
27 #include "llvm-c/Analysis.h"
28
29 #include "mini-llvm-cpp.h"
30
31  /*
32   * Information associated by mono with LLVM modules.
33   */
34 typedef struct {
35         LLVMModuleRef module;
36         LLVMValueRef throw, rethrow, throw_corlib_exception;
37         GHashTable *llvm_types;
38         LLVMValueRef got_var;
39         const char *got_symbol;
40         GHashTable *plt_entries;
41         GHashTable *plt_entries_ji;
42         GHashTable *method_to_lmethod;
43         char **bb_names;
44         int bb_names_len;
45         GPtrArray *used;
46         LLVMTypeRef ptr_type;
47         GPtrArray *subprogram_mds;
48         MonoEERef *mono_ee;
49         LLVMExecutionEngineRef ee;
50 } MonoLLVMModule;
51
52 /*
53  * Information associated by the backend with mono basic blocks.
54  */
55 typedef struct {
56         LLVMBasicBlockRef bblock, end_bblock;
57         LLVMValueRef finally_ind;
58         gboolean added, invoke_target;
59         /* 
60          * If this bblock is the start of a finally clause, this is a list of bblocks it
61          * needs to branch to in ENDFINALLY.
62          */
63         GSList *call_handler_return_bbs;
64         /*
65          * If this bblock is the start of a finally clause, this is the bblock that
66          * CALL_HANDLER needs to branch to.
67          */
68         LLVMBasicBlockRef call_handler_target_bb;
69         /* The list of switch statements generated by ENDFINALLY instructions */
70         GSList *endfinally_switch_ins_list;
71         GSList *phi_nodes;
72 } BBInfo;
73
74 /*
75  * Structure containing emit state
76  */
77 typedef struct {
78         MonoMemPool *mempool;
79
80         /* Maps method names to the corresponding LLVMValueRef */
81         GHashTable *emitted_method_decls;
82
83         MonoCompile *cfg;
84         LLVMValueRef lmethod;
85         MonoLLVMModule *lmodule;
86         LLVMModuleRef module;
87         BBInfo *bblocks;
88         int sindex, default_index, ex_index;
89         LLVMBuilderRef builder;
90         LLVMValueRef *values, *addresses;
91         MonoType **vreg_cli_types;
92         LLVMCallInfo *linfo;
93         MonoMethodSignature *sig;
94         GSList *builders;
95         GHashTable *region_to_handler;
96         LLVMBuilderRef alloca_builder;
97         LLVMValueRef last_alloca;
98         LLVMValueRef rgctx_arg;
99         LLVMTypeRef *vreg_types;
100         gboolean *is_dead;
101         gboolean *unreachable;
102         int *pindexes;
103         LLVMValueRef imt_rgctx_loc;
104         GHashTable *llvm_types;
105         LLVMValueRef dbg_md;
106         MonoDebugMethodInfo *minfo;
107         char temp_name [32];
108 } EmitContext;
109
110 typedef struct {
111         MonoBasicBlock *bb;
112         MonoInst *phi;
113         MonoBasicBlock *in_bb;
114         int sreg;
115 } PhiNode;
116
117 /*
118  * Instruction metadata
119  * This is the same as ins_info, but LREG != IREG.
120  */
121 #ifdef MINI_OP
122 #undef MINI_OP
123 #endif
124 #ifdef MINI_OP3
125 #undef MINI_OP3
126 #endif
127 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
128 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
129 #define NONE ' '
130 #define IREG 'i'
131 #define FREG 'f'
132 #define VREG 'v'
133 #define XREG 'x'
134 #define LREG 'l'
135 /* keep in sync with the enum in mini.h */
136 const char
137 llvm_ins_info[] = {
138 #include "mini-ops.h"
139 };
140 #undef MINI_OP
141 #undef MINI_OP3
142
143 #if SIZEOF_VOID_P == 4
144 #define GET_LONG_IMM(ins) (((guint64)(ins)->inst_ms_word << 32) | (guint64)(guint32)(ins)->inst_ls_word)
145 #else
146 #define GET_LONG_IMM(ins) ((ins)->inst_imm)
147 #endif
148
149 #define LLVM_INS_INFO(opcode) (&llvm_ins_info [((opcode) - OP_START - 1) * 4])
150
151 #if 0
152 #define TRACE_FAILURE(msg) do { printf ("%s\n", msg); } while (0)
153 #else
154 #define TRACE_FAILURE(msg)
155 #endif
156
157 #ifdef TARGET_X86
158 #define IS_TARGET_X86 1
159 #else
160 #define IS_TARGET_X86 0
161 #endif
162
163 #ifdef TARGET_AMD64
164 #define IS_TARGET_AMD64 1
165 #else
166 #define IS_TARGET_AMD64 0
167 #endif
168
169 #define LLVM_FAILURE(ctx, reason) do { \
170         TRACE_FAILURE (reason); \
171         (ctx)->cfg->exception_message = g_strdup (reason); \
172         (ctx)->cfg->disable_llvm = TRUE; \
173         goto FAILURE; \
174 } while (0)
175
176 #define CHECK_FAILURE(ctx) do { \
177     if ((ctx)->cfg->disable_llvm) \
178                 goto FAILURE; \
179 } while (0)
180
181 static LLVMIntPredicate cond_to_llvm_cond [] = {
182         LLVMIntEQ,
183         LLVMIntNE,
184         LLVMIntSLE,
185         LLVMIntSGE,
186         LLVMIntSLT,
187         LLVMIntSGT,
188         LLVMIntULE,
189         LLVMIntUGE,
190         LLVMIntULT,
191         LLVMIntUGT,
192 };
193
194 static LLVMRealPredicate fpcond_to_llvm_cond [] = {
195         LLVMRealOEQ,
196         LLVMRealUNE,
197         LLVMRealOLE,
198         LLVMRealOGE,
199         LLVMRealOLT,
200         LLVMRealOGT,
201         LLVMRealULE,
202         LLVMRealUGE,
203         LLVMRealULT,
204         LLVMRealUGT,
205 };
206
207 static MonoNativeTlsKey current_cfg_tls_id;
208
209 static MonoLLVMModule aot_module;
210 static int memset_param_count, memcpy_param_count;
211 static const char *memset_func_name;
212 static const char *memcpy_func_name;
213
214 static void init_jit_module (MonoDomain *domain);
215
216 static void emit_dbg_loc (EmitContext *ctx, LLVMBuilderRef builder, const unsigned char *cil_code);
217 static LLVMValueRef emit_dbg_subprogram (EmitContext *ctx, MonoCompile *cfg, LLVMValueRef method, const char *name);
218 static void emit_dbg_info (MonoLLVMModule *lmodule, const char *filename, const char *cu_name);
219
220 /*
221  * IntPtrType:
222  *
223  *   The LLVM type with width == sizeof (gpointer)
224  */
225 static LLVMTypeRef
226 IntPtrType (void)
227 {
228         return sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type ();
229 }
230
231 static LLVMTypeRef
232 ObjRefType (void)
233 {
234         return sizeof (gpointer) == 8 ? LLVMPointerType (LLVMInt64Type (), 0) : LLVMPointerType (LLVMInt32Type (), 0);
235 }
236
237 static LLVMTypeRef
238 ThisType (void)
239 {
240         return sizeof (gpointer) == 8 ? LLVMPointerType (LLVMInt64Type (), 0) : LLVMPointerType (LLVMInt32Type (), 0);
241 }
242
243 /*
244  * get_vtype_size:
245  *
246  *   Return the size of the LLVM representation of the vtype T.
247  */
248 static guint32
249 get_vtype_size (MonoType *t)
250 {
251         int size;
252
253         size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
254
255         while (size < 2 * sizeof (gpointer) && mono_is_power_of_two (size) == -1)
256                 size ++;
257
258         return size;
259 }
260
261 /*
262  * simd_class_to_llvm_type:
263  *
264  *   Return the LLVM type corresponding to the Mono.SIMD class KLASS
265  */
266 static LLVMTypeRef
267 simd_class_to_llvm_type (EmitContext *ctx, MonoClass *klass)
268 {
269         if (!strcmp (klass->name, "Vector2d")) {
270                 return LLVMVectorType (LLVMDoubleType (), 2);
271         } else if (!strcmp (klass->name, "Vector2l")) {
272                 return LLVMVectorType (LLVMInt64Type (), 2);
273         } else if (!strcmp (klass->name, "Vector2ul")) {
274                 return LLVMVectorType (LLVMInt64Type (), 2);
275         } else if (!strcmp (klass->name, "Vector4i")) {
276                 return LLVMVectorType (LLVMInt32Type (), 4);
277         } else if (!strcmp (klass->name, "Vector4ui")) {
278                 return LLVMVectorType (LLVMInt32Type (), 4);
279         } else if (!strcmp (klass->name, "Vector4f")) {
280                 return LLVMVectorType (LLVMFloatType (), 4);
281         } else if (!strcmp (klass->name, "Vector8s")) {
282                 return LLVMVectorType (LLVMInt16Type (), 8);
283         } else if (!strcmp (klass->name, "Vector8us")) {
284                 return LLVMVectorType (LLVMInt16Type (), 8);
285         } else if (!strcmp (klass->name, "Vector16sb")) {
286                 return LLVMVectorType (LLVMInt8Type (), 16);
287         } else if (!strcmp (klass->name, "Vector16b")) {
288                 return LLVMVectorType (LLVMInt8Type (), 16);
289         } else {
290                 printf ("%s\n", klass->name);
291                 NOT_IMPLEMENTED;
292                 return NULL;
293         }
294 }
295
296 /* Return the 128 bit SIMD type corresponding to the mono type TYPE */
297 static inline G_GNUC_UNUSED LLVMTypeRef
298 type_to_simd_type (int type)
299 {
300         switch (type) {
301         case MONO_TYPE_I1:
302                 return LLVMVectorType (LLVMInt8Type (), 16);
303         case MONO_TYPE_I2:
304                 return LLVMVectorType (LLVMInt16Type (), 8);
305         case MONO_TYPE_I4:
306                 return LLVMVectorType (LLVMInt32Type (), 4);
307         case MONO_TYPE_I8:
308                 return LLVMVectorType (LLVMInt64Type (), 2);
309         case MONO_TYPE_R8:
310                 return LLVMVectorType (LLVMDoubleType (), 2);
311         case MONO_TYPE_R4:
312                 return LLVMVectorType (LLVMFloatType (), 4);
313         default:
314                 g_assert_not_reached ();
315                 return NULL;
316         }
317 }
318
319 /*
320  * type_to_llvm_type:
321  *
322  *   Return the LLVM type corresponding to T.
323  */
324 static LLVMTypeRef
325 type_to_llvm_type (EmitContext *ctx, MonoType *t)
326 {
327         t = mini_replace_type (t);
328
329         if (t->byref)
330                 return LLVMPointerType (LLVMInt8Type (), 0);
331         switch (t->type) {
332         case MONO_TYPE_VOID:
333                 return LLVMVoidType ();
334         case MONO_TYPE_I1:
335                 return LLVMInt8Type ();
336         case MONO_TYPE_I2:
337                 return LLVMInt16Type ();
338         case MONO_TYPE_I4:
339                 return LLVMInt32Type ();
340         case MONO_TYPE_U1:
341                 return LLVMInt8Type ();
342         case MONO_TYPE_U2:
343                 return LLVMInt16Type ();
344         case MONO_TYPE_U4:
345                 return LLVMInt32Type ();
346         case MONO_TYPE_BOOLEAN:
347                 return LLVMInt8Type ();
348         case MONO_TYPE_I8:
349         case MONO_TYPE_U8:
350                 return LLVMInt64Type ();
351         case MONO_TYPE_CHAR:
352                 return LLVMInt16Type ();
353         case MONO_TYPE_R4:
354                 return LLVMFloatType ();
355         case MONO_TYPE_R8:
356                 return LLVMDoubleType ();
357         case MONO_TYPE_I:
358         case MONO_TYPE_U:
359                 return IntPtrType ();
360         case MONO_TYPE_OBJECT:
361         case MONO_TYPE_CLASS:
362         case MONO_TYPE_ARRAY:
363         case MONO_TYPE_SZARRAY:
364         case MONO_TYPE_STRING:
365         case MONO_TYPE_PTR:
366                 return ObjRefType ();
367         case MONO_TYPE_VAR:
368         case MONO_TYPE_MVAR:
369                 /* Because of generic sharing */
370                 return ObjRefType ();
371         case MONO_TYPE_GENERICINST:
372                 if (!mono_type_generic_inst_is_valuetype (t))
373                         return ObjRefType ();
374                 /* Fall through */
375         case MONO_TYPE_VALUETYPE:
376         case MONO_TYPE_TYPEDBYREF: {
377                 MonoClass *klass;
378                 LLVMTypeRef ltype;
379
380                 klass = mono_class_from_mono_type (t);
381
382                 if (MONO_CLASS_IS_SIMD (ctx->cfg, klass))
383                         return simd_class_to_llvm_type (ctx, klass);
384
385                 if (klass->enumtype)
386                         return type_to_llvm_type (ctx, mono_class_enum_basetype (klass));
387
388                 ltype = g_hash_table_lookup (ctx->lmodule->llvm_types, klass);
389                 if (!ltype) {
390                         int i, size;
391                         LLVMTypeRef *eltypes;
392                         char *name;
393
394                         size = get_vtype_size (t);
395
396                         eltypes = g_new (LLVMTypeRef, size);
397                         for (i = 0; i < size; ++i)
398                                 eltypes [i] = LLVMInt8Type ();
399
400                         name = mono_type_full_name (&klass->byval_arg);
401                         ltype = LLVMStructCreateNamed (LLVMGetGlobalContext (), name);
402                         LLVMStructSetBody (ltype, eltypes, size, FALSE);
403                         g_hash_table_insert (ctx->lmodule->llvm_types, klass, ltype);
404                         g_free (eltypes);
405                         g_free (name);
406                 }
407                 return ltype;
408         }
409
410         default:
411                 printf ("X: %d\n", t->type);
412                 ctx->cfg->exception_message = g_strdup_printf ("type %s", mono_type_full_name (t));
413                 ctx->cfg->disable_llvm = TRUE;
414                 return NULL;
415         }
416 }
417
418 /*
419  * type_is_unsigned:
420  *
421  *   Return whenever T is an unsigned int type.
422  */
423 static gboolean
424 type_is_unsigned (EmitContext *ctx, MonoType *t)
425 {
426         if (t->byref)
427                 return FALSE;
428         switch (t->type) {
429         case MONO_TYPE_U1:
430         case MONO_TYPE_U2:
431         case MONO_TYPE_CHAR:
432         case MONO_TYPE_U4:
433         case MONO_TYPE_U8:
434                 return TRUE;
435         default:
436                 return FALSE;
437         }
438 }
439
440 /*
441  * type_to_llvm_arg_type:
442  *
443  *   Same as type_to_llvm_type, but treat i8/i16 as i32.
444  */
445 static LLVMTypeRef
446 type_to_llvm_arg_type (EmitContext *ctx, MonoType *t)
447 {
448         LLVMTypeRef ptype = type_to_llvm_type (ctx, t);
449
450         /*
451          * This works on all abis except arm64/ios which passes multiple
452          * arguments in one stack slot.
453          */
454 #ifndef TARGET_ARM64
455         if (ptype == LLVMInt8Type () || ptype == LLVMInt16Type ()) {
456                 /* 
457                  * LLVM generates code which only sets the lower bits, while JITted
458                  * code expects all the bits to be set.
459                  */
460                 ptype = LLVMInt32Type ();
461         }
462 #endif
463
464         return ptype;
465 }
466
467 /*
468  * llvm_type_to_stack_type:
469  *
470  *   Return the LLVM type which needs to be used when a value of type TYPE is pushed
471  * on the IL stack.
472  */
473 static G_GNUC_UNUSED LLVMTypeRef
474 llvm_type_to_stack_type (LLVMTypeRef type)
475 {
476         if (type == NULL)
477                 return NULL;
478         if (type == LLVMInt8Type ())
479                 return LLVMInt32Type ();
480         else if (type == LLVMInt16Type ())
481                 return LLVMInt32Type ();
482         else if (type == LLVMFloatType ())
483                 return LLVMDoubleType ();
484         else
485                 return type;
486 }
487
488 /*
489  * regtype_to_llvm_type:
490  *
491  *   Return the LLVM type corresponding to the regtype C used in instruction 
492  * descriptions.
493  */
494 static LLVMTypeRef
495 regtype_to_llvm_type (char c)
496 {
497         switch (c) {
498         case 'i':
499                 return LLVMInt32Type ();
500         case 'l':
501                 return LLVMInt64Type ();
502         case 'f':
503                 return LLVMDoubleType ();
504         default:
505                 return NULL;
506         }
507 }
508
509 /*
510  * op_to_llvm_type:
511  *
512  *   Return the LLVM type corresponding to the unary/binary opcode OPCODE.
513  */
514 static LLVMTypeRef
515 op_to_llvm_type (int opcode)
516 {
517         switch (opcode) {
518         case OP_ICONV_TO_I1:
519         case OP_LCONV_TO_I1:
520                 return LLVMInt8Type ();
521         case OP_ICONV_TO_U1:
522         case OP_LCONV_TO_U1:
523                 return LLVMInt8Type ();
524         case OP_ICONV_TO_I2:
525         case OP_LCONV_TO_I2:
526                 return LLVMInt16Type ();
527         case OP_ICONV_TO_U2:
528         case OP_LCONV_TO_U2:
529                 return LLVMInt16Type ();
530         case OP_ICONV_TO_I4:
531         case OP_LCONV_TO_I4:
532                 return LLVMInt32Type ();
533         case OP_ICONV_TO_U4:
534         case OP_LCONV_TO_U4:
535                 return LLVMInt32Type ();
536         case OP_ICONV_TO_I8:
537                 return LLVMInt64Type ();
538         case OP_ICONV_TO_R4:
539                 return LLVMFloatType ();
540         case OP_ICONV_TO_R8:
541                 return LLVMDoubleType ();
542         case OP_ICONV_TO_U8:
543                 return LLVMInt64Type ();
544         case OP_FCONV_TO_I4:
545                 return LLVMInt32Type ();
546         case OP_FCONV_TO_I8:
547                 return LLVMInt64Type ();
548         case OP_FCONV_TO_I1:
549         case OP_FCONV_TO_U1:
550                 return LLVMInt8Type ();
551         case OP_FCONV_TO_I2:
552         case OP_FCONV_TO_U2:
553                 return LLVMInt16Type ();
554         case OP_FCONV_TO_I:
555         case OP_FCONV_TO_U:
556                 return sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type ();
557         case OP_IADD_OVF:
558         case OP_IADD_OVF_UN:
559         case OP_ISUB_OVF:
560         case OP_ISUB_OVF_UN:
561         case OP_IMUL_OVF:
562         case OP_IMUL_OVF_UN:
563                 return LLVMInt32Type ();
564         case OP_LADD_OVF:
565         case OP_LADD_OVF_UN:
566         case OP_LSUB_OVF:
567         case OP_LSUB_OVF_UN:
568         case OP_LMUL_OVF:
569         case OP_LMUL_OVF_UN:
570                 return LLVMInt64Type ();
571         default:
572                 printf ("%s\n", mono_inst_name (opcode));
573                 g_assert_not_reached ();
574                 return NULL;
575         }
576 }               
577
578 /*
579  * load_store_to_llvm_type:
580  *
581  *   Return the size/sign/zero extension corresponding to the load/store opcode
582  * OPCODE.
583  */
584 static LLVMTypeRef
585 load_store_to_llvm_type (int opcode, int *size, gboolean *sext, gboolean *zext)
586 {
587         *sext = FALSE;
588         *zext = FALSE;
589
590         switch (opcode) {
591         case OP_LOADI1_MEMBASE:
592         case OP_STOREI1_MEMBASE_REG:
593         case OP_STOREI1_MEMBASE_IMM:
594                 *size = 1;
595                 *sext = TRUE;
596                 return LLVMInt8Type ();
597         case OP_LOADU1_MEMBASE:
598         case OP_LOADU1_MEM:
599                 *size = 1;
600                 *zext = TRUE;
601                 return LLVMInt8Type ();
602         case OP_LOADI2_MEMBASE:
603         case OP_STOREI2_MEMBASE_REG:
604         case OP_STOREI2_MEMBASE_IMM:
605                 *size = 2;
606                 *sext = TRUE;
607                 return LLVMInt16Type ();
608         case OP_LOADU2_MEMBASE:
609         case OP_LOADU2_MEM:
610                 *size = 2;
611                 *zext = TRUE;
612                 return LLVMInt16Type ();
613         case OP_LOADI4_MEMBASE:
614         case OP_LOADU4_MEMBASE:
615         case OP_LOADI4_MEM:
616         case OP_LOADU4_MEM:
617         case OP_STOREI4_MEMBASE_REG:
618         case OP_STOREI4_MEMBASE_IMM:
619                 *size = 4;
620                 return LLVMInt32Type ();
621         case OP_LOADI8_MEMBASE:
622         case OP_LOADI8_MEM:
623         case OP_STOREI8_MEMBASE_REG:
624         case OP_STOREI8_MEMBASE_IMM:
625                 *size = 8;
626                 return LLVMInt64Type ();
627         case OP_LOADR4_MEMBASE:
628         case OP_STORER4_MEMBASE_REG:
629                 *size = 4;
630                 return LLVMFloatType ();
631         case OP_LOADR8_MEMBASE:
632         case OP_STORER8_MEMBASE_REG:
633                 *size = 8;
634                 return LLVMDoubleType ();
635         case OP_LOAD_MEMBASE:
636         case OP_LOAD_MEM:
637         case OP_STORE_MEMBASE_REG:
638         case OP_STORE_MEMBASE_IMM:
639                 *size = sizeof (gpointer);
640                 return IntPtrType ();
641         default:
642                 g_assert_not_reached ();
643                 return NULL;
644         }
645 }
646
647 /*
648  * ovf_op_to_intrins:
649  *
650  *   Return the LLVM intrinsics corresponding to the overflow opcode OPCODE.
651  */
652 static const char*
653 ovf_op_to_intrins (int opcode)
654 {
655         switch (opcode) {
656         case OP_IADD_OVF:
657                 return "llvm.sadd.with.overflow.i32";
658         case OP_IADD_OVF_UN:
659                 return "llvm.uadd.with.overflow.i32";
660         case OP_ISUB_OVF:
661                 return "llvm.ssub.with.overflow.i32";
662         case OP_ISUB_OVF_UN:
663                 return "llvm.usub.with.overflow.i32";
664         case OP_IMUL_OVF:
665                 return "llvm.smul.with.overflow.i32";
666         case OP_IMUL_OVF_UN:
667                 return "llvm.umul.with.overflow.i32";
668         case OP_LADD_OVF:
669                 return "llvm.sadd.with.overflow.i64";
670         case OP_LADD_OVF_UN:
671                 return "llvm.uadd.with.overflow.i64";
672         case OP_LSUB_OVF:
673                 return "llvm.ssub.with.overflow.i64";
674         case OP_LSUB_OVF_UN:
675                 return "llvm.usub.with.overflow.i64";
676         case OP_LMUL_OVF:
677                 return "llvm.smul.with.overflow.i64";
678         case OP_LMUL_OVF_UN:
679                 return "llvm.umul.with.overflow.i64";
680         default:
681                 g_assert_not_reached ();
682                 return NULL;
683         }
684 }
685
686 static const char*
687 simd_op_to_intrins (int opcode)
688 {
689         switch (opcode) {
690 #if defined(TARGET_X86) || defined(TARGET_AMD64)
691         case OP_MINPD:
692                 return "llvm.x86.sse2.min.pd";
693         case OP_MINPS:
694                 return "llvm.x86.sse.min.ps";
695         case OP_PMIND_UN:
696                 return "llvm.x86.sse41.pminud";
697         case OP_PMINW_UN:
698                 return "llvm.x86.sse41.pminuw";
699         case OP_PMINB_UN:
700                 return "llvm.x86.sse2.pminu.b";
701         case OP_PMINW:
702                 return "llvm.x86.sse2.pmins.w";
703         case OP_MAXPD:
704                 return "llvm.x86.sse2.max.pd";
705         case OP_MAXPS:
706                 return "llvm.x86.sse.max.ps";
707         case OP_HADDPD:
708                 return "llvm.x86.sse3.hadd.pd";
709         case OP_HADDPS:
710                 return "llvm.x86.sse3.hadd.ps";
711         case OP_HSUBPD:
712                 return "llvm.x86.sse3.hsub.pd";
713         case OP_HSUBPS:
714                 return "llvm.x86.sse3.hsub.ps";
715         case OP_PMAXD_UN:
716                 return "llvm.x86.sse41.pmaxud";
717         case OP_PMAXW_UN:
718                 return "llvm.x86.sse41.pmaxuw";
719         case OP_PMAXB_UN:
720                 return "llvm.x86.sse2.pmaxu.b";
721         case OP_ADDSUBPS:
722                 return "llvm.x86.sse3.addsub.ps";
723         case OP_ADDSUBPD:
724                 return "llvm.x86.sse3.addsub.pd";
725         case OP_EXTRACT_MASK:
726                 return "llvm.x86.sse2.pmovmskb.128";
727         case OP_PSHRW:
728         case OP_PSHRW_REG:
729                 return "llvm.x86.sse2.psrli.w";
730         case OP_PSHRD:
731         case OP_PSHRD_REG:
732                 return "llvm.x86.sse2.psrli.d";
733         case OP_PSHRQ:
734         case OP_PSHRQ_REG:
735                 return "llvm.x86.sse2.psrli.q";
736         case OP_PSHLW:
737         case OP_PSHLW_REG:
738                 return "llvm.x86.sse2.pslli.w";
739         case OP_PSHLD:
740         case OP_PSHLD_REG:
741                 return "llvm.x86.sse2.pslli.d";
742         case OP_PSHLQ:
743         case OP_PSHLQ_REG:
744                 return "llvm.x86.sse2.pslli.q";
745         case OP_PSARW:
746         case OP_PSARW_REG:
747                 return "llvm.x86.sse2.psrai.w";
748         case OP_PSARD:
749         case OP_PSARD_REG:
750                 return "llvm.x86.sse2.psrai.d";
751         case OP_PADDB_SAT:
752                 return "llvm.x86.sse2.padds.b";
753         case OP_PADDW_SAT:
754                 return "llvm.x86.sse2.padds.w";
755         case OP_PSUBB_SAT:
756                 return "llvm.x86.sse2.psubs.b";
757         case OP_PSUBW_SAT:
758                 return "llvm.x86.sse2.psubs.w";
759         case OP_PADDB_SAT_UN:
760                 return "llvm.x86.sse2.paddus.b";
761         case OP_PADDW_SAT_UN:
762                 return "llvm.x86.sse2.paddus.w";
763         case OP_PSUBB_SAT_UN:
764                 return "llvm.x86.sse2.psubus.b";
765         case OP_PSUBW_SAT_UN:
766                 return "llvm.x86.sse2.psubus.w";
767         case OP_PAVGB_UN:
768                 return "llvm.x86.sse2.pavg.b";
769         case OP_PAVGW_UN:
770                 return "llvm.x86.sse2.pavg.w";
771         case OP_SQRTPS:
772                 return "llvm.x86.sse.sqrt.ps";
773         case OP_SQRTPD:
774                 return "llvm.x86.sse2.sqrt.pd";
775         case OP_RSQRTPS:
776                 return "llvm.x86.sse.rsqrt.ps";
777         case OP_RCPPS:
778                 return "llvm.x86.sse.rcp.ps";
779         case OP_CVTDQ2PD:
780                 return "llvm.x86.sse2.cvtdq2pd";
781         case OP_CVTDQ2PS:
782                 return "llvm.x86.sse2.cvtdq2ps";
783         case OP_CVTPD2DQ:
784                 return "llvm.x86.sse2.cvtpd2dq";
785         case OP_CVTPS2DQ:
786                 return "llvm.x86.sse2.cvtps2dq";
787         case OP_CVTPD2PS:
788                 return "llvm.x86.sse2.cvtpd2ps";
789         case OP_CVTPS2PD:
790                 return "llvm.x86.sse2.cvtps2pd";
791         case OP_CVTTPD2DQ:
792                 return "llvm.x86.sse2.cvttpd2dq";
793         case OP_CVTTPS2DQ:
794                 return "llvm.x86.sse2.cvttps2dq";
795         case OP_COMPPS:
796                 return "llvm.x86.sse.cmp.ps";
797         case OP_COMPPD:
798                 return "llvm.x86.sse2.cmp.pd";
799         case OP_PACKW:
800                 return "llvm.x86.sse2.packsswb.128";
801         case OP_PACKD:
802                 return "llvm.x86.sse2.packssdw.128";
803         case OP_PACKW_UN:
804                 return "llvm.x86.sse2.packuswb.128";
805         case OP_PACKD_UN:
806                 return "llvm.x86.sse41.packusdw";
807         case OP_PMULW_HIGH:
808                 return "llvm.x86.sse2.pmulh.w";
809         case OP_PMULW_HIGH_UN:
810                 return "llvm.x86.sse2.pmulhu.w";
811 #endif
812         default:
813                 g_assert_not_reached ();
814                 return NULL;
815         }
816 }
817
818 static LLVMTypeRef
819 simd_op_to_llvm_type (int opcode)
820 {
821 #if defined(TARGET_X86) || defined(TARGET_AMD64)
822         switch (opcode) {
823         case OP_EXTRACT_R8:
824         case OP_EXPAND_R8:
825                 return type_to_simd_type (MONO_TYPE_R8);
826         case OP_EXTRACT_I8:
827         case OP_EXPAND_I8:
828                 return type_to_simd_type (MONO_TYPE_I8);
829         case OP_EXTRACT_I4:
830         case OP_EXPAND_I4:
831                 return type_to_simd_type (MONO_TYPE_I4);
832         case OP_EXTRACT_I2:
833         case OP_EXTRACT_U2:
834         case OP_EXTRACTX_U2:
835         case OP_EXPAND_I2:
836                 return type_to_simd_type (MONO_TYPE_I2);
837         case OP_EXTRACT_I1:
838         case OP_EXTRACT_U1:
839         case OP_EXPAND_I1:
840                 return type_to_simd_type (MONO_TYPE_I1);
841         case OP_EXPAND_R4:
842                 return type_to_simd_type (MONO_TYPE_R4);
843         case OP_CVTDQ2PD:
844         case OP_CVTDQ2PS:
845                 return type_to_simd_type (MONO_TYPE_I4);
846         case OP_CVTPD2DQ:
847         case OP_CVTPD2PS:
848         case OP_CVTTPD2DQ:
849                 return type_to_simd_type (MONO_TYPE_R8);
850         case OP_CVTPS2DQ:
851         case OP_CVTPS2PD:
852         case OP_CVTTPS2DQ:
853                 return type_to_simd_type (MONO_TYPE_R4);
854         case OP_EXTRACT_MASK:
855                 return type_to_simd_type (MONO_TYPE_I1);
856         case OP_SQRTPS:
857         case OP_RSQRTPS:
858         case OP_RCPPS:
859         case OP_DUPPS_LOW:
860         case OP_DUPPS_HIGH:
861                 return type_to_simd_type (MONO_TYPE_R4);
862         case OP_SQRTPD:
863         case OP_DUPPD:
864                 return type_to_simd_type (MONO_TYPE_R8);
865         default:
866                 g_assert_not_reached ();
867                 return NULL;
868         }
869 #else
870         return NULL;
871 #endif
872 }
873
874 /*
875  * get_bb:
876  *
877  *   Return the LLVM basic block corresponding to BB.
878  */
879 static LLVMBasicBlockRef
880 get_bb (EmitContext *ctx, MonoBasicBlock *bb)
881 {
882         char bb_name_buf [128];
883         char *bb_name;
884
885         if (ctx->bblocks [bb->block_num].bblock == NULL) {
886                 if (bb->flags & BB_EXCEPTION_HANDLER) {
887                         int clause_index = (mono_get_block_region_notry (ctx->cfg, bb->region) >> 8) - 1;
888                         sprintf (bb_name_buf, "EH_CLAUSE%d_BB%d", clause_index, bb->block_num);
889                         bb_name = bb_name_buf;
890                 } else if (bb->block_num < 256) {
891                         if (!ctx->lmodule->bb_names) {
892                                 ctx->lmodule->bb_names_len = 256;
893                                 ctx->lmodule->bb_names = g_new0 (char*, ctx->lmodule->bb_names_len);
894                         }
895                         if (!ctx->lmodule->bb_names [bb->block_num]) {
896                                 char *n;
897
898                                 n = g_strdup_printf ("BB%d", bb->block_num);
899                                 mono_memory_barrier ();
900                                 ctx->lmodule->bb_names [bb->block_num] = n;
901                         }
902                         bb_name = ctx->lmodule->bb_names [bb->block_num];
903                 } else {
904                         sprintf (bb_name_buf, "BB%d", bb->block_num);
905                         bb_name = bb_name_buf;
906                 }
907
908                 ctx->bblocks [bb->block_num].bblock = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
909                 ctx->bblocks [bb->block_num].end_bblock = ctx->bblocks [bb->block_num].bblock;
910         }
911
912         return ctx->bblocks [bb->block_num].bblock;
913 }
914
915 /* 
916  * get_end_bb:
917  *
918  *   Return the last LLVM bblock corresponding to BB.
919  * This might not be equal to the bb returned by get_bb () since we need to generate
920  * multiple LLVM bblocks for a mono bblock to handle throwing exceptions.
921  */
922 static LLVMBasicBlockRef
923 get_end_bb (EmitContext *ctx, MonoBasicBlock *bb)
924 {
925         get_bb (ctx, bb);
926         return ctx->bblocks [bb->block_num].end_bblock;
927 }
928
929 static LLVMBasicBlockRef
930 gen_bb (EmitContext *ctx, const char *prefix)
931 {
932         char bb_name [128];
933
934         sprintf (bb_name, "%s%d", prefix, ++ ctx->ex_index);
935         return LLVMAppendBasicBlock (ctx->lmethod, bb_name);
936 }
937
938 /*
939  * resolve_patch:
940  *
941  *   Return the target of the patch identified by TYPE and TARGET.
942  */
943 static gpointer
944 resolve_patch (MonoCompile *cfg, MonoJumpInfoType type, gconstpointer target)
945 {
946         MonoJumpInfo ji;
947
948         memset (&ji, 0, sizeof (ji));
949         ji.type = type;
950         ji.data.target = target;
951
952         return mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
953 }
954
955 /*
956  * convert_full:
957  *
958  *   Emit code to convert the LLVM value V to DTYPE.
959  */
960 static LLVMValueRef
961 convert_full (EmitContext *ctx, LLVMValueRef v, LLVMTypeRef dtype, gboolean is_unsigned)
962 {
963         LLVMTypeRef stype = LLVMTypeOf (v);
964
965         if (stype != dtype) {
966                 gboolean ext = FALSE;
967
968                 /* Extend */
969                 if (dtype == LLVMInt64Type () && (stype == LLVMInt32Type () || stype == LLVMInt16Type () || stype == LLVMInt8Type ()))
970                         ext = TRUE;
971                 else if (dtype == LLVMInt32Type () && (stype == LLVMInt16Type () || stype == LLVMInt8Type ()))
972                         ext = TRUE;
973                 else if (dtype == LLVMInt16Type () && (stype == LLVMInt8Type ()))
974                         ext = TRUE;
975
976                 if (ext)
977                         return is_unsigned ? LLVMBuildZExt (ctx->builder, v, dtype, "") : LLVMBuildSExt (ctx->builder, v, dtype, "");
978
979                 if (dtype == LLVMDoubleType () && stype == LLVMFloatType ())
980                         return LLVMBuildFPExt (ctx->builder, v, dtype, "");
981
982                 /* Trunc */
983                 if (stype == LLVMInt64Type () && (dtype == LLVMInt32Type () || dtype == LLVMInt16Type () || dtype == LLVMInt8Type ()))
984                         return LLVMBuildTrunc (ctx->builder, v, dtype, "");
985                 if (stype == LLVMInt32Type () && (dtype == LLVMInt16Type () || dtype == LLVMInt8Type ()))
986                         return LLVMBuildTrunc (ctx->builder, v, dtype, "");
987                 if (stype == LLVMInt16Type () && dtype == LLVMInt8Type ())
988                         return LLVMBuildTrunc (ctx->builder, v, dtype, "");
989                 if (stype == LLVMDoubleType () && dtype == LLVMFloatType ())
990                         return LLVMBuildFPTrunc (ctx->builder, v, dtype, "");
991
992                 if (LLVMGetTypeKind (stype) == LLVMPointerTypeKind && LLVMGetTypeKind (dtype) == LLVMPointerTypeKind)
993                         return LLVMBuildBitCast (ctx->builder, v, dtype, "");
994                 if (LLVMGetTypeKind (dtype) == LLVMPointerTypeKind)
995                         return LLVMBuildIntToPtr (ctx->builder, v, dtype, "");
996                 if (LLVMGetTypeKind (stype) == LLVMPointerTypeKind)
997                         return LLVMBuildPtrToInt (ctx->builder, v, dtype, "");
998
999                 if (mono_arch_is_soft_float ()) {
1000                         if (stype == LLVMInt32Type () && dtype == LLVMFloatType ())
1001                                 return LLVMBuildBitCast (ctx->builder, v, dtype, "");
1002                         if (stype == LLVMInt32Type () && dtype == LLVMDoubleType ())
1003                                 return LLVMBuildBitCast (ctx->builder, LLVMBuildZExt (ctx->builder, v, LLVMInt64Type (), ""), dtype, "");
1004                 }
1005
1006                 if (LLVMGetTypeKind (stype) == LLVMVectorTypeKind && LLVMGetTypeKind (dtype) == LLVMVectorTypeKind)
1007                         return LLVMBuildBitCast (ctx->builder, v, dtype, "");
1008
1009                 LLVMDumpValue (v);
1010                 LLVMDumpValue (LLVMConstNull (dtype));
1011                 g_assert_not_reached ();
1012                 return NULL;
1013         } else {
1014                 return v;
1015         }
1016 }
1017
1018 static LLVMValueRef
1019 convert (EmitContext *ctx, LLVMValueRef v, LLVMTypeRef dtype)
1020 {
1021         return convert_full (ctx, v, dtype, FALSE);
1022 }
1023
1024 /*
1025  * emit_volatile_load:
1026  *
1027  *   If vreg is volatile, emit a load from its address.
1028  */
1029 static LLVMValueRef
1030 emit_volatile_load (EmitContext *ctx, int vreg)
1031 {
1032         MonoType *t;
1033
1034         LLVMValueRef v = LLVMBuildLoad (ctx->builder, ctx->addresses [vreg], "");
1035         t = ctx->vreg_cli_types [vreg];
1036         if (t && !t->byref) {
1037                 /* 
1038                  * Might have to zero extend since llvm doesn't have 
1039                  * unsigned types.
1040                  */
1041                 if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_U2 || t->type == MONO_TYPE_CHAR || t->type == MONO_TYPE_BOOLEAN)
1042                         v = LLVMBuildZExt (ctx->builder, v, LLVMInt32Type (), "");
1043                 else if (t->type == MONO_TYPE_U8)
1044                         v = LLVMBuildZExt (ctx->builder, v, LLVMInt64Type (), "");
1045         }
1046
1047         return v;
1048 }
1049
1050 /*
1051  * emit_volatile_store:
1052  *
1053  *   If VREG is volatile, emit a store from its value to its address.
1054  */
1055 static void
1056 emit_volatile_store (EmitContext *ctx, int vreg)
1057 {
1058         MonoInst *var = get_vreg_to_inst (ctx->cfg, vreg);
1059
1060         if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
1061                 g_assert (ctx->addresses [vreg]);
1062                 LLVMBuildStore (ctx->builder, convert (ctx, ctx->values [vreg], type_to_llvm_type (ctx, var->inst_vtype)), ctx->addresses [vreg]);
1063         }
1064 }
1065
1066 typedef struct {
1067         /* 
1068          * Maps parameter indexes in the original signature to parameter indexes
1069          * in the LLVM signature.
1070          */
1071         int *pindexes;
1072         /* The indexes of various special arguments in the LLVM signature */
1073         int vret_arg_pindex, this_arg_pindex, rgctx_arg_pindex, imt_arg_pindex;
1074 } LLVMSigInfo;
1075
1076 /*
1077  * sig_to_llvm_sig_full:
1078  *
1079  *   Return the LLVM signature corresponding to the mono signature SIG using the
1080  * calling convention information in CINFO. Return parameter mapping information in SINFO.
1081  */
1082 static LLVMTypeRef
1083 sig_to_llvm_sig_full (EmitContext *ctx, MonoMethodSignature *sig, LLVMCallInfo *cinfo,
1084                                           LLVMSigInfo *sinfo)
1085 {
1086         LLVMTypeRef ret_type;
1087         LLVMTypeRef *param_types = NULL;
1088         LLVMTypeRef res;
1089         int i, j, pindex, vret_arg_pindex = 0;
1090         int *pindexes;
1091         gboolean vretaddr = FALSE;
1092         MonoType *rtype;
1093
1094         if (sinfo)
1095                 memset (sinfo, 0, sizeof (LLVMSigInfo));
1096
1097         rtype = mini_replace_type (sig->ret);
1098         ret_type = type_to_llvm_type (ctx, rtype);
1099         CHECK_FAILURE (ctx);
1100
1101         if (cinfo && cinfo->ret.storage == LLVMArgVtypeInReg) {
1102                 /* LLVM models this by returning an aggregate value */
1103                 if (cinfo->ret.pair_storage [0] == LLVMArgInIReg && cinfo->ret.pair_storage [1] == LLVMArgNone) {
1104                         LLVMTypeRef members [2];
1105
1106                         members [0] = IntPtrType ();
1107                         ret_type = LLVMStructType (members, 1, FALSE);
1108                 } else {
1109                         g_assert_not_reached ();
1110                 }
1111         } else if (cinfo && mini_type_is_vtype (ctx->cfg, rtype)) {
1112                 g_assert (cinfo->ret.storage == LLVMArgVtypeRetAddr);
1113                 vretaddr = TRUE;
1114                 ret_type = LLVMVoidType ();
1115         }
1116
1117         pindexes = g_new0 (int, sig->param_count);
1118         param_types = g_new0 (LLVMTypeRef, (sig->param_count * 2) + 3);
1119         pindex = 0;
1120         if (cinfo && cinfo->rgctx_arg) {
1121                 if (sinfo)
1122                         sinfo->rgctx_arg_pindex = pindex;
1123                 param_types [pindex] = ctx->lmodule->ptr_type;
1124                 pindex ++;
1125         }
1126         if (cinfo && cinfo->imt_arg) {
1127                 if (sinfo)
1128                         sinfo->imt_arg_pindex = pindex;
1129                 param_types [pindex] = ctx->lmodule->ptr_type;
1130                 pindex ++;
1131         }
1132         if (vretaddr) {
1133                 /* Compute the index in the LLVM signature where the vret arg needs to be passed */
1134                 vret_arg_pindex = pindex;
1135                 if (cinfo->vret_arg_index == 1) {
1136                         /* Add the slots consumed by the first argument */
1137                         LLVMArgInfo *ainfo = &cinfo->args [0];
1138                         switch (ainfo->storage) {
1139                         case LLVMArgVtypeInReg:
1140                                 for (j = 0; j < 2; ++j) {
1141                                         if (ainfo->pair_storage [j] == LLVMArgInIReg)
1142                                                 vret_arg_pindex ++;
1143                                 }
1144                                 break;
1145                         default:
1146                                 vret_arg_pindex ++;
1147                         }
1148                 }
1149
1150                 if (sinfo)
1151                         sinfo->vret_arg_pindex = vret_arg_pindex;
1152         }                               
1153
1154         if (vretaddr && vret_arg_pindex == pindex)
1155                 param_types [pindex ++] = IntPtrType ();
1156         if (sig->hasthis) {
1157                 if (sinfo)
1158                         sinfo->this_arg_pindex = pindex;
1159                 param_types [pindex ++] = ThisType ();
1160         }
1161         if (vretaddr && vret_arg_pindex == pindex)
1162                 param_types [pindex ++] = IntPtrType ();
1163         for (i = 0; i < sig->param_count; ++i) {
1164                 if (vretaddr && vret_arg_pindex == pindex)
1165                         param_types [pindex ++] = IntPtrType ();
1166                 pindexes [i] = pindex;
1167                 if (cinfo && cinfo->args [i + sig->hasthis].storage == LLVMArgVtypeInReg) {
1168                         for (j = 0; j < 2; ++j) {
1169                                 switch (cinfo->args [i + sig->hasthis].pair_storage [j]) {
1170                                 case LLVMArgInIReg:
1171                                         param_types [pindex ++] = LLVMIntType (sizeof (gpointer) * 8);
1172                                         break;
1173                                 case LLVMArgNone:
1174                                         break;
1175                                 default:
1176                                         g_assert_not_reached ();
1177                                 }
1178                         }
1179                 } else if (cinfo && cinfo->args [i + sig->hasthis].storage == LLVMArgVtypeByVal) {
1180                         param_types [pindex] = type_to_llvm_arg_type (ctx, sig->params [i]);
1181                         CHECK_FAILURE (ctx);
1182                         param_types [pindex] = LLVMPointerType (param_types [pindex], 0);
1183                         pindex ++;
1184                 } else {
1185                         param_types [pindex ++] = type_to_llvm_arg_type (ctx, sig->params [i]);
1186                 }                       
1187         }
1188         if (vretaddr && vret_arg_pindex == pindex)
1189                 param_types [pindex ++] = IntPtrType ();
1190
1191         CHECK_FAILURE (ctx);
1192
1193         res = LLVMFunctionType (ret_type, param_types, pindex, FALSE);
1194         g_free (param_types);
1195
1196         if (sinfo) {
1197                 sinfo->pindexes = pindexes;
1198         } else {
1199                 g_free (pindexes);
1200         }
1201
1202         return res;
1203
1204  FAILURE:
1205         g_free (param_types);
1206
1207         return NULL;
1208 }
1209
1210 static LLVMTypeRef
1211 sig_to_llvm_sig (EmitContext *ctx, MonoMethodSignature *sig)
1212 {
1213         return sig_to_llvm_sig_full (ctx, sig, NULL, NULL);
1214 }
1215
1216 /*
1217  * LLVMFunctionType1:
1218  *
1219  *   Create an LLVM function type from the arguments.
1220  */
1221 static G_GNUC_UNUSED LLVMTypeRef 
1222 LLVMFunctionType1(LLVMTypeRef ReturnType,
1223                                   LLVMTypeRef ParamType1,
1224                                   int IsVarArg)
1225 {
1226         LLVMTypeRef param_types [1];
1227
1228         param_types [0] = ParamType1;
1229
1230         return LLVMFunctionType (ReturnType, param_types, 1, IsVarArg);
1231 }
1232
1233 /*
1234  * LLVMFunctionType2:
1235  *
1236  *   Create an LLVM function type from the arguments.
1237  */
1238 static G_GNUC_UNUSED LLVMTypeRef
1239 LLVMFunctionType2(LLVMTypeRef ReturnType,
1240                                   LLVMTypeRef ParamType1,
1241                                   LLVMTypeRef ParamType2,
1242                                   int IsVarArg)
1243 {
1244         LLVMTypeRef param_types [2];
1245
1246         param_types [0] = ParamType1;
1247         param_types [1] = ParamType2;
1248
1249         return LLVMFunctionType (ReturnType, param_types, 2, IsVarArg);
1250 }
1251
1252 /*
1253  * LLVMFunctionType3:
1254  *
1255  *   Create an LLVM function type from the arguments.
1256  */
1257 static G_GNUC_UNUSED LLVMTypeRef
1258 LLVMFunctionType3(LLVMTypeRef ReturnType,
1259                                   LLVMTypeRef ParamType1,
1260                                   LLVMTypeRef ParamType2,
1261                                   LLVMTypeRef ParamType3,
1262                                   int IsVarArg)
1263 {
1264         LLVMTypeRef param_types [3];
1265
1266         param_types [0] = ParamType1;
1267         param_types [1] = ParamType2;
1268         param_types [2] = ParamType3;
1269
1270         return LLVMFunctionType (ReturnType, param_types, 3, IsVarArg);
1271 }
1272
1273 /*
1274  * create_builder:
1275  *
1276  *   Create an LLVM builder and remember it so it can be freed later.
1277  */
1278 static LLVMBuilderRef
1279 create_builder (EmitContext *ctx)
1280 {
1281         LLVMBuilderRef builder = LLVMCreateBuilder ();
1282
1283         ctx->builders = g_slist_prepend_mempool (ctx->cfg->mempool, ctx->builders, builder);
1284
1285         return builder;
1286 }
1287
1288 static LLVMValueRef
1289 get_plt_entry (EmitContext *ctx, LLVMTypeRef llvm_sig, MonoJumpInfoType type, gconstpointer data)
1290 {
1291         char *callee_name = mono_aot_get_plt_symbol (type, data);
1292         LLVMValueRef callee;
1293         MonoJumpInfo *ji = NULL;
1294
1295         if (!callee_name)
1296                 return NULL;
1297
1298         if (ctx->cfg->compile_aot)
1299                 /* Add a patch so referenced wrappers can be compiled in full aot mode */
1300                 mono_add_patch_info (ctx->cfg, 0, type, data);
1301
1302         // FIXME: Locking
1303         callee = g_hash_table_lookup (ctx->lmodule->plt_entries, callee_name);
1304         if (!callee) {
1305                 callee = LLVMAddFunction (ctx->module, callee_name, llvm_sig);
1306
1307                 LLVMSetVisibility (callee, LLVMHiddenVisibility);
1308
1309                 g_hash_table_insert (ctx->lmodule->plt_entries, (char*)callee_name, callee);
1310         }
1311
1312         if (ctx->cfg->compile_aot) {
1313                 ji = g_new0 (MonoJumpInfo, 1);
1314                 ji->type = type;
1315                 ji->data.target = data;
1316
1317                 g_hash_table_insert (ctx->lmodule->plt_entries_ji, ji, callee);
1318         }
1319
1320         return callee;
1321 }
1322
1323 static int
1324 get_handler_clause (MonoCompile *cfg, MonoBasicBlock *bb)
1325 {
1326         MonoMethodHeader *header = cfg->header;
1327         MonoExceptionClause *clause;
1328         int i;
1329
1330         /* Directly */
1331         if (bb->region != -1 && MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))
1332                 return (bb->region >> 8) - 1;
1333
1334         /* Indirectly */
1335         for (i = 0; i < header->num_clauses; ++i) {
1336                 clause = &header->clauses [i];
1337                            
1338                 if (MONO_OFFSET_IN_CLAUSE (clause, bb->real_offset) && clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
1339                         return i;
1340         }
1341
1342         return -1;
1343 }
1344
1345 static void
1346 set_metadata_flag (LLVMValueRef v, const char *flag_name)
1347 {
1348         LLVMValueRef md_arg;
1349         int md_kind;
1350
1351         md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1352         md_arg = LLVMMDString ("mono", 4);
1353         LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1354 }
1355
1356 static void
1357 set_invariant_load_flag (LLVMValueRef v)
1358 {
1359         LLVMValueRef md_arg;
1360         int md_kind;
1361         const char *flag_name;
1362
1363         // FIXME: Cache this
1364         flag_name = "invariant.load";
1365         md_kind = LLVMGetMDKindID (flag_name, strlen (flag_name));
1366         md_arg = LLVMMDString ("<index>", strlen ("<index>"));
1367         LLVMSetMetadata (v, md_kind, LLVMMDNode (&md_arg, 1));
1368 }
1369
1370 /*
1371  * emit_call:
1372  *
1373  *   Emit an LLVM call or invoke instruction depending on whenever the call is inside
1374  * a try region.
1375  */
1376 static LLVMValueRef
1377 emit_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, LLVMValueRef callee, LLVMValueRef *args, int pindex)
1378 {
1379         MonoCompile *cfg = ctx->cfg;
1380         LLVMValueRef lcall;
1381         LLVMBuilderRef builder = *builder_ref;
1382         int clause_index;
1383
1384         clause_index = get_handler_clause (cfg, bb);
1385
1386         if (clause_index != -1) {
1387                 MonoMethodHeader *header = cfg->header;
1388                 MonoExceptionClause *ec = &header->clauses [clause_index];
1389                 MonoBasicBlock *tblock;
1390                 LLVMBasicBlockRef ex_bb, noex_bb;
1391
1392                 /*
1393                  * Have to use an invoke instead of a call, branching to the
1394                  * handler bblock of the clause containing this bblock.
1395                  */
1396
1397                 g_assert (ec->flags == MONO_EXCEPTION_CLAUSE_NONE || ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY);
1398
1399                 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
1400                 g_assert (tblock);
1401
1402                 ctx->bblocks [tblock->block_num].invoke_target = TRUE;
1403
1404                 ex_bb = get_bb (ctx, tblock);
1405
1406                 noex_bb = gen_bb (ctx, "NOEX_BB");
1407
1408                 /* Use an invoke */
1409                 lcall = LLVMBuildInvoke (builder, callee, args, pindex, noex_bb, ex_bb, "");
1410
1411                 builder = ctx->builder = create_builder (ctx);
1412                 LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1413
1414                 ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1415         } else {
1416                 lcall = LLVMBuildCall (builder, callee, args, pindex, "");
1417                 ctx->builder = builder;
1418         }
1419
1420         *builder_ref = ctx->builder;
1421
1422         return lcall;
1423 }
1424
1425 static LLVMValueRef
1426 emit_load (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef addr, const char *name, gboolean is_faulting)
1427 {
1428         const char *intrins_name;
1429         LLVMValueRef args [16], res;
1430         LLVMTypeRef addr_type;
1431
1432         if (is_faulting && bb->region != -1) {
1433                 /*
1434                  * We handle loads which can fault by calling a mono specific intrinsic
1435                  * using an invoke, so they are handled properly inside try blocks.
1436                  * We can't use this outside clauses, since LLVM optimizes intrinsics which
1437                  * are marked with IntrReadArgMem.
1438                  */
1439                 switch (size) {
1440                 case 1:
1441                         intrins_name = "llvm.mono.load.i8.p0i8";
1442                         break;
1443                 case 2:
1444                         intrins_name = "llvm.mono.load.i16.p0i16";
1445                         break;
1446                 case 4:
1447                         intrins_name = "llvm.mono.load.i32.p0i32";
1448                         break;
1449                 case 8:
1450                         intrins_name = "llvm.mono.load.i64.p0i64";
1451                         break;
1452                 default:
1453                         g_assert_not_reached ();
1454                 }
1455
1456                 addr_type = LLVMTypeOf (addr);
1457                 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0) || addr_type == LLVMPointerType (LLVMFloatType (), 0))
1458                         addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1459
1460                 args [0] = addr;
1461                 args [1] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1462                 args [2] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1463                 res = emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 3);
1464
1465                 if (addr_type == LLVMPointerType (LLVMDoubleType (), 0))
1466                         res = LLVMBuildBitCast (*builder_ref, res, LLVMDoubleType (), "");
1467                 else if (addr_type == LLVMPointerType (LLVMFloatType (), 0))
1468                         res = LLVMBuildBitCast (*builder_ref, res, LLVMFloatType (), "");
1469                 
1470                 return res;
1471         } else {
1472                 LLVMValueRef res;
1473
1474                 /* 
1475                  * We emit volatile loads for loads which can fault, because otherwise
1476                  * LLVM will generate invalid code when encountering a load from a
1477                  * NULL address.
1478                  */
1479                  res = mono_llvm_build_load (*builder_ref, addr, name, is_faulting);
1480
1481                  /* Mark it with a custom metadata */
1482                  /*
1483                  if (is_faulting)
1484                          set_metadata_flag (res, "mono.faulting.load");
1485                  */
1486
1487                  return res;
1488         }
1489 }
1490
1491 static void
1492 emit_store (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, int size, LLVMValueRef value, LLVMValueRef addr, gboolean is_faulting)
1493 {
1494         const char *intrins_name;
1495         LLVMValueRef args [16];
1496
1497         if (is_faulting && bb->region != -1) {
1498                 switch (size) {
1499                 case 1:
1500                         intrins_name = "llvm.mono.store.i8.p0i8";
1501                         break;
1502                 case 2:
1503                         intrins_name = "llvm.mono.store.i16.p0i16";
1504                         break;
1505                 case 4:
1506                         intrins_name = "llvm.mono.store.i32.p0i32";
1507                         break;
1508                 case 8:
1509                         intrins_name = "llvm.mono.store.i64.p0i64";
1510                         break;
1511                 default:
1512                         g_assert_not_reached ();
1513                 }
1514
1515                 if (LLVMTypeOf (value) == LLVMDoubleType () || LLVMTypeOf (value) == LLVMFloatType ()) {
1516                         value = LLVMBuildBitCast (*builder_ref, value, LLVMIntType (size * 8), "");
1517                         addr = LLVMBuildBitCast (*builder_ref, addr, LLVMPointerType (LLVMIntType (size * 8), 0), "");
1518                 }
1519
1520                 args [0] = value;
1521                 args [1] = addr;
1522                 args [2] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1523                 args [3] = LLVMConstInt (LLVMInt1Type (), TRUE, FALSE);
1524                 emit_call (ctx, bb, builder_ref, LLVMGetNamedFunction (ctx->module, intrins_name), args, 4);
1525         } else {
1526                 LLVMBuildStore (*builder_ref, value, addr);
1527         }
1528 }
1529
1530 /*
1531  * emit_cond_system_exception:
1532  *
1533  *   Emit code to throw the exception EXC_TYPE if the condition CMP is false.
1534  * Might set the ctx exception.
1535  */
1536 static void
1537 emit_cond_system_exception (EmitContext *ctx, MonoBasicBlock *bb, const char *exc_type, LLVMValueRef cmp)
1538 {
1539         LLVMBasicBlockRef ex_bb, noex_bb;
1540         LLVMBuilderRef builder;
1541         MonoClass *exc_class;
1542         LLVMValueRef args [2];
1543         
1544         ex_bb = gen_bb (ctx, "EX_BB");
1545         noex_bb = gen_bb (ctx, "NOEX_BB");
1546
1547         LLVMBuildCondBr (ctx->builder, cmp, ex_bb, noex_bb);
1548
1549         exc_class = mono_class_from_name (mono_get_corlib (), "System", exc_type);
1550         g_assert (exc_class);
1551
1552         /* Emit exception throwing code */
1553         builder = create_builder (ctx);
1554         LLVMPositionBuilderAtEnd (builder, ex_bb);
1555
1556         if (!ctx->lmodule->throw_corlib_exception) {
1557                 LLVMValueRef callee;
1558                 LLVMTypeRef sig;
1559                 const char *icall_name;
1560
1561                 MonoMethodSignature *throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 2);
1562                 throw_sig->ret = &mono_get_void_class ()->byval_arg;
1563                 throw_sig->params [0] = &mono_get_int32_class ()->byval_arg;
1564                 icall_name = "llvm_throw_corlib_exception_abs_trampoline";
1565                 /* This will become i8* */
1566                 throw_sig->params [1] = &mono_get_byte_class ()->this_arg;
1567                 sig = sig_to_llvm_sig (ctx, throw_sig);
1568
1569                 if (ctx->cfg->compile_aot) {
1570                         callee = get_plt_entry (ctx, sig, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
1571                 } else {
1572                         callee = LLVMAddFunction (ctx->module, "llvm_throw_corlib_exception_trampoline", sig_to_llvm_sig (ctx, throw_sig));
1573
1574                         /*
1575                          * Differences between the LLVM/non-LLVM throw corlib exception trampoline:
1576                          * - On x86, LLVM generated code doesn't push the arguments
1577                          * - The trampoline takes the throw address as an arguments, not a pc offset.
1578                          */
1579                         LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (ctx->cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
1580                 }
1581
1582                 mono_memory_barrier ();
1583                 ctx->lmodule->throw_corlib_exception = callee;
1584         }
1585
1586         if (IS_TARGET_X86 || IS_TARGET_AMD64)
1587                 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token - MONO_TOKEN_TYPE_DEF, FALSE);
1588         else
1589                 args [0] = LLVMConstInt (LLVMInt32Type (), exc_class->type_token, FALSE);
1590
1591         /*
1592          * The LLVM mono branch contains changes so a block address can be passed as an
1593          * argument to a call.
1594          */
1595         args [1] = LLVMBlockAddress (ctx->lmethod, ex_bb);
1596         emit_call (ctx, bb, &builder, ctx->lmodule->throw_corlib_exception, args, 2);
1597
1598         LLVMBuildUnreachable (builder);
1599
1600         ctx->builder = create_builder (ctx);
1601         LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
1602
1603         ctx->bblocks [bb->block_num].end_bblock = noex_bb;
1604
1605         ctx->ex_index ++;
1606         return;
1607 }
1608
1609 /*
1610  * emit_reg_to_vtype:
1611  *
1612  *   Emit code to store the vtype in the registers REGS to the address ADDRESS.
1613  */
1614 static void
1615 emit_reg_to_vtype (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *regs)
1616 {
1617         int j, size;
1618
1619         size = get_vtype_size (t);
1620
1621         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1622                 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1623         }
1624
1625         for (j = 0; j < 2; ++j) {
1626                 LLVMValueRef index [2], addr;
1627                 int part_size = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1628                 LLVMTypeRef part_type;
1629
1630                 if (ainfo->pair_storage [j] == LLVMArgNone)
1631                         continue;
1632
1633                 part_type = LLVMIntType (part_size * 8);
1634                 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1635                         index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1636                         addr = LLVMBuildGEP (builder, address, index, 1, "");
1637                 } else {
1638                         index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1639                         index [1] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1640                         addr = LLVMBuildGEP (builder, address, index, 2, "");
1641                 }
1642                 switch (ainfo->pair_storage [j]) {
1643                 case LLVMArgInIReg:
1644                         LLVMBuildStore (builder, convert (ctx, regs [j], part_type), LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (part_type, 0), ""));
1645                         break;
1646                 case LLVMArgNone:
1647                         break;
1648                 default:
1649                         g_assert_not_reached ();
1650                 }
1651
1652                 size -= sizeof (gpointer);
1653         }
1654 }
1655
1656 /*
1657  * emit_vtype_to_reg:
1658  *
1659  *   Emit code to load a vtype at address ADDRESS into registers. Store the registers
1660  * into REGS, and the number of registers into NREGS.
1661  */
1662 static void
1663 emit_vtype_to_reg (EmitContext *ctx, LLVMBuilderRef builder, MonoType *t, LLVMValueRef address, LLVMArgInfo *ainfo, LLVMValueRef *regs, guint32 *nregs)
1664 {
1665         int pindex = 0;
1666         int j, size;
1667
1668         size = get_vtype_size (t);
1669
1670         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1671                 address = LLVMBuildBitCast (ctx->builder, address, LLVMPointerType (LLVMInt8Type (), 0), "");
1672         }
1673
1674         for (j = 0; j < 2; ++j) {
1675                 LLVMValueRef index [2], addr;
1676                 int partsize = size > sizeof (gpointer) ? sizeof (gpointer) : size;
1677
1678                 if (ainfo->pair_storage [j] == LLVMArgNone)
1679                         continue;
1680
1681                 if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (t))) {
1682                         index [0] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);
1683                         addr = LLVMBuildGEP (builder, address, index, 1, "");
1684                 } else {
1685                         index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
1686                         index [1] = LLVMConstInt (LLVMInt32Type (), j * sizeof (gpointer), FALSE);                              
1687                         addr = LLVMBuildGEP (builder, address, index, 2, "");
1688                 }
1689                 switch (ainfo->pair_storage [j]) {
1690                 case LLVMArgInIReg:
1691                         regs [pindex ++] = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (ctx->builder, addr, LLVMPointerType (LLVMIntType (partsize * 8), 0), ""), ""), IntPtrType ());
1692                         break;
1693                 case LLVMArgNone:
1694                         break;
1695                 default:
1696                         g_assert_not_reached ();
1697                 }
1698                 size -= sizeof (gpointer);
1699         }
1700
1701         *nregs = pindex;
1702 }
1703
1704 static LLVMValueRef
1705 build_alloca_llvm_type (EmitContext *ctx, LLVMTypeRef t, int align)
1706 {
1707         /*
1708          * Have to place all alloca's at the end of the entry bb, since otherwise they would
1709          * get executed every time control reaches them.
1710          */
1711         LLVMPositionBuilder (ctx->alloca_builder, get_bb (ctx, ctx->cfg->bb_entry), ctx->last_alloca);
1712
1713         ctx->last_alloca = mono_llvm_build_alloca (ctx->alloca_builder, t, NULL, align, "");
1714         return ctx->last_alloca;
1715 }
1716
1717 static LLVMValueRef
1718 build_alloca (EmitContext *ctx, MonoType *t)
1719 {
1720         MonoClass *k = mono_class_from_mono_type (t);
1721         int align;
1722
1723         if (MONO_CLASS_IS_SIMD (ctx->cfg, k))
1724                 align = 16;
1725         else
1726                 align = mono_class_min_align (k);
1727
1728         /* Sometimes align is not a power of 2 */
1729         while (mono_is_power_of_two (align) == -1)
1730                 align ++;
1731
1732         return build_alloca_llvm_type (ctx, type_to_llvm_type (ctx, t), align);
1733 }
1734
1735 /*
1736  * Put the global into the 'llvm.used' array to prevent it from being optimized away.
1737  */
1738 static void
1739 mark_as_used (MonoLLVMModule *lmodule, LLVMValueRef global)
1740 {
1741         if (!lmodule->used)
1742                 lmodule->used = g_ptr_array_sized_new (16);
1743         g_ptr_array_add (lmodule->used, global);
1744 }
1745
1746 static void
1747 emit_llvm_used (MonoLLVMModule *lmodule)
1748 {
1749         LLVMModuleRef module = lmodule->module;
1750         LLVMTypeRef used_type;
1751         LLVMValueRef used, *used_elem;
1752         int i;
1753                 
1754         if (!lmodule->used)
1755                 return;
1756
1757         used_type = LLVMArrayType (LLVMPointerType (LLVMInt8Type (), 0), lmodule->used->len);
1758         used = LLVMAddGlobal (module, used_type, "llvm.used");
1759         used_elem = g_new0 (LLVMValueRef, lmodule->used->len);
1760         for (i = 0; i < lmodule->used->len; ++i)
1761                 used_elem [i] = LLVMConstBitCast (g_ptr_array_index (lmodule->used, i), LLVMPointerType (LLVMInt8Type (), 0));
1762         LLVMSetInitializer (used, LLVMConstArray (LLVMPointerType (LLVMInt8Type (), 0), used_elem, lmodule->used->len));
1763         LLVMSetLinkage (used, LLVMAppendingLinkage);
1764         LLVMSetSection (used, "llvm.metadata");
1765 }
1766
1767 /*
1768  * emit_entry_bb:
1769  *
1770  *   Emit code to load/convert arguments.
1771  */
1772 static void
1773 emit_entry_bb (EmitContext *ctx, LLVMBuilderRef builder)
1774 {
1775         int i, pindex;
1776         MonoCompile *cfg = ctx->cfg;
1777         MonoMethodSignature *sig = ctx->sig;
1778         LLVMCallInfo *linfo = ctx->linfo;
1779         MonoBasicBlock *bb;
1780
1781         ctx->alloca_builder = create_builder (ctx);
1782
1783         /*
1784          * Handle indirect/volatile variables by allocating memory for them
1785          * using 'alloca', and storing their address in a temporary.
1786          */
1787         for (i = 0; i < cfg->num_varinfo; ++i) {
1788                 MonoInst *var = cfg->varinfo [i];
1789                 LLVMTypeRef vtype;
1790
1791                 if (var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT) || mini_type_is_vtype (cfg, var->inst_vtype)) {
1792                         vtype = type_to_llvm_type (ctx, var->inst_vtype);
1793                         CHECK_FAILURE (ctx);
1794                         /* Could be already created by an OP_VPHI */
1795                         if (!ctx->addresses [var->dreg])
1796                                 ctx->addresses [var->dreg] = build_alloca (ctx, var->inst_vtype);
1797                         ctx->vreg_cli_types [var->dreg] = var->inst_vtype;
1798                 }
1799         }
1800
1801         for (i = 0; i < sig->param_count; ++i) {
1802                 LLVMArgInfo *ainfo = &linfo->args [i + sig->hasthis];
1803                 int reg = cfg->args [i + sig->hasthis]->dreg;
1804
1805                 if (ainfo->storage == LLVMArgVtypeInReg) {
1806                         LLVMValueRef regs [2];
1807
1808                         /* 
1809                          * Emit code to save the argument from the registers to 
1810                          * the real argument.
1811                          */
1812                         pindex = ctx->pindexes [i];
1813                         regs [0] = LLVMGetParam (ctx->lmethod, pindex);
1814                         if (ainfo->pair_storage [1] != LLVMArgNone)
1815                                 regs [1] = LLVMGetParam (ctx->lmethod, pindex + 1);
1816                         else
1817                                 regs [1] = NULL;
1818
1819                         ctx->addresses [reg] = build_alloca (ctx, sig->params [i]);
1820
1821                         emit_reg_to_vtype (ctx, builder, sig->params [i], ctx->addresses [reg], ainfo, regs);
1822
1823                         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
1824                                 /* Treat these as normal values */
1825                                 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
1826                         }
1827                 } else if (ainfo->storage == LLVMArgVtypeByVal) {
1828                         ctx->addresses [reg] = LLVMGetParam (ctx->lmethod, ctx->pindexes [i]);
1829
1830                         if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
1831                                 /* Treat these as normal values */
1832                                 ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
1833                         }
1834                 } else {
1835                         ctx->values [reg] = convert_full (ctx, ctx->values [reg], llvm_type_to_stack_type (type_to_llvm_type (ctx, sig->params [i])), type_is_unsigned (ctx, sig->params [i]));
1836                 }
1837         }
1838
1839         if (cfg->vret_addr)
1840                 emit_volatile_store (ctx, cfg->vret_addr->dreg);
1841         if (sig->hasthis)
1842                 emit_volatile_store (ctx, cfg->args [0]->dreg);
1843         for (i = 0; i < sig->param_count; ++i)
1844                 if (!mini_type_is_vtype (cfg, sig->params [i]))
1845                         emit_volatile_store (ctx, cfg->args [i + sig->hasthis]->dreg);
1846
1847         if (sig->hasthis && !cfg->rgctx_var && cfg->generic_sharing_context) {
1848                 LLVMValueRef this_alloc;
1849
1850                 /*
1851                  * The exception handling code needs the location where the this argument was
1852                  * stored for gshared methods. We create a separate alloca to hold it, and mark it
1853                  * with the "mono.this" custom metadata to tell llvm that it needs to save its
1854                  * location into the LSDA.
1855                  */
1856                 this_alloc = mono_llvm_build_alloca (builder, ThisType (), LLVMConstInt (LLVMInt32Type (), 1, FALSE), 0, "");
1857                 /* This volatile store will keep the alloca alive */
1858                 mono_llvm_build_store (builder, ctx->values [cfg->args [0]->dreg], this_alloc, TRUE);
1859
1860                 set_metadata_flag (this_alloc, "mono.this");
1861         }
1862
1863         if (cfg->rgctx_var) {
1864                 LLVMValueRef rgctx_alloc, store;
1865
1866                 /*
1867                  * We handle the rgctx arg similarly to the this pointer.
1868                  */
1869                 g_assert (ctx->addresses [cfg->rgctx_var->dreg]);
1870                 rgctx_alloc = ctx->addresses [cfg->rgctx_var->dreg];
1871                 /* This volatile store will keep the alloca alive */
1872                 store = mono_llvm_build_store (builder, convert (ctx, ctx->rgctx_arg, IntPtrType ()), rgctx_alloc, TRUE);
1873
1874                 set_metadata_flag (rgctx_alloc, "mono.this");
1875         }
1876
1877         /*
1878          * For finally clauses, create an indicator variable telling OP_ENDFINALLY whenever
1879          * it needs to continue normally, or return back to the exception handling system.
1880          */
1881         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1882                 if (bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER))
1883                         g_hash_table_insert (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)), bb);
1884                 if (bb->region != -1 && (bb->flags & BB_EXCEPTION_HANDLER) && bb->in_scount == 0) {
1885                         char name [128];
1886                         LLVMValueRef val;
1887
1888                         sprintf (name, "finally_ind_bb%d", bb->block_num);
1889                         val = LLVMBuildAlloca (builder, LLVMInt32Type (), name);
1890                         LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), val);
1891
1892                         ctx->bblocks [bb->block_num].finally_ind = val;
1893
1894                         /*
1895                          * Create a new bblock which CALL_HANDLER can branch to, because branching to the
1896                          * LLVM bblock containing the call to llvm.eh.selector causes problems for the
1897                          * LLVM optimizer passes.
1898                          */
1899                         sprintf (name, "BB_%d_CALL_HANDLER_TARGET", bb->block_num);
1900                         ctx->bblocks [bb->block_num].call_handler_target_bb = LLVMAppendBasicBlock (ctx->lmethod, name);
1901                 }
1902         }
1903
1904  FAILURE:
1905         ;
1906 }
1907
1908 /* Have to export this for AOT */
1909 void
1910 mono_personality (void);
1911         
1912 void
1913 mono_personality (void)
1914 {
1915         /* Not used */
1916         g_assert_not_reached ();
1917 }
1918
1919 static void
1920 process_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, MonoInst *ins)
1921 {
1922         MonoCompile *cfg = ctx->cfg;
1923         LLVMModuleRef module = ctx->module;
1924         LLVMValueRef *values = ctx->values;
1925         LLVMValueRef *addresses = ctx->addresses;
1926         MonoCallInst *call = (MonoCallInst*)ins;
1927         MonoMethodSignature *sig = call->signature;
1928         LLVMValueRef callee = NULL, lcall;
1929         LLVMValueRef *args;
1930         LLVMCallInfo *cinfo;
1931         GSList *l;
1932         int i, len, nargs;
1933         gboolean vretaddr;
1934         LLVMTypeRef llvm_sig;
1935         gpointer target;
1936         gboolean virtual, calli;
1937         LLVMBuilderRef builder = *builder_ref;
1938         LLVMSigInfo sinfo;
1939
1940         if (call->signature->call_convention != MONO_CALL_DEFAULT)
1941                 LLVM_FAILURE (ctx, "non-default callconv");
1942
1943         cinfo = call->cinfo;
1944         if (call->rgctx_arg_reg)
1945                 cinfo->rgctx_arg = TRUE;
1946         if (call->imt_arg_reg)
1947                 cinfo->imt_arg = TRUE;
1948
1949         vretaddr = cinfo && cinfo->ret.storage == LLVMArgVtypeRetAddr;
1950
1951         llvm_sig = sig_to_llvm_sig_full (ctx, sig, cinfo, &sinfo);
1952         CHECK_FAILURE (ctx);
1953
1954         virtual = (ins->opcode == OP_VOIDCALL_MEMBASE || ins->opcode == OP_CALL_MEMBASE || ins->opcode == OP_VCALL_MEMBASE || ins->opcode == OP_LCALL_MEMBASE || ins->opcode == OP_FCALL_MEMBASE);
1955         calli = (ins->opcode == OP_VOIDCALL_REG || ins->opcode == OP_CALL_REG || ins->opcode == OP_VCALL_REG || ins->opcode == OP_LCALL_REG || ins->opcode == OP_FCALL_REG);
1956
1957         /* FIXME: Avoid creating duplicate methods */
1958
1959         if (ins->flags & MONO_INST_HAS_METHOD) {
1960                 if (virtual) {
1961                         callee = NULL;
1962                 } else {
1963                         if (cfg->compile_aot) {
1964                                 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_METHOD, call->method);
1965                                 if (!callee)
1966                                         LLVM_FAILURE (ctx, "can't encode patch");
1967                         } else {
1968                                 callee = LLVMAddFunction (module, "", llvm_sig);
1969  
1970                                 target =
1971                                         mono_create_jit_trampoline_in_domain (mono_domain_get (),
1972                                                                                                                   call->method);
1973                                 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
1974                         }
1975                 }
1976
1977                 if (call->method && strstr (call->method->klass->name, "AsyncVoidMethodBuilder"))
1978                         /* LLVM miscompiles async methods */
1979                         LLVM_FAILURE (ctx, "#13734");
1980         } else if (calli) {
1981         } else {
1982                 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
1983
1984                 if (info) {
1985                         /*
1986                           MonoJumpInfo ji;
1987
1988                           memset (&ji, 0, sizeof (ji));
1989                           ji.type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
1990                           ji.data.target = info->name;
1991
1992                           target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, &ji, FALSE);
1993                         */
1994                         if (cfg->compile_aot) {
1995                                 callee = get_plt_entry (ctx, llvm_sig, MONO_PATCH_INFO_INTERNAL_METHOD, (char*)info->name);
1996                                 if (!callee)
1997                                         LLVM_FAILURE (ctx, "can't encode patch");
1998                         } else {
1999                                 callee = LLVMAddFunction (module, "", llvm_sig);
2000                                 target = (gpointer)mono_icall_get_wrapper (info);
2001                                 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2002                         }
2003                 } else {
2004                         if (cfg->compile_aot) {
2005                                 callee = NULL;
2006                                 if (cfg->abs_patches) {
2007                                         MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
2008                                         if (abs_ji) {
2009                                                 callee = get_plt_entry (ctx, llvm_sig, abs_ji->type, abs_ji->data.target);
2010                                                 if (!callee)
2011                                                         LLVM_FAILURE (ctx, "can't encode patch");
2012                                         }
2013                                 }
2014                                 if (!callee)
2015                                         LLVM_FAILURE (ctx, "aot");
2016                         } else {
2017                                 callee = LLVMAddFunction (module, "", llvm_sig);
2018                                 target = NULL;
2019                                 if (cfg->abs_patches) {
2020                                         MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, call->fptr);
2021                                         if (abs_ji) {
2022                                                 /*
2023                                                  * FIXME: Some trampolines might have
2024                                                  * their own calling convention on some platforms.
2025                                                  */
2026 #ifndef TARGET_AMD64
2027                                                 if (abs_ji->type == MONO_PATCH_INFO_MONITOR_ENTER || abs_ji->type == MONO_PATCH_INFO_MONITOR_EXIT || abs_ji->type == MONO_PATCH_INFO_GENERIC_CLASS_INIT)
2028                                                         LLVM_FAILURE (ctx, "trampoline with own cconv");
2029 #endif
2030                                                 target = mono_resolve_patch_target (cfg->method, cfg->domain, NULL, abs_ji, FALSE);
2031                                                 LLVMAddGlobalMapping (ctx->lmodule->ee, callee, target);
2032                                         }
2033                                 }
2034                                 if (!target)
2035                                         LLVMAddGlobalMapping (ctx->lmodule->ee, callee, (gpointer)call->fptr);
2036                         }
2037                 }
2038         }
2039
2040         if (virtual) {
2041                 int size = sizeof (gpointer);
2042                 LLVMValueRef index;
2043
2044                 g_assert (ins->inst_offset % size == 0);
2045                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
2046
2047                 callee = convert (ctx, LLVMBuildLoad (builder, LLVMBuildGEP (builder, convert (ctx, values [ins->inst_basereg], LLVMPointerType (LLVMPointerType (IntPtrType (), 0), 0)), &index, 1, ""), ""), LLVMPointerType (llvm_sig, 0));
2048         } else if (calli) {
2049                 callee = convert (ctx, values [ins->sreg1], LLVMPointerType (llvm_sig, 0));
2050         } else {
2051                 if (ins->flags & MONO_INST_HAS_METHOD) {
2052                 }
2053         }
2054
2055         /* 
2056          * Collect and convert arguments
2057          */
2058         nargs = (sig->param_count * 2) + sig->hasthis + vretaddr + call->rgctx_reg + call->imt_arg_reg;
2059         len = sizeof (LLVMValueRef) * nargs;
2060         args = alloca (len);
2061         memset (args, 0, len);
2062         l = call->out_ireg_args;
2063
2064         if (call->rgctx_arg_reg) {
2065                 g_assert (values [call->rgctx_arg_reg]);
2066                 g_assert (sinfo.rgctx_arg_pindex < nargs);
2067                 /*
2068                  * On ARM, the imt/rgctx argument is passed in a caller save register, but some of our trampolines etc. clobber it, leading to
2069                  * problems is LLVM moves the arg assignment earlier. To work around this, save the argument into a stack slot and load
2070                  * it using a volatile load.
2071                  */
2072 #ifdef TARGET_ARM
2073                 if (!ctx->imt_rgctx_loc)
2074                         ctx->imt_rgctx_loc = build_alloca_llvm_type (ctx, ctx->lmodule->ptr_type, sizeof (gpointer));
2075                 LLVMBuildStore (builder, convert (ctx, ctx->values [call->rgctx_arg_reg], ctx->lmodule->ptr_type), ctx->imt_rgctx_loc);
2076                 args [sinfo.rgctx_arg_pindex] = mono_llvm_build_load (builder, ctx->imt_rgctx_loc, "", TRUE);
2077 #else
2078                 args [sinfo.rgctx_arg_pindex] = convert (ctx, values [call->rgctx_arg_reg], ctx->lmodule->ptr_type);
2079 #endif
2080         }
2081         if (call->imt_arg_reg) {
2082                 g_assert (values [call->imt_arg_reg]);
2083                 g_assert (sinfo.imt_arg_pindex < nargs);
2084 #ifdef TARGET_ARM
2085                 if (!ctx->imt_rgctx_loc)
2086                         ctx->imt_rgctx_loc = build_alloca_llvm_type (ctx, ctx->lmodule->ptr_type, sizeof (gpointer));
2087                 LLVMBuildStore (builder, convert (ctx, ctx->values [call->imt_arg_reg], ctx->lmodule->ptr_type), ctx->imt_rgctx_loc);
2088                 args [sinfo.imt_arg_pindex] = mono_llvm_build_load (builder, ctx->imt_rgctx_loc, "", TRUE);
2089 #else
2090                 args [sinfo.imt_arg_pindex] = convert (ctx, values [call->imt_arg_reg], ctx->lmodule->ptr_type);
2091 #endif
2092         }
2093
2094         if (vretaddr) {
2095                 if (!addresses [call->inst.dreg])
2096                         addresses [call->inst.dreg] = build_alloca (ctx, sig->ret);
2097                 g_assert (sinfo.vret_arg_pindex < nargs);
2098                 args [sinfo.vret_arg_pindex] = LLVMBuildPtrToInt (builder, addresses [call->inst.dreg], IntPtrType (), "");
2099         }
2100
2101         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2102                 guint32 regpair;
2103                 int reg, pindex;
2104                 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i] : NULL;
2105
2106                 if (sig->hasthis) {
2107                         if (i == 0)
2108                                 pindex = sinfo.this_arg_pindex;
2109                         else
2110                                 pindex = sinfo.pindexes [i - 1];
2111                 } else {
2112                         pindex = sinfo.pindexes [i];
2113                 }
2114
2115                 regpair = (guint32)(gssize)(l->data);
2116                 reg = regpair & 0xffffff;
2117                 args [pindex] = values [reg];
2118                 if (ainfo->storage == LLVMArgVtypeInReg) {
2119                         int j;
2120                         LLVMValueRef regs [2];
2121                         guint32 nregs;
2122
2123                         g_assert (ainfo);
2124
2125                         g_assert (addresses [reg]);
2126
2127                         emit_vtype_to_reg (ctx, builder, sig->params [i - sig->hasthis], addresses [reg], ainfo, regs, &nregs);
2128                         for (j = 0; j < nregs; ++j)
2129                                 args [pindex ++] = regs [j];
2130
2131                         // FIXME: alignment
2132                         // FIXME: Get rid of the VMOVE
2133                 } else if (ainfo->storage == LLVMArgVtypeByVal) {
2134                         g_assert (addresses [reg]);
2135                         args [pindex] = addresses [reg];
2136                 } else {
2137                         g_assert (args [pindex]);
2138                         if (i == 0 && sig->hasthis)
2139                                 args [pindex] = convert (ctx, args [pindex], ThisType ());
2140                         else
2141                                 args [pindex] = convert (ctx, args [pindex], type_to_llvm_arg_type (ctx, sig->params [i - sig->hasthis]));
2142                 }
2143
2144                 l = l->next;
2145         }
2146
2147         // FIXME: Align call sites
2148
2149         /*
2150          * Emit the call
2151          */
2152
2153         lcall = emit_call (ctx, bb, &builder, callee, args, LLVMCountParamTypes (llvm_sig));
2154
2155         /*
2156          * Modify cconv and parameter attributes to pass rgctx/imt correctly.
2157          */
2158 #if defined(MONO_ARCH_IMT_REG) && defined(MONO_ARCH_RGCTX_REG)
2159         g_assert (MONO_ARCH_IMT_REG == MONO_ARCH_RGCTX_REG);
2160 #endif
2161         /* The two can't be used together, so use only one LLVM calling conv to pass them */
2162         g_assert (!(call->rgctx_arg_reg && call->imt_arg_reg));
2163         if (!sig->pinvoke)
2164                 LLVMSetInstructionCallConv (lcall, LLVMMono1CallConv);
2165
2166         if (call->rgctx_arg_reg)
2167                 LLVMAddInstrAttribute (lcall, 1 + sinfo.rgctx_arg_pindex, LLVMInRegAttribute);
2168         if (call->imt_arg_reg)
2169                 LLVMAddInstrAttribute (lcall, 1 + sinfo.imt_arg_pindex, LLVMInRegAttribute);
2170
2171         /* Add byval attributes if needed */
2172         for (i = 0; i < sig->param_count; ++i) {
2173                 LLVMArgInfo *ainfo = call->cinfo ? &call->cinfo->args [i + sig->hasthis] : NULL;
2174
2175                 if (ainfo && ainfo->storage == LLVMArgVtypeByVal) {
2176                         LLVMAddInstrAttribute (lcall, 1 + sinfo.pindexes [i], LLVMByValAttribute);
2177                 }
2178         }
2179
2180         /*
2181          * Convert the result
2182          */
2183         if (cinfo && cinfo->ret.storage == LLVMArgVtypeInReg) {
2184                 LLVMValueRef regs [2];
2185
2186                 if (!addresses [ins->dreg])
2187                         addresses [ins->dreg] = build_alloca (ctx, sig->ret);
2188
2189                 regs [0] = LLVMBuildExtractValue (builder, lcall, 0, "");
2190                 if (cinfo->ret.pair_storage [1] != LLVMArgNone)
2191                         regs [1] = LLVMBuildExtractValue (builder, lcall, 1, "");
2192                                         
2193                 emit_reg_to_vtype (ctx, builder, sig->ret, addresses [ins->dreg], &cinfo->ret, regs);
2194         } else if (sig->ret->type != MONO_TYPE_VOID && !vretaddr) {
2195                 /* If the method returns an unsigned value, need to zext it */
2196
2197                 values [ins->dreg] = convert_full (ctx, lcall, llvm_type_to_stack_type (type_to_llvm_type (ctx, sig->ret)), type_is_unsigned (ctx, sig->ret));
2198         }
2199
2200         *builder_ref = ctx->builder;
2201
2202         g_free (sinfo.pindexes);
2203         
2204         return;
2205  FAILURE:
2206         return;
2207 }
2208
2209 static void
2210 process_bb (EmitContext *ctx, MonoBasicBlock *bb)
2211 {
2212         MonoCompile *cfg = ctx->cfg;
2213         MonoMethodSignature *sig = ctx->sig;
2214         LLVMValueRef method = ctx->lmethod;
2215         LLVMValueRef *values = ctx->values;
2216         LLVMValueRef *addresses = ctx->addresses;
2217         int i;
2218         LLVMCallInfo *linfo = ctx->linfo;
2219         LLVMModuleRef module = ctx->module;
2220         BBInfo *bblocks = ctx->bblocks;
2221         MonoInst *ins;
2222         LLVMBasicBlockRef cbb;
2223         LLVMBuilderRef builder, starting_builder;
2224         gboolean has_terminator;
2225         LLVMValueRef v;
2226         LLVMValueRef lhs, rhs;
2227         int nins = 0;
2228
2229         cbb = get_bb (ctx, bb);
2230         builder = create_builder (ctx);
2231         ctx->builder = builder;
2232         LLVMPositionBuilderAtEnd (builder, cbb);
2233
2234         if (bb == cfg->bb_entry)
2235                 emit_entry_bb (ctx, builder);
2236         CHECK_FAILURE (ctx);
2237
2238         if (bb->flags & BB_EXCEPTION_HANDLER) {
2239                 LLVMTypeRef i8ptr;
2240                 LLVMValueRef personality;
2241                 LLVMBasicBlockRef target_bb;
2242                 MonoInst *exvar;
2243                 static gint32 mapping_inited;
2244                 static int ti_generator;
2245                 char ti_name [128];
2246                 MonoClass **ti;
2247                 LLVMValueRef type_info;
2248                 int clause_index;
2249
2250                 if (!bblocks [bb->block_num].invoke_target) {
2251                         /*
2252                          * LLVM asserts if llvm.eh.selector is called from a bblock which
2253                          * doesn't have an invoke pointing at it.
2254                          * Update: LLVM no longer asserts, but some tests in exceptions.exe now fail.
2255                          */
2256                         LLVM_FAILURE (ctx, "handler without invokes");
2257                 }
2258
2259                 // <resultval> = landingpad <somety> personality <type> <pers_fn> <clause>+
2260
2261                 if (cfg->compile_aot) {
2262                         /* Use a dummy personality function */
2263                         personality = LLVMGetNamedFunction (module, "mono_aot_personality");
2264                         g_assert (personality);
2265                 } else {
2266                         personality = LLVMGetNamedFunction (module, "mono_personality");
2267                         if (InterlockedCompareExchange (&mapping_inited, 1, 0) == 0)
2268                                 LLVMAddGlobalMapping (ctx->lmodule->ee, personality, mono_personality);
2269                 }
2270
2271                 i8ptr = LLVMPointerType (LLVMInt8Type (), 0);
2272
2273                 clause_index = (mono_get_block_region_notry (cfg, bb->region) >> 8) - 1;
2274
2275                 /*
2276                  * Create the type info
2277                  */
2278                 sprintf (ti_name, "type_info_%d", ti_generator);
2279                 ti_generator ++;
2280
2281                 if (cfg->compile_aot) {
2282                         /* decode_eh_frame () in aot-runtime.c will decode this */
2283                         type_info = LLVMAddGlobal (module, LLVMInt32Type (), ti_name);
2284                         LLVMSetInitializer (type_info, LLVMConstInt (LLVMInt32Type (), clause_index, FALSE));
2285
2286                         /*
2287                          * These symbols are not really used, the clause_index is embedded into the EH tables generated by DwarfMonoException in LLVM.
2288                          */
2289                         LLVMSetLinkage (type_info, LLVMInternalLinkage);
2290
2291                         /* 
2292                          * Enabling this causes llc to crash:
2293                          * http://llvm.org/bugs/show_bug.cgi?id=6102
2294                          */
2295                         //LLVM_FAILURE (ctx, "aot+clauses");
2296 #ifdef TARGET_ARM
2297                         // test_0_invalid_unbox_arrays () fails
2298                         LLVM_FAILURE (ctx, "aot+clauses");
2299 #endif
2300                 } else {
2301                         /*
2302                          * After the cfg mempool is freed, the type info will point to stale memory,
2303                          * but this is not a problem, since we decode it once in exception_cb during
2304                          * compilation.
2305                          */
2306                         ti = mono_mempool_alloc (cfg->mempool, sizeof (gint32));
2307                         *(gint32*)ti = clause_index;
2308
2309                         type_info = LLVMAddGlobal (module, i8ptr, ti_name);
2310
2311                         LLVMAddGlobalMapping (ctx->lmodule->ee, type_info, ti);
2312                 }
2313
2314                 {
2315                         LLVMTypeRef members [2], ret_type;
2316                         LLVMValueRef landing_pad;
2317
2318                         members [0] = i8ptr;
2319                         members [1] = LLVMInt32Type ();
2320                         ret_type = LLVMStructType (members, 2, FALSE);
2321
2322                         landing_pad = LLVMBuildLandingPad (builder, ret_type, personality, 1, "");
2323                         LLVMAddClause (landing_pad, type_info);
2324
2325                         /* Store the exception into the exvar */
2326                         if (bb->in_scount == 1) {
2327                                 g_assert (bb->in_scount == 1);
2328                                 exvar = bb->in_stack [0];
2329
2330                                 // FIXME: This is shared with filter clauses ?
2331                                 g_assert (!values [exvar->dreg]);
2332
2333                                 values [exvar->dreg] = LLVMBuildExtractValue (builder, landing_pad, 0, "ex_obj");
2334                                 emit_volatile_store (ctx, exvar->dreg);
2335                         }
2336                 }
2337
2338                 /* Start a new bblock which CALL_HANDLER can branch to */
2339                 target_bb = bblocks [bb->block_num].call_handler_target_bb;
2340                 if (target_bb) {
2341                         LLVMBuildBr (builder, target_bb);
2342
2343                         ctx->builder = builder = create_builder (ctx);
2344                         LLVMPositionBuilderAtEnd (ctx->builder, target_bb);
2345
2346                         ctx->bblocks [bb->block_num].end_bblock = target_bb;
2347                 }
2348         }
2349
2350         has_terminator = FALSE;
2351         starting_builder = builder;
2352         for (ins = bb->code; ins; ins = ins->next) {
2353                 const char *spec = LLVM_INS_INFO (ins->opcode);
2354                 char *dname = NULL;
2355                 char dname_buf [128];
2356
2357                 emit_dbg_loc (ctx, builder, ins->cil_code);
2358
2359                 nins ++;
2360                 if (nins > 5000 && builder == starting_builder) {
2361                         /* some steps in llc are non-linear in the size of basic blocks, see #5714 */
2362                         LLVM_FAILURE (ctx, "basic block too long");
2363                 }
2364
2365                 if (has_terminator)
2366                         /* There could be instructions after a terminator, skip them */
2367                         break;
2368
2369                 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins)) {
2370                         sprintf (dname_buf, "t%d", ins->dreg);
2371                         dname = dname_buf;
2372                 }
2373
2374                 if (spec [MONO_INST_SRC1] != ' ' && spec [MONO_INST_SRC1] != 'v') {
2375                         MonoInst *var = get_vreg_to_inst (cfg, ins->sreg1);
2376
2377                         if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2378                                 lhs = emit_volatile_load (ctx, ins->sreg1);
2379                         } else {
2380                                 /* It is ok for SETRET to have an uninitialized argument */
2381                                 if (!values [ins->sreg1] && ins->opcode != OP_SETRET)
2382                                         LLVM_FAILURE (ctx, "sreg1");
2383                                 lhs = values [ins->sreg1];
2384                         }
2385                 } else {
2386                         lhs = NULL;
2387                 }
2388
2389                 if (spec [MONO_INST_SRC2] != ' ' && spec [MONO_INST_SRC2] != ' ') {
2390                         MonoInst *var = get_vreg_to_inst (cfg, ins->sreg2);
2391                         if (var && var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) {
2392                                 rhs = emit_volatile_load (ctx, ins->sreg2);
2393                         } else {
2394                                 if (!values [ins->sreg2])
2395                                         LLVM_FAILURE (ctx, "sreg2");
2396                                 rhs = values [ins->sreg2];
2397                         }
2398                 } else {
2399                         rhs = NULL;
2400                 }
2401
2402                 //mono_print_ins (ins);
2403                 switch (ins->opcode) {
2404                 case OP_NOP:
2405                 case OP_NOT_NULL:
2406                 case OP_LIVERANGE_START:
2407                 case OP_LIVERANGE_END:
2408                         break;
2409                 case OP_ICONST:
2410                         values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE);
2411                         break;
2412                 case OP_I8CONST:
2413 #if SIZEOF_VOID_P == 4
2414                         values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2415 #else
2416                         values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), (gint64)ins->inst_c0, FALSE);
2417 #endif
2418                         break;
2419                 case OP_R8CONST:
2420                         values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), *(double*)ins->inst_p0);
2421                         break;
2422                 case OP_R4CONST:
2423                         values [ins->dreg] = LLVMConstFPExt (LLVMConstReal (LLVMFloatType (), *(float*)ins->inst_p0), LLVMDoubleType ());
2424                         break;
2425                 case OP_DUMMY_ICONST:
2426                         values [ins->dreg] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
2427                         break;
2428                 case OP_DUMMY_I8CONST:
2429                         values [ins->dreg] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
2430                         break;
2431                 case OP_DUMMY_R8CONST:
2432                         values [ins->dreg] = LLVMConstReal (LLVMDoubleType (), 0.0f);
2433                         break;
2434                 case OP_BR:
2435                         LLVMBuildBr (builder, get_bb (ctx, ins->inst_target_bb));
2436                         has_terminator = TRUE;
2437                         break;
2438                 case OP_SWITCH: {
2439                         int i;
2440                         LLVMValueRef v;
2441                         char bb_name [128];
2442                         LLVMBasicBlockRef new_bb;
2443                         LLVMBuilderRef new_builder;
2444
2445                         // The default branch is already handled
2446                         // FIXME: Handle it here
2447
2448                         /* Start new bblock */
2449                         sprintf (bb_name, "SWITCH_DEFAULT_BB%d", ctx->default_index ++);
2450                         new_bb = LLVMAppendBasicBlock (ctx->lmethod, bb_name);
2451
2452                         lhs = convert (ctx, lhs, LLVMInt32Type ());
2453                         v = LLVMBuildSwitch (builder, lhs, new_bb, GPOINTER_TO_UINT (ins->klass));
2454                         for (i = 0; i < GPOINTER_TO_UINT (ins->klass); ++i) {
2455                                 MonoBasicBlock *target_bb = ins->inst_many_bb [i];
2456
2457                                 LLVMAddCase (v, LLVMConstInt (LLVMInt32Type (), i, FALSE), get_bb (ctx, target_bb));
2458                         }
2459
2460                         new_builder = create_builder (ctx);
2461                         LLVMPositionBuilderAtEnd (new_builder, new_bb);
2462                         LLVMBuildUnreachable (new_builder);
2463
2464                         has_terminator = TRUE;
2465                         g_assert (!ins->next);
2466                                 
2467                         break;
2468                 }
2469
2470                 case OP_SETRET:
2471                         if (linfo->ret.storage == LLVMArgVtypeInReg) {
2472                                 LLVMTypeRef ret_type = LLVMGetReturnType (LLVMGetElementType (LLVMTypeOf (method)));
2473                                 LLVMValueRef part1, retval;
2474                                 int size;
2475
2476                                 size = get_vtype_size (sig->ret);
2477
2478                                 g_assert (addresses [ins->sreg1]);
2479
2480                                 g_assert (linfo->ret.pair_storage [0] == LLVMArgInIReg);
2481                                 g_assert (linfo->ret.pair_storage [1] == LLVMArgNone);
2482                                         
2483                                 part1 = convert (ctx, LLVMBuildLoad (builder, LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMIntType (size * 8), 0), ""), ""), IntPtrType ());
2484
2485                                 retval = LLVMBuildInsertValue (builder, LLVMGetUndef (ret_type), part1, 0, "");
2486
2487                                 LLVMBuildRet (builder, retval);
2488                                 break;
2489                         }
2490
2491                         if (linfo->ret.storage == LLVMArgVtypeRetAddr) {
2492                                 LLVMBuildRetVoid (builder);
2493                                 break;
2494                         }
2495
2496                         if (!lhs || ctx->is_dead [ins->sreg1]) {
2497                                 /* 
2498                                  * The method did not set its return value, probably because it
2499                                  * ends with a throw.
2500                                  */
2501                                 if (cfg->vret_addr)
2502                                         LLVMBuildRetVoid (builder);
2503                                 else
2504                                         LLVMBuildRet (builder, LLVMConstNull (type_to_llvm_type (ctx, sig->ret)));
2505                         } else {
2506                                 LLVMBuildRet (builder, convert (ctx, lhs, type_to_llvm_type (ctx, sig->ret)));
2507                         }
2508                         has_terminator = TRUE;
2509                         break;
2510                 case OP_ICOMPARE:
2511                 case OP_FCOMPARE:
2512                 case OP_LCOMPARE:
2513                 case OP_COMPARE:
2514                 case OP_ICOMPARE_IMM:
2515                 case OP_LCOMPARE_IMM:
2516                 case OP_COMPARE_IMM: {
2517                         CompRelation rel;
2518                         LLVMValueRef cmp;
2519
2520                         if (ins->next->opcode == OP_NOP)
2521                                 break;
2522
2523                         if (ins->next->opcode == OP_BR)
2524                                 /* The comparison result is not needed */
2525                                 continue;
2526
2527                         rel = mono_opcode_to_cond (ins->next->opcode);
2528
2529                         if (ins->opcode == OP_ICOMPARE_IMM) {
2530                                 lhs = convert (ctx, lhs, LLVMInt32Type ());
2531                                 rhs = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2532                         }
2533                         if (ins->opcode == OP_LCOMPARE_IMM) {
2534                                 lhs = convert (ctx, lhs, LLVMInt64Type ());
2535                                 rhs = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2536                         }
2537                         if (ins->opcode == OP_LCOMPARE) {
2538                                 lhs = convert (ctx, lhs, LLVMInt64Type ());
2539                                 rhs = convert (ctx, rhs, LLVMInt64Type ());
2540                         }
2541                         if (ins->opcode == OP_ICOMPARE) {
2542                                 lhs = convert (ctx, lhs, LLVMInt32Type ());
2543                                 rhs = convert (ctx, rhs, LLVMInt32Type ());
2544                         }
2545
2546                         if (lhs && rhs) {
2547                                 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
2548                                         rhs = convert (ctx, rhs, LLVMTypeOf (lhs));
2549                                 else if (LLVMGetTypeKind (LLVMTypeOf (rhs)) == LLVMPointerTypeKind)
2550                                         lhs = convert (ctx, lhs, LLVMTypeOf (rhs));
2551                         }
2552
2553                         /* We use COMPARE+SETcc/Bcc, llvm uses SETcc+br cond */
2554                         if (ins->opcode == OP_FCOMPARE)
2555                                 cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
2556                         else if (ins->opcode == OP_COMPARE_IMM) {
2557                                 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind && ins->inst_imm == 0)
2558                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, LLVMConstNull (LLVMTypeOf (lhs)), "");
2559                                 else
2560                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), "");
2561                         } else if (ins->opcode == OP_LCOMPARE_IMM) {
2562                                 if (SIZEOF_REGISTER == 4 && COMPILE_LLVM (cfg))  {
2563                                         /* The immediate is encoded in two fields */
2564                                         guint64 l = ((guint64)(guint32)ins->inst_offset << 32) | ((guint32)ins->inst_imm);
2565                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), l, FALSE), "");
2566                                 } else {
2567                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, LLVMInt64Type ()), LLVMConstInt (LLVMInt64Type (), ins->inst_imm, FALSE), "");
2568                                 }
2569                         }
2570                         else if (ins->opcode == OP_COMPARE) {
2571                                 if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind && LLVMTypeOf (lhs) == LLVMTypeOf (rhs))
2572                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
2573                                 else
2574                                         cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], convert (ctx, lhs, IntPtrType ()), convert (ctx, rhs, IntPtrType ()), "");
2575                         } else
2576                                 cmp = LLVMBuildICmp (builder, cond_to_llvm_cond [rel], lhs, rhs, "");
2577
2578                         if (MONO_IS_COND_BRANCH_OP (ins->next)) {
2579                                 if (ins->next->inst_true_bb == ins->next->inst_false_bb) {
2580                                         /*
2581                                          * If the target bb contains PHI instructions, LLVM requires
2582                                          * two PHI entries for this bblock, while we only generate one.
2583                                          * So convert this to an unconditional bblock. (bxc #171).
2584                                          */
2585                                         LLVMBuildBr (builder, get_bb (ctx, ins->next->inst_true_bb));
2586                                 } else {
2587                                         LLVMBuildCondBr (builder, cmp, get_bb (ctx, ins->next->inst_true_bb), get_bb (ctx, ins->next->inst_false_bb));
2588                                 }
2589                                 has_terminator = TRUE;
2590                         } else if (MONO_IS_SETCC (ins->next)) {
2591                                 sprintf (dname_buf, "t%d", ins->next->dreg);
2592                                 dname = dname_buf;
2593                                 values [ins->next->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
2594
2595                                 /* Add stores for volatile variables */
2596                                 emit_volatile_store (ctx, ins->next->dreg);
2597                         } else if (MONO_IS_COND_EXC (ins->next)) {
2598                                 emit_cond_system_exception (ctx, bb, ins->next->inst_p1, cmp);
2599                                 CHECK_FAILURE (ctx);
2600                                 builder = ctx->builder;
2601                         } else {
2602                                 LLVM_FAILURE (ctx, "next");
2603                         }
2604
2605                         ins = ins->next;
2606                         break;
2607                 }
2608                 case OP_FCEQ:
2609                 case OP_FCLT:
2610                 case OP_FCLT_UN:
2611                 case OP_FCGT:
2612                 case OP_FCGT_UN: {
2613                         CompRelation rel;
2614                         LLVMValueRef cmp;
2615
2616                         rel = mono_opcode_to_cond (ins->opcode);
2617
2618                         cmp = LLVMBuildFCmp (builder, fpcond_to_llvm_cond [rel], convert (ctx, lhs, LLVMDoubleType ()), convert (ctx, rhs, LLVMDoubleType ()), "");
2619                         values [ins->dreg] = LLVMBuildZExt (builder, cmp, LLVMInt32Type (), dname);
2620                         break;
2621                 }
2622                 case OP_PHI:
2623                 case OP_FPHI:
2624                 case OP_VPHI:
2625                 case OP_XPHI: {
2626                         int i;
2627                         gboolean empty = TRUE;
2628
2629                         /* Check that all input bblocks really branch to us */
2630                         for (i = 0; i < bb->in_count; ++i) {
2631                                 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_NOT_REACHED)
2632                                         ins->inst_phi_args [i + 1] = -1;
2633                                 else
2634                                         empty = FALSE;
2635                         }
2636
2637                         if (empty) {
2638                                 /* LLVM doesn't like phi instructions with zero operands */
2639                                 ctx->is_dead [ins->dreg] = TRUE;
2640                                 break;
2641                         }                                       
2642
2643                         /* Created earlier, insert it now */
2644                         LLVMInsertIntoBuilder (builder, values [ins->dreg]);
2645
2646                         for (i = 0; i < ins->inst_phi_args [0]; i++) {
2647                                 int sreg1 = ins->inst_phi_args [i + 1];
2648                                 int count, j;
2649
2650                                 /* 
2651                                  * Count the number of times the incoming bblock branches to us,
2652                                  * since llvm requires a separate entry for each.
2653                                  */
2654                                 if (bb->in_bb [i]->last_ins && bb->in_bb [i]->last_ins->opcode == OP_SWITCH) {
2655                                         MonoInst *switch_ins = bb->in_bb [i]->last_ins;
2656
2657                                         count = 0;
2658                                         for (j = 0; j < GPOINTER_TO_UINT (switch_ins->klass); ++j) {
2659                                                 if (switch_ins->inst_many_bb [j] == bb)
2660                                                         count ++;
2661                                         }
2662                                 } else {
2663                                         count = 1;
2664                                 }
2665
2666                                 /* Remember for later */
2667                                 for (j = 0; j < count; ++j) {
2668                                         PhiNode *node = mono_mempool_alloc0 (ctx->mempool, sizeof (PhiNode));
2669                                         node->bb = bb;
2670                                         node->phi = ins;
2671                                         node->in_bb = bb->in_bb [i];
2672                                         node->sreg = sreg1;
2673                                         bblocks [bb->in_bb [i]->block_num].phi_nodes = g_slist_prepend_mempool (ctx->mempool, bblocks [bb->in_bb [i]->block_num].phi_nodes, node);
2674                                 }
2675                         }
2676                         break;
2677                 }
2678                 case OP_MOVE:
2679                 case OP_LMOVE:
2680                 case OP_XMOVE:
2681                 case OP_SETFRET:
2682                         g_assert (lhs);
2683                         values [ins->dreg] = lhs;
2684                         break;
2685                 case OP_FMOVE: {
2686                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
2687                                 
2688                         g_assert (lhs);
2689                         values [ins->dreg] = lhs;
2690
2691                         if (var && var->klass->byval_arg.type == MONO_TYPE_R4) {
2692                                 /* 
2693                                  * This is added by the spilling pass in case of the JIT,
2694                                  * but we have to do it ourselves.
2695                                  */
2696                                 values [ins->dreg] = convert (ctx, values [ins->dreg], LLVMFloatType ());
2697                         }
2698                         break;
2699                 }
2700                 case OP_IADD:
2701                 case OP_ISUB:
2702                 case OP_IAND:
2703                 case OP_IMUL:
2704                 case OP_IDIV:
2705                 case OP_IDIV_UN:
2706                 case OP_IREM:
2707                 case OP_IREM_UN:
2708                 case OP_IOR:
2709                 case OP_IXOR:
2710                 case OP_ISHL:
2711                 case OP_ISHR:
2712                 case OP_ISHR_UN:
2713                 case OP_FADD:
2714                 case OP_FSUB:
2715                 case OP_FMUL:
2716                 case OP_FDIV:
2717                 case OP_LADD:
2718                 case OP_LSUB:
2719                 case OP_LMUL:
2720                 case OP_LDIV:
2721                 case OP_LDIV_UN:
2722                 case OP_LREM:
2723                 case OP_LREM_UN:
2724                 case OP_LAND:
2725                 case OP_LOR:
2726                 case OP_LXOR:
2727                 case OP_LSHL:
2728                 case OP_LSHR:
2729                 case OP_LSHR_UN:
2730                         lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
2731                         rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
2732
2733                         switch (ins->opcode) {
2734                         case OP_IADD:
2735                         case OP_LADD:
2736                                 values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, dname);
2737                                 break;
2738                         case OP_ISUB:
2739                         case OP_LSUB:
2740                                 values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, dname);
2741                                 break;
2742                         case OP_IMUL:
2743                         case OP_LMUL:
2744                                 values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, dname);
2745                                 break;
2746                         case OP_IREM:
2747                         case OP_LREM:
2748                                 values [ins->dreg] = LLVMBuildSRem (builder, lhs, rhs, dname);
2749                                 break;
2750                         case OP_IREM_UN:
2751                         case OP_LREM_UN:
2752                                 values [ins->dreg] = LLVMBuildURem (builder, lhs, rhs, dname);
2753                                 break;
2754                         case OP_IDIV:
2755                         case OP_LDIV:
2756                                 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, rhs, dname);
2757                                 break;
2758                         case OP_IDIV_UN:
2759                         case OP_LDIV_UN:
2760                                 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, rhs, dname);
2761                                 break;
2762                         case OP_FDIV:
2763                                 values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, dname);
2764                                 break;
2765                         case OP_IAND:
2766                         case OP_LAND:
2767                                 values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, dname);
2768                                 break;
2769                         case OP_IOR:
2770                         case OP_LOR:
2771                                 values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, dname);
2772                                 break;
2773                         case OP_IXOR:
2774                         case OP_LXOR:
2775                                 values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, dname);
2776                                 break;
2777                         case OP_ISHL:
2778                         case OP_LSHL:
2779                                 values [ins->dreg] = LLVMBuildShl (builder, lhs, rhs, dname);
2780                                 break;
2781                         case OP_ISHR:
2782                         case OP_LSHR:
2783                                 values [ins->dreg] = LLVMBuildAShr (builder, lhs, rhs, dname);
2784                                 break;
2785                         case OP_ISHR_UN:
2786                         case OP_LSHR_UN:
2787                                 values [ins->dreg] = LLVMBuildLShr (builder, lhs, rhs, dname);
2788                                 break;
2789
2790                         case OP_FADD:
2791                                 values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, dname);
2792                                 break;
2793                         case OP_FSUB:
2794                                 values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, dname);
2795                                 break;
2796                         case OP_FMUL:
2797                                 values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, dname);
2798                                 break;
2799
2800                         default:
2801                                 g_assert_not_reached ();
2802                         }
2803                         break;
2804                 case OP_IADD_IMM:
2805                 case OP_ISUB_IMM:
2806                 case OP_IMUL_IMM:
2807                 case OP_IREM_IMM:
2808                 case OP_IREM_UN_IMM:
2809                 case OP_IDIV_IMM:
2810                 case OP_IDIV_UN_IMM:
2811                 case OP_IAND_IMM:
2812                 case OP_IOR_IMM:
2813                 case OP_IXOR_IMM:
2814                 case OP_ISHL_IMM:
2815                 case OP_ISHR_IMM:
2816                 case OP_ISHR_UN_IMM:
2817                 case OP_LADD_IMM:
2818                 case OP_LSUB_IMM:
2819                 case OP_LREM_IMM:
2820                 case OP_LAND_IMM:
2821                 case OP_LOR_IMM:
2822                 case OP_LXOR_IMM:
2823                 case OP_LSHL_IMM:
2824                 case OP_LSHR_IMM:
2825                 case OP_LSHR_UN_IMM:
2826                 case OP_ADD_IMM:
2827                 case OP_AND_IMM:
2828                 case OP_MUL_IMM:
2829                 case OP_SHL_IMM:
2830                 case OP_SHR_IMM:
2831                 case OP_SHR_UN_IMM: {
2832                         LLVMValueRef imm;
2833
2834                         if (spec [MONO_INST_SRC1] == 'l') {
2835                                 imm = LLVMConstInt (LLVMInt64Type (), GET_LONG_IMM (ins), FALSE);
2836                         } else {
2837                                 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2838                         }
2839
2840 #if SIZEOF_VOID_P == 4
2841                         if (ins->opcode == OP_LSHL_IMM || ins->opcode == OP_LSHR_IMM || ins->opcode == OP_LSHR_UN_IMM)
2842                                 imm = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
2843 #endif
2844
2845                         if (LLVMGetTypeKind (LLVMTypeOf (lhs)) == LLVMPointerTypeKind)
2846                                 lhs = convert (ctx, lhs, IntPtrType ());
2847                         imm = convert (ctx, imm, LLVMTypeOf (lhs));
2848                         switch (ins->opcode) {
2849                         case OP_IADD_IMM:
2850                         case OP_LADD_IMM:
2851                         case OP_ADD_IMM:
2852                                 values [ins->dreg] = LLVMBuildAdd (builder, lhs, imm, dname);
2853                                 break;
2854                         case OP_ISUB_IMM:
2855                         case OP_LSUB_IMM:
2856                                 values [ins->dreg] = LLVMBuildSub (builder, lhs, imm, dname);
2857                                 break;
2858                         case OP_IMUL_IMM:
2859                         case OP_MUL_IMM:
2860                                 values [ins->dreg] = LLVMBuildMul (builder, lhs, imm, dname);
2861                                 break;
2862                         case OP_IDIV_IMM:
2863                         case OP_LDIV_IMM:
2864                                 values [ins->dreg] = LLVMBuildSDiv (builder, lhs, imm, dname);
2865                                 break;
2866                         case OP_IDIV_UN_IMM:
2867                         case OP_LDIV_UN_IMM:
2868                                 values [ins->dreg] = LLVMBuildUDiv (builder, lhs, imm, dname);
2869                                 break;
2870                         case OP_IREM_IMM:
2871                         case OP_LREM_IMM:
2872                                 values [ins->dreg] = LLVMBuildSRem (builder, lhs, imm, dname);
2873                                 break;
2874                         case OP_IREM_UN_IMM:
2875                                 values [ins->dreg] = LLVMBuildURem (builder, lhs, imm, dname);
2876                                 break;
2877                         case OP_IAND_IMM:
2878                         case OP_LAND_IMM:
2879                         case OP_AND_IMM:
2880                                 values [ins->dreg] = LLVMBuildAnd (builder, lhs, imm, dname);
2881                                 break;
2882                         case OP_IOR_IMM:
2883                         case OP_LOR_IMM:
2884                                 values [ins->dreg] = LLVMBuildOr (builder, lhs, imm, dname);
2885                                 break;
2886                         case OP_IXOR_IMM:
2887                         case OP_LXOR_IMM:
2888                                 values [ins->dreg] = LLVMBuildXor (builder, lhs, imm, dname);
2889                                 break;
2890                         case OP_ISHL_IMM:
2891                         case OP_LSHL_IMM:
2892                         case OP_SHL_IMM:
2893                                 values [ins->dreg] = LLVMBuildShl (builder, lhs, imm, dname);
2894                                 break;
2895                         case OP_ISHR_IMM:
2896                         case OP_LSHR_IMM:
2897                         case OP_SHR_IMM:
2898                                 values [ins->dreg] = LLVMBuildAShr (builder, lhs, imm, dname);
2899                                 break;
2900                         case OP_ISHR_UN_IMM:
2901                                 /* This is used to implement conv.u4, so the lhs could be an i8 */
2902                                 lhs = convert (ctx, lhs, LLVMInt32Type ());
2903                                 imm = convert (ctx, imm, LLVMInt32Type ());
2904                                 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
2905                                 break;
2906                         case OP_LSHR_UN_IMM:
2907                         case OP_SHR_UN_IMM:
2908                                 values [ins->dreg] = LLVMBuildLShr (builder, lhs, imm, dname);
2909                                 break;
2910                         default:
2911                                 g_assert_not_reached ();
2912                         }
2913                         break;
2914                 }
2915                 case OP_INEG:
2916                         values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
2917                         break;
2918                 case OP_LNEG:
2919                         values [ins->dreg] = LLVMBuildSub (builder, LLVMConstInt (LLVMInt64Type (), 0, FALSE), lhs, dname);
2920                         break;
2921                 case OP_FNEG:
2922                         lhs = convert (ctx, lhs, LLVMDoubleType ());
2923                         values [ins->dreg] = LLVMBuildFSub (builder, LLVMConstReal (LLVMDoubleType (), 0.0), lhs, dname);
2924                         break;
2925                 case OP_INOT: {
2926                         guint32 v = 0xffffffff;
2927                         values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt32Type (), v, FALSE), convert (ctx, lhs, LLVMInt32Type ()), dname);
2928                         break;
2929                 }
2930                 case OP_LNOT: {
2931                         guint64 v = 0xffffffffffffffffLL;
2932                         values [ins->dreg] = LLVMBuildXor (builder, LLVMConstInt (LLVMInt64Type (), v, FALSE), lhs, dname);
2933                         break;
2934                 }
2935 #if defined(TARGET_X86) || defined(TARGET_AMD64)
2936                 case OP_X86_LEA: {
2937                         LLVMValueRef v1, v2;
2938
2939                         v1 = LLVMBuildMul (builder, convert (ctx, rhs, IntPtrType ()), LLVMConstInt (IntPtrType (), (1 << ins->backend.shift_amount), FALSE), "");
2940                         v2 = LLVMBuildAdd (builder, convert (ctx, lhs, IntPtrType ()), v1, "");
2941                         values [ins->dreg] = LLVMBuildAdd (builder, v2, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), dname);
2942                         break;
2943                 }
2944 #endif
2945
2946                 case OP_ICONV_TO_I1:
2947                 case OP_ICONV_TO_I2:
2948                 case OP_ICONV_TO_I4:
2949                 case OP_ICONV_TO_U1:
2950                 case OP_ICONV_TO_U2:
2951                 case OP_ICONV_TO_U4:
2952                 case OP_LCONV_TO_I1:
2953                 case OP_LCONV_TO_I2:
2954                 case OP_LCONV_TO_U1:
2955                 case OP_LCONV_TO_U2:
2956                 case OP_LCONV_TO_U4: {
2957                         gboolean sign;
2958
2959                         sign = (ins->opcode == OP_ICONV_TO_I1) || (ins->opcode == OP_ICONV_TO_I2) || (ins->opcode == OP_ICONV_TO_I4) || (ins->opcode == OP_LCONV_TO_I1) || (ins->opcode == OP_LCONV_TO_I2);
2960
2961                         /* Have to do two casts since our vregs have type int */
2962                         v = LLVMBuildTrunc (builder, lhs, op_to_llvm_type (ins->opcode), "");
2963                         if (sign)
2964                                 values [ins->dreg] = LLVMBuildSExt (builder, v, LLVMInt32Type (), dname);
2965                         else
2966                                 values [ins->dreg] = LLVMBuildZExt (builder, v, LLVMInt32Type (), dname);
2967                         break;
2968                 }
2969                 case OP_ICONV_TO_I8:
2970                         values [ins->dreg] = LLVMBuildSExt (builder, lhs, LLVMInt64Type (), dname);
2971                         break;
2972                 case OP_ICONV_TO_U8:
2973                         values [ins->dreg] = LLVMBuildZExt (builder, lhs, LLVMInt64Type (), dname);
2974                         break;
2975                 case OP_FCONV_TO_I4:
2976                         values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt32Type (), dname);
2977                         break;
2978                 case OP_FCONV_TO_I1:
2979                         values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
2980                         break;
2981                 case OP_FCONV_TO_U1:
2982                         values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt8Type (), dname), LLVMInt32Type (), "");
2983                         break;
2984                 case OP_FCONV_TO_I2:
2985                         values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildFPToSI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
2986                         break;
2987                 case OP_FCONV_TO_U2:
2988                         values [ins->dreg] = LLVMBuildZExt (builder, LLVMBuildFPToUI (builder, lhs, LLVMInt16Type (), dname), LLVMInt32Type (), "");
2989                         break;
2990                 case OP_FCONV_TO_I8:
2991                         values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, LLVMInt64Type (), dname);
2992                         break;
2993                 case OP_FCONV_TO_I:
2994                         values [ins->dreg] = LLVMBuildFPToSI (builder, lhs, IntPtrType (), dname);
2995                         break;
2996                 case OP_ICONV_TO_R8:
2997                 case OP_LCONV_TO_R8:
2998                         values [ins->dreg] = LLVMBuildSIToFP (builder, lhs, LLVMDoubleType (), dname);
2999                         break;
3000                 case OP_LCONV_TO_R_UN:
3001                         values [ins->dreg] = LLVMBuildUIToFP (builder, lhs, LLVMDoubleType (), dname);
3002                         break;
3003 #if SIZEOF_VOID_P == 4
3004                 case OP_LCONV_TO_U:
3005 #endif
3006                 case OP_LCONV_TO_I4:
3007                         values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
3008                         break;
3009                 case OP_ICONV_TO_R4:
3010                 case OP_LCONV_TO_R4:
3011                         v = LLVMBuildSIToFP (builder, lhs, LLVMFloatType (), "");
3012                         values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
3013                         break;
3014                 case OP_FCONV_TO_R4:
3015                         v = LLVMBuildFPTrunc (builder, lhs, LLVMFloatType (), "");
3016                         values [ins->dreg] = LLVMBuildFPExt (builder, v, LLVMDoubleType (), dname);
3017                         break;
3018                 case OP_SEXT_I4:
3019                         values [ins->dreg] = LLVMBuildSExt (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMInt64Type (), dname);
3020                         break;
3021                 case OP_ZEXT_I4:
3022                         values [ins->dreg] = LLVMBuildZExt (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMInt64Type (), dname);
3023                         break;
3024                 case OP_TRUNC_I4:
3025                         values [ins->dreg] = LLVMBuildTrunc (builder, lhs, LLVMInt32Type (), dname);
3026                         break;
3027                 case OP_LOCALLOC_IMM: {
3028                         LLVMValueRef v;
3029
3030                         guint32 size = ins->inst_imm;
3031                         size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
3032
3033                         v = mono_llvm_build_alloca (builder, LLVMInt8Type (), LLVMConstInt (LLVMInt32Type (), size, FALSE), MONO_ARCH_FRAME_ALIGNMENT, "");
3034
3035                         if (ins->flags & MONO_INST_INIT) {
3036                                 LLVMValueRef args [5];
3037
3038                                 args [0] = v;
3039                                 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3040                                 args [2] = LLVMConstInt (LLVMInt32Type (), size, FALSE);
3041                                 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
3042                                 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3043                                 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3044                         }
3045
3046                         values [ins->dreg] = v;
3047                         break;
3048                 }
3049                 case OP_LOCALLOC: {
3050                         LLVMValueRef v, size;
3051                                 
3052                         size = LLVMBuildAnd (builder, LLVMBuildAdd (builder, convert (ctx, lhs, LLVMInt32Type ()), LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT - 1, FALSE), ""), LLVMConstInt (LLVMInt32Type (), ~ (MONO_ARCH_FRAME_ALIGNMENT - 1), FALSE), "");
3053
3054                         v = mono_llvm_build_alloca (builder, LLVMInt8Type (), size, MONO_ARCH_FRAME_ALIGNMENT, "");
3055
3056                         if (ins->flags & MONO_INST_INIT) {
3057                                 LLVMValueRef args [5];
3058
3059                                 args [0] = v;
3060                                 args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3061                                 args [2] = size;
3062                                 args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
3063                                 args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3064                                 LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3065                         }
3066                         values [ins->dreg] = v;
3067                         break;
3068                 }
3069
3070                 case OP_LOADI1_MEMBASE:
3071                 case OP_LOADU1_MEMBASE:
3072                 case OP_LOADI2_MEMBASE:
3073                 case OP_LOADU2_MEMBASE:
3074                 case OP_LOADI4_MEMBASE:
3075                 case OP_LOADU4_MEMBASE:
3076                 case OP_LOADI8_MEMBASE:
3077                 case OP_LOADR4_MEMBASE:
3078                 case OP_LOADR8_MEMBASE:
3079                 case OP_LOAD_MEMBASE:
3080                 case OP_LOADI8_MEM:
3081                 case OP_LOADU1_MEM:
3082                 case OP_LOADU2_MEM:
3083                 case OP_LOADI4_MEM:
3084                 case OP_LOADU4_MEM:
3085                 case OP_LOAD_MEM: {
3086                         int size = 8;
3087                         LLVMValueRef base, index, addr;
3088                         LLVMTypeRef t;
3089                         gboolean sext = FALSE, zext = FALSE;
3090                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3091
3092                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3093
3094                         if (sext || zext)
3095                                 dname = (char*)"";
3096
3097                         if ((ins->opcode == OP_LOADI8_MEM) || (ins->opcode == OP_LOAD_MEM) || (ins->opcode == OP_LOADI4_MEM) || (ins->opcode == OP_LOADU4_MEM) || (ins->opcode == OP_LOADU1_MEM) || (ins->opcode == OP_LOADU2_MEM)) {
3098                                 addr = LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE);
3099                         } else {
3100                                 /* _MEMBASE */
3101                                 base = lhs;
3102
3103                                 if (ins->inst_offset == 0) {
3104                                         addr = base;
3105                                 } else if (ins->inst_offset % size != 0) {
3106                                         /* Unaligned load */
3107                                         index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3108                                         addr = LLVMBuildGEP (builder, convert (ctx, base, LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3109                                 } else {
3110                                         index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);
3111                                         addr = LLVMBuildGEP (builder, convert (ctx, base, LLVMPointerType (t, 0)), &index, 1, "");
3112                                 }
3113                         }
3114
3115                         addr = convert (ctx, addr, LLVMPointerType (t, 0));
3116
3117                         values [ins->dreg] = emit_load (ctx, bb, &builder, size, addr, dname, is_volatile);
3118
3119                         if (!is_volatile && (ins->flags & MONO_INST_INVARIANT_LOAD)) {
3120                                 /*
3121                                  * These will signal LLVM that these loads do not alias any stores, and
3122                                  * they can't fail, allowing them to be hoisted out of loops.
3123                                  */
3124                                 set_invariant_load_flag (values [ins->dreg]);
3125                                 set_metadata_flag (values [ins->dreg], "mono.nofail.load");
3126                         }
3127
3128                         if (sext)
3129                                 values [ins->dreg] = LLVMBuildSExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3130                         else if (zext)
3131                                 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), dname);
3132                         else if (ins->opcode == OP_LOADR4_MEMBASE)
3133                                 values [ins->dreg] = LLVMBuildFPExt (builder, values [ins->dreg], LLVMDoubleType (), dname);
3134                         break;
3135                 }
3136                                 
3137                 case OP_STOREI1_MEMBASE_REG:
3138                 case OP_STOREI2_MEMBASE_REG:
3139                 case OP_STOREI4_MEMBASE_REG:
3140                 case OP_STOREI8_MEMBASE_REG:
3141                 case OP_STORER4_MEMBASE_REG:
3142                 case OP_STORER8_MEMBASE_REG:
3143                 case OP_STORE_MEMBASE_REG: {
3144                         int size = 8;
3145                         LLVMValueRef index, addr;
3146                         LLVMTypeRef t;
3147                         gboolean sext = FALSE, zext = FALSE;
3148                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3149
3150                         if (!values [ins->inst_destbasereg])
3151                                 LLVM_FAILURE (ctx, "inst_destbasereg");
3152
3153                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3154
3155                         if (ins->inst_offset % size != 0) {
3156                                 /* Unaligned store */
3157                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3158                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3159                         } else {
3160                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);                                
3161                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3162                         }
3163                         emit_store (ctx, bb, &builder, size, convert (ctx, values [ins->sreg1], t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
3164                         break;
3165                 }
3166
3167                 case OP_STOREI1_MEMBASE_IMM:
3168                 case OP_STOREI2_MEMBASE_IMM:
3169                 case OP_STOREI4_MEMBASE_IMM:
3170                 case OP_STOREI8_MEMBASE_IMM:
3171                 case OP_STORE_MEMBASE_IMM: {
3172                         int size = 8;
3173                         LLVMValueRef index, addr;
3174                         LLVMTypeRef t;
3175                         gboolean sext = FALSE, zext = FALSE;
3176                         gboolean is_volatile = (ins->flags & MONO_INST_FAULT);
3177
3178                         t = load_store_to_llvm_type (ins->opcode, &size, &sext, &zext);
3179
3180                         if (ins->inst_offset % size != 0) {
3181                                 /* Unaligned store */
3182                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset, FALSE);
3183                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (LLVMInt8Type (), 0)), &index, 1, "");
3184                         } else {
3185                                 index = LLVMConstInt (LLVMInt32Type (), ins->inst_offset / size, FALSE);                                
3186                                 addr = LLVMBuildGEP (builder, convert (ctx, values [ins->inst_destbasereg], LLVMPointerType (t, 0)), &index, 1, "");
3187                         }
3188                         emit_store (ctx, bb, &builder, size, convert (ctx, LLVMConstInt (IntPtrType (), ins->inst_imm, FALSE), t), convert (ctx, addr, LLVMPointerType (t, 0)), is_volatile);
3189                         break;
3190                 }
3191
3192                 case OP_CHECK_THIS:
3193                         emit_load (ctx, bb, &builder, sizeof (gpointer), convert (ctx, lhs, LLVMPointerType (IntPtrType (), 0)), "", TRUE);
3194                         break;
3195                 case OP_OUTARG_VTRETADDR:
3196                         break;
3197                 case OP_VOIDCALL:
3198                 case OP_CALL:
3199                 case OP_LCALL:
3200                 case OP_FCALL:
3201                 case OP_VCALL:
3202                 case OP_VOIDCALL_MEMBASE:
3203                 case OP_CALL_MEMBASE:
3204                 case OP_LCALL_MEMBASE:
3205                 case OP_FCALL_MEMBASE:
3206                 case OP_VCALL_MEMBASE:
3207                 case OP_VOIDCALL_REG:
3208                 case OP_CALL_REG:
3209                 case OP_LCALL_REG:
3210                 case OP_FCALL_REG:
3211                 case OP_VCALL_REG: {
3212                         process_call (ctx, bb, &builder, ins);
3213                         CHECK_FAILURE (ctx);
3214                         break;
3215                 }
3216                 case OP_AOTCONST: {
3217                         guint32 got_offset;
3218                         LLVMValueRef indexes [2];
3219                         MonoJumpInfo *ji;
3220                         LLVMValueRef got_entry_addr;
3221
3222                         /* 
3223                          * FIXME: Can't allocate from the cfg mempool since that is freed if
3224                          * the LLVM compile fails.
3225                          */
3226                         ji = g_new0 (MonoJumpInfo, 1);
3227                         ji->type = (MonoJumpInfoType)ins->inst_i1;
3228                         ji->data.target = ins->inst_p0;
3229
3230                         ji = mono_aot_patch_info_dup (ji);
3231
3232                         ji->next = cfg->patch_info;
3233                         cfg->patch_info = ji;
3234                                    
3235                         //mono_add_patch_info (cfg, 0, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
3236                         got_offset = mono_aot_get_got_offset (cfg->patch_info);
3237  
3238                         indexes [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3239                         indexes [1] = LLVMConstInt (LLVMInt32Type (), (gssize)got_offset, FALSE);
3240                         got_entry_addr = LLVMBuildGEP (builder, ctx->lmodule->got_var, indexes, 2, "");
3241
3242                         values [ins->dreg] = LLVMBuildLoad (builder, got_entry_addr, dname);
3243                         set_invariant_load_flag (values [ins->dreg]);
3244                         break;
3245                 }
3246                 case OP_NOT_REACHED:
3247                         LLVMBuildUnreachable (builder);
3248                         has_terminator = TRUE;
3249                         g_assert (bb->block_num < cfg->max_block_num);
3250                         ctx->unreachable [bb->block_num] = TRUE;
3251                         /* Might have instructions after this */
3252                         while (ins->next) {
3253                                 MonoInst *next = ins->next;
3254                                 /* 
3255                                  * FIXME: If later code uses the regs defined by these instructions,
3256                                  * compilation will fail.
3257                                  */
3258                                 MONO_DELETE_INS (bb, next);
3259                         }                               
3260                         break;
3261                 case OP_LDADDR: {
3262                         MonoInst *var = ins->inst_p0;
3263
3264                         values [ins->dreg] = addresses [var->dreg];
3265                         break;
3266                 }
3267                 case OP_SIN: {
3268                         LLVMValueRef args [1];
3269
3270                         args [0] = convert (ctx, lhs, LLVMDoubleType ());
3271                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sin.f64"), args, 1, dname);
3272                         break;
3273                 }
3274                 case OP_COS: {
3275                         LLVMValueRef args [1];
3276
3277                         args [0] = convert (ctx, lhs, LLVMDoubleType ());
3278                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.cos.f64"), args, 1, dname);
3279                         break;
3280                 }
3281                 case OP_SQRT: {
3282                         LLVMValueRef args [1];
3283
3284 #if 0
3285                         /* This no longer seems to happen */
3286                         /*
3287                          * LLVM optimizes sqrt(nan) into undefined in
3288                          * lib/Analysis/ConstantFolding.cpp
3289                          * Also, sqrt(NegativeInfinity) is optimized into 0.
3290                          */
3291                         LLVM_FAILURE (ctx, "sqrt");
3292 #endif
3293                         args [0] = convert (ctx, lhs, LLVMDoubleType ());
3294                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.sqrt.f64"), args, 1, dname);
3295                         break;
3296                 }
3297                 case OP_ABS: {
3298                         LLVMValueRef args [1];
3299
3300                         args [0] = convert (ctx, lhs, LLVMDoubleType ());
3301                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, "fabs"), args, 1, dname);
3302                         break;
3303                 }
3304
3305                 case OP_IMIN:
3306                 case OP_LMIN:
3307                 case OP_IMAX:
3308                 case OP_LMAX:
3309                 case OP_IMIN_UN:
3310                 case OP_LMIN_UN:
3311                 case OP_IMAX_UN:
3312                 case OP_LMAX_UN: {
3313                         LLVMValueRef v;
3314
3315                         lhs = convert (ctx, lhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3316                         rhs = convert (ctx, rhs, regtype_to_llvm_type (spec [MONO_INST_DEST]));
3317
3318                         switch (ins->opcode) {
3319                         case OP_IMIN:
3320                         case OP_LMIN:
3321                                 v = LLVMBuildICmp (builder, LLVMIntSLE, lhs, rhs, "");
3322                                 break;
3323                         case OP_IMAX:
3324                         case OP_LMAX:
3325                                 v = LLVMBuildICmp (builder, LLVMIntSGE, lhs, rhs, "");
3326                                 break;
3327                         case OP_IMIN_UN:
3328                         case OP_LMIN_UN:
3329                                 v = LLVMBuildICmp (builder, LLVMIntULE, lhs, rhs, "");
3330                                 break;
3331                         case OP_IMAX_UN:
3332                         case OP_LMAX_UN:
3333                                 v = LLVMBuildICmp (builder, LLVMIntUGE, lhs, rhs, "");
3334                                 break;
3335                         default:
3336                                 g_assert_not_reached ();
3337                                 break;
3338                         }
3339                         values [ins->dreg] = LLVMBuildSelect (builder, v, lhs, rhs, dname);
3340                         break;
3341                 }
3342                 case OP_ATOMIC_EXCHANGE_I4:
3343                 case OP_ATOMIC_EXCHANGE_I8: {
3344                         LLVMValueRef args [2];
3345                         LLVMTypeRef t;
3346                                 
3347                         if (ins->opcode == OP_ATOMIC_EXCHANGE_I4)
3348                                 t = LLVMInt32Type ();
3349                         else
3350                                 t = LLVMInt64Type ();
3351
3352                         g_assert (ins->inst_offset == 0);
3353
3354                         args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3355                         args [1] = convert (ctx, rhs, t);
3356
3357                         values [ins->dreg] = mono_llvm_build_atomic_rmw (builder, LLVM_ATOMICRMW_OP_XCHG, args [0], args [1]);
3358                         break;
3359                 }
3360                 case OP_ATOMIC_ADD_I4:
3361                 case OP_ATOMIC_ADD_I8: {
3362                         LLVMValueRef args [2];
3363                         LLVMTypeRef t;
3364                                 
3365                         if (ins->opcode == OP_ATOMIC_ADD_I4)
3366                                 t = LLVMInt32Type ();
3367                         else
3368                                 t = LLVMInt64Type ();
3369
3370                         g_assert (ins->inst_offset == 0);
3371
3372                         args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3373                         args [1] = convert (ctx, rhs, t);
3374                         values [ins->dreg] = LLVMBuildAdd (builder, mono_llvm_build_atomic_rmw (builder, LLVM_ATOMICRMW_OP_ADD, args [0], args [1]), args [1], dname);
3375                         break;
3376                 }
3377                 case OP_ATOMIC_CAS_I4:
3378                 case OP_ATOMIC_CAS_I8: {
3379                         LLVMValueRef args [3], val;
3380                         LLVMTypeRef t;
3381                                 
3382                         if (ins->opcode == OP_ATOMIC_CAS_I4)
3383                                 t = LLVMInt32Type ();
3384                         else
3385                                 t = LLVMInt64Type ();
3386
3387                         args [0] = convert (ctx, lhs, LLVMPointerType (t, 0));
3388                         /* comparand */
3389                         args [1] = convert (ctx, values [ins->sreg3], t);
3390                         /* new value */
3391                         args [2] = convert (ctx, values [ins->sreg2], t);
3392                         val = mono_llvm_build_cmpxchg (builder, args [0], args [1], args [2]);
3393 #if LLVM_API_VERSION >= 1
3394                         /* cmpxchg returns a pair */
3395                         values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, "");
3396 #else
3397                         values [ins->dreg] = val;
3398 #endif
3399                         break;
3400                 }
3401                 case OP_MEMORY_BARRIER: {
3402                         mono_llvm_build_fence (builder);
3403                         break;
3404                 }
3405                 case OP_RELAXED_NOP: {
3406 #if defined(TARGET_AMD64) || defined(TARGET_X86)
3407                         emit_call (ctx, bb, &builder, LLVMGetNamedFunction (ctx->module, "llvm.x86.sse2.pause"), NULL, 0);
3408                         break;
3409 #else
3410                         break;
3411 #endif
3412                 }
3413                 case OP_TLS_GET: {
3414 #if (defined(TARGET_AMD64) || defined(TARGET_X86)) && defined(__linux__)
3415 #ifdef TARGET_AMD64
3416                         // 257 == FS segment register
3417                         LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 257);
3418 #else
3419                         // 256 == GS segment register
3420                         LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3421 #endif
3422                         // FIXME: XEN
3423                         values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), ins->inst_offset, TRUE), ptrtype, ""), "");
3424 #elif defined(TARGET_AMD64) && defined(TARGET_OSX)
3425                         /* See mono_amd64_emit_tls_get () */
3426                         int offset = mono_amd64_get_tls_gs_offset () + (ins->inst_offset * 8);
3427
3428                         // 256 == GS segment register
3429                         LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3430                         values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, LLVMConstInt (IntPtrType (), offset, TRUE), ptrtype, ""), "");
3431 #else
3432                         LLVM_FAILURE (ctx, "opcode tls-get");
3433 #endif
3434
3435                         break;
3436                 }
3437                 case OP_TLS_GET_REG: {
3438 #if defined(TARGET_AMD64) && defined(TARGET_OSX)
3439                         /* See emit_tls_get_reg () */
3440                         // 256 == GS segment register
3441                         LLVMTypeRef ptrtype = LLVMPointerType (IntPtrType (), 256);
3442                         values [ins->dreg] = LLVMBuildLoad (builder, LLVMBuildIntToPtr (builder, convert (ctx, lhs, LLVMInt32Type ()), ptrtype, ""), "");
3443 #else
3444                         LLVM_FAILURE (ctx, "opcode tls-get");
3445 #endif
3446                         break;
3447                 }
3448
3449                         /*
3450                          * Overflow opcodes.
3451                          */
3452                 case OP_IADD_OVF:
3453                 case OP_IADD_OVF_UN:
3454                 case OP_ISUB_OVF:
3455                 case OP_ISUB_OVF_UN:
3456                 case OP_IMUL_OVF:
3457                 case OP_IMUL_OVF_UN:
3458 #if SIZEOF_VOID_P == 8
3459                 case OP_LADD_OVF:
3460                 case OP_LADD_OVF_UN:
3461                 case OP_LSUB_OVF:
3462                 case OP_LSUB_OVF_UN:
3463                 case OP_LMUL_OVF:
3464                 case OP_LMUL_OVF_UN:
3465 #endif
3466                         {
3467                                 LLVMValueRef args [2], val, ovf, func;
3468
3469                                 args [0] = convert (ctx, lhs, op_to_llvm_type (ins->opcode));
3470                                 args [1] = convert (ctx, rhs, op_to_llvm_type (ins->opcode));
3471                                 func = LLVMGetNamedFunction (module, ovf_op_to_intrins (ins->opcode));
3472                                 g_assert (func);
3473                                 val = LLVMBuildCall (builder, func, args, 2, "");
3474                                 values [ins->dreg] = LLVMBuildExtractValue (builder, val, 0, dname);
3475                                 ovf = LLVMBuildExtractValue (builder, val, 1, "");
3476                                 emit_cond_system_exception (ctx, bb, "OverflowException", ovf);
3477                                 CHECK_FAILURE (ctx);
3478                                 builder = ctx->builder;
3479                                 break;
3480                         }
3481
3482                         /* 
3483                          * Valuetypes.
3484                          *   We currently model them using arrays. Promotion to local vregs is 
3485                          * disabled for them in mono_handle_global_vregs () in the LLVM case, 
3486                          * so we always have an entry in cfg->varinfo for them.
3487                          * FIXME: Is this needed ?
3488                          */
3489                 case OP_VZERO: {
3490                         MonoClass *klass = ins->klass;
3491                         LLVMValueRef args [5];
3492
3493                         if (!klass) {
3494                                 // FIXME:
3495                                 LLVM_FAILURE (ctx, "!klass");
3496                                 break;
3497                         }
3498
3499                         if (!addresses [ins->dreg])
3500                                 addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3501                         args [0] = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3502                         args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
3503                         args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
3504                         // FIXME: Alignment
3505                         args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3506                         args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3507                         LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
3508                         break;
3509                 }
3510                 case OP_DUMMY_VZERO:
3511                         break;
3512
3513                 case OP_STOREV_MEMBASE:
3514                 case OP_LOADV_MEMBASE:
3515                 case OP_VMOVE: {
3516                         MonoClass *klass = ins->klass;
3517                         LLVMValueRef src = NULL, dst, args [5];
3518                         gboolean done = FALSE;
3519
3520                         if (!klass) {
3521                                 // FIXME:
3522                                 LLVM_FAILURE (ctx, "!klass");
3523                                 break;
3524                         }
3525
3526                         if (mini_is_gsharedvt_klass (cfg, klass)) {
3527                                 // FIXME:
3528                                 LLVM_FAILURE (ctx, "gsharedvt");
3529                                 break;
3530                         }
3531
3532                         switch (ins->opcode) {
3533                         case OP_STOREV_MEMBASE:
3534                                 if (cfg->gen_write_barriers && klass->has_references && ins->inst_destbasereg != cfg->frame_reg &&
3535                                         LLVMGetInstructionOpcode (values [ins->inst_destbasereg]) != LLVMAlloca) {
3536                                         /* Decomposed earlier */
3537                                         g_assert_not_reached ();
3538                                         break;
3539                                 }
3540                                 if (!addresses [ins->sreg1]) {
3541                                         /* SIMD */
3542                                         g_assert (values [ins->sreg1]);
3543                                         dst = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (type_to_llvm_type (ctx, &klass->byval_arg), 0));
3544                                         LLVMBuildStore (builder, values [ins->sreg1], dst);
3545                                         done = TRUE;
3546                                 } else {
3547                                         src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
3548                                         dst = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
3549                                 }
3550                                 break;
3551                         case OP_LOADV_MEMBASE:
3552                                 if (!addresses [ins->dreg])
3553                                         addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3554                                 src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (LLVMInt8Type (), 0));
3555                                 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3556                                 break;
3557                         case OP_VMOVE:
3558                                 if (!addresses [ins->sreg1])
3559                                         addresses [ins->sreg1] = build_alloca (ctx, &klass->byval_arg);
3560                                 if (!addresses [ins->dreg])
3561                                         addresses [ins->dreg] = build_alloca (ctx, &klass->byval_arg);
3562                                 src = LLVMBuildBitCast (builder, addresses [ins->sreg1], LLVMPointerType (LLVMInt8Type (), 0), "");
3563                                 dst = LLVMBuildBitCast (builder, addresses [ins->dreg], LLVMPointerType (LLVMInt8Type (), 0), "");
3564                                 break;
3565                         default:
3566                                 g_assert_not_reached ();
3567                         }
3568                         CHECK_FAILURE (ctx);
3569
3570                         if (done)
3571                                 break;
3572
3573                         args [0] = dst;
3574                         args [1] = src;
3575                         args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
3576                         args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3577                         // FIXME: Alignment
3578                         args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3579                         args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
3580                         LLVMBuildCall (builder, LLVMGetNamedFunction (module, memcpy_func_name), args, memcpy_param_count, "");
3581                         break;
3582                 }
3583                 case OP_LLVM_OUTARG_VT:
3584                         if (!addresses [ins->sreg1]) {
3585                                 addresses [ins->sreg1] = build_alloca (ctx, &ins->klass->byval_arg);
3586                                 g_assert (values [ins->sreg1]);
3587                                 LLVMBuildStore (builder, values [ins->sreg1], addresses [ins->sreg1]);
3588                         }
3589                         addresses [ins->dreg] = addresses [ins->sreg1];
3590                         break;
3591
3592                         /* 
3593                          * SIMD
3594                          */
3595 #if defined(TARGET_X86) || defined(TARGET_AMD64)
3596                 case OP_XZERO: {
3597                         values [ins->dreg] = LLVMConstNull (type_to_llvm_type (ctx, &ins->klass->byval_arg));
3598                         break;
3599                 }
3600                 case OP_LOADX_MEMBASE: {
3601                         LLVMTypeRef t = type_to_llvm_type (ctx, &ins->klass->byval_arg);
3602                         LLVMValueRef src;
3603
3604                         src = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_basereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
3605                         values [ins->dreg] = mono_llvm_build_aligned_load (builder, src, "", FALSE, 1);
3606                         break;
3607                 }
3608                 case OP_STOREX_MEMBASE: {
3609                         LLVMTypeRef t = LLVMTypeOf (values [ins->sreg1]);
3610                         LLVMValueRef dest;
3611
3612                         dest = convert (ctx, LLVMBuildAdd (builder, convert (ctx, values [ins->inst_destbasereg], IntPtrType ()), LLVMConstInt (IntPtrType (), ins->inst_offset, FALSE), ""), LLVMPointerType (t, 0));
3613                         mono_llvm_build_aligned_store (builder, values [ins->sreg1], dest, FALSE, 1);
3614                         break;
3615                 }
3616                 case OP_PADDB:
3617                 case OP_PADDW:
3618                 case OP_PADDD:
3619                 case OP_PADDQ:
3620                         values [ins->dreg] = LLVMBuildAdd (builder, lhs, rhs, "");
3621                         break;
3622                 case OP_ADDPD:
3623                 case OP_ADDPS:
3624                         values [ins->dreg] = LLVMBuildFAdd (builder, lhs, rhs, "");
3625                         break;
3626                 case OP_PSUBB:
3627                 case OP_PSUBW:
3628                 case OP_PSUBD:
3629                 case OP_PSUBQ:
3630                         values [ins->dreg] = LLVMBuildSub (builder, lhs, rhs, "");
3631                         break;
3632                 case OP_SUBPD:
3633                 case OP_SUBPS:
3634                         values [ins->dreg] = LLVMBuildFSub (builder, lhs, rhs, "");
3635                         break;
3636                 case OP_MULPD:
3637                 case OP_MULPS:
3638                         values [ins->dreg] = LLVMBuildFMul (builder, lhs, rhs, "");
3639                         break;
3640                 case OP_DIVPD:
3641                 case OP_DIVPS:
3642                         values [ins->dreg] = LLVMBuildFDiv (builder, lhs, rhs, "");
3643                         break;
3644                 case OP_PAND:
3645                         values [ins->dreg] = LLVMBuildAnd (builder, lhs, rhs, "");
3646                         break;
3647                 case OP_POR:
3648                         values [ins->dreg] = LLVMBuildOr (builder, lhs, rhs, "");
3649                         break;
3650                 case OP_PXOR:
3651                         values [ins->dreg] = LLVMBuildXor (builder, lhs, rhs, "");
3652                         break;
3653                 case OP_PMULW:
3654                 case OP_PMULD:
3655                         values [ins->dreg] = LLVMBuildMul (builder, lhs, rhs, "");
3656                         break;
3657                 case OP_ANDPS:
3658                 case OP_ANDNPS:
3659                 case OP_ORPS:
3660                 case OP_XORPS:
3661                 case OP_ANDPD:
3662                 case OP_ANDNPD:
3663                 case OP_ORPD:
3664                 case OP_XORPD: {
3665                         LLVMTypeRef t, rt;
3666                         LLVMValueRef v = NULL;
3667
3668                         switch (ins->opcode) {
3669                         case OP_ANDPS:
3670                         case OP_ANDNPS:
3671                         case OP_ORPS:
3672                         case OP_XORPS:
3673                                 t = LLVMVectorType (LLVMInt32Type (), 4);
3674                                 rt = LLVMVectorType (LLVMFloatType (), 4);
3675                                 break;
3676                         case OP_ANDPD:
3677                         case OP_ANDNPD:
3678                         case OP_ORPD:
3679                         case OP_XORPD:
3680                                 t = LLVMVectorType (LLVMInt64Type (), 2);
3681                                 rt = LLVMVectorType (LLVMDoubleType (), 2);
3682                                 break;
3683                         default:
3684                                 t = LLVMInt32Type ();
3685                                 rt = LLVMInt32Type ();
3686                                 g_assert_not_reached ();
3687                         }
3688
3689                         lhs = LLVMBuildBitCast (builder, lhs, t, "");
3690                         rhs = LLVMBuildBitCast (builder, rhs, t, "");
3691                         switch (ins->opcode) {
3692                         case OP_ANDPS:
3693                         case OP_ANDPD:
3694                                 v = LLVMBuildAnd (builder, lhs, rhs, "");
3695                                 break;
3696                         case OP_ORPS:
3697                         case OP_ORPD:
3698                                 v = LLVMBuildOr (builder, lhs, rhs, "");
3699                                 break;
3700                         case OP_XORPS:
3701                         case OP_XORPD:
3702                                 v = LLVMBuildXor (builder, lhs, rhs, "");
3703                                 break;
3704                         case OP_ANDNPS:
3705                         case OP_ANDNPD:
3706                                 v = LLVMBuildAnd (builder, rhs, LLVMBuildNot (builder, lhs, ""), "");
3707                                 break;
3708                         }
3709                         values [ins->dreg] = LLVMBuildBitCast (builder, v, rt, "");
3710                         break;
3711                 }
3712                 case OP_MINPD:
3713                 case OP_MINPS:
3714                 case OP_MAXPD:
3715                 case OP_MAXPS:
3716                 case OP_ADDSUBPD:
3717                 case OP_ADDSUBPS:
3718                 case OP_PMIND_UN:
3719                 case OP_PMINW_UN:
3720                 case OP_PMINB_UN:
3721                 case OP_PMINW:
3722                 case OP_PMAXD_UN:
3723                 case OP_PMAXW_UN:
3724                 case OP_PMAXB_UN:
3725                 case OP_HADDPD:
3726                 case OP_HADDPS:
3727                 case OP_HSUBPD:
3728                 case OP_HSUBPS:
3729                 case OP_PADDB_SAT:
3730                 case OP_PADDW_SAT:
3731                 case OP_PSUBB_SAT:
3732                 case OP_PSUBW_SAT:
3733                 case OP_PADDB_SAT_UN:
3734                 case OP_PADDW_SAT_UN:
3735                 case OP_PSUBB_SAT_UN:
3736                 case OP_PSUBW_SAT_UN:
3737                 case OP_PAVGB_UN:
3738                 case OP_PAVGW_UN:
3739                 case OP_PACKW:
3740                 case OP_PACKD:
3741                 case OP_PACKW_UN:
3742                 case OP_PACKD_UN:
3743                 case OP_PMULW_HIGH:
3744                 case OP_PMULW_HIGH_UN: {
3745                         LLVMValueRef args [2];
3746
3747                         args [0] = lhs;
3748                         args [1] = rhs;
3749
3750                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
3751                         break;
3752                 }
3753                 case OP_PCMPEQB:
3754                 case OP_PCMPEQW:
3755                 case OP_PCMPEQD:
3756                 case OP_PCMPEQQ: {
3757                         values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildICmp (builder, LLVMIntEQ, lhs, rhs, ""), LLVMTypeOf (lhs), "");
3758                         break;
3759                 }
3760                 case OP_PCMPGTB: {
3761                         values [ins->dreg] = LLVMBuildSExt (builder, LLVMBuildICmp (builder, LLVMIntSGT, lhs, rhs, ""), LLVMTypeOf (lhs), "");
3762                         break;
3763                 }
3764                 case OP_EXTRACT_R8:
3765                 case OP_EXTRACT_I8:
3766                 case OP_EXTRACT_I4:
3767                 case OP_EXTRACT_I2:
3768                 case OP_EXTRACT_U2:
3769                 case OP_EXTRACTX_U2:
3770                 case OP_EXTRACT_I1:
3771                 case OP_EXTRACT_U1: {
3772                         LLVMTypeRef t;
3773                         gboolean zext = FALSE;
3774
3775                         t = simd_op_to_llvm_type (ins->opcode);
3776
3777                         switch (ins->opcode) {
3778                         case OP_EXTRACT_R8:
3779                         case OP_EXTRACT_I8:
3780                         case OP_EXTRACT_I4:
3781                         case OP_EXTRACT_I2:
3782                         case OP_EXTRACT_I1:
3783                                 break;
3784                         case OP_EXTRACT_U2:
3785                         case OP_EXTRACTX_U2:
3786                         case OP_EXTRACT_U1:
3787                                 zext = TRUE;
3788                                 break;
3789                         default:
3790                                 t = LLVMInt32Type ();
3791                                 g_assert_not_reached ();
3792                         }
3793
3794                         lhs = LLVMBuildBitCast (builder, lhs, t, "");
3795                         values [ins->dreg] = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), "");
3796                         if (zext)
3797                                 values [ins->dreg] = LLVMBuildZExt (builder, values [ins->dreg], LLVMInt32Type (), "");
3798                         break;
3799                 }
3800
3801                 case OP_EXPAND_I1:
3802                 case OP_EXPAND_I2:
3803                 case OP_EXPAND_I4:
3804                 case OP_EXPAND_I8:
3805                 case OP_EXPAND_R4:
3806                 case OP_EXPAND_R8: {
3807                         LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
3808                         LLVMValueRef mask [16], v;
3809
3810                         for (i = 0; i < 16; ++i)
3811                                 mask [i] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
3812
3813                         v = convert (ctx, values [ins->sreg1], LLVMGetElementType (t));
3814
3815                         values [ins->dreg] = LLVMBuildInsertElement (builder, LLVMConstNull (t), v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
3816                         values [ins->dreg] = LLVMBuildShuffleVector (builder, values [ins->dreg], LLVMGetUndef (t), LLVMConstVector (mask, LLVMGetVectorSize (t)), "");
3817                         break;
3818                 }
3819
3820                 case OP_INSERT_I1:
3821                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt8Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3822                         break;
3823                 case OP_INSERT_I2:
3824                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt16Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3825                         break;
3826                 case OP_INSERT_I4:
3827                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt32Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3828                         break;
3829                 case OP_INSERT_I8:
3830                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMInt64Type ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3831                         break;
3832                 case OP_INSERT_R4:
3833                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMFloatType ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3834                         break;
3835                 case OP_INSERT_R8:
3836                         values [ins->dreg] = LLVMBuildInsertElement (builder, values [ins->sreg1], convert (ctx, values [ins->sreg2], LLVMDoubleType ()), LLVMConstInt (LLVMInt32Type (), ins->inst_c0, FALSE), dname);
3837                         break;
3838
3839                 case OP_CVTDQ2PD:
3840                 case OP_CVTDQ2PS:
3841                 case OP_CVTPD2DQ:
3842                 case OP_CVTPS2DQ:
3843                 case OP_CVTPD2PS:
3844                 case OP_CVTPS2PD:
3845                 case OP_CVTTPD2DQ:
3846                 case OP_CVTTPS2DQ:
3847                 case OP_EXTRACT_MASK:
3848                 case OP_SQRTPS:
3849                 case OP_SQRTPD:
3850                 case OP_RSQRTPS:
3851                 case OP_RCPPS: {
3852                         LLVMValueRef v;
3853
3854                         v = convert (ctx, values [ins->sreg1], simd_op_to_llvm_type (ins->opcode));
3855
3856                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), &v, 1, dname);
3857                         break;
3858                 }
3859
3860                 case OP_ICONV_TO_R8_RAW:
3861                         /* Same as OP_ICONV_TO_R8 */
3862                         values [ins->dreg] = convert (ctx, LLVMBuildBitCast (builder, lhs, LLVMFloatType (), ""), LLVMDoubleType ());
3863                         break;
3864
3865                 case OP_COMPPS:
3866                 case OP_COMPPD: {
3867                         LLVMValueRef args [3];
3868
3869                         args [0] = lhs;
3870                         args [1] = rhs;
3871                         args [2] = LLVMConstInt (LLVMInt8Type (), ins->inst_c0, FALSE);
3872
3873                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 3, dname);
3874                         break;
3875                 }
3876
3877                 case OP_ICONV_TO_X:
3878                         /* This is only used for implementing shifts by non-immediate */
3879                         values [ins->dreg] = lhs;
3880                         break;
3881
3882                 case OP_PSHRW:
3883                 case OP_PSHRD:
3884                 case OP_PSHRQ:
3885                 case OP_PSARW:
3886                 case OP_PSARD:
3887                 case OP_PSHLW:
3888                 case OP_PSHLD:
3889                 case OP_PSHLQ: {
3890                         LLVMValueRef args [3];
3891
3892                         args [0] = lhs;
3893                         args [1] = LLVMConstInt (LLVMInt32Type (), ins->inst_imm, FALSE);
3894
3895                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
3896                         break;
3897                 }
3898
3899                 case OP_PSHRW_REG:
3900                 case OP_PSHRD_REG:
3901                 case OP_PSHRQ_REG:
3902                 case OP_PSARW_REG:
3903                 case OP_PSARD_REG:
3904                 case OP_PSHLW_REG:
3905                 case OP_PSHLD_REG:
3906                 case OP_PSHLQ_REG: {
3907                         LLVMValueRef args [3];
3908
3909                         args [0] = lhs;
3910                         args [1] = values [ins->sreg2];
3911
3912                         values [ins->dreg] = LLVMBuildCall (builder, LLVMGetNamedFunction (module, simd_op_to_intrins (ins->opcode)), args, 2, dname);
3913                         break;
3914                 }
3915
3916                 case OP_SHUFPS:
3917                 case OP_SHUFPD:
3918                 case OP_PSHUFLED:
3919                 case OP_PSHUFLEW_LOW:
3920                 case OP_PSHUFLEW_HIGH: {
3921                         int mask [16];
3922                         LLVMValueRef v1 = NULL, v2 = NULL, mask_values [16];
3923                         int i, mask_size = 0;
3924                         int imask = ins->inst_c0;
3925         
3926                         /* Convert the x86 shuffle mask to LLVM's */
3927                         switch (ins->opcode) {
3928                         case OP_SHUFPS:
3929                                 mask_size = 4;
3930                                 mask [0] = ((imask >> 0) & 3);
3931                                 mask [1] = ((imask >> 2) & 3);
3932                                 mask [2] = ((imask >> 4) & 3) + 4;
3933                                 mask [3] = ((imask >> 6) & 3) + 4;
3934                                 v1 = values [ins->sreg1];
3935                                 v2 = values [ins->sreg2];
3936                                 break;
3937                         case OP_SHUFPD:
3938                                 mask_size = 2;
3939                                 mask [0] = ((imask >> 0) & 1);
3940                                 mask [1] = ((imask >> 1) & 1) + 2;
3941                                 v1 = values [ins->sreg1];
3942                                 v2 = values [ins->sreg2];
3943                                 break;
3944                         case OP_PSHUFLEW_LOW:
3945                                 mask_size = 8;
3946                                 mask [0] = ((imask >> 0) & 3);
3947                                 mask [1] = ((imask >> 2) & 3);
3948                                 mask [2] = ((imask >> 4) & 3);
3949                                 mask [3] = ((imask >> 6) & 3);
3950                                 mask [4] = 4 + 0;
3951                                 mask [5] = 4 + 1;
3952                                 mask [6] = 4 + 2;
3953                                 mask [7] = 4 + 3;
3954                                 v1 = values [ins->sreg1];
3955                                 v2 = LLVMGetUndef (LLVMTypeOf (v1));
3956                                 break;
3957                         case OP_PSHUFLEW_HIGH:
3958                                 mask_size = 8;
3959                                 mask [0] = 0;
3960                                 mask [1] = 1;
3961                                 mask [2] = 2;
3962                                 mask [3] = 3;
3963                                 mask [4] = 4 + ((imask >> 0) & 3);
3964                                 mask [5] = 4 + ((imask >> 2) & 3);
3965                                 mask [6] = 4 + ((imask >> 4) & 3);
3966                                 mask [7] = 4 + ((imask >> 6) & 3);
3967                                 v1 = values [ins->sreg1];
3968                                 v2 = LLVMGetUndef (LLVMTypeOf (v1));
3969                                 break;
3970                         case OP_PSHUFLED:
3971                                 mask_size = 4;
3972                                 mask [0] = ((imask >> 0) & 3);
3973                                 mask [1] = ((imask >> 2) & 3);
3974                                 mask [2] = ((imask >> 4) & 3);
3975                                 mask [3] = ((imask >> 6) & 3);
3976                                 v1 = values [ins->sreg1];
3977                                 v2 = LLVMGetUndef (LLVMTypeOf (v1));
3978                                 break;
3979                         default:
3980                                 g_assert_not_reached ();
3981                         }
3982                         for (i = 0; i < mask_size; ++i)
3983                                 mask_values [i] = LLVMConstInt (LLVMInt32Type (), mask [i], FALSE);
3984
3985                         values [ins->dreg] =
3986                                 LLVMBuildShuffleVector (builder, v1, v2,
3987                                                                                 LLVMConstVector (mask_values, mask_size), dname);
3988                         break;
3989                 }
3990
3991                 case OP_UNPACK_LOWB:
3992                 case OP_UNPACK_LOWW:
3993                 case OP_UNPACK_LOWD:
3994                 case OP_UNPACK_LOWQ:
3995                 case OP_UNPACK_LOWPS:
3996                 case OP_UNPACK_LOWPD:
3997                 case OP_UNPACK_HIGHB:
3998                 case OP_UNPACK_HIGHW:
3999                 case OP_UNPACK_HIGHD:
4000                 case OP_UNPACK_HIGHQ:
4001                 case OP_UNPACK_HIGHPS:
4002                 case OP_UNPACK_HIGHPD: {
4003                         int mask [16];
4004                         LLVMValueRef mask_values [16];
4005                         int i, mask_size = 0;
4006                         gboolean low = FALSE;
4007
4008                         switch (ins->opcode) {
4009                         case OP_UNPACK_LOWB:
4010                                 mask_size = 16;
4011                                 low = TRUE;
4012                                 break;
4013                         case OP_UNPACK_LOWW:
4014                                 mask_size = 8;
4015                                 low = TRUE;
4016                                 break;
4017                         case OP_UNPACK_LOWD:
4018                         case OP_UNPACK_LOWPS:
4019                                 mask_size = 4;
4020                                 low = TRUE;
4021                                 break;
4022                         case OP_UNPACK_LOWQ:
4023                         case OP_UNPACK_LOWPD:
4024                                 mask_size = 2;
4025                                 low = TRUE;
4026                                 break;
4027                         case OP_UNPACK_HIGHB:
4028                                 mask_size = 16;
4029                                 break;
4030                         case OP_UNPACK_HIGHW:
4031                                 mask_size = 8;
4032                                 break;
4033                         case OP_UNPACK_HIGHD:
4034                         case OP_UNPACK_HIGHPS:
4035                                 mask_size = 4;
4036                                 break;
4037                         case OP_UNPACK_HIGHQ:
4038                         case OP_UNPACK_HIGHPD:
4039                                 mask_size = 2;
4040                                 break;
4041                         default:
4042                                 g_assert_not_reached ();
4043                         }
4044
4045                         if (low) {
4046                                 for (i = 0; i < (mask_size / 2); ++i) {
4047                                         mask [(i * 2)] = i;
4048                                         mask [(i * 2) + 1] = mask_size + i;
4049                                 }
4050                         } else {
4051                                 for (i = 0; i < (mask_size / 2); ++i) {
4052                                         mask [(i * 2)] = (mask_size / 2) + i;
4053                                         mask [(i * 2) + 1] = mask_size + (mask_size / 2) + i;
4054                                 }
4055                         }
4056
4057                         for (i = 0; i < mask_size; ++i)
4058                                 mask_values [i] = LLVMConstInt (LLVMInt32Type (), mask [i], FALSE);
4059                         
4060                         values [ins->dreg] =
4061                                 LLVMBuildShuffleVector (builder, values [ins->sreg1], values [ins->sreg2],
4062                                                                                 LLVMConstVector (mask_values, mask_size), dname);
4063                         break;
4064                 }
4065
4066                 case OP_DUPPD: {
4067                         LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4068                         LLVMValueRef v, val;
4069
4070                         v = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4071                         val = LLVMConstNull (t);
4072                         val = LLVMBuildInsertElement (builder, val, v, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4073                         val = LLVMBuildInsertElement (builder, val, v, LLVMConstInt (LLVMInt32Type (), 1, FALSE), dname);
4074
4075                         values [ins->dreg] = val;
4076                         break;
4077                 }
4078                 case OP_DUPPS_LOW:
4079                 case OP_DUPPS_HIGH: {
4080                         LLVMTypeRef t = simd_op_to_llvm_type (ins->opcode);
4081                         LLVMValueRef v1, v2, val;
4082                         
4083
4084                         if (ins->opcode == OP_DUPPS_LOW) {
4085                                 v1 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4086                                 v2 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 2, FALSE), "");
4087                         } else {
4088                                 v1 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 1, FALSE), "");
4089                                 v2 = LLVMBuildExtractElement (builder, lhs, LLVMConstInt (LLVMInt32Type (), 3, FALSE), "");
4090                         }
4091                         val = LLVMConstNull (t);
4092                         val = LLVMBuildInsertElement (builder, val, v1, LLVMConstInt (LLVMInt32Type (), 0, FALSE), "");
4093                         val = LLVMBuildInsertElement (builder, val, v1, LLVMConstInt (LLVMInt32Type (), 1, FALSE), "");
4094                         val = LLVMBuildInsertElement (builder, val, v2, LLVMConstInt (LLVMInt32Type (), 2, FALSE), "");
4095                         val = LLVMBuildInsertElement (builder, val, v2, LLVMConstInt (LLVMInt32Type (), 3, FALSE), "");
4096                         
4097                         values [ins->dreg] = val;
4098                         break;
4099                 }
4100
4101 #endif /* SIMD */
4102
4103                 case OP_DUMMY_USE:
4104                         break;
4105
4106                         /*
4107                          * EXCEPTION HANDLING
4108                          */
4109                 case OP_IMPLICIT_EXCEPTION:
4110                         /* This marks a place where an implicit exception can happen */
4111                         if (bb->region != -1)
4112                                 LLVM_FAILURE (ctx, "implicit-exception");
4113                         break;
4114                 case OP_THROW:
4115                 case OP_RETHROW: {
4116                         MonoMethodSignature *throw_sig;
4117                         LLVMValueRef callee, arg;
4118                         gboolean rethrow = (ins->opcode == OP_RETHROW);
4119                         const char *icall_name;
4120                                 
4121                         callee = rethrow ? ctx->lmodule->rethrow : ctx->lmodule->throw;
4122                         icall_name = rethrow ? "mono_arch_rethrow_exception" : "mono_arch_throw_exception";
4123
4124                         if (!callee) {
4125                                 throw_sig = mono_metadata_signature_alloc (mono_get_corlib (), 1);
4126                                 throw_sig->ret = &mono_get_void_class ()->byval_arg;
4127                                 throw_sig->params [0] = &mono_get_object_class ()->byval_arg;
4128                                 if (cfg->compile_aot) {
4129                                         callee = get_plt_entry (ctx, sig_to_llvm_sig (ctx, throw_sig), MONO_PATCH_INFO_INTERNAL_METHOD, icall_name);
4130                                 } else {
4131                                         callee = LLVMAddFunction (module, icall_name, sig_to_llvm_sig (ctx, throw_sig));
4132
4133 #ifdef TARGET_X86
4134                                         /* 
4135                                          * LLVM doesn't push the exception argument, so we need a different
4136                                          * trampoline.
4137                                          */
4138                                         LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, rethrow ? "llvm_rethrow_exception_trampoline" : "llvm_throw_exception_trampoline"));
4139 #else
4140                                         LLVMAddGlobalMapping (ctx->lmodule->ee, callee, resolve_patch (cfg, MONO_PATCH_INFO_INTERNAL_METHOD, icall_name));
4141 #endif
4142                                 }
4143
4144                                 mono_memory_barrier ();
4145                                 if (rethrow)
4146                                         ctx->lmodule->rethrow = callee;
4147                                 else
4148                                         ctx->lmodule->throw = callee;
4149                         }
4150                         arg = convert (ctx, lhs, type_to_llvm_type (ctx, &mono_get_object_class ()->byval_arg));
4151                         emit_call (ctx, bb, &builder, callee, &arg, 1);
4152                         break;
4153                 }
4154                 case OP_CALL_HANDLER: {
4155                         /* 
4156                          * We don't 'call' handlers, but instead simply branch to them.
4157                          * The code generated by ENDFINALLY will branch back to us.
4158                          */
4159                         LLVMBasicBlockRef noex_bb;
4160                         GSList *bb_list;
4161                         BBInfo *info = &bblocks [ins->inst_target_bb->block_num];
4162
4163                         bb_list = info->call_handler_return_bbs;
4164
4165                         /* 
4166                          * Set the indicator variable for the finally clause.
4167                          */
4168                         lhs = info->finally_ind;
4169                         g_assert (lhs);
4170                         LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), g_slist_length (bb_list) + 1, FALSE), lhs);
4171                                 
4172                         /* Branch to the finally clause */
4173                         LLVMBuildBr (builder, info->call_handler_target_bb);
4174
4175                         noex_bb = gen_bb (ctx, "CALL_HANDLER_CONT_BB");
4176                         info->call_handler_return_bbs = g_slist_append_mempool (cfg->mempool, info->call_handler_return_bbs, noex_bb);
4177
4178                         builder = ctx->builder = create_builder (ctx);
4179                         LLVMPositionBuilderAtEnd (ctx->builder, noex_bb);
4180
4181                         bblocks [bb->block_num].end_bblock = noex_bb;
4182                         break;
4183                 }
4184                 case OP_START_HANDLER: {
4185                         break;
4186                 }
4187                 case OP_ENDFINALLY: {
4188                         LLVMBasicBlockRef resume_bb;
4189                         MonoBasicBlock *handler_bb;
4190                         LLVMValueRef val, switch_ins, callee;
4191                         GSList *bb_list;
4192                         BBInfo *info;
4193
4194                         handler_bb = g_hash_table_lookup (ctx->region_to_handler, GUINT_TO_POINTER (mono_get_block_region_notry (cfg, bb->region)));
4195                         g_assert (handler_bb);
4196                         info = &bblocks [handler_bb->block_num];
4197                         lhs = info->finally_ind;
4198                         g_assert (lhs);
4199
4200                         bb_list = info->call_handler_return_bbs;
4201
4202                         resume_bb = gen_bb (ctx, "ENDFINALLY_RESUME_BB");
4203
4204                         /* Load the finally variable */
4205                         val = LLVMBuildLoad (builder, lhs, "");
4206
4207                         /* Reset the variable */
4208                         LLVMBuildStore (builder, LLVMConstInt (LLVMInt32Type (), 0, FALSE), lhs);
4209
4210                         /* Branch to either resume_bb, or to the bblocks in bb_list */
4211                         switch_ins = LLVMBuildSwitch (builder, val, resume_bb, g_slist_length (bb_list));
4212                         /* 
4213                          * The other targets are added at the end to handle OP_CALL_HANDLER
4214                          * opcodes processed later.
4215                          */
4216                         info->endfinally_switch_ins_list = g_slist_append_mempool (cfg->mempool, info->endfinally_switch_ins_list, switch_ins);
4217
4218                         builder = ctx->builder = create_builder (ctx);
4219                         LLVMPositionBuilderAtEnd (ctx->builder, resume_bb);
4220
4221                         if (ctx->cfg->compile_aot) {
4222                                 callee = get_plt_entry (ctx, LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE), MONO_PATCH_INFO_INTERNAL_METHOD, "llvm_resume_unwind_trampoline");
4223                         } else {
4224                                 callee = LLVMGetNamedFunction (module, "llvm_resume_unwind_trampoline");
4225                         }
4226                         LLVMBuildCall (builder, callee, NULL, 0, "");
4227
4228                         LLVMBuildUnreachable (builder);
4229                         has_terminator = TRUE;
4230                         break;
4231                 }
4232                 default: {
4233                         char reason [128];
4234
4235                         sprintf (reason, "opcode %s", mono_inst_name (ins->opcode));
4236                         LLVM_FAILURE (ctx, reason);
4237                         break;
4238                 }
4239                 }
4240
4241                 /* Convert the value to the type required by phi nodes */
4242                 if (spec [MONO_INST_DEST] != ' ' && !MONO_IS_STORE_MEMBASE (ins) && ctx->vreg_types [ins->dreg]) {
4243                         if (!values [ins->dreg])
4244                                 /* vtypes */
4245                                 values [ins->dreg] = addresses [ins->dreg];
4246                         else
4247                                 values [ins->dreg] = convert (ctx, values [ins->dreg], ctx->vreg_types [ins->dreg]);
4248                 }
4249
4250                 /* Add stores for volatile variables */
4251                 if (spec [MONO_INST_DEST] != ' ' && spec [MONO_INST_DEST] != 'v' && !MONO_IS_STORE_MEMBASE (ins))
4252                         emit_volatile_store (ctx, ins->dreg);
4253         }
4254
4255         if (!has_terminator && bb->next_bb && (bb == cfg->bb_entry || bb->in_count > 0))
4256                 LLVMBuildBr (builder, get_bb (ctx, bb->next_bb));
4257
4258         if (bb == cfg->bb_exit && sig->ret->type == MONO_TYPE_VOID) {
4259                 emit_dbg_loc (ctx, builder, cfg->header->code + cfg->header->code_size - 1);
4260                 LLVMBuildRetVoid (builder);
4261         }
4262
4263         if (bb == cfg->bb_entry)
4264                 ctx->last_alloca = LLVMGetLastInstruction (get_bb (ctx, cfg->bb_entry));
4265
4266         return;
4267
4268  FAILURE:
4269         return;
4270 }
4271
4272 /*
4273  * mono_llvm_check_method_supported:
4274  *
4275  *   Do some quick checks to decide whenever cfg->method can be compiled by LLVM, to avoid
4276  * compiling a method twice.
4277  */
4278 void
4279 mono_llvm_check_method_supported (MonoCompile *cfg)
4280 {
4281         MonoMethodHeader *header = cfg->header;
4282         MonoExceptionClause *clause;
4283         int i;
4284
4285         if (cfg->method->save_lmf) {
4286                 cfg->exception_message = g_strdup ("lmf");
4287                 cfg->disable_llvm = TRUE;
4288         }
4289         if (cfg->disable_llvm)
4290                 return;
4291
4292 #if 1
4293         for (i = 0; i < header->num_clauses; ++i) {
4294                 clause = &header->clauses [i];
4295
4296                 if (i > 0 && clause->try_offset <= header->clauses [i - 1].handler_offset + header->clauses [i - 1].handler_len) {
4297                         /*
4298                          * FIXME: Some tests still fail with nested clauses.
4299                          */
4300                         cfg->exception_message = g_strdup ("nested clauses");
4301                         cfg->disable_llvm = TRUE;
4302                         break;
4303                 }
4304         }
4305         if (cfg->disable_llvm)
4306                 return;
4307 #endif
4308
4309         /* FIXME: */
4310         if (cfg->method->dynamic) {
4311                 cfg->exception_message = g_strdup ("dynamic.");
4312                 cfg->disable_llvm = TRUE;
4313         }
4314         if (cfg->disable_llvm)
4315                 return;
4316 }
4317
4318 /*
4319  * mono_llvm_emit_method:
4320  *
4321  *   Emit LLVM IL from the mono IL, and compile it to native code using LLVM.
4322  */
4323 void
4324 mono_llvm_emit_method (MonoCompile *cfg)
4325 {
4326         EmitContext *ctx;
4327         MonoMethodSignature *sig;
4328         MonoBasicBlock *bb;
4329         LLVMTypeRef method_type;
4330         LLVMValueRef method = NULL;
4331         char *method_name;
4332         LLVMValueRef *values;
4333         int i, max_block_num, bb_index;
4334         gboolean last = FALSE;
4335         GPtrArray *phi_values;
4336         LLVMCallInfo *linfo;
4337         GSList *l;
4338         LLVMModuleRef module;
4339         BBInfo *bblocks;
4340         GPtrArray *bblock_list;
4341         MonoMethodHeader *header;
4342         MonoExceptionClause *clause;
4343         LLVMSigInfo sinfo;
4344         char **names;
4345
4346         /* The code below might acquire the loader lock, so use it for global locking */
4347         mono_loader_lock ();
4348
4349         /* Used to communicate with the callbacks */
4350         mono_native_tls_set_value (current_cfg_tls_id, cfg);
4351
4352         ctx = g_new0 (EmitContext, 1);
4353         ctx->cfg = cfg;
4354         ctx->mempool = cfg->mempool;
4355
4356         /*
4357          * This maps vregs to the LLVM instruction defining them
4358          */
4359         values = g_new0 (LLVMValueRef, cfg->next_vreg);
4360         /*
4361          * This maps vregs for volatile variables to the LLVM instruction defining their
4362          * address.
4363          */
4364         ctx->addresses = g_new0 (LLVMValueRef, cfg->next_vreg);
4365         ctx->vreg_types = g_new0 (LLVMTypeRef, cfg->next_vreg);
4366         ctx->vreg_cli_types = g_new0 (MonoType*, cfg->next_vreg);
4367         phi_values = g_ptr_array_sized_new (256);
4368         /* 
4369          * This signals whenever the vreg was defined by a phi node with no input vars
4370          * (i.e. all its input bblocks end with NOT_REACHABLE).
4371          */
4372         ctx->is_dead = g_new0 (gboolean, cfg->next_vreg);
4373         /* Whenever the bblock is unreachable */
4374         ctx->unreachable = g_new0 (gboolean, cfg->max_block_num);
4375
4376         bblock_list = g_ptr_array_sized_new (256);
4377
4378         ctx->values = values;
4379         ctx->region_to_handler = g_hash_table_new (NULL, NULL);
4380  
4381         if (cfg->compile_aot) {
4382                 ctx->lmodule = &aot_module;
4383                 method_name = mono_aot_get_method_name (cfg);
4384                 cfg->llvm_method_name = g_strdup (method_name);
4385         } else {
4386                 init_jit_module (cfg->domain);
4387                 ctx->lmodule = domain_jit_info (cfg->domain)->llvm_module;
4388                 method_name = mono_method_full_name (cfg->method, TRUE);
4389         }
4390
4391         module = ctx->module = ctx->lmodule->module;
4392
4393         if (cfg->gsharedvt)
4394                 LLVM_FAILURE (ctx, "gsharedvt");
4395
4396 #if 1
4397         {
4398                 static int count = 0;
4399                 count ++;
4400
4401                 if (g_getenv ("LLVM_COUNT")) {
4402                         if (count == atoi (g_getenv ("LLVM_COUNT"))) {
4403                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
4404                                 fflush (stdout);
4405                                 last = TRUE;
4406                         }
4407                         if (count > atoi (g_getenv ("LLVM_COUNT")))
4408                                 LLVM_FAILURE (ctx, "");
4409                 }
4410         }
4411 #endif
4412
4413         sig = mono_method_signature (cfg->method);
4414         ctx->sig = sig;
4415
4416         linfo = mono_arch_get_llvm_call_info (cfg, sig);
4417         ctx->linfo = linfo;
4418         CHECK_FAILURE (ctx);
4419
4420         if (cfg->rgctx_var)
4421                 linfo->rgctx_arg = TRUE;
4422         method_type = sig_to_llvm_sig_full (ctx, sig, linfo, &sinfo);
4423         CHECK_FAILURE (ctx);
4424
4425         /* 
4426          * This maps parameter indexes in the original signature to the indexes in
4427          * the LLVM signature.
4428          */
4429         ctx->pindexes = sinfo.pindexes;
4430
4431         method = LLVMAddFunction (module, method_name, method_type);
4432         ctx->lmethod = method;
4433
4434         LLVMSetFunctionCallConv (method, LLVMMono1CallConv);
4435         LLVMSetLinkage (method, LLVMPrivateLinkage);
4436
4437         LLVMAddFunctionAttr (method, LLVMUWTable);
4438
4439         if (cfg->compile_aot) {
4440                 LLVMSetLinkage (method, LLVMInternalLinkage);
4441 #if LLVM_API_VERSION == 0
4442                 /* This causes an assertion in later LLVM versions */
4443                 LLVMSetVisibility (method, LLVMHiddenVisibility);
4444 #endif
4445         } else {
4446                 LLVMSetLinkage (method, LLVMPrivateLinkage);
4447         }
4448
4449         if (cfg->method->save_lmf)
4450                 LLVM_FAILURE (ctx, "lmf");
4451
4452         if (sig->pinvoke && cfg->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
4453                 LLVM_FAILURE (ctx, "pinvoke signature");
4454
4455         header = cfg->header;
4456         for (i = 0; i < header->num_clauses; ++i) {
4457                 clause = &header->clauses [i];
4458                 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
4459                         LLVM_FAILURE (ctx, "non-finally/catch clause.");
4460         }
4461
4462         if (linfo->rgctx_arg) {
4463                 ctx->rgctx_arg = LLVMGetParam (method, sinfo.rgctx_arg_pindex);
4464                 /*
4465                  * We mark the rgctx parameter with the inreg attribute, which is mapped to
4466                  * MONO_ARCH_RGCTX_REG in the Mono calling convention in llvm, i.e.
4467                  * CC_X86_64_Mono in X86CallingConv.td.
4468                  */
4469                 LLVMAddAttribute (ctx->rgctx_arg, LLVMInRegAttribute);
4470                 LLVMSetValueName (ctx->rgctx_arg, "rgctx");
4471         }
4472         if (cfg->vret_addr) {
4473                 values [cfg->vret_addr->dreg] = LLVMGetParam (method, sinfo.vret_arg_pindex);
4474                 LLVMSetValueName (values [cfg->vret_addr->dreg], "vret");
4475         }
4476         if (sig->hasthis) {
4477                 values [cfg->args [0]->dreg] = LLVMGetParam (method, sinfo.this_arg_pindex);
4478                 LLVMSetValueName (values [cfg->args [0]->dreg], "this");
4479         }
4480
4481         names = g_new (char *, sig->param_count);
4482         mono_method_get_param_names (cfg->method, (const char **) names);
4483
4484         for (i = 0; i < sig->param_count; ++i) {
4485                 char *name;
4486
4487                 values [cfg->args [i + sig->hasthis]->dreg] = LLVMGetParam (method, sinfo.pindexes [i]);
4488                 if (names [i] && names [i][0] != '\0')
4489                         name = g_strdup_printf ("arg_%s", names [i]);
4490                 else
4491                         name = g_strdup_printf ("arg_%d", i);
4492                 LLVMSetValueName (values [cfg->args [i + sig->hasthis]->dreg], name);
4493                 g_free (name);
4494                 if (linfo->args [i + sig->hasthis].storage == LLVMArgVtypeByVal)
4495                         LLVMAddAttribute (LLVMGetParam (method, sinfo.pindexes [i]), LLVMByValAttribute);
4496         }
4497         g_free (names);
4498
4499         // See emit_dbg_info ()
4500         if (FALSE && cfg->compile_aot && mono_debug_enabled ()) {
4501                 ctx->minfo = mono_debug_lookup_method (cfg->method);
4502                 ctx->dbg_md = emit_dbg_subprogram (ctx, cfg, method, method_name);
4503         }
4504
4505         max_block_num = 0;
4506         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4507                 max_block_num = MAX (max_block_num, bb->block_num);
4508         ctx->bblocks = bblocks = g_new0 (BBInfo, max_block_num + 1);
4509
4510         /* Add branches between non-consecutive bblocks */
4511         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4512                 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
4513                         bb->next_bb != bb->last_ins->inst_false_bb) {
4514                         
4515                         MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
4516                         inst->opcode = OP_BR;
4517                         inst->inst_target_bb = bb->last_ins->inst_false_bb;
4518                         mono_bblock_add_inst (bb, inst);
4519                 }
4520         }
4521
4522         /*
4523          * The INDIRECT flag added by OP_LDADDR inhibits optimizations, even if the LDADDR
4524          * was later optimized away, so clear these flags, and add them back for the still
4525          * present OP_LDADDR instructions.
4526          */
4527         for (i = 0; i < cfg->next_vreg; ++i) {
4528                 MonoInst *ins;
4529
4530                 ins = get_vreg_to_inst (cfg, i);
4531                 if (ins && ins != cfg->rgctx_var)
4532                         ins->flags &= ~MONO_INST_INDIRECT;
4533         }
4534
4535         /*
4536          * Make a first pass over the code to precreate PHI nodes/set INDIRECT flags.
4537          */
4538         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4539                 MonoInst *ins;
4540                 LLVMBuilderRef builder;
4541                 char *dname;
4542                 char dname_buf[128];
4543
4544                 builder = create_builder (ctx);
4545
4546                 for (ins = bb->code; ins; ins = ins->next) {
4547                         switch (ins->opcode) {
4548                         case OP_PHI:
4549                         case OP_FPHI:
4550                         case OP_VPHI:
4551                         case OP_XPHI: {
4552                                 LLVMTypeRef phi_type = llvm_type_to_stack_type (type_to_llvm_type (ctx, &ins->klass->byval_arg));
4553
4554                                 CHECK_FAILURE (ctx);
4555
4556                                 if (ins->opcode == OP_VPHI) {
4557                                         /* Treat valuetype PHI nodes as operating on the address itself */
4558                                         g_assert (ins->klass);
4559                                         phi_type = LLVMPointerType (type_to_llvm_type (ctx, &ins->klass->byval_arg), 0);
4560                                 }
4561
4562                                 /* 
4563                                  * Have to precreate these, as they can be referenced by
4564                                  * earlier instructions.
4565                                  */
4566                                 sprintf (dname_buf, "t%d", ins->dreg);
4567                                 dname = dname_buf;
4568                                 values [ins->dreg] = LLVMBuildPhi (builder, phi_type, dname);
4569
4570                                 if (ins->opcode == OP_VPHI)
4571                                         ctx->addresses [ins->dreg] = values [ins->dreg];
4572
4573                                 g_ptr_array_add (phi_values, values [ins->dreg]);
4574
4575                                 /* 
4576                                  * Set the expected type of the incoming arguments since these have
4577                                  * to have the same type.
4578                                  */
4579                                 for (i = 0; i < ins->inst_phi_args [0]; i++) {
4580                                         int sreg1 = ins->inst_phi_args [i + 1];
4581                                         
4582                                         if (sreg1 != -1)
4583                                                 ctx->vreg_types [sreg1] = phi_type;
4584                                 }
4585                                 break;
4586                                 }
4587                         case OP_LDADDR:
4588                                 ((MonoInst*)ins->inst_p0)->flags |= MONO_INST_INDIRECT;
4589                                 break;
4590                         default:
4591                                 break;
4592                         }
4593                 }
4594         }
4595
4596         /* 
4597          * Create an ordering for bblocks, use the depth first order first, then
4598          * put the exception handling bblocks last.
4599          */
4600         for (bb_index = 0; bb_index < cfg->num_bblocks; ++bb_index) {
4601                 bb = cfg->bblocks [bb_index];
4602                 if (!(bb->region != -1 && !MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))) {
4603                         g_ptr_array_add (bblock_list, bb);
4604                         bblocks [bb->block_num].added = TRUE;
4605                 }
4606         }
4607
4608         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4609                 if (!bblocks [bb->block_num].added)
4610                         g_ptr_array_add (bblock_list, bb);
4611         }
4612
4613         /*
4614          * Second pass: generate code.
4615          */
4616         for (bb_index = 0; bb_index < bblock_list->len; ++bb_index) {
4617                 bb = g_ptr_array_index (bblock_list, bb_index);
4618
4619                 if (!(bb == cfg->bb_entry || bb->in_count > 0))
4620                         continue;
4621
4622                 process_bb (ctx, bb);
4623                 CHECK_FAILURE (ctx);
4624         }
4625
4626         /* Add incoming phi values */
4627         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4628                 GSList *l, *ins_list;
4629
4630                 ins_list = bblocks [bb->block_num].phi_nodes;
4631
4632                 for (l = ins_list; l; l = l->next) {
4633                         PhiNode *node = l->data;
4634                         MonoInst *phi = node->phi;
4635                         int sreg1 = node->sreg;
4636                         LLVMBasicBlockRef in_bb;
4637
4638                         if (sreg1 == -1)
4639                                 continue;
4640
4641                         in_bb = get_end_bb (ctx, node->in_bb);
4642
4643                         if (ctx->unreachable [node->in_bb->block_num])
4644                                 continue;
4645
4646                         if (!values [sreg1])
4647                                 /* Can happen with values in EH clauses */
4648                                 LLVM_FAILURE (ctx, "incoming phi sreg1");
4649
4650                         if (phi->opcode == OP_VPHI) {
4651                                 g_assert (LLVMTypeOf (ctx->addresses [sreg1]) == LLVMTypeOf (values [phi->dreg]));
4652                                 LLVMAddIncoming (values [phi->dreg], &ctx->addresses [sreg1], &in_bb, 1);
4653                         } else {
4654                                 if (LLVMTypeOf (values [sreg1]) != LLVMTypeOf (values [phi->dreg]))
4655                                         // FIXME:
4656                                         LLVM_FAILURE (ctx, "incoming phi arg type mismatch");
4657                                 g_assert (LLVMTypeOf (values [sreg1]) == LLVMTypeOf (values [phi->dreg]));
4658                                 LLVMAddIncoming (values [phi->dreg], &values [sreg1], &in_bb, 1);
4659                         }
4660                 }
4661         }
4662
4663         /* Create the SWITCH statements for ENDFINALLY instructions */
4664         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4665                 BBInfo *info = &bblocks [bb->block_num];
4666                 GSList *l;
4667                 for (l = info->endfinally_switch_ins_list; l; l = l->next) {
4668                         LLVMValueRef switch_ins = l->data;
4669                         GSList *bb_list = info->call_handler_return_bbs;
4670
4671                         for (i = 0; i < g_slist_length (bb_list); ++i)
4672                                 LLVMAddCase (switch_ins, LLVMConstInt (LLVMInt32Type (), i + 1, FALSE), g_slist_nth (bb_list, i)->data);
4673                 }
4674         }
4675
4676         if (cfg->verbose_level > 1)
4677                 mono_llvm_dump_value (method);
4678
4679         if (cfg->compile_aot)
4680                 mark_as_used (ctx->lmodule, method);
4681
4682         if (cfg->compile_aot) {
4683                 LLVMValueRef md_args [16];
4684                 LLVMValueRef md_node;
4685                 int method_index;
4686
4687                 method_index = mono_aot_get_method_index (cfg->orig_method);
4688                 md_args [0] = LLVMMDString (method_name, strlen (method_name));
4689                 md_args [1] = LLVMConstInt (LLVMInt32Type (), method_index, FALSE);
4690                 md_node = LLVMMDNode (md_args, 2);
4691                 LLVMAddNamedMetadataOperand (module, "mono.function_indexes", md_node);
4692                 //LLVMSetMetadata (method, md_kind, LLVMMDNode (&md_arg, 1));
4693         }
4694
4695         if (cfg->compile_aot) {
4696                 /* Don't generate native code, keep the LLVM IR */
4697                 if (cfg->compile_aot && cfg->verbose_level)
4698                         printf ("%s emitted as %s\n", mono_method_full_name (cfg->method, TRUE), method_name);
4699
4700                 //LLVMVerifyFunction(method, 0);
4701         } else {
4702                 mono_llvm_optimize_method (ctx->lmodule->mono_ee, method);
4703
4704                 if (cfg->verbose_level > 1)
4705                         mono_llvm_dump_value (method);
4706
4707                 cfg->native_code = LLVMGetPointerToGlobal (ctx->lmodule->ee, method);
4708
4709                 /* Set by emit_cb */
4710                 g_assert (cfg->code_len);
4711
4712                 /* FIXME: Free the LLVM IL for the function */
4713         }
4714
4715         if (ctx->lmodule->method_to_lmethod)
4716                 g_hash_table_insert (ctx->lmodule->method_to_lmethod, cfg->method, method);
4717
4718         goto CLEANUP;
4719
4720  FAILURE:
4721
4722         if (method) {
4723                 /* Need to add unused phi nodes as they can be referenced by other values */
4724                 LLVMBasicBlockRef phi_bb = LLVMAppendBasicBlock (method, "PHI_BB");
4725                 LLVMBuilderRef builder;
4726
4727                 builder = create_builder (ctx);
4728                 LLVMPositionBuilderAtEnd (builder, phi_bb);
4729
4730                 for (i = 0; i < phi_values->len; ++i) {
4731                         LLVMValueRef v = g_ptr_array_index (phi_values, i);
4732                         if (LLVMGetInstructionParent (v) == NULL)
4733                                 LLVMInsertIntoBuilder (builder, v);
4734                 }
4735                 
4736                 LLVMDeleteFunction (method);
4737         }
4738
4739  CLEANUP:
4740         g_free (values);
4741         g_free (ctx->addresses);
4742         g_free (ctx->vreg_types);
4743         g_free (ctx->vreg_cli_types);
4744         g_free (ctx->pindexes);
4745         g_free (ctx->is_dead);
4746         g_free (ctx->unreachable);
4747         g_ptr_array_free (phi_values, TRUE);
4748         g_free (ctx->bblocks);
4749         g_hash_table_destroy (ctx->region_to_handler);
4750         g_free (method_name);
4751         g_ptr_array_free (bblock_list, TRUE);
4752
4753         for (l = ctx->builders; l; l = l->next) {
4754                 LLVMBuilderRef builder = l->data;
4755                 LLVMDisposeBuilder (builder);
4756         }
4757
4758         g_free (ctx);
4759
4760         mono_native_tls_set_value (current_cfg_tls_id, NULL);
4761
4762         mono_loader_unlock ();
4763 }
4764
4765 /*
4766  * mono_llvm_emit_call:
4767  *
4768  *   Same as mono_arch_emit_call () for LLVM.
4769  */
4770 void
4771 mono_llvm_emit_call (MonoCompile *cfg, MonoCallInst *call)
4772 {
4773         MonoInst *in;
4774         MonoMethodSignature *sig;
4775         int i, n, stack_size;
4776         LLVMArgInfo *ainfo;
4777
4778         stack_size = 0;
4779
4780         sig = call->signature;
4781         n = sig->param_count + sig->hasthis;
4782
4783         call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
4784
4785         if (cfg->disable_llvm)
4786                 return;
4787
4788         if (sig->call_convention == MONO_CALL_VARARG) {
4789                 cfg->exception_message = g_strdup ("varargs");
4790                 cfg->disable_llvm = TRUE;
4791         }
4792
4793         for (i = 0; i < n; ++i) {
4794                 MonoInst *ins;
4795
4796                 ainfo = call->cinfo->args + i;
4797
4798                 in = call->args [i];
4799                         
4800                 /* Simply remember the arguments */
4801                 switch (ainfo->storage) {
4802                 case LLVMArgInIReg:
4803                 case LLVMArgInFPReg: {
4804                         MonoType *t = (sig->hasthis && i == 0) ? &mono_get_intptr_class ()->byval_arg : sig->params [i - sig->hasthis];
4805                         int opcode;
4806
4807                         opcode = mono_type_to_regmove (cfg, t);
4808                         if (opcode == OP_FMOVE) {
4809                                 MONO_INST_NEW (cfg, ins, OP_FMOVE);
4810                                 ins->dreg = mono_alloc_freg (cfg);
4811                         } else if (opcode == OP_LMOVE) {
4812                                 MONO_INST_NEW (cfg, ins, OP_LMOVE);
4813                                 ins->dreg = mono_alloc_lreg (cfg);
4814                         } else {
4815                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
4816                                 ins->dreg = mono_alloc_ireg (cfg);
4817                         }
4818                         ins->sreg1 = in->dreg;
4819                         break;
4820                 }
4821                 case LLVMArgVtypeByVal:
4822                 case LLVMArgVtypeInReg:
4823                         MONO_INST_NEW (cfg, ins, OP_LLVM_OUTARG_VT);
4824                         ins->dreg = mono_alloc_ireg (cfg);
4825                         ins->sreg1 = in->dreg;
4826                         ins->klass = mono_class_from_mono_type (sig->params [i - sig->hasthis]);
4827                         break;
4828                 default:
4829                         call->cinfo = mono_arch_get_llvm_call_info (cfg, sig);
4830                         cfg->exception_message = g_strdup ("ainfo->storage");
4831                         cfg->disable_llvm = TRUE;
4832                         return;
4833                 }
4834
4835                 if (!cfg->disable_llvm) {
4836                         MONO_ADD_INS (cfg->cbb, ins);
4837                         mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, 0, FALSE);
4838                 }
4839         }
4840 }
4841
4842 static unsigned char*
4843 alloc_cb (LLVMValueRef function, int size)
4844 {
4845         MonoCompile *cfg;
4846
4847         cfg = mono_native_tls_get_value (current_cfg_tls_id);
4848
4849         if (cfg) {
4850                 // FIXME: dynamic
4851                 return mono_domain_code_reserve (cfg->domain, size);
4852         } else {
4853                 return mono_domain_code_reserve (mono_domain_get (), size);
4854         }
4855 }
4856
4857 static void
4858 emitted_cb (LLVMValueRef function, void *start, void *end)
4859 {
4860         MonoCompile *cfg;
4861
4862         cfg = mono_native_tls_get_value (current_cfg_tls_id);
4863         g_assert (cfg);
4864         cfg->code_len = (guint8*)end - (guint8*)start;
4865 }
4866
4867 static void
4868 exception_cb (void *data)
4869 {
4870         MonoCompile *cfg;
4871         MonoJitExceptionInfo *ei;
4872         guint32 ei_len, i, j, nested_len, nindex;
4873         gpointer *type_info;
4874         int this_reg, this_offset;
4875
4876         cfg = mono_native_tls_get_value (current_cfg_tls_id);
4877         g_assert (cfg);
4878
4879         /*
4880          * data points to a DWARF FDE structure, convert it to our unwind format and
4881          * save it.
4882          * An alternative would be to save it directly, and modify our unwinder to work
4883          * with it.
4884          */
4885         cfg->encoded_unwind_ops = mono_unwind_decode_fde ((guint8*)data, &cfg->encoded_unwind_ops_len, NULL, &ei, &ei_len, &type_info, &this_reg, &this_offset);
4886         if (cfg->verbose_level > 1)
4887                 mono_print_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
4888
4889         /* Count nested clauses */
4890         nested_len = 0;
4891         for (i = 0; i < ei_len; ++i) {
4892                 for (j = 0; j < ei_len; ++j) {
4893                         gint32 cindex1 = *(gint32*)type_info [i];
4894                         MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
4895                         gint32 cindex2 = *(gint32*)type_info [j];
4896                         MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
4897
4898                         if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
4899                                 nested_len ++;
4900                         }
4901                 }
4902         }
4903
4904         cfg->llvm_ex_info = mono_mempool_alloc0 (cfg->mempool, (ei_len + nested_len) * sizeof (MonoJitExceptionInfo));
4905         cfg->llvm_ex_info_len = ei_len + nested_len;
4906         memcpy (cfg->llvm_ex_info, ei, ei_len * sizeof (MonoJitExceptionInfo));
4907         /* Fill the rest of the information from the type info */
4908         for (i = 0; i < ei_len; ++i) {
4909                 gint32 clause_index = *(gint32*)type_info [i];
4910                 MonoExceptionClause *clause = &cfg->header->clauses [clause_index];
4911
4912                 cfg->llvm_ex_info [i].flags = clause->flags;
4913                 cfg->llvm_ex_info [i].data.catch_class = clause->data.catch_class;
4914         }
4915
4916         /*
4917          * For nested clauses, the LLVM produced exception info associates the try interval with
4918          * the innermost handler, while mono expects it to be associated with all nesting clauses.
4919          */
4920         /* FIXME: These should be order with the normal clauses */
4921         nindex = ei_len;
4922         for (i = 0; i < ei_len; ++i) {
4923                 for (j = 0; j < ei_len; ++j) {
4924                         gint32 cindex1 = *(gint32*)type_info [i];
4925                         MonoExceptionClause *clause1 = &cfg->header->clauses [cindex1];
4926                         gint32 cindex2 = *(gint32*)type_info [j];
4927                         MonoExceptionClause *clause2 = &cfg->header->clauses [cindex2];
4928
4929                         if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset) {
4930                                 /* 
4931                                  * The try interval comes from the nested clause, everything else from the
4932                                  * nesting clause.
4933                                  */
4934                                 memcpy (&cfg->llvm_ex_info [nindex], &cfg->llvm_ex_info [j], sizeof (MonoJitExceptionInfo));
4935                                 cfg->llvm_ex_info [nindex].try_start = cfg->llvm_ex_info [i].try_start;
4936                                 cfg->llvm_ex_info [nindex].try_end = cfg->llvm_ex_info [i].try_end;
4937                                 nindex ++;
4938                         }
4939                 }
4940         }
4941         g_assert (nindex == ei_len + nested_len);
4942         cfg->llvm_this_reg = this_reg;
4943         cfg->llvm_this_offset = this_offset;
4944
4945         /* type_info [i] is cfg mempool allocated, no need to free it */
4946
4947         g_free (ei);
4948         g_free (type_info);
4949 }
4950
4951 static char*
4952 dlsym_cb (const char *name, void **symbol)
4953 {
4954         MonoDl *current;
4955         char *err;
4956
4957         err = NULL;
4958         if (!strcmp (name, "__bzero")) {
4959                 *symbol = (void*)bzero;
4960         } else {
4961                 current = mono_dl_open (NULL, 0, NULL);
4962                 g_assert (current);
4963
4964                 err = mono_dl_symbol (current, name, symbol);
4965
4966                 mono_dl_close (current);
4967         }
4968 #ifdef MONO_ARCH_HAVE_CREATE_LLVM_NATIVE_THUNK
4969         *symbol = (char*)mono_arch_create_llvm_native_thunk (mono_domain_get (), (guint8*)(*symbol));
4970 #endif
4971         return err;
4972 }
4973
4974 static inline void
4975 AddFunc (LLVMModuleRef module, const char *name, LLVMTypeRef ret_type, LLVMTypeRef *param_types, int nparams)
4976 {
4977         LLVMAddFunction (module, name, LLVMFunctionType (ret_type, param_types, nparams, FALSE));
4978 }
4979
4980 static inline void
4981 AddFunc2 (LLVMModuleRef module, const char *name, LLVMTypeRef ret_type, LLVMTypeRef param_type1, LLVMTypeRef param_type2)
4982 {
4983         LLVMTypeRef param_types [4];
4984
4985         param_types [0] = param_type1;
4986         param_types [1] = param_type2;
4987
4988         AddFunc (module, name, ret_type, param_types, 2);
4989 }
4990
4991 static void
4992 add_intrinsics (LLVMModuleRef module)
4993 {
4994         /* Emit declarations of instrinsics */
4995         /*
4996          * It would be nicer to emit only the intrinsics actually used, but LLVM's Module
4997          * type doesn't seem to do any locking.
4998          */
4999         {
5000                 LLVMTypeRef memset_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMInt8Type (), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
5001
5002                 memset_param_count = 5;
5003                 memset_func_name = "llvm.memset.p0i8.i32";
5004
5005                 LLVMAddFunction (module, memset_func_name, LLVMFunctionType (LLVMVoidType (), memset_params, memset_param_count, FALSE));
5006         }
5007
5008         {
5009                 LLVMTypeRef memcpy_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMPointerType (LLVMInt8Type (), 0), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
5010
5011                 memcpy_param_count = 5;
5012                 memcpy_func_name = "llvm.memcpy.p0i8.p0i8.i32";
5013
5014                 LLVMAddFunction (module, memcpy_func_name, LLVMFunctionType (LLVMVoidType (), memcpy_params, memcpy_param_count, FALSE));
5015         }
5016
5017         {
5018                 LLVMTypeRef params [] = { LLVMDoubleType () };
5019
5020                 LLVMAddFunction (module, "llvm.sin.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5021                 LLVMAddFunction (module, "llvm.cos.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5022                 LLVMAddFunction (module, "llvm.sqrt.f64", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5023
5024                 /* This isn't an intrinsic, instead llvm seems to special case it by name */
5025                 LLVMAddFunction (module, "fabs", LLVMFunctionType (LLVMDoubleType (), params, 1, FALSE));
5026         }
5027
5028         {
5029                 LLVMTypeRef ovf_res_i32 [] = { LLVMInt32Type (), LLVMInt1Type () };
5030                 LLVMTypeRef ovf_params_i32 [] = { LLVMInt32Type (), LLVMInt32Type () };
5031
5032                 LLVMAddFunction (module, "llvm.sadd.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5033                 LLVMAddFunction (module, "llvm.uadd.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5034                 LLVMAddFunction (module, "llvm.ssub.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5035                 LLVMAddFunction (module, "llvm.usub.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5036                 LLVMAddFunction (module, "llvm.smul.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5037                 LLVMAddFunction (module, "llvm.umul.with.overflow.i32", LLVMFunctionType (LLVMStructType (ovf_res_i32, 2, FALSE), ovf_params_i32, 2, FALSE));
5038         }
5039
5040         {
5041                 LLVMTypeRef ovf_res_i64 [] = { LLVMInt64Type (), LLVMInt1Type () };
5042                 LLVMTypeRef ovf_params_i64 [] = { LLVMInt64Type (), LLVMInt64Type () };
5043
5044                 LLVMAddFunction (module, "llvm.sadd.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5045                 LLVMAddFunction (module, "llvm.uadd.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5046                 LLVMAddFunction (module, "llvm.ssub.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5047                 LLVMAddFunction (module, "llvm.usub.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5048                 LLVMAddFunction (module, "llvm.smul.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5049                 LLVMAddFunction (module, "llvm.umul.with.overflow.i64", LLVMFunctionType (LLVMStructType (ovf_res_i64, 2, FALSE), ovf_params_i64, 2, FALSE));
5050         }
5051
5052         /* EH intrinsics */
5053         {
5054                 LLVMTypeRef arg_types [2];
5055                 LLVMTypeRef ret_type;
5056
5057                 arg_types [0] = LLVMPointerType (LLVMInt8Type (), 0);
5058                 arg_types [1] = LLVMPointerType (LLVMInt8Type (), 0);
5059                 ret_type = LLVMInt32Type ();
5060
5061                 LLVMAddFunction (module, "mono_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5062
5063                 LLVMAddFunction (module, "llvm_resume_unwind_trampoline", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5064         }
5065
5066         /* SSE intrinsics */
5067 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5068         {
5069                 LLVMTypeRef ret_type, arg_types [16];
5070
5071                 /* Binary ops */
5072                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5073                 arg_types [0] = ret_type;
5074                 arg_types [1] = ret_type;
5075                 AddFunc (module, "llvm.x86.sse41.pminud", ret_type, arg_types, 2);
5076                 AddFunc (module, "llvm.x86.sse41.pmaxud", ret_type, arg_types, 2);
5077
5078                 ret_type = type_to_simd_type (MONO_TYPE_I2);
5079                 arg_types [0] = ret_type;
5080                 arg_types [1] = ret_type;
5081                 AddFunc (module, "llvm.x86.sse41.pminuw", ret_type, arg_types, 2);
5082                 AddFunc (module, "llvm.x86.sse2.pmins.w", ret_type, arg_types, 2);
5083                 AddFunc (module, "llvm.x86.sse41.pmaxuw", ret_type, arg_types, 2);
5084                 AddFunc (module, "llvm.x86.sse2.padds.w", ret_type, arg_types, 2);
5085                 AddFunc (module, "llvm.x86.sse2.psubs.w", ret_type, arg_types, 2);
5086                 AddFunc (module, "llvm.x86.sse2.paddus.w", ret_type, arg_types, 2);
5087                 AddFunc (module, "llvm.x86.sse2.psubus.w", ret_type, arg_types, 2);
5088                 AddFunc (module, "llvm.x86.sse2.pavg.w", ret_type, arg_types, 2);
5089                 AddFunc (module, "llvm.x86.sse2.pmulh.w", ret_type, arg_types, 2);
5090                 AddFunc (module, "llvm.x86.sse2.pmulhu.w", ret_type, arg_types, 2);
5091
5092                 ret_type = type_to_simd_type (MONO_TYPE_I1);
5093                 arg_types [0] = ret_type;
5094                 arg_types [1] = ret_type;
5095                 AddFunc (module, "llvm.x86.sse2.pminu.b", ret_type, arg_types, 2);
5096                 AddFunc (module, "llvm.x86.sse2.pmaxu.b", ret_type, arg_types, 2);
5097                 AddFunc (module, "llvm.x86.sse2.padds.b", ret_type, arg_types, 2);
5098                 AddFunc (module, "llvm.x86.sse2.psubs.b", ret_type, arg_types, 2);
5099                 AddFunc (module, "llvm.x86.sse2.paddus.b", ret_type, arg_types, 2);
5100                 AddFunc (module, "llvm.x86.sse2.psubus.b", ret_type, arg_types, 2);
5101                 AddFunc (module, "llvm.x86.sse2.pavg.b", ret_type, arg_types, 2);
5102
5103                 ret_type = type_to_simd_type (MONO_TYPE_R8);
5104                 arg_types [0] = ret_type;
5105                 arg_types [1] = ret_type;
5106                 AddFunc (module, "llvm.x86.sse2.min.pd", ret_type, arg_types, 2);
5107                 AddFunc (module, "llvm.x86.sse2.max.pd", ret_type, arg_types, 2);
5108                 AddFunc (module, "llvm.x86.sse3.hadd.pd", ret_type, arg_types, 2);
5109                 AddFunc (module, "llvm.x86.sse3.hsub.pd", ret_type, arg_types, 2);
5110                 AddFunc (module, "llvm.x86.sse3.addsub.pd", ret_type, arg_types, 2);
5111
5112                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5113                 arg_types [0] = ret_type;
5114                 arg_types [1] = ret_type;
5115                 AddFunc (module, "llvm.x86.sse.min.ps", ret_type, arg_types, 2);
5116                 AddFunc (module, "llvm.x86.sse.max.ps", ret_type, arg_types, 2);
5117                 AddFunc (module, "llvm.x86.sse3.hadd.ps", ret_type, arg_types, 2);
5118                 AddFunc (module, "llvm.x86.sse3.hsub.ps", ret_type, arg_types, 2);
5119                 AddFunc (module, "llvm.x86.sse3.addsub.ps", ret_type, arg_types, 2);
5120
5121                 /* pack */
5122                 ret_type = type_to_simd_type (MONO_TYPE_I1);
5123                 arg_types [0] = type_to_simd_type (MONO_TYPE_I2);
5124                 arg_types [1] = type_to_simd_type (MONO_TYPE_I2);
5125                 AddFunc (module, "llvm.x86.sse2.packsswb.128", ret_type, arg_types, 2);
5126                 AddFunc (module, "llvm.x86.sse2.packuswb.128", ret_type, arg_types, 2);
5127                 ret_type = type_to_simd_type (MONO_TYPE_I2);
5128                 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5129                 arg_types [1] = type_to_simd_type (MONO_TYPE_I4);
5130                 AddFunc (module, "llvm.x86.sse2.packssdw.128", ret_type, arg_types, 2);
5131                 AddFunc (module, "llvm.x86.sse41.packusdw", ret_type, arg_types, 2);
5132
5133                 /* cmp pd/ps */
5134                 ret_type = type_to_simd_type (MONO_TYPE_R8);
5135                 arg_types [0] = ret_type;
5136                 arg_types [1] = ret_type;
5137                 arg_types [2] = LLVMInt8Type ();
5138                 AddFunc (module, "llvm.x86.sse2.cmp.pd", ret_type, arg_types, 3);
5139                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5140                 arg_types [0] = ret_type;
5141                 arg_types [1] = ret_type;
5142                 arg_types [2] = LLVMInt8Type ();
5143                 AddFunc (module, "llvm.x86.sse.cmp.ps", ret_type, arg_types, 3);
5144
5145                 /* Conversion ops */
5146                 ret_type = type_to_simd_type (MONO_TYPE_R8);
5147                 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5148                 AddFunc (module, "llvm.x86.sse2.cvtdq2pd", ret_type, arg_types, 1);
5149                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5150                 arg_types [0] = type_to_simd_type (MONO_TYPE_I4);
5151                 AddFunc (module, "llvm.x86.sse2.cvtdq2ps", ret_type, arg_types, 1);
5152                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5153                 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5154                 AddFunc (module, "llvm.x86.sse2.cvtpd2dq", ret_type, arg_types, 1);
5155                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5156                 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5157                 AddFunc (module, "llvm.x86.sse2.cvtps2dq", ret_type, arg_types, 1);
5158                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5159                 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5160                 AddFunc (module, "llvm.x86.sse2.cvtpd2ps", ret_type, arg_types, 1);
5161                 ret_type = type_to_simd_type (MONO_TYPE_R8);
5162                 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5163                 AddFunc (module, "llvm.x86.sse2.cvtps2pd", ret_type, arg_types, 1);
5164
5165                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5166                 arg_types [0] = type_to_simd_type (MONO_TYPE_R8);
5167                 AddFunc (module, "llvm.x86.sse2.cvttpd2dq", ret_type, arg_types, 1);
5168                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5169                 arg_types [0] = type_to_simd_type (MONO_TYPE_R4);
5170                 AddFunc (module, "llvm.x86.sse2.cvttps2dq", ret_type, arg_types, 1);
5171
5172                 /* Unary ops */
5173                 ret_type = type_to_simd_type (MONO_TYPE_R8);
5174                 arg_types [0] = ret_type;
5175                 AddFunc (module, "llvm.x86.sse2.sqrt.pd", ret_type, arg_types, 1);
5176                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5177                 arg_types [0] = ret_type;
5178                 AddFunc (module, "llvm.x86.sse.sqrt.ps", ret_type, arg_types, 1);
5179                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5180                 arg_types [0] = ret_type;
5181                 AddFunc (module, "llvm.x86.sse.rsqrt.ps", ret_type, arg_types, 1);
5182                 ret_type = type_to_simd_type (MONO_TYPE_R4);
5183                 arg_types [0] = ret_type;
5184                 AddFunc (module, "llvm.x86.sse.rcp.ps", ret_type, arg_types, 1);
5185
5186                 /* shifts */
5187                 ret_type = type_to_simd_type (MONO_TYPE_I2);
5188                 arg_types [0] = ret_type;
5189                 arg_types [1] = LLVMInt32Type ();
5190                 AddFunc (module, "llvm.x86.sse2.psrli.w", ret_type, arg_types, 2);
5191                 AddFunc (module, "llvm.x86.sse2.psrai.w", ret_type, arg_types, 2);
5192                 AddFunc (module, "llvm.x86.sse2.pslli.w", ret_type, arg_types, 2);
5193                 ret_type = type_to_simd_type (MONO_TYPE_I4);
5194                 arg_types [0] = ret_type;
5195                 arg_types [1] = LLVMInt32Type ();
5196                 AddFunc (module, "llvm.x86.sse2.psrli.d", ret_type, arg_types, 2);
5197                 AddFunc (module, "llvm.x86.sse2.psrai.d", ret_type, arg_types, 2);
5198                 AddFunc (module, "llvm.x86.sse2.pslli.d", ret_type, arg_types, 2);
5199                 ret_type = type_to_simd_type (MONO_TYPE_I8);
5200                 arg_types [0] = ret_type;
5201                 arg_types [1] = LLVMInt32Type ();
5202                 AddFunc (module, "llvm.x86.sse2.psrli.q", ret_type, arg_types, 2);
5203                 AddFunc (module, "llvm.x86.sse2.pslli.q", ret_type, arg_types, 2);
5204
5205                 /* pmovmskb */
5206                 ret_type = LLVMInt32Type ();
5207                 arg_types [0] = type_to_simd_type (MONO_TYPE_I1);
5208                 AddFunc (module, "llvm.x86.sse2.pmovmskb.128", ret_type, arg_types, 1);
5209         }
5210
5211         AddFunc (module, "llvm.x86.sse2.pause", LLVMVoidType (), NULL, 0);
5212 #endif
5213
5214         /* Load/Store intrinsics */
5215         {
5216                 LLVMTypeRef arg_types [5];
5217                 int i;
5218                 char name [128];
5219
5220                 for (i = 1; i <= 8; i *= 2) {
5221                         arg_types [0] = LLVMPointerType (LLVMIntType (i * 8), 0);
5222                         arg_types [1] = LLVMInt32Type ();
5223                         arg_types [2] = LLVMInt1Type ();
5224                         sprintf (name, "llvm.mono.load.i%d.p0i%d", i * 8, i * 8);
5225                         LLVMAddFunction (module, name, LLVMFunctionType (LLVMIntType (i * 8), arg_types, 3, FALSE));
5226
5227                         arg_types [0] = LLVMIntType (i * 8);
5228                         arg_types [1] = LLVMPointerType (LLVMIntType (i * 8), 0);
5229                         arg_types [2] = LLVMInt32Type ();
5230                         arg_types [3] = LLVMInt1Type ();
5231                         sprintf (name, "llvm.mono.store.i%d.p0i%d", i * 8, i * 8);
5232                         LLVMAddFunction (module, name, LLVMFunctionType (LLVMVoidType (), arg_types, 4, FALSE));
5233                 }
5234         }
5235 }
5236
5237 static void
5238 add_types (MonoLLVMModule *lmodule)
5239 {
5240         lmodule->ptr_type = LLVMPointerType (sizeof (gpointer) == 8 ? LLVMInt64Type () : LLVMInt32Type (), 0);
5241 }
5242
5243 void
5244 mono_llvm_init (void)
5245 {
5246         mono_native_tls_alloc (&current_cfg_tls_id, NULL);
5247 }
5248
5249 static void
5250 init_jit_module (MonoDomain *domain)
5251 {
5252         MonoJitICallInfo *info;
5253         MonoJitDomainInfo *dinfo;
5254         MonoLLVMModule *module;
5255         char *name;
5256
5257         dinfo = domain_jit_info (domain);
5258         if (dinfo->llvm_module)
5259                 return;
5260
5261         mono_loader_lock ();
5262
5263         if (dinfo->llvm_module) {
5264                 mono_loader_unlock ();
5265                 return;
5266         }
5267
5268         module = g_new0 (MonoLLVMModule, 1);
5269
5270         name = g_strdup_printf ("mono-%s", domain->friendly_name);
5271         module->module = LLVMModuleCreateWithName (name);
5272
5273         module->mono_ee = mono_llvm_create_ee (LLVMCreateModuleProviderForExistingModule (module->module), alloc_cb, emitted_cb, exception_cb, dlsym_cb, &module->ee);
5274
5275         add_intrinsics (module->module);
5276         add_types (module);
5277
5278         module->llvm_types = g_hash_table_new (NULL, NULL);
5279
5280         info = mono_find_jit_icall_by_name ("llvm_resume_unwind_trampoline");
5281         g_assert (info);
5282         LLVMAddGlobalMapping (module->ee, LLVMGetNamedFunction (module->module, "llvm_resume_unwind_trampoline"), (void*)info->func);
5283
5284         mono_memory_barrier ();
5285
5286         dinfo->llvm_module = module;
5287
5288         mono_loader_unlock ();
5289 }
5290
5291 void
5292 mono_llvm_cleanup (void)
5293 {
5294         if (aot_module.module)
5295                 LLVMDisposeModule (aot_module.module);
5296
5297         LLVMContextDispose (LLVMGetGlobalContext ());
5298 }
5299
5300 void
5301 mono_llvm_free_domain_info (MonoDomain *domain)
5302 {
5303         MonoJitDomainInfo *info = domain_jit_info (domain);
5304         MonoLLVMModule *module = info->llvm_module;
5305         int i;
5306
5307         if (!module)
5308                 return;
5309
5310         if (module->llvm_types)
5311                 g_hash_table_destroy (module->llvm_types);
5312
5313         mono_llvm_dispose_ee (module->mono_ee);
5314
5315         if (module->bb_names) {
5316                 for (i = 0; i < module->bb_names_len; ++i)
5317                         g_free (module->bb_names [i]);
5318                 g_free (module->bb_names);
5319         }
5320         //LLVMDisposeModule (module->module);
5321
5322         g_free (module);
5323
5324         info->llvm_module = NULL;
5325 }
5326
5327 void
5328 mono_llvm_create_aot_module (const char *got_symbol)
5329 {
5330         /* Delete previous module */
5331         if (aot_module.plt_entries)
5332                 g_hash_table_destroy (aot_module.plt_entries);
5333         if (aot_module.module)
5334                 LLVMDisposeModule (aot_module.module);
5335
5336         memset (&aot_module, 0, sizeof (aot_module));
5337
5338         aot_module.module = LLVMModuleCreateWithName ("aot");
5339         aot_module.got_symbol = got_symbol;
5340
5341         add_intrinsics (aot_module.module);
5342         add_types (&aot_module);
5343
5344         /* Add GOT */
5345         /*
5346          * We couldn't compute the type of the LLVM global representing the got because
5347          * its size is only known after all the methods have been emitted. So create
5348          * a dummy variable, and replace all uses it with the real got variable when
5349          * its size is known in mono_llvm_emit_aot_module ().
5350          */
5351         {
5352                 LLVMTypeRef got_type = LLVMArrayType (aot_module.ptr_type, 0);
5353
5354                 aot_module.got_var = LLVMAddGlobal (aot_module.module, got_type, "mono_dummy_got");
5355                 LLVMSetInitializer (aot_module.got_var, LLVMConstNull (got_type));
5356         }
5357
5358         /* Add a dummy personality function */
5359         {
5360                 LLVMBasicBlockRef lbb;
5361                 LLVMBuilderRef lbuilder;
5362                 LLVMValueRef personality;
5363
5364                 personality = LLVMAddFunction (aot_module.module, "mono_aot_personality", LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE));
5365                 LLVMSetLinkage (personality, LLVMInternalLinkage);
5366                 lbb = LLVMAppendBasicBlock (personality, "BB0");
5367                 lbuilder = LLVMCreateBuilder ();
5368                 LLVMPositionBuilderAtEnd (lbuilder, lbb);
5369                 LLVMBuildRetVoid (lbuilder);
5370         }
5371
5372         aot_module.llvm_types = g_hash_table_new (NULL, NULL);
5373         aot_module.plt_entries = g_hash_table_new (g_str_hash, g_str_equal);
5374         aot_module.plt_entries_ji = g_hash_table_new (NULL, NULL);
5375         aot_module.method_to_lmethod = g_hash_table_new (NULL, NULL);
5376 }
5377
5378 /*
5379  * Emit the aot module into the LLVM bitcode file FILENAME.
5380  */
5381 void
5382 mono_llvm_emit_aot_module (const char *filename, const char *cu_name, int got_size)
5383 {
5384         LLVMTypeRef got_type;
5385         LLVMValueRef real_got;
5386         MonoLLVMModule *module = &aot_module;
5387
5388         /* 
5389          * Create the real got variable and replace all uses of the dummy variable with
5390          * the real one.
5391          */
5392         got_type = LLVMArrayType (aot_module.ptr_type, got_size);
5393         real_got = LLVMAddGlobal (aot_module.module, got_type, aot_module.got_symbol);
5394         LLVMSetInitializer (real_got, LLVMConstNull (got_type));
5395         LLVMSetLinkage (real_got, LLVMInternalLinkage);
5396
5397         mono_llvm_replace_uses_of (aot_module.got_var, real_got);
5398
5399         mark_as_used (&aot_module, real_got);
5400
5401         /* Delete the dummy got so it doesn't become a global */
5402         LLVMDeleteGlobal (aot_module.got_var);
5403
5404         emit_llvm_used (&aot_module);
5405         emit_dbg_info (&aot_module, filename, cu_name);
5406
5407         /* Replace PLT entries for directly callable methods with the methods themselves */
5408         {
5409                 GHashTableIter iter;
5410                 MonoJumpInfo *ji;
5411                 LLVMValueRef callee;
5412
5413                 g_hash_table_iter_init (&iter, aot_module.plt_entries_ji);
5414                 while (g_hash_table_iter_next (&iter, (void**)&ji, (void**)&callee)) {
5415                         if (mono_aot_is_direct_callable (ji)) {
5416                                 LLVMValueRef lmethod;
5417
5418                                 lmethod = g_hash_table_lookup (module->method_to_lmethod, ji->data.method);
5419                                 /* The types might not match because the caller might pass an rgctx */
5420                                 if (lmethod && LLVMTypeOf (callee) == LLVMTypeOf (lmethod)) {
5421                                         mono_llvm_replace_uses_of (callee, lmethod);
5422                                         mono_aot_mark_unused_llvm_plt_entry (ji);
5423                                 }
5424                         }
5425                 }
5426         }
5427
5428 #if 0
5429         {
5430                 char *verifier_err;
5431
5432                 if (LLVMVerifyModule (aot_module.module, LLVMReturnStatusAction, &verifier_err)) {
5433                         g_assert_not_reached ();
5434                 }
5435         }
5436 #endif
5437
5438         LLVMWriteBitcodeToFile (aot_module.module, filename);
5439 }
5440
5441
5442 static LLVMValueRef
5443 md_string (const char *s)
5444 {
5445         return LLVMMDString (s, strlen (s));
5446 }
5447
5448 /* Debugging support */
5449
5450 static void
5451 emit_dbg_info (MonoLLVMModule *lmodule, const char *filename, const char *cu_name)
5452 {
5453         LLVMModuleRef module = lmodule->module;
5454         LLVMValueRef args [16], cu_args [16], cu, ver;
5455         int n_cuargs;
5456         char *build_info, *s, *dir;
5457
5458         //
5459         // FIXME: This cannot be enabled, since the AOT compiler also emits dwarf info,
5460         // and the abbrev indexes will not be correct since llvm has added its own
5461         // abbrevs.
5462         //
5463         return;
5464
5465         /*
5466          * Emit dwarf info in the form of LLVM metadata. There is some
5467          * out-of-date documentation at:
5468          * http://llvm.org/docs/SourceLevelDebugging.html
5469          * but most of this was gathered from the llvm and
5470          * clang sources.
5471          */
5472
5473         n_cuargs = 0;
5474         cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), DW_TAG_compile_unit, FALSE);
5475         /* CU name/compilation dir */
5476         dir = g_path_get_dirname (filename);
5477         args [0] = LLVMMDString (cu_name, strlen (cu_name));
5478         args [1] = LLVMMDString (dir, strlen (dir));
5479         cu_args [n_cuargs ++] = LLVMMDNode (args, 2);
5480         g_free (dir);
5481         /* Language */
5482         cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), DW_LANG_C99, FALSE);
5483         /* Producer */
5484         build_info = mono_get_runtime_build_info ();
5485         s = g_strdup_printf ("Mono AOT Compiler %s (LLVM)", build_info);
5486         cu_args [n_cuargs ++] = LLVMMDString (s, strlen (s));
5487         g_free (build_info);
5488         /* Optimized */
5489         cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5490         /* Flags */
5491         cu_args [n_cuargs ++] = LLVMMDString ("", strlen (""));
5492         /* Runtime version */
5493         cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5494         /* Enums */
5495         cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5496         cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5497         /* Subprograms */
5498         if (lmodule->subprogram_mds) {
5499                 LLVMValueRef *mds;
5500                 int i;
5501
5502                 mds = g_new0 (LLVMValueRef, lmodule->subprogram_mds->len);
5503                 for (i = 0; i < lmodule->subprogram_mds->len; ++i)
5504                         mds [i] = g_ptr_array_index (lmodule->subprogram_mds, i);
5505                 cu_args [n_cuargs ++] = LLVMMDNode (mds, lmodule->subprogram_mds->len);
5506         } else {
5507                 cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5508         }
5509         /* GVs */
5510         cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5511         /* Imported modules */
5512         cu_args [n_cuargs ++] = LLVMMDNode (args, 0);
5513         /* SplitName */
5514         cu_args [n_cuargs ++] = LLVMMDString ("", strlen (""));
5515         /* DebugEmissionKind = FullDebug */
5516         cu_args [n_cuargs ++] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5517         cu = LLVMMDNode (cu_args, n_cuargs);
5518         LLVMAddNamedMetadataOperand (module, "llvm.dbg.cu", cu);
5519
5520         args [0] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5521         args [1] = LLVMMDString ("Dwarf Version", strlen ("Dwarf Version"));
5522         args [2] = LLVMConstInt (LLVMInt32Type (), 2, FALSE);
5523         ver = LLVMMDNode (args, 3);
5524         LLVMAddNamedMetadataOperand (module, "llvm.module.flags", ver);
5525
5526         args [0] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5527         args [1] = LLVMMDString ("Debug Info Version", strlen ("Debug Info Version"));
5528         args [2] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5529         ver = LLVMMDNode (args, 3);
5530         LLVMAddNamedMetadataOperand (module, "llvm.module.flags", ver);
5531 }
5532
5533 static LLVMValueRef
5534 emit_dbg_subprogram (EmitContext *ctx, MonoCompile *cfg, LLVMValueRef method, const char *name)
5535 {
5536         MonoLLVMModule *module = ctx->lmodule;
5537         MonoDebugMethodInfo *minfo = ctx->minfo;
5538         char *source_file, *dir, *filename;
5539         LLVMValueRef md, args [16], ctx_args [16], md_args [64], type_args [16], ctx_md, type_md;
5540         int n_il_offsets;
5541         int *il_offsets;
5542         int *line_numbers;
5543
5544         if (!minfo)
5545                 return NULL;
5546
5547         mono_debug_symfile_get_line_numbers_full (minfo, &source_file, NULL, &n_il_offsets, &il_offsets, &line_numbers, NULL, NULL, NULL, NULL);
5548         if (!source_file)
5549                 source_file = g_strdup ("<unknown>");
5550         dir = g_path_get_dirname (source_file);
5551         filename = g_path_get_basename (source_file);
5552
5553         ctx_args [0] = LLVMConstInt (LLVMInt32Type (), 0x29, FALSE);
5554         args [0] = md_string (filename);
5555         args [1] = md_string (dir);
5556         ctx_args [1] = LLVMMDNode (args, 2);
5557         ctx_md = LLVMMDNode (ctx_args, 2);
5558
5559         type_args [0] = LLVMConstInt (LLVMInt32Type (), DW_TAG_subroutine_type, FALSE);
5560         type_args [1] = NULL;
5561         type_args [2] = NULL;
5562         type_args [3] = LLVMMDString ("", 0);
5563         type_args [4] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5564         type_args [5] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5565         type_args [6] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5566         type_args [7] = LLVMConstInt (LLVMInt64Type (), 0, FALSE);
5567         type_args [8] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5568         type_args [9] = NULL;
5569         type_args [10] = NULL;
5570         type_args [11] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5571         type_args [12] = NULL;
5572         type_args [13] = NULL;
5573         type_args [14] = NULL;
5574         type_md = LLVMMDNode (type_args, 14);
5575
5576         /* http://llvm.org/docs/SourceLevelDebugging.html#subprogram-descriptors */
5577         md_args [0] = LLVMConstInt (LLVMInt32Type (), DW_TAG_subprogram, FALSE);
5578         /* Source directory + file pair */
5579         args [0] = md_string (filename);
5580         args [1] = md_string (dir);
5581         md_args [1] = LLVMMDNode (args ,2);
5582         md_args [2] = ctx_md;
5583         md_args [3] = md_string (cfg->method->name);
5584         md_args [4] = md_string (name);
5585         md_args [5] = md_string (name);
5586         /* Line number */
5587         if (n_il_offsets)
5588                 md_args [6] = LLVMConstInt (LLVMInt32Type (), line_numbers [0], FALSE);
5589         else
5590                 md_args [6] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5591         /* Type */
5592         md_args [7] = type_md;
5593         /* static */
5594         md_args [8] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
5595         /* not extern */
5596         md_args [9] = LLVMConstInt (LLVMInt1Type (), 1, FALSE);
5597         /* Virtuality */
5598         md_args [10] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
5599         /* Index into a virtual function */
5600         md_args [11] = NULL;
5601         md_args [12] = NULL;
5602         /* Flags */
5603         md_args [13] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
5604         /* isOptimized */
5605         md_args [14] = LLVMConstInt (LLVMInt1Type (), 1, FALSE);
5606         /* Pointer to LLVM function */
5607         md_args [15] = method;
5608         /* Function template parameter */
5609         md_args [16] = NULL;
5610         /* Function declaration descriptor */
5611         md_args [17] = NULL;
5612         /* List of function variables */
5613         md_args [18] = LLVMMDNode (args, 0);
5614         /* Line number */
5615         md_args [19] = LLVMConstInt (LLVMInt32Type (), 1, FALSE);
5616         md = LLVMMDNode (md_args, 20);
5617
5618         if (!module->subprogram_mds)
5619                 module->subprogram_mds = g_ptr_array_new ();
5620         g_ptr_array_add (module->subprogram_mds, md);
5621
5622         g_free (dir);
5623         g_free (filename);
5624         g_free (source_file);
5625         g_free (il_offsets);
5626         g_free (line_numbers);
5627
5628         return md;
5629 }
5630
5631 static void
5632 emit_dbg_loc (EmitContext *ctx, LLVMBuilderRef builder, const unsigned char *cil_code)
5633 {
5634         MonoCompile *cfg = ctx->cfg;
5635
5636         if (ctx->minfo && cil_code && cil_code >= cfg->header->code && cil_code < cfg->header->code + cfg->header->code_size) {
5637                 MonoDebugSourceLocation *loc;
5638                 LLVMValueRef loc_md, md_args [16];
5639                 int nmd_args;
5640
5641                 loc = mono_debug_symfile_lookup_location (ctx->minfo, cil_code - cfg->header->code);
5642
5643                 if (loc) {
5644                         nmd_args = 0;
5645                         md_args [nmd_args ++] = LLVMConstInt (LLVMInt32Type (), loc->row, FALSE);
5646                         md_args [nmd_args ++] = LLVMConstInt (LLVMInt32Type (), loc->column, FALSE);
5647                         md_args [nmd_args ++] = ctx->dbg_md;
5648                         md_args [nmd_args ++] = NULL;
5649                         loc_md = LLVMMDNode (md_args, nmd_args);
5650                         LLVMSetCurrentDebugLocation (builder, loc_md);
5651                         mono_debug_symfile_free_location (loc);
5652                 }
5653         }
5654 }
5655
5656 /*
5657   DESIGN:
5658   - Emit LLVM IR from the mono IR using the LLVM C API.
5659   - The original arch specific code remains, so we can fall back to it if we run
5660     into something we can't handle.
5661 */
5662
5663 /*  
5664   A partial list of issues:
5665   - Handling of opcodes which can throw exceptions.
5666
5667       In the mono JIT, these are implemented using code like this:
5668           method:
5669       <compare>
5670           throw_pos:
5671           b<cond> ex_label
5672           <rest of code>
5673       ex_label:
5674           push throw_pos - method
5675           call <exception trampoline>
5676
5677           The problematic part is push throw_pos - method, which cannot be represented
5678       in the LLVM IR, since it does not support label values.
5679           -> this can be implemented in AOT mode using inline asm + labels, but cannot
5680           be implemented in JIT mode ?
5681           -> a possible but slower implementation would use the normal exception 
5682       throwing code but it would need to control the placement of the throw code
5683       (it needs to be exactly after the compare+branch).
5684           -> perhaps add a PC offset intrinsics ?
5685
5686   - efficient implementation of .ovf opcodes.
5687
5688           These are currently implemented as:
5689           <ins which sets the condition codes>
5690           b<cond> ex_label
5691
5692           Some overflow opcodes are now supported by LLVM SVN.
5693
5694   - exception handling, unwinding.
5695     - SSA is disabled for methods with exception handlers    
5696         - How to obtain unwind info for LLVM compiled methods ?
5697           -> this is now solved by converting the unwind info generated by LLVM
5698              into our format.
5699         - LLVM uses the c++ exception handling framework, while we use our home grown
5700       code, and couldn't use the c++ one:
5701       - its not supported under VC++, other exotic platforms.
5702           - it might be impossible to support filter clauses with it.
5703
5704   - trampolines.
5705   
5706     The trampolines need a predictable call sequence, since they need to disasm
5707     the calling code to obtain register numbers / offsets.
5708
5709     LLVM currently generates this code in non-JIT mode:
5710            mov    -0x98(%rax),%eax
5711            callq  *%rax
5712     Here, the vtable pointer is lost. 
5713     -> solution: use one vtable trampoline per class.
5714
5715   - passing/receiving the IMT pointer/RGCTX.
5716     -> solution: pass them as normal arguments ?
5717
5718   - argument passing.
5719   
5720           LLVM does not allow the specification of argument registers etc. This means
5721       that all calls are made according to the platform ABI.
5722
5723   - passing/receiving vtypes.
5724
5725       Vtypes passed/received in registers are handled by the front end by using
5726           a signature with scalar arguments, and loading the parts of the vtype into those
5727           arguments.
5728
5729           Vtypes passed on the stack are handled using the 'byval' attribute.
5730
5731   - ldaddr.
5732
5733     Supported though alloca, we need to emit the load/store code.
5734
5735   - types.
5736
5737     The mono JIT uses pointer sized iregs/double fregs, while LLVM uses precisely
5738     typed registers, so we have to keep track of the precise LLVM type of each vreg.
5739     This is made easier because the IR is already in SSA form.
5740     An additional problem is that our IR is not consistent with types, i.e. i32/ia64 
5741         types are frequently used incorrectly.
5742 */
5743
5744 /*
5745   AOT SUPPORT:
5746   Emit LLVM bytecode into a .bc file, compile it using llc into a .s file, then 
5747   append the AOT data structures to that file. For methods which cannot be
5748   handled by LLVM, the normal JIT compiled versions are used.
5749 */
5750
5751 /* FIXME: Normalize some aspects of the mono IR to allow easier translation, like:
5752  *   - each bblock should end with a branch
5753  *   - setting the return value, making cfg->ret non-volatile
5754  * - avoid some transformations in the JIT which make it harder for us to generate
5755  *   code.
5756  * - use pointer types to help optimizations.
5757  */