]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/builder.rs
8750b67f78a112b046adec2d762df4a21090a8de
[rust.git] / src / librustc_codegen_llvm / builder.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use llvm::{AtomicRmwBinOp, AtomicOrdering, SynchronizationScope, AsmDialect};
12 use llvm::{IntPredicate, RealPredicate, False, OperandBundleDef};
13 use llvm::{self, BasicBlock};
14 use common::*;
15 use type_::Type;
16 use value::Value;
17 use libc::{c_uint, c_char};
18 use rustc::ty::TyCtxt;
19 use rustc::ty::layout::{Align, Size};
20 use rustc::session::{config, Session};
21 use rustc_data_structures::small_c_str::SmallCStr;
22 use traits::BuilderMethods;
23
24 use std::borrow::Cow;
25 use std::ops::Range;
26 use std::ptr;
27
28 // All Builders must have an llfn associated with them
29 #[must_use]
30 pub struct Builder<'a, 'll: 'a, 'tcx: 'll, V: 'll = &'ll Value> {
31     pub llbuilder: &'ll mut llvm::Builder<'ll>,
32     pub cx: &'a CodegenCx<'ll, 'tcx, V>,
33 }
34
35 impl<V> Drop for Builder<'_, '_, '_, V> {
36     fn drop(&mut self) {
37         unsafe {
38             llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
39         }
40     }
41 }
42
43 // This is a really awful way to get a zero-length c-string, but better (and a
44 // lot more efficient) than doing str::as_c_str("", ...) every time.
45 fn noname() -> *const c_char {
46     static CNULL: c_char = 0;
47     &CNULL
48 }
49
50 bitflags! {
51     pub struct MemFlags: u8 {
52         const VOLATILE = 1 << 0;
53         const NONTEMPORAL = 1 << 1;
54         const UNALIGNED = 1 << 2;
55     }
56 }
57
58 impl BuilderMethods<'a, 'll, 'tcx, Value, BasicBlock>
59     for Builder<'a, 'll, 'tcx> {
60     fn new_block<'b>(
61         cx: &'a CodegenCx<'ll, 'tcx>,
62         llfn: &'ll Value,
63         name: &'b str
64     ) -> Self {
65         let bx = Builder::with_cx(cx);
66         let llbb = unsafe {
67             let name = SmallCStr::new(name);
68             llvm::LLVMAppendBasicBlockInContext(
69                 cx.llcx,
70                 llfn,
71                 name.as_ptr()
72             )
73         };
74         bx.position_at_end(llbb);
75         bx
76     }
77
78     fn with_cx(cx: &'a CodegenCx<'ll, 'tcx>) -> Self {
79         // Create a fresh builder from the crate context.
80         let llbuilder = unsafe {
81             llvm::LLVMCreateBuilderInContext(cx.llcx)
82         };
83         Builder {
84             llbuilder,
85             cx,
86         }
87     }
88
89     fn build_sibling_block<'b>(&self, name: &'b str) -> Self {
90         Builder::new_block(self.cx, self.llfn(), name)
91     }
92
93     fn sess(&self) -> &Session {
94         self.cx.sess()
95     }
96
97     fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
98         self.cx.tcx
99     }
100
101     fn llfn(&self) -> &'ll Value {
102         unsafe {
103             llvm::LLVMGetBasicBlockParent(self.llbb())
104         }
105     }
106
107     fn llbb(&self) -> &'ll BasicBlock {
108         unsafe {
109             llvm::LLVMGetInsertBlock(self.llbuilder)
110         }
111     }
112
113     fn count_insn(&self, category: &str) {
114         if self.cx().sess().codegen_stats() {
115             self.cx().stats.borrow_mut().n_llvm_insns += 1;
116         }
117         if self.cx().sess().count_llvm_insns() {
118             *self.cx().stats
119                       .borrow_mut()
120                       .llvm_insns
121                       .entry(category.to_string())
122                       .or_insert(0) += 1;
123         }
124     }
125
126     fn set_value_name(&self, value: &'ll Value, name: &str) {
127         let cname = SmallCStr::new(name);
128         unsafe {
129             llvm::LLVMSetValueName(value, cname.as_ptr());
130         }
131     }
132
133     fn position_at_end(&self, llbb: &'ll BasicBlock) {
134         unsafe {
135             llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
136         }
137     }
138
139     fn position_at_start(&self, llbb: &'ll BasicBlock) {
140         unsafe {
141             llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
142         }
143     }
144
145     fn ret_void(&self) {
146         self.count_insn("retvoid");
147         unsafe {
148             llvm::LLVMBuildRetVoid(self.llbuilder);
149         }
150     }
151
152     fn ret(&self, v: &'ll Value) {
153         self.count_insn("ret");
154         unsafe {
155             llvm::LLVMBuildRet(self.llbuilder, v);
156         }
157     }
158
159     fn br(&self, dest: &'ll BasicBlock) {
160         self.count_insn("br");
161         unsafe {
162             llvm::LLVMBuildBr(self.llbuilder, dest);
163         }
164     }
165
166     fn cond_br(
167         &self,
168         cond: &'ll Value,
169         then_llbb: &'ll BasicBlock,
170         else_llbb: &'ll BasicBlock,
171     ) {
172         self.count_insn("condbr");
173         unsafe {
174             llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
175         }
176     }
177
178     fn switch(
179         &self,
180         v: &'ll Value,
181         else_llbb: &'ll BasicBlock,
182         num_cases: usize,
183     ) -> &'ll Value {
184         unsafe {
185             llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint)
186         }
187     }
188
189     fn invoke(&self,
190                   llfn: &'ll Value,
191                   args: &[&'ll Value],
192                   then: &'ll BasicBlock,
193                   catch: &'ll BasicBlock,
194                   bundle: Option<&OperandBundleDef<'ll>>) -> &'ll Value {
195         self.count_insn("invoke");
196
197         debug!("Invoke {:?} with args ({:?})",
198                llfn,
199                args);
200
201         let args = self.check_call("invoke", llfn, args);
202         let bundle = bundle.map(|b| &*b.raw);
203
204         unsafe {
205             llvm::LLVMRustBuildInvoke(self.llbuilder,
206                                       llfn,
207                                       args.as_ptr(),
208                                       args.len() as c_uint,
209                                       then,
210                                       catch,
211                                       bundle,
212                                       noname())
213         }
214     }
215
216     fn unreachable(&self) {
217         self.count_insn("unreachable");
218         unsafe {
219             llvm::LLVMBuildUnreachable(self.llbuilder);
220         }
221     }
222
223     /* Arithmetic */
224     fn add(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
225         self.count_insn("add");
226         unsafe {
227             llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
228         }
229     }
230
231     fn fadd(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
232         self.count_insn("fadd");
233         unsafe {
234             llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
235         }
236     }
237
238     fn fadd_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
239         self.count_insn("fadd");
240         unsafe {
241             let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname());
242             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
243             instr
244         }
245     }
246
247     fn sub(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
248         self.count_insn("sub");
249         unsafe {
250             llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
251         }
252     }
253
254     fn fsub(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
255         self.count_insn("fsub");
256         unsafe {
257             llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
258         }
259     }
260
261     fn fsub_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
262         self.count_insn("fsub");
263         unsafe {
264             let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname());
265             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
266             instr
267         }
268     }
269
270     fn mul(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
271         self.count_insn("mul");
272         unsafe {
273             llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
274         }
275     }
276
277     fn fmul(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
278         self.count_insn("fmul");
279         unsafe {
280             llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
281         }
282     }
283
284     fn fmul_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
285         self.count_insn("fmul");
286         unsafe {
287             let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname());
288             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
289             instr
290         }
291     }
292
293
294     fn udiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
295         self.count_insn("udiv");
296         unsafe {
297             llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
298         }
299     }
300
301     fn exactudiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
302         self.count_insn("exactudiv");
303         unsafe {
304             llvm::LLVMBuildExactUDiv(self.llbuilder, lhs, rhs, noname())
305         }
306     }
307
308     fn sdiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
309         self.count_insn("sdiv");
310         unsafe {
311             llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
312         }
313     }
314
315     fn exactsdiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
316         self.count_insn("exactsdiv");
317         unsafe {
318             llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
319         }
320     }
321
322     fn fdiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
323         self.count_insn("fdiv");
324         unsafe {
325             llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
326         }
327     }
328
329     fn fdiv_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
330         self.count_insn("fdiv");
331         unsafe {
332             let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname());
333             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
334             instr
335         }
336     }
337
338     fn urem(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
339         self.count_insn("urem");
340         unsafe {
341             llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
342         }
343     }
344
345     fn srem(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
346         self.count_insn("srem");
347         unsafe {
348             llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
349         }
350     }
351
352     fn frem(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
353         self.count_insn("frem");
354         unsafe {
355             llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
356         }
357     }
358
359     fn frem_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
360         self.count_insn("frem");
361         unsafe {
362             let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname());
363             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
364             instr
365         }
366     }
367
368     fn shl(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
369         self.count_insn("shl");
370         unsafe {
371             llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
372         }
373     }
374
375     fn lshr(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
376         self.count_insn("lshr");
377         unsafe {
378             llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
379         }
380     }
381
382     fn ashr(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
383         self.count_insn("ashr");
384         unsafe {
385             llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
386         }
387     }
388
389     fn and(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
390         self.count_insn("and");
391         unsafe {
392             llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
393         }
394     }
395
396     fn or(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
397         self.count_insn("or");
398         unsafe {
399             llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
400         }
401     }
402
403     fn xor(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
404         self.count_insn("xor");
405         unsafe {
406             llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
407         }
408     }
409
410     fn neg(&self, v: &'ll Value) -> &'ll Value {
411         self.count_insn("neg");
412         unsafe {
413             llvm::LLVMBuildNeg(self.llbuilder, v, noname())
414         }
415     }
416
417     fn fneg(&self, v: &'ll Value) -> &'ll Value {
418         self.count_insn("fneg");
419         unsafe {
420             llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
421         }
422     }
423
424     fn not(&self, v: &'ll Value) -> &'ll Value {
425         self.count_insn("not");
426         unsafe {
427             llvm::LLVMBuildNot(self.llbuilder, v, noname())
428         }
429     }
430
431     fn alloca(&self, ty: &'ll Type, name: &str, align: Align) -> &'ll Value {
432         let bx = Builder::with_cx(self.cx);
433         bx.position_at_start(unsafe {
434             llvm::LLVMGetFirstBasicBlock(self.llfn())
435         });
436         bx.dynamic_alloca(ty, name, align)
437     }
438
439     fn dynamic_alloca(&self, ty: &'ll Type, name: &str, align: Align) -> &'ll Value {
440         self.count_insn("alloca");
441         unsafe {
442             let alloca = if name.is_empty() {
443                 llvm::LLVMBuildAlloca(self.llbuilder, ty, noname())
444             } else {
445                 let name = SmallCStr::new(name);
446                 llvm::LLVMBuildAlloca(self.llbuilder, ty,
447                                       name.as_ptr())
448             };
449             llvm::LLVMSetAlignment(alloca, align.abi() as c_uint);
450             alloca
451         }
452     }
453
454     fn array_alloca(&self,
455                         ty: &'ll Type,
456                         len: &'ll Value,
457                         name: &str,
458                         align: Align) -> &'ll Value {
459         self.count_insn("alloca");
460         unsafe {
461             let alloca = if name.is_empty() {
462                 llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len, noname())
463             } else {
464                 let name = SmallCStr::new(name);
465                 llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len,
466                                            name.as_ptr())
467             };
468             llvm::LLVMSetAlignment(alloca, align.abi() as c_uint);
469             alloca
470         }
471     }
472
473     fn load(&self, ptr: &'ll Value, align: Align) -> &'ll Value {
474         self.count_insn("load");
475         unsafe {
476             let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
477             llvm::LLVMSetAlignment(load, align.abi() as c_uint);
478             load
479         }
480     }
481
482     fn volatile_load(&self, ptr: &'ll Value) -> &'ll Value {
483         self.count_insn("load.volatile");
484         unsafe {
485             let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
486             llvm::LLVMSetVolatile(insn, llvm::True);
487             insn
488         }
489     }
490
491     fn atomic_load(&self, ptr: &'ll Value, order: AtomicOrdering, size: Size) -> &'ll Value {
492         self.count_insn("load.atomic");
493         unsafe {
494             let load = llvm::LLVMRustBuildAtomicLoad(self.llbuilder, ptr, noname(), order);
495             // LLVM requires the alignment of atomic loads to be at least the size of the type.
496             llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
497             load
498         }
499     }
500
501
502     fn range_metadata(&self, load: &'ll Value, range: Range<u128>) {
503         if self.sess().target.target.arch == "amdgpu" {
504             // amdgpu/LLVM does something weird and thinks a i64 value is
505             // split into a v2i32, halving the bitwidth LLVM expects,
506             // tripping an assertion. So, for now, just disable this
507             // optimization.
508             return;
509         }
510
511         unsafe {
512             let llty = val_ty(load);
513             let v = [
514                 C_uint_big(llty, range.start),
515                 C_uint_big(llty, range.end)
516             ];
517
518             llvm::LLVMSetMetadata(load, llvm::MD_range as c_uint,
519                                   llvm::LLVMMDNodeInContext(self.cx.llcx,
520                                                             v.as_ptr(),
521                                                             v.len() as c_uint));
522         }
523     }
524
525     fn nonnull_metadata(&self, load: &'ll Value) {
526         unsafe {
527             llvm::LLVMSetMetadata(load, llvm::MD_nonnull as c_uint,
528                                   llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
529         }
530     }
531
532     fn store(&self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
533         self.store_with_flags(val, ptr, align, MemFlags::empty())
534     }
535
536     fn store_with_flags(
537         &self,
538         val: &'ll Value,
539         ptr: &'ll Value,
540         align: Align,
541         flags: MemFlags,
542     ) -> &'ll Value {
543         debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
544         self.count_insn("store");
545         let ptr = self.check_store(val, ptr);
546         unsafe {
547             let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
548             let align = if flags.contains(MemFlags::UNALIGNED) {
549                 1
550             } else {
551                 align.abi() as c_uint
552             };
553             llvm::LLVMSetAlignment(store, align);
554             if flags.contains(MemFlags::VOLATILE) {
555                 llvm::LLVMSetVolatile(store, llvm::True);
556             }
557             if flags.contains(MemFlags::NONTEMPORAL) {
558                 // According to LLVM [1] building a nontemporal store must
559                 // *always* point to a metadata value of the integer 1.
560                 //
561                 // [1]: http://llvm.org/docs/LangRef.html#store-instruction
562                 let one = C_i32(self.cx, 1);
563                 let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
564                 llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
565             }
566             store
567         }
568     }
569
570    fn atomic_store(&self, val: &'ll Value, ptr: &'ll Value,
571                    order: AtomicOrdering, size: Size) {
572         debug!("Store {:?} -> {:?}", val, ptr);
573         self.count_insn("store.atomic");
574         let ptr = self.check_store(val, ptr);
575         unsafe {
576             let store = llvm::LLVMRustBuildAtomicStore(self.llbuilder, val, ptr, order);
577             // LLVM requires the alignment of atomic stores to be at least the size of the type.
578             llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
579         }
580     }
581
582     fn gep(&self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
583         self.count_insn("gep");
584         unsafe {
585             llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
586                                indices.len() as c_uint, noname())
587         }
588     }
589
590     fn inbounds_gep(&self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
591         self.count_insn("inboundsgep");
592         unsafe {
593             llvm::LLVMBuildInBoundsGEP(
594                 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
595         }
596     }
597
598     /* Casts */
599     fn trunc(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
600         self.count_insn("trunc");
601         unsafe {
602             llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, noname())
603         }
604     }
605
606     fn sext(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
607         self.count_insn("sext");
608         unsafe {
609             llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, noname())
610         }
611     }
612
613     fn fptoui(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
614         self.count_insn("fptoui");
615         unsafe {
616             llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, noname())
617         }
618     }
619
620     fn fptosi(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
621         self.count_insn("fptosi");
622         unsafe {
623             llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty,noname())
624         }
625     }
626
627     fn uitofp(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
628         self.count_insn("uitofp");
629         unsafe {
630             llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, noname())
631         }
632     }
633
634     fn sitofp(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
635         self.count_insn("sitofp");
636         unsafe {
637             llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, noname())
638         }
639     }
640
641     fn fptrunc(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
642         self.count_insn("fptrunc");
643         unsafe {
644             llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, noname())
645         }
646     }
647
648     fn fpext(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
649         self.count_insn("fpext");
650         unsafe {
651             llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, noname())
652         }
653     }
654
655     fn ptrtoint(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
656         self.count_insn("ptrtoint");
657         unsafe {
658             llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, noname())
659         }
660     }
661
662     fn inttoptr(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
663         self.count_insn("inttoptr");
664         unsafe {
665             llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, noname())
666         }
667     }
668
669     fn bitcast(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
670         self.count_insn("bitcast");
671         unsafe {
672             llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, noname())
673         }
674     }
675
676
677     fn intcast(&self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
678         self.count_insn("intcast");
679         unsafe {
680             llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed)
681         }
682     }
683
684     fn pointercast(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
685         self.count_insn("pointercast");
686         unsafe {
687             llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, noname())
688         }
689     }
690
691     /* Comparisons */
692     fn icmp(&self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
693         self.count_insn("icmp");
694         unsafe {
695             llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
696         }
697     }
698
699     fn fcmp(&self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
700         self.count_insn("fcmp");
701         unsafe {
702             llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
703         }
704     }
705
706     /* Miscellaneous instructions */
707     fn empty_phi(&self, ty: &'ll Type) -> &'ll Value {
708         self.count_insn("emptyphi");
709         unsafe {
710             llvm::LLVMBuildPhi(self.llbuilder, ty, noname())
711         }
712     }
713
714     fn phi(&self, ty: &'ll Type, vals: &[&'ll Value], bbs: &[&'ll BasicBlock]) -> &'ll Value {
715         assert_eq!(vals.len(), bbs.len());
716         let phi = self.empty_phi(ty);
717         self.count_insn("addincoming");
718         unsafe {
719             llvm::LLVMAddIncoming(phi, vals.as_ptr(),
720                                   bbs.as_ptr(),
721                                   vals.len() as c_uint);
722             phi
723         }
724     }
725
726     fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
727                        inputs: &[&'ll Value], output: &'ll Type,
728                        volatile: bool, alignstack: bool,
729                        dia: AsmDialect) -> Option<&'ll Value> {
730         self.count_insn("inlineasm");
731
732         let volatile = if volatile { llvm::True }
733                        else        { llvm::False };
734         let alignstack = if alignstack { llvm::True }
735                          else          { llvm::False };
736
737         let argtys = inputs.iter().map(|v| {
738             debug!("Asm Input Type: {:?}", *v);
739             val_ty(*v)
740         }).collect::<Vec<_>>();
741
742         debug!("Asm Output Type: {:?}", output);
743         let fty = Type::func::<Value>(&argtys[..], output);
744         unsafe {
745             // Ask LLVM to verify that the constraints are well-formed.
746             let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons);
747             debug!("Constraint verification result: {:?}", constraints_ok);
748             if constraints_ok {
749                 let v = llvm::LLVMRustInlineAsm(
750                     fty, asm, cons, volatile, alignstack, dia);
751                 Some(self.call(v, inputs, None))
752             } else {
753                 // LLVM has detected an issue with our constraints, bail out
754                 None
755             }
756         }
757     }
758
759     fn memcpy(&self, dst: &'ll Value, dst_align: u64,
760                   src: &'ll Value, src_align: u64,
761                   size: &'ll Value, is_volatile: bool) -> &'ll Value {
762         unsafe {
763             llvm::LLVMRustBuildMemCpy(self.llbuilder, dst, dst_align as c_uint,
764                                       src, src_align as c_uint, size, is_volatile)
765         }
766     }
767
768     fn memmove(&self, dst: &'ll Value, dst_align: u64,
769                   src: &'ll Value, src_align: u64,
770                   size: &'ll Value, is_volatile: bool) -> &'ll Value {
771         unsafe {
772             llvm::LLVMRustBuildMemMove(self.llbuilder, dst, dst_align as c_uint,
773                                       src, src_align as c_uint, size, is_volatile)
774         }
775     }
776
777     fn minnum(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
778         self.count_insn("minnum");
779         unsafe {
780             let instr = llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs);
781             instr.expect("LLVMRustBuildMinNum is not available in LLVM version < 6.0")
782         }
783     }
784     fn maxnum(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
785         self.count_insn("maxnum");
786         unsafe {
787             let instr = llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs);
788             instr.expect("LLVMRustBuildMaxNum is not available in LLVM version < 6.0")
789         }
790     }
791
792     fn select(
793         &self, cond: &'ll Value,
794         then_val: &'ll Value,
795         else_val: &'ll Value,
796     ) -> &'ll Value {
797         self.count_insn("select");
798         unsafe {
799             llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
800         }
801     }
802
803     #[allow(dead_code)]
804     fn va_arg(&self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
805         self.count_insn("vaarg");
806         unsafe {
807             llvm::LLVMBuildVAArg(self.llbuilder, list, ty, noname())
808         }
809     }
810
811     fn extract_element(&self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
812         self.count_insn("extractelement");
813         unsafe {
814             llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
815         }
816     }
817
818     fn insert_element(
819         &self, vec: &'ll Value,
820         elt: &'ll Value,
821         idx: &'ll Value,
822     ) -> &'ll Value {
823         self.count_insn("insertelement");
824         unsafe {
825             llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
826         }
827     }
828
829     fn shuffle_vector(&self, v1: &'ll Value, v2: &'ll Value, mask: &'ll Value) -> &'ll Value {
830         self.count_insn("shufflevector");
831         unsafe {
832             llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
833         }
834     }
835
836     fn vector_splat(&self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
837         unsafe {
838             let elt_ty = val_ty(elt);
839             let undef = llvm::LLVMGetUndef(Type::vector::<Value>(elt_ty, num_elts as u64));
840             let vec = self.insert_element(undef, elt, C_i32(self.cx, 0));
841             let vec_i32_ty = Type::vector::<Value>(Type::i32(self.cx), num_elts as u64);
842             self.shuffle_vector(vec, undef, C_null(vec_i32_ty))
843         }
844     }
845
846     fn vector_reduce_fadd_fast(&self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
847         self.count_insn("vector.reduce.fadd_fast");
848         unsafe {
849             // FIXME: add a non-fast math version once
850             // https://bugs.llvm.org/show_bug.cgi?id=36732
851             // is fixed.
852             let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
853             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
854             instr
855         }
856     }
857     fn vector_reduce_fmul_fast(&self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
858         self.count_insn("vector.reduce.fmul_fast");
859         unsafe {
860             // FIXME: add a non-fast math version once
861             // https://bugs.llvm.org/show_bug.cgi?id=36732
862             // is fixed.
863             let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
864             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
865             instr
866         }
867     }
868     fn vector_reduce_add(&self, src: &'ll Value) -> &'ll Value {
869         self.count_insn("vector.reduce.add");
870         unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
871     }
872     fn vector_reduce_mul(&self, src: &'ll Value) -> &'ll Value {
873         self.count_insn("vector.reduce.mul");
874         unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
875     }
876     fn vector_reduce_and(&self, src: &'ll Value) -> &'ll Value {
877         self.count_insn("vector.reduce.and");
878         unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
879     }
880     fn vector_reduce_or(&self, src: &'ll Value) -> &'ll Value {
881         self.count_insn("vector.reduce.or");
882         unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
883     }
884     fn vector_reduce_xor(&self, src: &'ll Value) -> &'ll Value {
885         self.count_insn("vector.reduce.xor");
886         unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
887     }
888     fn vector_reduce_fmin(&self, src: &'ll Value) -> &'ll Value {
889         self.count_insn("vector.reduce.fmin");
890         unsafe { llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false) }
891     }
892     fn vector_reduce_fmax(&self, src: &'ll Value) -> &'ll Value {
893         self.count_insn("vector.reduce.fmax");
894         unsafe { llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false) }
895     }
896     fn vector_reduce_fmin_fast(&self, src: &'ll Value) -> &'ll Value {
897         self.count_insn("vector.reduce.fmin_fast");
898         unsafe {
899             let instr = llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
900             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
901             instr
902         }
903     }
904     fn vector_reduce_fmax_fast(&self, src: &'ll Value) -> &'ll Value {
905         self.count_insn("vector.reduce.fmax_fast");
906         unsafe {
907             let instr = llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
908             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
909             instr
910         }
911     }
912     fn vector_reduce_min(&self, src: &'ll Value, is_signed: bool) -> &'ll Value {
913         self.count_insn("vector.reduce.min");
914         unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
915     }
916     fn vector_reduce_max(&self, src: &'ll Value, is_signed: bool) -> &'ll Value {
917         self.count_insn("vector.reduce.max");
918         unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
919     }
920
921     fn extract_value(&self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
922         self.count_insn("extractvalue");
923         assert_eq!(idx as c_uint as u64, idx);
924         unsafe {
925             llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
926         }
927     }
928
929     fn insert_value(&self, agg_val: &'ll Value, elt: &'ll Value,
930                        idx: u64) -> &'ll Value {
931         self.count_insn("insertvalue");
932         assert_eq!(idx as c_uint as u64, idx);
933         unsafe {
934             llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
935                                        noname())
936         }
937     }
938
939     fn landing_pad(&self, ty: &'ll Type, pers_fn: &'ll Value,
940                        num_clauses: usize) -> &'ll Value {
941         self.count_insn("landingpad");
942         unsafe {
943             llvm::LLVMBuildLandingPad(self.llbuilder, ty, pers_fn,
944                                       num_clauses as c_uint, noname())
945         }
946     }
947
948     fn add_clause(&self, landing_pad: &'ll Value, clause: &'ll Value) {
949         unsafe {
950             llvm::LLVMAddClause(landing_pad, clause);
951         }
952     }
953
954     fn set_cleanup(&self, landing_pad: &'ll Value) {
955         self.count_insn("setcleanup");
956         unsafe {
957             llvm::LLVMSetCleanup(landing_pad, llvm::True);
958         }
959     }
960
961     fn resume(&self, exn: &'ll Value) -> &'ll Value {
962         self.count_insn("resume");
963         unsafe {
964             llvm::LLVMBuildResume(self.llbuilder, exn)
965         }
966     }
967
968     fn cleanup_pad(&self,
969                        parent: Option<&'ll Value>,
970                        args: &[&'ll Value]) -> &'ll Value {
971         self.count_insn("cleanuppad");
972         let name = const_cstr!("cleanuppad");
973         let ret = unsafe {
974             llvm::LLVMRustBuildCleanupPad(self.llbuilder,
975                                           parent,
976                                           args.len() as c_uint,
977                                           args.as_ptr(),
978                                           name.as_ptr())
979         };
980         ret.expect("LLVM does not have support for cleanuppad")
981     }
982
983     fn cleanup_ret(
984         &self, cleanup: &'ll Value,
985         unwind: Option<&'ll BasicBlock>,
986     ) -> &'ll Value {
987         self.count_insn("cleanupret");
988         let ret = unsafe {
989             llvm::LLVMRustBuildCleanupRet(self.llbuilder, cleanup, unwind)
990         };
991         ret.expect("LLVM does not have support for cleanupret")
992     }
993
994     fn catch_pad(&self,
995                      parent: &'ll Value,
996                      args: &[&'ll Value]) -> &'ll Value {
997         self.count_insn("catchpad");
998         let name = const_cstr!("catchpad");
999         let ret = unsafe {
1000             llvm::LLVMRustBuildCatchPad(self.llbuilder, parent,
1001                                         args.len() as c_uint, args.as_ptr(),
1002                                         name.as_ptr())
1003         };
1004         ret.expect("LLVM does not have support for catchpad")
1005     }
1006
1007     fn catch_ret(&self, pad: &'ll Value, unwind: &'ll BasicBlock) -> &'ll Value {
1008         self.count_insn("catchret");
1009         let ret = unsafe {
1010             llvm::LLVMRustBuildCatchRet(self.llbuilder, pad, unwind)
1011         };
1012         ret.expect("LLVM does not have support for catchret")
1013     }
1014
1015     fn catch_switch(
1016         &self,
1017         parent: Option<&'ll Value>,
1018         unwind: Option<&'ll BasicBlock>,
1019         num_handlers: usize,
1020     ) -> &'ll Value {
1021         self.count_insn("catchswitch");
1022         let name = const_cstr!("catchswitch");
1023         let ret = unsafe {
1024             llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind,
1025                                            num_handlers as c_uint,
1026                                            name.as_ptr())
1027         };
1028         ret.expect("LLVM does not have support for catchswitch")
1029     }
1030
1031     fn add_handler(&self, catch_switch: &'ll Value, handler: &'ll BasicBlock) {
1032         unsafe {
1033             llvm::LLVMRustAddHandler(catch_switch, handler);
1034         }
1035     }
1036
1037     fn set_personality_fn(&self, personality: &'ll Value) {
1038         unsafe {
1039             llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1040         }
1041     }
1042
1043     // Atomic Operations
1044     fn atomic_cmpxchg(
1045         &self,
1046         dst: &'ll Value,
1047         cmp: &'ll Value,
1048         src: &'ll Value,
1049         order: AtomicOrdering,
1050         failure_order: AtomicOrdering,
1051         weak: llvm::Bool,
1052     ) -> &'ll Value {
1053         unsafe {
1054             llvm::LLVMRustBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
1055                                              order, failure_order, weak)
1056         }
1057     }
1058     fn atomic_rmw(
1059         &self,
1060         op: AtomicRmwBinOp,
1061         dst: &'ll Value,
1062         src: &'ll Value,
1063         order: AtomicOrdering,
1064     ) -> &'ll Value {
1065         unsafe {
1066             llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False)
1067         }
1068     }
1069
1070     fn atomic_fence(&self, order: AtomicOrdering, scope: SynchronizationScope) {
1071         unsafe {
1072             llvm::LLVMRustBuildAtomicFence(self.llbuilder, order, scope);
1073         }
1074     }
1075
1076     fn add_case(&self, s: &'ll Value, on_val: &'ll Value, dest: &'ll BasicBlock) {
1077         unsafe {
1078             llvm::LLVMAddCase(s, on_val, dest)
1079         }
1080     }
1081
1082     fn add_incoming_to_phi(&self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1083         self.count_insn("addincoming");
1084         unsafe {
1085             llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1086         }
1087     }
1088
1089     fn set_invariant_load(&self, load: &'ll Value) {
1090         unsafe {
1091             llvm::LLVMSetMetadata(load, llvm::MD_invariant_load as c_uint,
1092                                   llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
1093         }
1094     }
1095
1096     /// Returns the ptr value that should be used for storing `val`.
1097     fn check_store<'b>(&self,
1098                        val: &'ll Value,
1099                        ptr: &'ll Value) -> &'ll Value {
1100         let dest_ptr_ty = val_ty(ptr);
1101         let stored_ty = val_ty(val);
1102         let stored_ptr_ty = stored_ty.ptr_to();
1103
1104         assert_eq!(dest_ptr_ty.kind(), llvm::TypeKind::Pointer);
1105
1106         if dest_ptr_ty == stored_ptr_ty {
1107             ptr
1108         } else {
1109             debug!("Type mismatch in store. \
1110                     Expected {:?}, got {:?}; inserting bitcast",
1111                    dest_ptr_ty, stored_ptr_ty);
1112             self.bitcast(ptr, stored_ptr_ty)
1113         }
1114     }
1115
1116     /// Returns the args that should be used for a call to `llfn`.
1117     fn check_call<'b>(&self,
1118                       typ: &str,
1119                       llfn: &'ll Value,
1120                       args: &'b [&'ll Value]) -> Cow<'b, [&'ll Value]> {
1121         let mut fn_ty = val_ty(llfn);
1122         // Strip off pointers
1123         while fn_ty.kind() == llvm::TypeKind::Pointer {
1124             fn_ty = fn_ty.element_type();
1125         }
1126
1127         assert!(fn_ty.kind() == llvm::TypeKind::Function,
1128                 "builder::{} not passed a function, but {:?}", typ, fn_ty);
1129
1130         let param_tys = fn_ty.func_params();
1131
1132         let all_args_match = param_tys.iter()
1133             .zip(args.iter().map(|&v| val_ty(v)))
1134             .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1135
1136         if all_args_match {
1137             return Cow::Borrowed(args);
1138         }
1139
1140         let casted_args: Vec<_> = param_tys.into_iter()
1141             .zip(args.iter())
1142             .enumerate()
1143             .map(|(i, (expected_ty, &actual_val))| {
1144                 let actual_ty = val_ty(actual_val);
1145                 if expected_ty != actual_ty {
1146                     debug!("Type mismatch in function call of {:?}. \
1147                             Expected {:?} for param {}, got {:?}; injecting bitcast",
1148                            llfn, expected_ty, i, actual_ty);
1149                     self.bitcast(actual_val, expected_ty)
1150                 } else {
1151                     actual_val
1152                 }
1153             })
1154             .collect();
1155
1156         Cow::Owned(casted_args)
1157     }
1158
1159     fn lifetime_start(&self, ptr: &'ll Value, size: Size) {
1160         self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1161     }
1162
1163     fn lifetime_end(&self, ptr: &'ll Value, size: Size) {
1164         self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1165     }
1166
1167     /// If LLVM lifetime intrinsic support is enabled (i.e. optimizations
1168     /// on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
1169     /// and the intrinsic for `lt` and passes them to `emit`, which is in
1170     /// charge of generating code to call the passed intrinsic on whatever
1171     /// block of generated code is targeted for the intrinsic.
1172     ///
1173     /// If LLVM lifetime intrinsic support is disabled (i.e.  optimizations
1174     /// off) or `ptr` is zero-sized, then no-op (does not call `emit`).
1175     fn call_lifetime_intrinsic(&self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1176         if self.cx.sess().opts.optimize == config::OptLevel::No {
1177             return;
1178         }
1179
1180         let size = size.bytes();
1181         if size == 0 {
1182             return;
1183         }
1184
1185         let lifetime_intrinsic = self.cx.get_intrinsic(intrinsic);
1186
1187         let ptr = self.pointercast(ptr, Type::i8p(self.cx));
1188         self.call(lifetime_intrinsic, &[C_u64(self.cx, size), ptr], None);
1189     }
1190
1191     fn call(&self, llfn: &'ll Value, args: &[&'ll Value],
1192                 bundle: Option<&OperandBundleDef<'ll>>) -> &'ll Value {
1193         self.count_insn("call");
1194
1195         debug!("Call {:?} with args ({:?})",
1196                llfn,
1197                args);
1198
1199         let args = self.check_call("call", llfn, args);
1200         let bundle = bundle.map(|b| &*b.raw);
1201
1202         unsafe {
1203             llvm::LLVMRustBuildCall(
1204                 self.llbuilder,
1205                 llfn,
1206                 args.as_ptr() as *const &llvm::Value,
1207                 args.len() as c_uint,
1208                 bundle, noname()
1209             )
1210         }
1211     }
1212
1213     fn zext(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1214         self.count_insn("zext");
1215         unsafe {
1216             llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, noname())
1217         }
1218     }
1219
1220     fn struct_gep(&self, ptr: &'ll Value, idx: u64) -> &'ll Value {
1221         self.count_insn("structgep");
1222         assert_eq!(idx as c_uint as u64, idx);
1223         unsafe {
1224             llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
1225         }
1226     }
1227
1228     fn cx(&self) -> &'a CodegenCx<'ll, 'tcx, &'ll Value> {
1229         &self.cx
1230     }
1231 }