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