]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/builder.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / librustc_trans / trans / 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 #![allow(dead_code)] // FFI wrappers
12
13 use llvm;
14 use llvm::{CallConv, AtomicBinOp, AtomicOrdering, AsmDialect, AttrBuilder};
15 use llvm::{Opcode, IntPredicate, RealPredicate, False};
16 use llvm::{ValueRef, BasicBlockRef, BuilderRef, ModuleRef};
17 use trans::base;
18 use trans::common::*;
19 use trans::machine::llalign_of_pref;
20 use trans::type_::Type;
21 use util::nodemap::FnvHashMap;
22 use libc::{c_uint, c_char};
23
24 use std::ffi::CString;
25 use std::ptr;
26 use syntax::codemap::Span;
27
28 pub struct Builder<'a, 'tcx: 'a> {
29     pub llbuilder: BuilderRef,
30     pub ccx: &'a CrateContext<'a, 'tcx>,
31 }
32
33 // This is a really awful way to get a zero-length c-string, but better (and a
34 // lot more efficient) than doing str::as_c_str("", ...) every time.
35 pub fn noname() -> *const c_char {
36     static CNULL: c_char = 0;
37     &CNULL
38 }
39
40 impl<'a, 'tcx> Builder<'a, 'tcx> {
41     pub fn new(ccx: &'a CrateContext<'a, 'tcx>) -> Builder<'a, 'tcx> {
42         Builder {
43             llbuilder: ccx.raw_builder(),
44             ccx: ccx,
45         }
46     }
47
48     pub fn count_insn(&self, category: &str) {
49         if self.ccx.sess().trans_stats() {
50             self.ccx.stats().n_llvm_insns.set(self.ccx
51                                                 .stats()
52                                                 .n_llvm_insns
53                                                 .get() + 1);
54         }
55         self.ccx.count_llvm_insn();
56         if self.ccx.sess().count_llvm_insns() {
57             base::with_insn_ctxt(|v| {
58                 let mut h = self.ccx.stats().llvm_insns.borrow_mut();
59
60                 // Build version of path with cycles removed.
61
62                 // Pass 1: scan table mapping str -> rightmost pos.
63                 let mut mm = FnvHashMap();
64                 let len = v.len();
65                 let mut i = 0;
66                 while i < len {
67                     mm.insert(v[i], i);
68                     i += 1;
69                 }
70
71                 // Pass 2: concat strings for each elt, skipping
72                 // forwards over any cycles by advancing to rightmost
73                 // occurrence of each element in path.
74                 let mut s = String::from_str(".");
75                 i = 0;
76                 while i < len {
77                     i = mm[v[i]];
78                     s.push('/');
79                     s.push_str(v[i]);
80                     i += 1;
81                 }
82
83                 s.push('/');
84                 s.push_str(category);
85
86                 let n = match h.get(&s) {
87                     Some(&n) => n,
88                     _ => 0
89                 };
90                 h.insert(s, n+1);
91             })
92         }
93     }
94
95     pub fn position_before(&self, insn: ValueRef) {
96         unsafe {
97             llvm::LLVMPositionBuilderBefore(self.llbuilder, insn);
98         }
99     }
100
101     pub fn position_at_end(&self, llbb: BasicBlockRef) {
102         unsafe {
103             llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
104         }
105     }
106
107     pub fn ret_void(&self) {
108         self.count_insn("retvoid");
109         unsafe {
110             llvm::LLVMBuildRetVoid(self.llbuilder);
111         }
112     }
113
114     pub fn ret(&self, v: ValueRef) {
115         self.count_insn("ret");
116         unsafe {
117             llvm::LLVMBuildRet(self.llbuilder, v);
118         }
119     }
120
121     pub fn aggregate_ret(&self, ret_vals: &[ValueRef]) {
122         unsafe {
123             llvm::LLVMBuildAggregateRet(self.llbuilder,
124                                         ret_vals.as_ptr(),
125                                         ret_vals.len() as c_uint);
126         }
127     }
128
129     pub fn br(&self, dest: BasicBlockRef) {
130         self.count_insn("br");
131         unsafe {
132             llvm::LLVMBuildBr(self.llbuilder, dest);
133         }
134     }
135
136     pub fn cond_br(&self, cond: ValueRef, then_llbb: BasicBlockRef, else_llbb: BasicBlockRef) {
137         self.count_insn("condbr");
138         unsafe {
139             llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
140         }
141     }
142
143     pub fn switch(&self, v: ValueRef, else_llbb: BasicBlockRef, num_cases: uint) -> ValueRef {
144         unsafe {
145             llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint)
146         }
147     }
148
149     pub fn indirect_br(&self, addr: ValueRef, num_dests: uint) {
150         self.count_insn("indirectbr");
151         unsafe {
152             llvm::LLVMBuildIndirectBr(self.llbuilder, addr, num_dests as c_uint);
153         }
154     }
155
156     pub fn invoke(&self,
157                   llfn: ValueRef,
158                   args: &[ValueRef],
159                   then: BasicBlockRef,
160                   catch: BasicBlockRef,
161                   attributes: Option<AttrBuilder>)
162                   -> ValueRef {
163         self.count_insn("invoke");
164
165         debug!("Invoke {} with args ({})",
166                self.ccx.tn().val_to_string(llfn),
167                args.iter()
168                    .map(|&v| self.ccx.tn().val_to_string(v))
169                    .collect::<Vec<String>>()
170                    .connect(", "));
171
172         unsafe {
173             let v = llvm::LLVMBuildInvoke(self.llbuilder,
174                                           llfn,
175                                           args.as_ptr(),
176                                           args.len() as c_uint,
177                                           then,
178                                           catch,
179                                           noname());
180             match attributes {
181                 Some(a) => a.apply_callsite(v),
182                 None => {}
183             }
184             v
185         }
186     }
187
188     pub fn unreachable(&self) {
189         self.count_insn("unreachable");
190         unsafe {
191             llvm::LLVMBuildUnreachable(self.llbuilder);
192         }
193     }
194
195     /* Arithmetic */
196     pub fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
197         self.count_insn("add");
198         unsafe {
199             llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
200         }
201     }
202
203     pub fn nswadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
204         self.count_insn("nswadd");
205         unsafe {
206             llvm::LLVMBuildNSWAdd(self.llbuilder, lhs, rhs, noname())
207         }
208     }
209
210     pub fn nuwadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
211         self.count_insn("nuwadd");
212         unsafe {
213             llvm::LLVMBuildNUWAdd(self.llbuilder, lhs, rhs, noname())
214         }
215     }
216
217     pub fn fadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
218         self.count_insn("fadd");
219         unsafe {
220             llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
221         }
222     }
223
224     pub fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
225         self.count_insn("sub");
226         unsafe {
227             llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
228         }
229     }
230
231     pub fn nswsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
232         self.count_insn("nwsub");
233         unsafe {
234             llvm::LLVMBuildNSWSub(self.llbuilder, lhs, rhs, noname())
235         }
236     }
237
238     pub fn nuwsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
239         self.count_insn("nuwsub");
240         unsafe {
241             llvm::LLVMBuildNUWSub(self.llbuilder, lhs, rhs, noname())
242         }
243     }
244
245     pub fn fsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
246         self.count_insn("sub");
247         unsafe {
248             llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
249         }
250     }
251
252     pub fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
253         self.count_insn("mul");
254         unsafe {
255             llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
256         }
257     }
258
259     pub fn nswmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
260         self.count_insn("nswmul");
261         unsafe {
262             llvm::LLVMBuildNSWMul(self.llbuilder, lhs, rhs, noname())
263         }
264     }
265
266     pub fn nuwmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
267         self.count_insn("nuwmul");
268         unsafe {
269             llvm::LLVMBuildNUWMul(self.llbuilder, lhs, rhs, noname())
270         }
271     }
272
273     pub fn fmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
274         self.count_insn("fmul");
275         unsafe {
276             llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
277         }
278     }
279
280     pub fn udiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
281         self.count_insn("udiv");
282         unsafe {
283             llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
284         }
285     }
286
287     pub fn sdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
288         self.count_insn("sdiv");
289         unsafe {
290             llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
291         }
292     }
293
294     pub fn exactsdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
295         self.count_insn("exactsdiv");
296         unsafe {
297             llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
298         }
299     }
300
301     pub fn fdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
302         self.count_insn("fdiv");
303         unsafe {
304             llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
305         }
306     }
307
308     pub fn urem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
309         self.count_insn("urem");
310         unsafe {
311             llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
312         }
313     }
314
315     pub fn srem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
316         self.count_insn("srem");
317         unsafe {
318             llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
319         }
320     }
321
322     pub fn frem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
323         self.count_insn("frem");
324         unsafe {
325             llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
326         }
327     }
328
329     pub fn shl(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
330         self.count_insn("shl");
331         unsafe {
332             llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
333         }
334     }
335
336     pub fn lshr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
337         self.count_insn("lshr");
338         unsafe {
339             llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
340         }
341     }
342
343     pub fn ashr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
344         self.count_insn("ashr");
345         unsafe {
346             llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
347         }
348     }
349
350     pub fn and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
351         self.count_insn("and");
352         unsafe {
353             llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
354         }
355     }
356
357     pub fn or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
358         self.count_insn("or");
359         unsafe {
360             llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
361         }
362     }
363
364     pub fn xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
365         self.count_insn("xor");
366         unsafe {
367             llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
368         }
369     }
370
371     pub fn binop(&self, op: Opcode, lhs: ValueRef, rhs: ValueRef)
372               -> ValueRef {
373         self.count_insn("binop");
374         unsafe {
375             llvm::LLVMBuildBinOp(self.llbuilder, op, lhs, rhs, noname())
376         }
377     }
378
379     pub fn neg(&self, v: ValueRef) -> ValueRef {
380         self.count_insn("neg");
381         unsafe {
382             llvm::LLVMBuildNeg(self.llbuilder, v, noname())
383         }
384     }
385
386     pub fn nswneg(&self, v: ValueRef) -> ValueRef {
387         self.count_insn("nswneg");
388         unsafe {
389             llvm::LLVMBuildNSWNeg(self.llbuilder, v, noname())
390         }
391     }
392
393     pub fn nuwneg(&self, v: ValueRef) -> ValueRef {
394         self.count_insn("nuwneg");
395         unsafe {
396             llvm::LLVMBuildNUWNeg(self.llbuilder, v, noname())
397         }
398     }
399     pub fn fneg(&self, v: ValueRef) -> ValueRef {
400         self.count_insn("fneg");
401         unsafe {
402             llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
403         }
404     }
405
406     pub fn not(&self, v: ValueRef) -> ValueRef {
407         self.count_insn("not");
408         unsafe {
409             llvm::LLVMBuildNot(self.llbuilder, v, noname())
410         }
411     }
412
413     /* Memory */
414     pub fn malloc(&self, ty: Type) -> ValueRef {
415         self.count_insn("malloc");
416         unsafe {
417             llvm::LLVMBuildMalloc(self.llbuilder, ty.to_ref(), noname())
418         }
419     }
420
421     pub fn array_malloc(&self, ty: Type, val: ValueRef) -> ValueRef {
422         self.count_insn("arraymalloc");
423         unsafe {
424             llvm::LLVMBuildArrayMalloc(self.llbuilder, ty.to_ref(), val, noname())
425         }
426     }
427
428     pub fn alloca(&self, ty: Type, name: &str) -> ValueRef {
429         self.count_insn("alloca");
430         unsafe {
431             if name.is_empty() {
432                 llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), noname())
433             } else {
434                 let name = CString::new(name).unwrap();
435                 llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(),
436                                       name.as_ptr())
437             }
438         }
439     }
440
441     pub fn array_alloca(&self, ty: Type, val: ValueRef) -> ValueRef {
442         self.count_insn("arrayalloca");
443         unsafe {
444             llvm::LLVMBuildArrayAlloca(self.llbuilder, ty.to_ref(), val, noname())
445         }
446     }
447
448     pub fn free(&self, ptr: ValueRef) {
449         self.count_insn("free");
450         unsafe {
451             llvm::LLVMBuildFree(self.llbuilder, ptr);
452         }
453     }
454
455     pub fn load(&self, ptr: ValueRef) -> ValueRef {
456         self.count_insn("load");
457         unsafe {
458             llvm::LLVMBuildLoad(self.llbuilder, ptr, noname())
459         }
460     }
461
462     pub fn volatile_load(&self, ptr: ValueRef) -> ValueRef {
463         self.count_insn("load.volatile");
464         unsafe {
465             let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
466             llvm::LLVMSetVolatile(insn, llvm::True);
467             insn
468         }
469     }
470
471     pub fn atomic_load(&self, ptr: ValueRef, order: AtomicOrdering) -> ValueRef {
472         self.count_insn("load.atomic");
473         unsafe {
474             let ty = Type::from_ref(llvm::LLVMTypeOf(ptr));
475             let align = llalign_of_pref(self.ccx, ty.element_type());
476             llvm::LLVMBuildAtomicLoad(self.llbuilder, ptr, noname(), order,
477                                       align as c_uint)
478         }
479     }
480
481
482     pub fn load_range_assert(&self, ptr: ValueRef, lo: u64,
483                              hi: u64, signed: llvm::Bool) -> ValueRef {
484         let value = self.load(ptr);
485
486         unsafe {
487             let t = llvm::LLVMGetElementType(llvm::LLVMTypeOf(ptr));
488             let min = llvm::LLVMConstInt(t, lo, signed);
489             let max = llvm::LLVMConstInt(t, hi, signed);
490
491             let v = [min, max];
492
493             llvm::LLVMSetMetadata(value, llvm::MD_range as c_uint,
494                                   llvm::LLVMMDNodeInContext(self.ccx.llcx(),
495                                                             v.as_ptr(),
496                                                             v.len() as c_uint));
497         }
498
499         value
500     }
501
502     pub fn load_nonnull(&self, ptr: ValueRef) -> ValueRef {
503         let value = self.load(ptr);
504         unsafe {
505             llvm::LLVMSetMetadata(value, llvm::MD_nonnull as c_uint,
506                                   llvm::LLVMMDNodeInContext(self.ccx.llcx(), ptr::null(), 0));
507         }
508
509         value
510     }
511
512     pub fn store(&self, val: ValueRef, ptr: ValueRef) {
513         debug!("Store {} -> {}",
514                self.ccx.tn().val_to_string(val),
515                self.ccx.tn().val_to_string(ptr));
516         assert!(!self.llbuilder.is_null());
517         self.count_insn("store");
518         unsafe {
519             llvm::LLVMBuildStore(self.llbuilder, val, ptr);
520         }
521     }
522
523     pub fn volatile_store(&self, val: ValueRef, ptr: ValueRef) {
524         debug!("Store {} -> {}",
525                self.ccx.tn().val_to_string(val),
526                self.ccx.tn().val_to_string(ptr));
527         assert!(!self.llbuilder.is_null());
528         self.count_insn("store.volatile");
529         unsafe {
530             let insn = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
531             llvm::LLVMSetVolatile(insn, llvm::True);
532         }
533     }
534
535     pub fn atomic_store(&self, val: ValueRef, ptr: ValueRef, order: AtomicOrdering) {
536         debug!("Store {} -> {}",
537                self.ccx.tn().val_to_string(val),
538                self.ccx.tn().val_to_string(ptr));
539         self.count_insn("store.atomic");
540         unsafe {
541             let ty = Type::from_ref(llvm::LLVMTypeOf(ptr));
542             let align = llalign_of_pref(self.ccx, ty.element_type());
543             llvm::LLVMBuildAtomicStore(self.llbuilder, val, ptr, order, align as c_uint);
544         }
545     }
546
547     pub fn gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
548         self.count_insn("gep");
549         unsafe {
550             llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
551                                indices.len() as c_uint, noname())
552         }
553     }
554
555     // Simple wrapper around GEP that takes an array of ints and wraps them
556     // in C_i32()
557     #[inline]
558     pub fn gepi(&self, base: ValueRef, ixs: &[uint]) -> ValueRef {
559         // Small vector optimization. This should catch 100% of the cases that
560         // we care about.
561         if ixs.len() < 16 {
562             let mut small_vec = [ C_i32(self.ccx, 0); 16 ];
563             for (small_vec_e, &ix) in small_vec.iter_mut().zip(ixs.iter()) {
564                 *small_vec_e = C_i32(self.ccx, ix as i32);
565             }
566             self.inbounds_gep(base, &small_vec[..ixs.len()])
567         } else {
568             let v = ixs.iter().map(|i| C_i32(self.ccx, *i as i32)).collect::<Vec<ValueRef>>();
569             self.count_insn("gepi");
570             self.inbounds_gep(base, &v[..])
571         }
572     }
573
574     pub fn inbounds_gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
575         self.count_insn("inboundsgep");
576         unsafe {
577             llvm::LLVMBuildInBoundsGEP(
578                 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
579         }
580     }
581
582     pub fn struct_gep(&self, ptr: ValueRef, idx: uint) -> ValueRef {
583         self.count_insn("structgep");
584         unsafe {
585             llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
586         }
587     }
588
589     pub fn global_string(&self, _str: *const c_char) -> ValueRef {
590         self.count_insn("globalstring");
591         unsafe {
592             llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname())
593         }
594     }
595
596     pub fn global_string_ptr(&self, _str: *const c_char) -> ValueRef {
597         self.count_insn("globalstringptr");
598         unsafe {
599             llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname())
600         }
601     }
602
603     /* Casts */
604     pub fn trunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
605         self.count_insn("trunc");
606         unsafe {
607             llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
608         }
609     }
610
611     pub fn zext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
612         self.count_insn("zext");
613         unsafe {
614             llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty.to_ref(), noname())
615         }
616     }
617
618     pub fn sext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
619         self.count_insn("sext");
620         unsafe {
621             llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty.to_ref(), noname())
622         }
623     }
624
625     pub fn fptoui(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
626         self.count_insn("fptoui");
627         unsafe {
628             llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty.to_ref(), noname())
629         }
630     }
631
632     pub fn fptosi(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
633         self.count_insn("fptosi");
634         unsafe {
635             llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty.to_ref(),noname())
636         }
637     }
638
639     pub fn uitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
640         self.count_insn("uitofp");
641         unsafe {
642             llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
643         }
644     }
645
646     pub fn sitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
647         self.count_insn("sitofp");
648         unsafe {
649             llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
650         }
651     }
652
653     pub fn fptrunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
654         self.count_insn("fptrunc");
655         unsafe {
656             llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
657         }
658     }
659
660     pub fn fpext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
661         self.count_insn("fpext");
662         unsafe {
663             llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty.to_ref(), noname())
664         }
665     }
666
667     pub fn ptrtoint(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
668         self.count_insn("ptrtoint");
669         unsafe {
670             llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty.to_ref(), noname())
671         }
672     }
673
674     pub fn inttoptr(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
675         self.count_insn("inttoptr");
676         unsafe {
677             llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty.to_ref(), noname())
678         }
679     }
680
681     pub fn bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
682         self.count_insn("bitcast");
683         unsafe {
684             llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
685         }
686     }
687
688     pub fn zext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
689         self.count_insn("zextorbitcast");
690         unsafe {
691             llvm::LLVMBuildZExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
692         }
693     }
694
695     pub fn sext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
696         self.count_insn("sextorbitcast");
697         unsafe {
698             llvm::LLVMBuildSExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
699         }
700     }
701
702     pub fn trunc_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
703         self.count_insn("truncorbitcast");
704         unsafe {
705             llvm::LLVMBuildTruncOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
706         }
707     }
708
709     pub fn cast(&self, op: Opcode, val: ValueRef, dest_ty: Type) -> ValueRef {
710         self.count_insn("cast");
711         unsafe {
712             llvm::LLVMBuildCast(self.llbuilder, op, val, dest_ty.to_ref(), noname())
713         }
714     }
715
716     pub fn pointercast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
717         self.count_insn("pointercast");
718         unsafe {
719             llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty.to_ref(), noname())
720         }
721     }
722
723     pub fn intcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
724         self.count_insn("intcast");
725         unsafe {
726             llvm::LLVMBuildIntCast(self.llbuilder, val, dest_ty.to_ref(), noname())
727         }
728     }
729
730     pub fn fpcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
731         self.count_insn("fpcast");
732         unsafe {
733             llvm::LLVMBuildFPCast(self.llbuilder, val, dest_ty.to_ref(), noname())
734         }
735     }
736
737
738     /* Comparisons */
739     pub fn icmp(&self, op: IntPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
740         self.count_insn("icmp");
741         unsafe {
742             llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
743         }
744     }
745
746     pub fn fcmp(&self, op: RealPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
747         self.count_insn("fcmp");
748         unsafe {
749             llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
750         }
751     }
752
753     /* Miscellaneous instructions */
754     pub fn empty_phi(&self, ty: Type) -> ValueRef {
755         self.count_insn("emptyphi");
756         unsafe {
757             llvm::LLVMBuildPhi(self.llbuilder, ty.to_ref(), noname())
758         }
759     }
760
761     pub fn phi(&self, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef {
762         assert_eq!(vals.len(), bbs.len());
763         let phi = self.empty_phi(ty);
764         self.count_insn("addincoming");
765         unsafe {
766             llvm::LLVMAddIncoming(phi, vals.as_ptr(),
767                                   bbs.as_ptr(),
768                                   vals.len() as c_uint);
769             phi
770         }
771     }
772
773     pub fn add_span_comment(&self, sp: Span, text: &str) {
774         if self.ccx.sess().asm_comments() {
775             let s = format!("{} ({})",
776                             text,
777                             self.ccx.sess().codemap().span_to_string(sp));
778             debug!("{}", &s[..]);
779             self.add_comment(&s[..]);
780         }
781     }
782
783     pub fn add_comment(&self, text: &str) {
784         if self.ccx.sess().asm_comments() {
785             let sanitized = text.replace("$", "");
786             let comment_text = format!("{} {}", "#",
787                                        sanitized.replace("\n", "\n\t# "));
788             self.count_insn("inlineasm");
789             let comment_text = CString::new(comment_text).unwrap();
790             let asm = unsafe {
791                 llvm::LLVMConstInlineAsm(Type::func(&[], &Type::void(self.ccx)).to_ref(),
792                                          comment_text.as_ptr(), noname(), False,
793                                          False)
794             };
795             self.call(asm, &[], None);
796         }
797     }
798
799     pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
800                          inputs: &[ValueRef], output: Type,
801                          volatile: bool, alignstack: bool,
802                          dia: AsmDialect) -> ValueRef {
803         self.count_insn("inlineasm");
804
805         let volatile = if volatile { llvm::True }
806                        else        { llvm::False };
807         let alignstack = if alignstack { llvm::True }
808                          else          { llvm::False };
809
810         let argtys = inputs.iter().map(|v| {
811             debug!("Asm Input Type: {}", self.ccx.tn().val_to_string(*v));
812             val_ty(*v)
813         }).collect::<Vec<_>>();
814
815         debug!("Asm Output Type: {}", self.ccx.tn().type_to_string(output));
816         let fty = Type::func(&argtys[..], &output);
817         unsafe {
818             let v = llvm::LLVMInlineAsm(
819                 fty.to_ref(), asm, cons, volatile, alignstack, dia as c_uint);
820             self.call(v, inputs, None)
821         }
822     }
823
824     pub fn call(&self, llfn: ValueRef, args: &[ValueRef],
825                 attributes: Option<AttrBuilder>) -> ValueRef {
826         self.count_insn("call");
827
828         debug!("Call {} with args ({})",
829                self.ccx.tn().val_to_string(llfn),
830                args.iter()
831                    .map(|&v| self.ccx.tn().val_to_string(v))
832                    .collect::<Vec<String>>()
833                    .connect(", "));
834
835         unsafe {
836             let v = llvm::LLVMBuildCall(self.llbuilder, llfn, args.as_ptr(),
837                                         args.len() as c_uint, noname());
838             match attributes {
839                 Some(a) => a.apply_callsite(v),
840                 None => {}
841             }
842             v
843         }
844     }
845
846     pub fn call_with_conv(&self, llfn: ValueRef, args: &[ValueRef],
847                           conv: CallConv, attributes: Option<AttrBuilder>) -> ValueRef {
848         self.count_insn("callwithconv");
849         let v = self.call(llfn, args, attributes);
850         llvm::SetInstructionCallConv(v, conv);
851         v
852     }
853
854     pub fn select(&self, cond: ValueRef, then_val: ValueRef, else_val: ValueRef) -> ValueRef {
855         self.count_insn("select");
856         unsafe {
857             llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
858         }
859     }
860
861     pub fn va_arg(&self, list: ValueRef, ty: Type) -> ValueRef {
862         self.count_insn("vaarg");
863         unsafe {
864             llvm::LLVMBuildVAArg(self.llbuilder, list, ty.to_ref(), noname())
865         }
866     }
867
868     pub fn extract_element(&self, vec: ValueRef, idx: ValueRef) -> ValueRef {
869         self.count_insn("extractelement");
870         unsafe {
871             llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
872         }
873     }
874
875     pub fn insert_element(&self, vec: ValueRef, elt: ValueRef, idx: ValueRef) -> ValueRef {
876         self.count_insn("insertelement");
877         unsafe {
878             llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
879         }
880     }
881
882     pub fn shuffle_vector(&self, v1: ValueRef, v2: ValueRef, mask: ValueRef) -> ValueRef {
883         self.count_insn("shufflevector");
884         unsafe {
885             llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
886         }
887     }
888
889     pub fn vector_splat(&self, num_elts: uint, elt: ValueRef) -> ValueRef {
890         unsafe {
891             let elt_ty = val_ty(elt);
892             let undef = llvm::LLVMGetUndef(Type::vector(&elt_ty, num_elts as u64).to_ref());
893             let vec = self.insert_element(undef, elt, C_i32(self.ccx, 0));
894             let vec_i32_ty = Type::vector(&Type::i32(self.ccx), num_elts as u64);
895             self.shuffle_vector(vec, undef, C_null(vec_i32_ty))
896         }
897     }
898
899     pub fn extract_value(&self, agg_val: ValueRef, idx: uint) -> ValueRef {
900         self.count_insn("extractvalue");
901         unsafe {
902             llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
903         }
904     }
905
906     pub fn insert_value(&self, agg_val: ValueRef, elt: ValueRef,
907                        idx: uint) -> ValueRef {
908         self.count_insn("insertvalue");
909         unsafe {
910             llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
911                                        noname())
912         }
913     }
914
915     pub fn is_null(&self, val: ValueRef) -> ValueRef {
916         self.count_insn("isnull");
917         unsafe {
918             llvm::LLVMBuildIsNull(self.llbuilder, val, noname())
919         }
920     }
921
922     pub fn is_not_null(&self, val: ValueRef) -> ValueRef {
923         self.count_insn("isnotnull");
924         unsafe {
925             llvm::LLVMBuildIsNotNull(self.llbuilder, val, noname())
926         }
927     }
928
929     pub fn ptrdiff(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
930         self.count_insn("ptrdiff");
931         unsafe {
932             llvm::LLVMBuildPtrDiff(self.llbuilder, lhs, rhs, noname())
933         }
934     }
935
936     pub fn trap(&self) {
937         unsafe {
938             let bb: BasicBlockRef = llvm::LLVMGetInsertBlock(self.llbuilder);
939             let fn_: ValueRef = llvm::LLVMGetBasicBlockParent(bb);
940             let m: ModuleRef = llvm::LLVMGetGlobalParent(fn_);
941             let p = "llvm.trap\0".as_ptr();
942             let t: ValueRef = llvm::LLVMGetNamedFunction(m, p as *const _);
943             assert!((t as int != 0));
944             let args: &[ValueRef] = &[];
945             self.count_insn("trap");
946             llvm::LLVMBuildCall(
947                 self.llbuilder, t, args.as_ptr(), args.len() as c_uint, noname());
948         }
949     }
950
951     pub fn landing_pad(&self, ty: Type, pers_fn: ValueRef, num_clauses: uint) -> ValueRef {
952         self.count_insn("landingpad");
953         unsafe {
954             llvm::LLVMBuildLandingPad(
955                 self.llbuilder, ty.to_ref(), pers_fn, num_clauses as c_uint, noname())
956         }
957     }
958
959     pub fn set_cleanup(&self, landing_pad: ValueRef) {
960         self.count_insn("setcleanup");
961         unsafe {
962             llvm::LLVMSetCleanup(landing_pad, llvm::True);
963         }
964     }
965
966     pub fn resume(&self, exn: ValueRef) -> ValueRef {
967         self.count_insn("resume");
968         unsafe {
969             llvm::LLVMBuildResume(self.llbuilder, exn)
970         }
971     }
972
973     // Atomic Operations
974     pub fn atomic_cmpxchg(&self, dst: ValueRef,
975                          cmp: ValueRef, src: ValueRef,
976                          order: AtomicOrdering,
977                          failure_order: AtomicOrdering) -> ValueRef {
978         unsafe {
979             llvm::LLVMBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
980                                          order, failure_order)
981         }
982     }
983     pub fn atomic_rmw(&self, op: AtomicBinOp,
984                      dst: ValueRef, src: ValueRef,
985                      order: AtomicOrdering) -> ValueRef {
986         unsafe {
987             llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False)
988         }
989     }
990
991     pub fn atomic_fence(&self, order: AtomicOrdering) {
992         unsafe {
993             llvm::LLVMBuildAtomicFence(self.llbuilder, order);
994         }
995     }
996 }