]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/builder.rs
Rollup merge of #60895 - chandde:master, r=alexcrichton
[rust.git] / src / librustc_codegen_llvm / builder.rs
1 use crate::llvm::{AtomicRmwBinOp, AtomicOrdering, SynchronizationScope};
2 use crate::llvm::{self, False, BasicBlock};
3 use crate::common::Funclet;
4 use crate::context::CodegenCx;
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::value::Value;
8 use syntax::symbol::LocalInternedString;
9 use rustc_codegen_ssa::common::{IntPredicate, TypeKind, RealPredicate};
10 use rustc_codegen_ssa::MemFlags;
11 use libc::{c_uint, c_char};
12 use rustc::ty::{self, Ty, TyCtxt};
13 use rustc::ty::layout::{self, Align, Size, TyLayout};
14 use rustc::hir::def_id::DefId;
15 use rustc::session::config;
16 use rustc_data_structures::small_c_str::SmallCStr;
17 use rustc_codegen_ssa::traits::*;
18 use rustc_codegen_ssa::base::to_immediate;
19 use rustc_codegen_ssa::mir::operand::{OperandValue, OperandRef};
20 use rustc_codegen_ssa::mir::place::PlaceRef;
21 use rustc_target::spec::{HasTargetSpec, Target};
22 use std::borrow::Cow;
23 use std::ops::{Deref, Range};
24 use std::ptr;
25 use std::iter::TrustedLen;
26
27 // All Builders must have an llfn associated with them
28 #[must_use]
29 pub struct Builder<'a, 'll: 'a, 'tcx: 'll> {
30     pub llbuilder: &'ll mut llvm::Builder<'ll>,
31     pub cx: &'a CodegenCx<'ll, 'tcx>,
32 }
33
34 impl Drop for Builder<'a, 'll, 'tcx> {
35     fn drop(&mut self) {
36         unsafe {
37             llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
38         }
39     }
40 }
41
42 // This is a really awful way to get a zero-length c-string, but better (and a
43 // lot more efficient) than doing str::as_c_str("", ...) every time.
44 fn noname() -> *const c_char {
45     static CNULL: c_char = 0;
46     &CNULL
47 }
48
49 impl BackendTypes for Builder<'_, 'll, 'tcx> {
50     type Value = <CodegenCx<'ll, 'tcx> as BackendTypes>::Value;
51     type BasicBlock = <CodegenCx<'ll, 'tcx> as BackendTypes>::BasicBlock;
52     type Type = <CodegenCx<'ll, 'tcx> as BackendTypes>::Type;
53     type Funclet = <CodegenCx<'ll, 'tcx> as BackendTypes>::Funclet;
54
55     type DIScope = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIScope;
56 }
57
58 impl ty::layout::HasDataLayout for Builder<'_, '_, '_> {
59     fn data_layout(&self) -> &ty::layout::TargetDataLayout {
60         self.cx.data_layout()
61     }
62 }
63
64 impl ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
65     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
66         self.cx.tcx
67     }
68 }
69
70 impl ty::layout::HasParamEnv<'tcx> for Builder<'_, '_, 'tcx> {
71     fn param_env(&self) -> ty::ParamEnv<'tcx> {
72         self.cx.param_env()
73     }
74 }
75
76 impl HasTargetSpec for Builder<'_, '_, 'tcx> {
77     fn target_spec(&self) -> &Target {
78         &self.cx.target_spec()
79     }
80 }
81
82 impl ty::layout::LayoutOf for Builder<'_, '_, 'tcx> {
83     type Ty = Ty<'tcx>;
84     type TyLayout = TyLayout<'tcx>;
85
86     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
87         self.cx.layout_of(ty)
88     }
89 }
90
91 impl Deref for Builder<'_, 'll, 'tcx> {
92     type Target = CodegenCx<'ll, 'tcx>;
93
94     fn deref(&self) -> &Self::Target {
95         self.cx
96     }
97 }
98
99 impl HasCodegen<'tcx> for Builder<'_, 'll, 'tcx> {
100     type CodegenCx = CodegenCx<'ll, 'tcx>;
101 }
102
103 impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
104     fn new_block<'b>(
105         cx: &'a CodegenCx<'ll, 'tcx>,
106         llfn: &'ll Value,
107         name: &'b str
108     ) -> Self {
109         let mut bx = Builder::with_cx(cx);
110         let llbb = unsafe {
111             let name = SmallCStr::new(name);
112             llvm::LLVMAppendBasicBlockInContext(
113                 cx.llcx,
114                 llfn,
115                 name.as_ptr()
116             )
117         };
118         bx.position_at_end(llbb);
119         bx
120     }
121
122     fn with_cx(cx: &'a CodegenCx<'ll, 'tcx>) -> Self {
123         // Create a fresh builder from the crate context.
124         let llbuilder = unsafe {
125             llvm::LLVMCreateBuilderInContext(cx.llcx)
126         };
127         Builder {
128             llbuilder,
129             cx,
130         }
131     }
132
133     fn build_sibling_block<'b>(&self, name: &'b str) -> Self {
134         Builder::new_block(self.cx, self.llfn(), name)
135     }
136
137     fn llbb(&self) -> &'ll BasicBlock {
138         unsafe {
139             llvm::LLVMGetInsertBlock(self.llbuilder)
140         }
141     }
142
143     fn position_at_end(&mut self, llbb: &'ll BasicBlock) {
144         unsafe {
145             llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
146         }
147     }
148
149     fn ret_void(&mut self) {
150         self.count_insn("retvoid");
151         unsafe {
152             llvm::LLVMBuildRetVoid(self.llbuilder);
153         }
154     }
155
156     fn ret(&mut self, v: &'ll Value) {
157         self.count_insn("ret");
158         unsafe {
159             llvm::LLVMBuildRet(self.llbuilder, v);
160         }
161     }
162
163     fn br(&mut self, dest: &'ll BasicBlock) {
164         self.count_insn("br");
165         unsafe {
166             llvm::LLVMBuildBr(self.llbuilder, dest);
167         }
168     }
169
170     fn cond_br(
171         &mut self,
172         cond: &'ll Value,
173         then_llbb: &'ll BasicBlock,
174         else_llbb: &'ll BasicBlock,
175     ) {
176         self.count_insn("condbr");
177         unsafe {
178             llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
179         }
180     }
181
182     fn switch(
183         &mut self,
184         v: &'ll Value,
185         else_llbb: &'ll BasicBlock,
186         cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)> + TrustedLen,
187     ) {
188         let switch = unsafe {
189             llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint)
190         };
191         for (on_val, dest) in cases {
192             let on_val = self.const_uint_big(self.val_ty(v), on_val);
193             unsafe {
194                 llvm::LLVMAddCase(switch, on_val, dest)
195             }
196         }
197     }
198
199     fn invoke(
200         &mut self,
201         llfn: &'ll Value,
202         args: &[&'ll Value],
203         then: &'ll BasicBlock,
204         catch: &'ll BasicBlock,
205         funclet: Option<&Funclet<'ll>>,
206     ) -> &'ll Value {
207         self.count_insn("invoke");
208
209         debug!("Invoke {:?} with args ({:?})",
210                llfn,
211                args);
212
213         let args = self.check_call("invoke", llfn, args);
214         let bundle = funclet.map(|funclet| funclet.bundle());
215         let bundle = bundle.as_ref().map(|b| &*b.raw);
216
217         unsafe {
218             llvm::LLVMRustBuildInvoke(self.llbuilder,
219                                       llfn,
220                                       args.as_ptr(),
221                                       args.len() as c_uint,
222                                       then,
223                                       catch,
224                                       bundle,
225                                       noname())
226         }
227     }
228
229     fn unreachable(&mut self) {
230         self.count_insn("unreachable");
231         unsafe {
232             llvm::LLVMBuildUnreachable(self.llbuilder);
233         }
234     }
235
236     /* Arithmetic */
237     fn add(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
238         self.count_insn("add");
239         unsafe {
240             llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
241         }
242     }
243
244     fn fadd(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
245         self.count_insn("fadd");
246         unsafe {
247             llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
248         }
249     }
250
251     fn fadd_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
252         self.count_insn("fadd");
253         unsafe {
254             let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname());
255             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
256             instr
257         }
258     }
259
260     fn sub(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
261         self.count_insn("sub");
262         unsafe {
263             llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
264         }
265     }
266
267     fn fsub(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
268         self.count_insn("fsub");
269         unsafe {
270             llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
271         }
272     }
273
274     fn fsub_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
275         self.count_insn("fsub");
276         unsafe {
277             let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname());
278             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
279             instr
280         }
281     }
282
283     fn mul(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
284         self.count_insn("mul");
285         unsafe {
286             llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
287         }
288     }
289
290     fn fmul(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
291         self.count_insn("fmul");
292         unsafe {
293             llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
294         }
295     }
296
297     fn fmul_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
298         self.count_insn("fmul");
299         unsafe {
300             let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname());
301             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
302             instr
303         }
304     }
305
306
307     fn udiv(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
308         self.count_insn("udiv");
309         unsafe {
310             llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
311         }
312     }
313
314     fn exactudiv(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
315         self.count_insn("exactudiv");
316         unsafe {
317             llvm::LLVMBuildExactUDiv(self.llbuilder, lhs, rhs, noname())
318         }
319     }
320
321     fn sdiv(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
322         self.count_insn("sdiv");
323         unsafe {
324             llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
325         }
326     }
327
328     fn exactsdiv(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
329         self.count_insn("exactsdiv");
330         unsafe {
331             llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
332         }
333     }
334
335     fn fdiv(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
336         self.count_insn("fdiv");
337         unsafe {
338             llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
339         }
340     }
341
342     fn fdiv_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
343         self.count_insn("fdiv");
344         unsafe {
345             let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname());
346             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
347             instr
348         }
349     }
350
351     fn urem(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
352         self.count_insn("urem");
353         unsafe {
354             llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
355         }
356     }
357
358     fn srem(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
359         self.count_insn("srem");
360         unsafe {
361             llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
362         }
363     }
364
365     fn frem(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
366         self.count_insn("frem");
367         unsafe {
368             llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
369         }
370     }
371
372     fn frem_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
373         self.count_insn("frem");
374         unsafe {
375             let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname());
376             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
377             instr
378         }
379     }
380
381     fn shl(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
382         self.count_insn("shl");
383         unsafe {
384             llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
385         }
386     }
387
388     fn lshr(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
389         self.count_insn("lshr");
390         unsafe {
391             llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
392         }
393     }
394
395     fn ashr(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
396         self.count_insn("ashr");
397         unsafe {
398             llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
399         }
400     }
401
402     fn and(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
403         self.count_insn("and");
404         unsafe {
405             llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
406         }
407     }
408
409     fn or(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
410         self.count_insn("or");
411         unsafe {
412             llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
413         }
414     }
415
416     fn xor(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
417         self.count_insn("xor");
418         unsafe {
419             llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
420         }
421     }
422
423     fn neg(&mut self, v: &'ll Value) -> &'ll Value {
424         self.count_insn("neg");
425         unsafe {
426             llvm::LLVMBuildNeg(self.llbuilder, v, noname())
427         }
428     }
429
430     fn fneg(&mut self, v: &'ll Value) -> &'ll Value {
431         self.count_insn("fneg");
432         unsafe {
433             llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
434         }
435     }
436
437     fn not(&mut self, v: &'ll Value) -> &'ll Value {
438         self.count_insn("not");
439         unsafe {
440             llvm::LLVMBuildNot(self.llbuilder, v, noname())
441         }
442     }
443
444     fn checked_binop(
445         &mut self,
446         oop: OverflowOp,
447         ty: Ty<'_>,
448         lhs: Self::Value,
449         rhs: Self::Value,
450     ) -> (Self::Value, Self::Value) {
451         use syntax::ast::IntTy::*;
452         use syntax::ast::UintTy::*;
453         use rustc::ty::{Int, Uint};
454
455         let new_sty = match ty.sty {
456             Int(Isize) => Int(self.tcx.sess.target.isize_ty),
457             Uint(Usize) => Uint(self.tcx.sess.target.usize_ty),
458             ref t @ Uint(_) | ref t @ Int(_) => t.clone(),
459             _ => panic!("tried to get overflow intrinsic for op applied to non-int type")
460         };
461
462         let name = match oop {
463             OverflowOp::Add => match new_sty {
464                 Int(I8) => "llvm.sadd.with.overflow.i8",
465                 Int(I16) => "llvm.sadd.with.overflow.i16",
466                 Int(I32) => "llvm.sadd.with.overflow.i32",
467                 Int(I64) => "llvm.sadd.with.overflow.i64",
468                 Int(I128) => "llvm.sadd.with.overflow.i128",
469
470                 Uint(U8) => "llvm.uadd.with.overflow.i8",
471                 Uint(U16) => "llvm.uadd.with.overflow.i16",
472                 Uint(U32) => "llvm.uadd.with.overflow.i32",
473                 Uint(U64) => "llvm.uadd.with.overflow.i64",
474                 Uint(U128) => "llvm.uadd.with.overflow.i128",
475
476                 _ => unreachable!(),
477             },
478             OverflowOp::Sub => match new_sty {
479                 Int(I8) => "llvm.ssub.with.overflow.i8",
480                 Int(I16) => "llvm.ssub.with.overflow.i16",
481                 Int(I32) => "llvm.ssub.with.overflow.i32",
482                 Int(I64) => "llvm.ssub.with.overflow.i64",
483                 Int(I128) => "llvm.ssub.with.overflow.i128",
484
485                 Uint(U8) => "llvm.usub.with.overflow.i8",
486                 Uint(U16) => "llvm.usub.with.overflow.i16",
487                 Uint(U32) => "llvm.usub.with.overflow.i32",
488                 Uint(U64) => "llvm.usub.with.overflow.i64",
489                 Uint(U128) => "llvm.usub.with.overflow.i128",
490
491                 _ => unreachable!(),
492             },
493             OverflowOp::Mul => match new_sty {
494                 Int(I8) => "llvm.smul.with.overflow.i8",
495                 Int(I16) => "llvm.smul.with.overflow.i16",
496                 Int(I32) => "llvm.smul.with.overflow.i32",
497                 Int(I64) => "llvm.smul.with.overflow.i64",
498                 Int(I128) => "llvm.smul.with.overflow.i128",
499
500                 Uint(U8) => "llvm.umul.with.overflow.i8",
501                 Uint(U16) => "llvm.umul.with.overflow.i16",
502                 Uint(U32) => "llvm.umul.with.overflow.i32",
503                 Uint(U64) => "llvm.umul.with.overflow.i64",
504                 Uint(U128) => "llvm.umul.with.overflow.i128",
505
506                 _ => unreachable!(),
507             },
508         };
509
510         let intrinsic = self.get_intrinsic(&name);
511         let res = self.call(intrinsic, &[lhs, rhs], None);
512         (
513             self.extract_value(res, 0),
514             self.extract_value(res, 1),
515         )
516     }
517
518     fn alloca(&mut self, ty: &'ll Type, name: &str, align: Align) -> &'ll Value {
519         let mut bx = Builder::with_cx(self.cx);
520         bx.position_at_start(unsafe {
521             llvm::LLVMGetFirstBasicBlock(self.llfn())
522         });
523         bx.dynamic_alloca(ty, name, align)
524     }
525
526     fn dynamic_alloca(&mut self, ty: &'ll Type, name: &str, align: Align) -> &'ll Value {
527         self.count_insn("alloca");
528         unsafe {
529             let alloca = if name.is_empty() {
530                 llvm::LLVMBuildAlloca(self.llbuilder, ty, noname())
531             } else {
532                 let name = SmallCStr::new(name);
533                 llvm::LLVMBuildAlloca(self.llbuilder, ty,
534                                       name.as_ptr())
535             };
536             llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
537             alloca
538         }
539     }
540
541     fn array_alloca(&mut self,
542                         ty: &'ll Type,
543                         len: &'ll Value,
544                         name: &str,
545                         align: Align) -> &'ll Value {
546         self.count_insn("alloca");
547         unsafe {
548             let alloca = if name.is_empty() {
549                 llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len, noname())
550             } else {
551                 let name = SmallCStr::new(name);
552                 llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len,
553                                            name.as_ptr())
554             };
555             llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
556             alloca
557         }
558     }
559
560     fn load(&mut self, ptr: &'ll Value, align: Align) -> &'ll Value {
561         self.count_insn("load");
562         unsafe {
563             let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
564             llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
565             load
566         }
567     }
568
569     fn volatile_load(&mut self, ptr: &'ll Value) -> &'ll Value {
570         self.count_insn("load.volatile");
571         unsafe {
572             let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
573             llvm::LLVMSetVolatile(insn, llvm::True);
574             insn
575         }
576     }
577
578     fn atomic_load(
579         &mut self,
580         ptr: &'ll Value,
581         order: rustc_codegen_ssa::common::AtomicOrdering,
582         size: Size,
583     ) -> &'ll Value {
584         self.count_insn("load.atomic");
585         unsafe {
586             let load = llvm::LLVMRustBuildAtomicLoad(
587                 self.llbuilder,
588                 ptr,
589                 noname(),
590                 AtomicOrdering::from_generic(order),
591             );
592             // LLVM requires the alignment of atomic loads to be at least the size of the type.
593             llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
594             load
595         }
596     }
597
598     fn load_operand(
599         &mut self,
600         place: PlaceRef<'tcx, &'ll Value>
601     ) -> OperandRef<'tcx, &'ll Value> {
602         debug!("PlaceRef::load: {:?}", place);
603
604         assert_eq!(place.llextra.is_some(), place.layout.is_unsized());
605
606         if place.layout.is_zst() {
607             return OperandRef::new_zst(self, place.layout);
608         }
609
610         fn scalar_load_metadata<'a, 'll, 'tcx>(
611             bx: &mut Builder<'a, 'll, 'tcx>,
612             load: &'ll Value,
613             scalar: &layout::Scalar
614         ) {
615             let vr = scalar.valid_range.clone();
616             match scalar.value {
617                 layout::Int(..) => {
618                     let range = scalar.valid_range_exclusive(bx);
619                     if range.start != range.end {
620                         bx.range_metadata(load, range);
621                     }
622                 }
623                 layout::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
624                     bx.nonnull_metadata(load);
625                 }
626                 _ => {}
627             }
628         }
629
630         let val = if let Some(llextra) = place.llextra {
631             OperandValue::Ref(place.llval, Some(llextra), place.align)
632         } else if place.layout.is_llvm_immediate() {
633             let mut const_llval = None;
634             unsafe {
635                 if let Some(global) = llvm::LLVMIsAGlobalVariable(place.llval) {
636                     if llvm::LLVMIsGlobalConstant(global) == llvm::True {
637                         const_llval = llvm::LLVMGetInitializer(global);
638                     }
639                 }
640             }
641             let llval = const_llval.unwrap_or_else(|| {
642                 let load = self.load(place.llval, place.align);
643                 if let layout::Abi::Scalar(ref scalar) = place.layout.abi {
644                     scalar_load_metadata(self, load, scalar);
645                 }
646                 load
647             });
648             OperandValue::Immediate(to_immediate(self, llval, place.layout))
649         } else if let layout::Abi::ScalarPair(ref a, ref b) = place.layout.abi {
650             let b_offset = a.value.size(self).align_to(b.value.align(self).abi);
651
652             let mut load = |i, scalar: &layout::Scalar, align| {
653                 let llptr = self.struct_gep(place.llval, i as u64);
654                 let load = self.load(llptr, align);
655                 scalar_load_metadata(self, load, scalar);
656                 if scalar.is_bool() {
657                     self.trunc(load, self.type_i1())
658                 } else {
659                     load
660                 }
661             };
662
663             OperandValue::Pair(
664                 load(0, a, place.align),
665                 load(1, b, place.align.restrict_for_offset(b_offset)),
666             )
667         } else {
668             OperandValue::Ref(place.llval, None, place.align)
669         };
670
671         OperandRef { val, layout: place.layout }
672     }
673
674     fn write_operand_repeatedly(
675         mut self,
676         cg_elem: OperandRef<'tcx, &'ll Value>,
677         count: u64,
678         dest: PlaceRef<'tcx, &'ll Value>,
679     ) -> Self {
680         let zero = self.const_usize(0);
681         let count = self.const_usize(count);
682         let start = dest.project_index(&mut self, zero).llval;
683         let end = dest.project_index(&mut self, count).llval;
684
685         let mut header_bx = self.build_sibling_block("repeat_loop_header");
686         let mut body_bx = self.build_sibling_block("repeat_loop_body");
687         let next_bx = self.build_sibling_block("repeat_loop_next");
688
689         self.br(header_bx.llbb());
690         let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
691
692         let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
693         header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb());
694
695         let align = dest.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
696         cg_elem.val.store(&mut body_bx,
697             PlaceRef::new_sized(current, cg_elem.layout, align));
698
699         let next = body_bx.inbounds_gep(current, &[self.const_usize(1)]);
700         body_bx.br(header_bx.llbb());
701         header_bx.add_incoming_to_phi(current, next, body_bx.llbb());
702
703         next_bx
704     }
705
706     fn range_metadata(&mut self, load: &'ll Value, range: Range<u128>) {
707         if self.sess().target.target.arch == "amdgpu" {
708             // amdgpu/LLVM does something weird and thinks a i64 value is
709             // split into a v2i32, halving the bitwidth LLVM expects,
710             // tripping an assertion. So, for now, just disable this
711             // optimization.
712             return;
713         }
714
715         unsafe {
716             let llty = self.cx.val_ty(load);
717             let v = [
718                 self.cx.const_uint_big(llty, range.start),
719                 self.cx.const_uint_big(llty, range.end)
720             ];
721
722             llvm::LLVMSetMetadata(load, llvm::MD_range as c_uint,
723                                   llvm::LLVMMDNodeInContext(self.cx.llcx,
724                                                             v.as_ptr(),
725                                                             v.len() as c_uint));
726         }
727     }
728
729     fn nonnull_metadata(&mut self, load: &'ll Value) {
730         unsafe {
731             llvm::LLVMSetMetadata(load, llvm::MD_nonnull as c_uint,
732                                   llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
733         }
734     }
735
736     fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
737         self.store_with_flags(val, ptr, align, MemFlags::empty())
738     }
739
740     fn store_with_flags(
741         &mut self,
742         val: &'ll Value,
743         ptr: &'ll Value,
744         align: Align,
745         flags: MemFlags,
746     ) -> &'ll Value {
747         debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
748         self.count_insn("store");
749         let ptr = self.check_store(val, ptr);
750         unsafe {
751             let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
752             let align = if flags.contains(MemFlags::UNALIGNED) {
753                 1
754             } else {
755                 align.bytes() as c_uint
756             };
757             llvm::LLVMSetAlignment(store, align);
758             if flags.contains(MemFlags::VOLATILE) {
759                 llvm::LLVMSetVolatile(store, llvm::True);
760             }
761             if flags.contains(MemFlags::NONTEMPORAL) {
762                 // According to LLVM [1] building a nontemporal store must
763                 // *always* point to a metadata value of the integer 1.
764                 //
765                 // [1]: http://llvm.org/docs/LangRef.html#store-instruction
766                 let one = self.cx.const_i32(1);
767                 let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
768                 llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
769             }
770             store
771         }
772     }
773
774    fn atomic_store(&mut self, val: &'ll Value, ptr: &'ll Value,
775                    order: rustc_codegen_ssa::common::AtomicOrdering, size: Size) {
776         debug!("Store {:?} -> {:?}", val, ptr);
777         self.count_insn("store.atomic");
778         let ptr = self.check_store(val, ptr);
779         unsafe {
780             let store = llvm::LLVMRustBuildAtomicStore(
781                 self.llbuilder,
782                 val,
783                 ptr,
784                 AtomicOrdering::from_generic(order),
785             );
786             // LLVM requires the alignment of atomic stores to be at least the size of the type.
787             llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
788         }
789     }
790
791     fn gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
792         self.count_insn("gep");
793         unsafe {
794             llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
795                                indices.len() as c_uint, noname())
796         }
797     }
798
799     fn inbounds_gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
800         self.count_insn("inboundsgep");
801         unsafe {
802             llvm::LLVMBuildInBoundsGEP(
803                 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
804         }
805     }
806
807     fn struct_gep(&mut self, ptr: &'ll Value, idx: u64) -> &'ll Value {
808         self.count_insn("structgep");
809         assert_eq!(idx as c_uint as u64, idx);
810         unsafe {
811             llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
812         }
813     }
814
815     /* Casts */
816     fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
817         self.count_insn("trunc");
818         unsafe {
819             llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, noname())
820         }
821     }
822
823     fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
824         self.count_insn("sext");
825         unsafe {
826             llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, noname())
827         }
828     }
829
830     fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
831         self.count_insn("fptoui");
832         unsafe {
833             llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, noname())
834         }
835     }
836
837     fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
838         self.count_insn("fptosi");
839         unsafe {
840             llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty,noname())
841         }
842     }
843
844     fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
845         self.count_insn("uitofp");
846         unsafe {
847             llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, noname())
848         }
849     }
850
851     fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
852         self.count_insn("sitofp");
853         unsafe {
854             llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, noname())
855         }
856     }
857
858     fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
859         self.count_insn("fptrunc");
860         unsafe {
861             llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, noname())
862         }
863     }
864
865     fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
866         self.count_insn("fpext");
867         unsafe {
868             llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, noname())
869         }
870     }
871
872     fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
873         self.count_insn("ptrtoint");
874         unsafe {
875             llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, noname())
876         }
877     }
878
879     fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
880         self.count_insn("inttoptr");
881         unsafe {
882             llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, noname())
883         }
884     }
885
886     fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
887         self.count_insn("bitcast");
888         unsafe {
889             llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, noname())
890         }
891     }
892
893
894     fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
895         self.count_insn("intcast");
896         unsafe {
897             llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed)
898         }
899     }
900
901     fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
902         self.count_insn("pointercast");
903         unsafe {
904             llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, noname())
905         }
906     }
907
908     /* Comparisons */
909     fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
910         self.count_insn("icmp");
911         let op = llvm::IntPredicate::from_generic(op);
912         unsafe {
913             llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
914         }
915     }
916
917     fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
918         self.count_insn("fcmp");
919         unsafe {
920             llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
921         }
922     }
923
924     /* Miscellaneous instructions */
925     fn memcpy(&mut self, dst: &'ll Value, dst_align: Align,
926                   src: &'ll Value, src_align: Align,
927                   size: &'ll Value, flags: MemFlags) {
928         if flags.contains(MemFlags::NONTEMPORAL) {
929             // HACK(nox): This is inefficient but there is no nontemporal memcpy.
930             let val = self.load(src, src_align);
931             let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
932             self.store_with_flags(val, ptr, dst_align, flags);
933             return;
934         }
935         let size = self.intcast(size, self.type_isize(), false);
936         let is_volatile = flags.contains(MemFlags::VOLATILE);
937         let dst = self.pointercast(dst, self.type_i8p());
938         let src = self.pointercast(src, self.type_i8p());
939         unsafe {
940             llvm::LLVMRustBuildMemCpy(self.llbuilder, dst, dst_align.bytes() as c_uint,
941                                       src, src_align.bytes() as c_uint, size, is_volatile);
942         }
943     }
944
945     fn memmove(&mut self, dst: &'ll Value, dst_align: Align,
946                   src: &'ll Value, src_align: Align,
947                   size: &'ll Value, flags: MemFlags) {
948         if flags.contains(MemFlags::NONTEMPORAL) {
949             // HACK(nox): This is inefficient but there is no nontemporal memmove.
950             let val = self.load(src, src_align);
951             let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
952             self.store_with_flags(val, ptr, dst_align, flags);
953             return;
954         }
955         let size = self.intcast(size, self.type_isize(), false);
956         let is_volatile = flags.contains(MemFlags::VOLATILE);
957         let dst = self.pointercast(dst, self.type_i8p());
958         let src = self.pointercast(src, self.type_i8p());
959         unsafe {
960             llvm::LLVMRustBuildMemMove(self.llbuilder, dst, dst_align.bytes() as c_uint,
961                                       src, src_align.bytes() as c_uint, size, is_volatile);
962         }
963     }
964
965     fn memset(
966         &mut self,
967         ptr: &'ll Value,
968         fill_byte: &'ll Value,
969         size: &'ll Value,
970         align: Align,
971         flags: MemFlags,
972     ) {
973         let ptr_width = &self.sess().target.target.target_pointer_width;
974         let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
975         let llintrinsicfn = self.get_intrinsic(&intrinsic_key);
976         let ptr = self.pointercast(ptr, self.type_i8p());
977         let align = self.const_u32(align.bytes() as u32);
978         let volatile = self.const_bool(flags.contains(MemFlags::VOLATILE));
979         self.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None);
980     }
981
982     fn select(
983         &mut self, cond: &'ll Value,
984         then_val: &'ll Value,
985         else_val: &'ll Value,
986     ) -> &'ll Value {
987         self.count_insn("select");
988         unsafe {
989             llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
990         }
991     }
992
993     #[allow(dead_code)]
994     fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
995         self.count_insn("vaarg");
996         unsafe {
997             llvm::LLVMBuildVAArg(self.llbuilder, list, ty, noname())
998         }
999     }
1000
1001     fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1002         self.count_insn("extractelement");
1003         unsafe {
1004             llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
1005         }
1006     }
1007
1008     fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1009         unsafe {
1010             let elt_ty = self.cx.val_ty(elt);
1011             let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1012             let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1013             let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1014             self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1015         }
1016     }
1017
1018     fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1019         self.count_insn("extractvalue");
1020         assert_eq!(idx as c_uint as u64, idx);
1021         unsafe {
1022             llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
1023         }
1024     }
1025
1026     fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value,
1027                        idx: u64) -> &'ll Value {
1028         self.count_insn("insertvalue");
1029         assert_eq!(idx as c_uint as u64, idx);
1030         unsafe {
1031             llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
1032                                        noname())
1033         }
1034     }
1035
1036     fn landing_pad(&mut self, ty: &'ll Type, pers_fn: &'ll Value,
1037                        num_clauses: usize) -> &'ll Value {
1038         self.count_insn("landingpad");
1039         unsafe {
1040             llvm::LLVMBuildLandingPad(self.llbuilder, ty, pers_fn,
1041                                       num_clauses as c_uint, noname())
1042         }
1043     }
1044
1045     fn set_cleanup(&mut self, landing_pad: &'ll Value) {
1046         self.count_insn("setcleanup");
1047         unsafe {
1048             llvm::LLVMSetCleanup(landing_pad, llvm::True);
1049         }
1050     }
1051
1052     fn resume(&mut self, exn: &'ll Value) -> &'ll Value {
1053         self.count_insn("resume");
1054         unsafe {
1055             llvm::LLVMBuildResume(self.llbuilder, exn)
1056         }
1057     }
1058
1059     fn cleanup_pad(&mut self,
1060                        parent: Option<&'ll Value>,
1061                        args: &[&'ll Value]) -> Funclet<'ll> {
1062         self.count_insn("cleanuppad");
1063         let name = const_cstr!("cleanuppad");
1064         let ret = unsafe {
1065             llvm::LLVMRustBuildCleanupPad(self.llbuilder,
1066                                           parent,
1067                                           args.len() as c_uint,
1068                                           args.as_ptr(),
1069                                           name.as_ptr())
1070         };
1071         Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1072     }
1073
1074     fn cleanup_ret(
1075         &mut self, funclet: &Funclet<'ll>,
1076         unwind: Option<&'ll BasicBlock>,
1077     ) -> &'ll Value {
1078         self.count_insn("cleanupret");
1079         let ret = unsafe {
1080             llvm::LLVMRustBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1081         };
1082         ret.expect("LLVM does not have support for cleanupret")
1083     }
1084
1085     fn catch_pad(&mut self,
1086                      parent: &'ll Value,
1087                      args: &[&'ll Value]) -> Funclet<'ll> {
1088         self.count_insn("catchpad");
1089         let name = const_cstr!("catchpad");
1090         let ret = unsafe {
1091             llvm::LLVMRustBuildCatchPad(self.llbuilder, parent,
1092                                         args.len() as c_uint, args.as_ptr(),
1093                                         name.as_ptr())
1094         };
1095         Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1096     }
1097
1098     fn catch_switch(
1099         &mut self,
1100         parent: Option<&'ll Value>,
1101         unwind: Option<&'ll BasicBlock>,
1102         num_handlers: usize,
1103     ) -> &'ll Value {
1104         self.count_insn("catchswitch");
1105         let name = const_cstr!("catchswitch");
1106         let ret = unsafe {
1107             llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind,
1108                                            num_handlers as c_uint,
1109                                            name.as_ptr())
1110         };
1111         ret.expect("LLVM does not have support for catchswitch")
1112     }
1113
1114     fn add_handler(&mut self, catch_switch: &'ll Value, handler: &'ll BasicBlock) {
1115         unsafe {
1116             llvm::LLVMRustAddHandler(catch_switch, handler);
1117         }
1118     }
1119
1120     fn set_personality_fn(&mut self, personality: &'ll Value) {
1121         unsafe {
1122             llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1123         }
1124     }
1125
1126     // Atomic Operations
1127     fn atomic_cmpxchg(
1128         &mut self,
1129         dst: &'ll Value,
1130         cmp: &'ll Value,
1131         src: &'ll Value,
1132         order: rustc_codegen_ssa::common::AtomicOrdering,
1133         failure_order: rustc_codegen_ssa::common::AtomicOrdering,
1134         weak: bool,
1135     ) -> &'ll Value {
1136         let weak = if weak { llvm::True } else { llvm::False };
1137         unsafe {
1138             llvm::LLVMRustBuildAtomicCmpXchg(
1139                 self.llbuilder,
1140                 dst,
1141                 cmp,
1142                 src,
1143                 AtomicOrdering::from_generic(order),
1144                 AtomicOrdering::from_generic(failure_order),
1145                 weak
1146             )
1147         }
1148     }
1149     fn atomic_rmw(
1150         &mut self,
1151         op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1152         dst: &'ll Value,
1153         src: &'ll Value,
1154         order: rustc_codegen_ssa::common::AtomicOrdering,
1155     ) -> &'ll Value {
1156         unsafe {
1157             llvm::LLVMBuildAtomicRMW(
1158                 self.llbuilder,
1159                 AtomicRmwBinOp::from_generic(op),
1160                 dst,
1161                 src,
1162                 AtomicOrdering::from_generic(order),
1163                 False)
1164         }
1165     }
1166
1167     fn atomic_fence(
1168         &mut self,
1169         order: rustc_codegen_ssa::common::AtomicOrdering,
1170         scope: rustc_codegen_ssa::common::SynchronizationScope
1171     ) {
1172         unsafe {
1173             llvm::LLVMRustBuildAtomicFence(
1174                 self.llbuilder,
1175                 AtomicOrdering::from_generic(order),
1176                 SynchronizationScope::from_generic(scope)
1177             );
1178         }
1179     }
1180
1181     fn set_invariant_load(&mut self, load: &'ll Value) {
1182         unsafe {
1183             llvm::LLVMSetMetadata(load, llvm::MD_invariant_load as c_uint,
1184                                   llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
1185         }
1186     }
1187
1188     fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1189         self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1190     }
1191
1192     fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1193         self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1194     }
1195
1196     fn call(
1197         &mut self,
1198         llfn: &'ll Value,
1199         args: &[&'ll Value],
1200         funclet: Option<&Funclet<'ll>>,
1201     ) -> &'ll Value {
1202         self.count_insn("call");
1203
1204         debug!("Call {:?} with args ({:?})",
1205                llfn,
1206                args);
1207
1208         let args = self.check_call("call", llfn, args);
1209         let bundle = funclet.map(|funclet| funclet.bundle());
1210         let bundle = bundle.as_ref().map(|b| &*b.raw);
1211
1212         unsafe {
1213             llvm::LLVMRustBuildCall(
1214                 self.llbuilder,
1215                 llfn,
1216                 args.as_ptr() as *const &llvm::Value,
1217                 args.len() as c_uint,
1218                 bundle, noname()
1219             )
1220         }
1221     }
1222
1223     fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1224         self.count_insn("zext");
1225         unsafe {
1226             llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, noname())
1227         }
1228     }
1229
1230
1231     fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
1232         self.cx
1233     }
1234
1235     unsafe fn delete_basic_block(&mut self, bb: &'ll BasicBlock) {
1236         llvm::LLVMDeleteBasicBlock(bb);
1237     }
1238
1239     fn do_not_inline(&mut self, llret: &'ll Value) {
1240         llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
1241     }
1242 }
1243
1244 impl StaticBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
1245 fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1246         // Forward to the `get_static` method of `CodegenCx`
1247         self.cx().get_static(def_id)
1248     }
1249
1250     fn static_panic_msg(
1251         &mut self,
1252         msg: Option<LocalInternedString>,
1253         filename: LocalInternedString,
1254         line: Self::Value,
1255         col: Self::Value,
1256         kind: &str,
1257     ) -> Self::Value {
1258         let align = self.tcx.data_layout.aggregate_align.abi
1259             .max(self.tcx.data_layout.i32_align.abi)
1260             .max(self.tcx.data_layout.pointer_align.abi);
1261
1262         let filename = self.const_str_slice(filename);
1263
1264         let with_msg_components;
1265         let without_msg_components;
1266
1267         let components = if let Some(msg) = msg {
1268             let msg = self.const_str_slice(msg);
1269             with_msg_components = [msg, filename, line, col];
1270             &with_msg_components as &[_]
1271         } else {
1272             without_msg_components = [filename, line, col];
1273             &without_msg_components as &[_]
1274         };
1275
1276         let struct_ = self.const_struct(&components, false);
1277         self.static_addr_of(struct_, align, Some(kind))
1278     }
1279 }
1280
1281 impl Builder<'a, 'll, 'tcx> {
1282     pub fn llfn(&self) -> &'ll Value {
1283         unsafe {
1284             llvm::LLVMGetBasicBlockParent(self.llbb())
1285         }
1286     }
1287
1288     fn count_insn(&self, category: &str) {
1289         if self.sess().codegen_stats() {
1290             self.stats.borrow_mut().n_llvm_insns += 1;
1291         }
1292         if self.sess().count_llvm_insns() {
1293             *self.stats
1294                       .borrow_mut()
1295                       .llvm_insns
1296                       .entry(category.to_string())
1297                       .or_insert(0) += 1;
1298         }
1299     }
1300
1301     fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1302         unsafe {
1303             llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1304         }
1305     }
1306
1307     pub fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1308         self.count_insn("minnum");
1309         unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
1310     }
1311
1312     pub fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1313         self.count_insn("maxnum");
1314         unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
1315     }
1316
1317     pub fn insert_element(
1318         &mut self, vec: &'ll Value,
1319         elt: &'ll Value,
1320         idx: &'ll Value,
1321     ) -> &'ll Value {
1322         self.count_insn("insertelement");
1323         unsafe {
1324             llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
1325         }
1326     }
1327
1328     pub fn shuffle_vector(
1329         &mut self,
1330         v1: &'ll Value,
1331         v2: &'ll Value,
1332         mask: &'ll Value,
1333     ) -> &'ll Value {
1334         self.count_insn("shufflevector");
1335         unsafe {
1336             llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
1337         }
1338     }
1339
1340     pub fn vector_reduce_fadd_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1341         self.count_insn("vector.reduce.fadd_fast");
1342         unsafe {
1343             // FIXME: add a non-fast math version once
1344             // https://bugs.llvm.org/show_bug.cgi?id=36732
1345             // is fixed.
1346             let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1347             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1348             instr
1349         }
1350     }
1351     pub fn vector_reduce_fmul_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1352         self.count_insn("vector.reduce.fmul_fast");
1353         unsafe {
1354             // FIXME: add a non-fast math version once
1355             // https://bugs.llvm.org/show_bug.cgi?id=36732
1356             // is fixed.
1357             let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1358             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1359             instr
1360         }
1361     }
1362     pub fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1363         self.count_insn("vector.reduce.add");
1364         unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
1365     }
1366     pub fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1367         self.count_insn("vector.reduce.mul");
1368         unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
1369     }
1370     pub fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1371         self.count_insn("vector.reduce.and");
1372         unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
1373     }
1374     pub fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1375         self.count_insn("vector.reduce.or");
1376         unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
1377     }
1378     pub fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1379         self.count_insn("vector.reduce.xor");
1380         unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
1381     }
1382     pub fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1383         self.count_insn("vector.reduce.fmin");
1384         unsafe { llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false) }
1385     }
1386     pub fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1387         self.count_insn("vector.reduce.fmax");
1388         unsafe { llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false) }
1389     }
1390     pub fn vector_reduce_fmin_fast(&mut self, src: &'ll Value) -> &'ll Value {
1391         self.count_insn("vector.reduce.fmin_fast");
1392         unsafe {
1393             let instr = llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
1394             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1395             instr
1396         }
1397     }
1398     pub fn vector_reduce_fmax_fast(&mut self, src: &'ll Value) -> &'ll Value {
1399         self.count_insn("vector.reduce.fmax_fast");
1400         unsafe {
1401             let instr = llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
1402             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1403             instr
1404         }
1405     }
1406     pub fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1407         self.count_insn("vector.reduce.min");
1408         unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
1409     }
1410     pub fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1411         self.count_insn("vector.reduce.max");
1412         unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
1413     }
1414
1415     pub fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1416         unsafe {
1417             llvm::LLVMAddClause(landing_pad, clause);
1418         }
1419     }
1420
1421     pub fn catch_ret(&mut self, funclet: &Funclet<'ll>, unwind: &'ll BasicBlock) -> &'ll Value {
1422         self.count_insn("catchret");
1423         let ret = unsafe {
1424             llvm::LLVMRustBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind)
1425         };
1426         ret.expect("LLVM does not have support for catchret")
1427     }
1428
1429     fn check_store<'b>(&mut self,
1430                        val: &'ll Value,
1431                        ptr: &'ll Value) -> &'ll Value {
1432         let dest_ptr_ty = self.cx.val_ty(ptr);
1433         let stored_ty = self.cx.val_ty(val);
1434         let stored_ptr_ty = self.cx.type_ptr_to(stored_ty);
1435
1436         assert_eq!(self.cx.type_kind(dest_ptr_ty), TypeKind::Pointer);
1437
1438         if dest_ptr_ty == stored_ptr_ty {
1439             ptr
1440         } else {
1441             debug!("Type mismatch in store. \
1442                     Expected {:?}, got {:?}; inserting bitcast",
1443                    dest_ptr_ty, stored_ptr_ty);
1444             self.bitcast(ptr, stored_ptr_ty)
1445         }
1446     }
1447
1448     fn check_call<'b>(&mut self,
1449                       typ: &str,
1450                       llfn: &'ll Value,
1451                       args: &'b [&'ll Value]) -> Cow<'b, [&'ll Value]> {
1452         let mut fn_ty = self.cx.val_ty(llfn);
1453         // Strip off pointers
1454         while self.cx.type_kind(fn_ty) == TypeKind::Pointer {
1455             fn_ty = self.cx.element_type(fn_ty);
1456         }
1457
1458         assert!(self.cx.type_kind(fn_ty) == TypeKind::Function,
1459                 "builder::{} not passed a function, but {:?}", typ, fn_ty);
1460
1461         let param_tys = self.cx.func_params_types(fn_ty);
1462
1463         let all_args_match = param_tys.iter()
1464             .zip(args.iter().map(|&v| self.val_ty(v)))
1465             .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1466
1467         if all_args_match {
1468             return Cow::Borrowed(args);
1469         }
1470
1471         let casted_args: Vec<_> = param_tys.into_iter()
1472             .zip(args.iter())
1473             .enumerate()
1474             .map(|(i, (expected_ty, &actual_val))| {
1475                 let actual_ty = self.val_ty(actual_val);
1476                 if expected_ty != actual_ty {
1477                     debug!("Type mismatch in function call of {:?}. \
1478                             Expected {:?} for param {}, got {:?}; injecting bitcast",
1479                            llfn, expected_ty, i, actual_ty);
1480                     self.bitcast(actual_val, expected_ty)
1481                 } else {
1482                     actual_val
1483                 }
1484             })
1485             .collect();
1486
1487         Cow::Owned(casted_args)
1488     }
1489
1490     pub fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1491         self.count_insn("vaarg");
1492         unsafe {
1493             llvm::LLVMBuildVAArg(self.llbuilder, list, ty, noname())
1494         }
1495     }
1496
1497     fn call_lifetime_intrinsic(&mut self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1498         if self.cx.sess().opts.optimize == config::OptLevel::No {
1499             return;
1500         }
1501
1502         let size = size.bytes();
1503         if size == 0 {
1504             return;
1505         }
1506
1507         let lifetime_intrinsic = self.cx.get_intrinsic(intrinsic);
1508
1509         let ptr = self.pointercast(ptr, self.cx.type_i8p());
1510         self.call(lifetime_intrinsic, &[self.cx.const_u64(size), ptr], None);
1511     }
1512
1513     fn phi(&mut self, ty: &'ll Type, vals: &[&'ll Value], bbs: &[&'ll BasicBlock]) -> &'ll Value {
1514         self.count_insn("addincoming");
1515         assert_eq!(vals.len(), bbs.len());
1516         let phi = unsafe {
1517             llvm::LLVMBuildPhi(self.llbuilder, ty, noname())
1518         };
1519         unsafe {
1520             llvm::LLVMAddIncoming(phi, vals.as_ptr(),
1521                                   bbs.as_ptr(),
1522                                   vals.len() as c_uint);
1523             phi
1524         }
1525     }
1526
1527     fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1528         self.count_insn("addincoming");
1529         unsafe {
1530             llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1531         }
1532     }
1533 }