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