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