]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/builder.rs
497e0ae422c1fa3659c17eadb3e0140b518f5956
[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, SynchronizationScope, 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: usize) -> 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: usize) {
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) -> 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) -> 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             insn
533         }
534     }
535
536     pub fn atomic_store(&self, val: ValueRef, ptr: ValueRef, order: AtomicOrdering) {
537         debug!("Store {} -> {}",
538                self.ccx.tn().val_to_string(val),
539                self.ccx.tn().val_to_string(ptr));
540         self.count_insn("store.atomic");
541         unsafe {
542             let ty = Type::from_ref(llvm::LLVMTypeOf(ptr));
543             let align = llalign_of_pref(self.ccx, ty.element_type());
544             llvm::LLVMBuildAtomicStore(self.llbuilder, val, ptr, order, align as c_uint);
545         }
546     }
547
548     pub fn gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
549         self.count_insn("gep");
550         unsafe {
551             llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
552                                indices.len() as c_uint, noname())
553         }
554     }
555
556     // Simple wrapper around GEP that takes an array of ints and wraps them
557     // in C_i32()
558     #[inline]
559     pub fn gepi(&self, base: ValueRef, ixs: &[usize]) -> ValueRef {
560         // Small vector optimization. This should catch 100% of the cases that
561         // we care about.
562         if ixs.len() < 16 {
563             let mut small_vec = [ C_i32(self.ccx, 0); 16 ];
564             for (small_vec_e, &ix) in small_vec.iter_mut().zip(ixs.iter()) {
565                 *small_vec_e = C_i32(self.ccx, ix as i32);
566             }
567             self.inbounds_gep(base, &small_vec[..ixs.len()])
568         } else {
569             let v = ixs.iter().map(|i| C_i32(self.ccx, *i as i32)).collect::<Vec<ValueRef>>();
570             self.count_insn("gepi");
571             self.inbounds_gep(base, &v[..])
572         }
573     }
574
575     pub fn inbounds_gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
576         self.count_insn("inboundsgep");
577         unsafe {
578             llvm::LLVMBuildInBoundsGEP(
579                 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
580         }
581     }
582
583     pub fn struct_gep(&self, ptr: ValueRef, idx: usize) -> ValueRef {
584         self.count_insn("structgep");
585         unsafe {
586             llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
587         }
588     }
589
590     pub fn global_string(&self, _str: *const c_char) -> ValueRef {
591         self.count_insn("globalstring");
592         unsafe {
593             llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname())
594         }
595     }
596
597     pub fn global_string_ptr(&self, _str: *const c_char) -> ValueRef {
598         self.count_insn("globalstringptr");
599         unsafe {
600             llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname())
601         }
602     }
603
604     /* Casts */
605     pub fn trunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
606         self.count_insn("trunc");
607         unsafe {
608             llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
609         }
610     }
611
612     pub fn zext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
613         self.count_insn("zext");
614         unsafe {
615             llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty.to_ref(), noname())
616         }
617     }
618
619     pub fn sext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
620         self.count_insn("sext");
621         unsafe {
622             llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty.to_ref(), noname())
623         }
624     }
625
626     pub fn fptoui(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
627         self.count_insn("fptoui");
628         unsafe {
629             llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty.to_ref(), noname())
630         }
631     }
632
633     pub fn fptosi(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
634         self.count_insn("fptosi");
635         unsafe {
636             llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty.to_ref(),noname())
637         }
638     }
639
640     pub fn uitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
641         self.count_insn("uitofp");
642         unsafe {
643             llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
644         }
645     }
646
647     pub fn sitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
648         self.count_insn("sitofp");
649         unsafe {
650             llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
651         }
652     }
653
654     pub fn fptrunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
655         self.count_insn("fptrunc");
656         unsafe {
657             llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
658         }
659     }
660
661     pub fn fpext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
662         self.count_insn("fpext");
663         unsafe {
664             llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty.to_ref(), noname())
665         }
666     }
667
668     pub fn ptrtoint(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
669         self.count_insn("ptrtoint");
670         unsafe {
671             llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty.to_ref(), noname())
672         }
673     }
674
675     pub fn inttoptr(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
676         self.count_insn("inttoptr");
677         unsafe {
678             llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty.to_ref(), noname())
679         }
680     }
681
682     pub fn bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
683         self.count_insn("bitcast");
684         unsafe {
685             llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
686         }
687     }
688
689     pub fn zext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
690         self.count_insn("zextorbitcast");
691         unsafe {
692             llvm::LLVMBuildZExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
693         }
694     }
695
696     pub fn sext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
697         self.count_insn("sextorbitcast");
698         unsafe {
699             llvm::LLVMBuildSExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
700         }
701     }
702
703     pub fn trunc_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
704         self.count_insn("truncorbitcast");
705         unsafe {
706             llvm::LLVMBuildTruncOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
707         }
708     }
709
710     pub fn cast(&self, op: Opcode, val: ValueRef, dest_ty: Type) -> ValueRef {
711         self.count_insn("cast");
712         unsafe {
713             llvm::LLVMBuildCast(self.llbuilder, op, val, dest_ty.to_ref(), noname())
714         }
715     }
716
717     pub fn pointercast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
718         self.count_insn("pointercast");
719         unsafe {
720             llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty.to_ref(), noname())
721         }
722     }
723
724     pub fn intcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
725         self.count_insn("intcast");
726         unsafe {
727             llvm::LLVMBuildIntCast(self.llbuilder, val, dest_ty.to_ref(), noname())
728         }
729     }
730
731     pub fn fpcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
732         self.count_insn("fpcast");
733         unsafe {
734             llvm::LLVMBuildFPCast(self.llbuilder, val, dest_ty.to_ref(), noname())
735         }
736     }
737
738
739     /* Comparisons */
740     pub fn icmp(&self, op: IntPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
741         self.count_insn("icmp");
742         unsafe {
743             llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
744         }
745     }
746
747     pub fn fcmp(&self, op: RealPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
748         self.count_insn("fcmp");
749         unsafe {
750             llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
751         }
752     }
753
754     /* Miscellaneous instructions */
755     pub fn empty_phi(&self, ty: Type) -> ValueRef {
756         self.count_insn("emptyphi");
757         unsafe {
758             llvm::LLVMBuildPhi(self.llbuilder, ty.to_ref(), noname())
759         }
760     }
761
762     pub fn phi(&self, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef {
763         assert_eq!(vals.len(), bbs.len());
764         let phi = self.empty_phi(ty);
765         self.count_insn("addincoming");
766         unsafe {
767             llvm::LLVMAddIncoming(phi, vals.as_ptr(),
768                                   bbs.as_ptr(),
769                                   vals.len() as c_uint);
770             phi
771         }
772     }
773
774     pub fn add_span_comment(&self, sp: Span, text: &str) {
775         if self.ccx.sess().asm_comments() {
776             let s = format!("{} ({})",
777                             text,
778                             self.ccx.sess().codemap().span_to_string(sp));
779             debug!("{}", &s[..]);
780             self.add_comment(&s[..]);
781         }
782     }
783
784     pub fn add_comment(&self, text: &str) {
785         if self.ccx.sess().asm_comments() {
786             let sanitized = text.replace("$", "");
787             let comment_text = format!("{} {}", "#",
788                                        sanitized.replace("\n", "\n\t# "));
789             self.count_insn("inlineasm");
790             let comment_text = CString::new(comment_text).unwrap();
791             let asm = unsafe {
792                 llvm::LLVMConstInlineAsm(Type::func(&[], &Type::void(self.ccx)).to_ref(),
793                                          comment_text.as_ptr(), noname(), False,
794                                          False)
795             };
796             self.call(asm, &[], None);
797         }
798     }
799
800     pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
801                          inputs: &[ValueRef], output: Type,
802                          volatile: bool, alignstack: bool,
803                          dia: AsmDialect) -> ValueRef {
804         self.count_insn("inlineasm");
805
806         let volatile = if volatile { llvm::True }
807                        else        { llvm::False };
808         let alignstack = if alignstack { llvm::True }
809                          else          { llvm::False };
810
811         let argtys = inputs.iter().map(|v| {
812             debug!("Asm Input Type: {}", self.ccx.tn().val_to_string(*v));
813             val_ty(*v)
814         }).collect::<Vec<_>>();
815
816         debug!("Asm Output Type: {}", self.ccx.tn().type_to_string(output));
817         let fty = Type::func(&argtys[..], &output);
818         unsafe {
819             let v = llvm::LLVMInlineAsm(
820                 fty.to_ref(), asm, cons, volatile, alignstack, dia as c_uint);
821             self.call(v, inputs, None)
822         }
823     }
824
825     pub fn call(&self, llfn: ValueRef, args: &[ValueRef],
826                 attributes: Option<AttrBuilder>) -> ValueRef {
827         self.count_insn("call");
828
829         debug!("Call {} with args ({})",
830                self.ccx.tn().val_to_string(llfn),
831                args.iter()
832                    .map(|&v| self.ccx.tn().val_to_string(v))
833                    .collect::<Vec<String>>()
834                    .connect(", "));
835
836         unsafe {
837             let v = llvm::LLVMBuildCall(self.llbuilder, llfn, args.as_ptr(),
838                                         args.len() as c_uint, noname());
839             match attributes {
840                 Some(a) => a.apply_callsite(v),
841                 None => {}
842             }
843             v
844         }
845     }
846
847     pub fn call_with_conv(&self, llfn: ValueRef, args: &[ValueRef],
848                           conv: CallConv, attributes: Option<AttrBuilder>) -> ValueRef {
849         self.count_insn("callwithconv");
850         let v = self.call(llfn, args, attributes);
851         llvm::SetInstructionCallConv(v, conv);
852         v
853     }
854
855     pub fn select(&self, cond: ValueRef, then_val: ValueRef, else_val: ValueRef) -> ValueRef {
856         self.count_insn("select");
857         unsafe {
858             llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
859         }
860     }
861
862     pub fn va_arg(&self, list: ValueRef, ty: Type) -> ValueRef {
863         self.count_insn("vaarg");
864         unsafe {
865             llvm::LLVMBuildVAArg(self.llbuilder, list, ty.to_ref(), noname())
866         }
867     }
868
869     pub fn extract_element(&self, vec: ValueRef, idx: ValueRef) -> ValueRef {
870         self.count_insn("extractelement");
871         unsafe {
872             llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
873         }
874     }
875
876     pub fn insert_element(&self, vec: ValueRef, elt: ValueRef, idx: ValueRef) -> ValueRef {
877         self.count_insn("insertelement");
878         unsafe {
879             llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
880         }
881     }
882
883     pub fn shuffle_vector(&self, v1: ValueRef, v2: ValueRef, mask: ValueRef) -> ValueRef {
884         self.count_insn("shufflevector");
885         unsafe {
886             llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
887         }
888     }
889
890     pub fn vector_splat(&self, num_elts: usize, elt: ValueRef) -> ValueRef {
891         unsafe {
892             let elt_ty = val_ty(elt);
893             let undef = llvm::LLVMGetUndef(Type::vector(&elt_ty, num_elts as u64).to_ref());
894             let vec = self.insert_element(undef, elt, C_i32(self.ccx, 0));
895             let vec_i32_ty = Type::vector(&Type::i32(self.ccx), num_elts as u64);
896             self.shuffle_vector(vec, undef, C_null(vec_i32_ty))
897         }
898     }
899
900     pub fn extract_value(&self, agg_val: ValueRef, idx: usize) -> ValueRef {
901         self.count_insn("extractvalue");
902         unsafe {
903             llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
904         }
905     }
906
907     pub fn insert_value(&self, agg_val: ValueRef, elt: ValueRef,
908                        idx: usize) -> ValueRef {
909         self.count_insn("insertvalue");
910         unsafe {
911             llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
912                                        noname())
913         }
914     }
915
916     pub fn is_null(&self, val: ValueRef) -> ValueRef {
917         self.count_insn("isnull");
918         unsafe {
919             llvm::LLVMBuildIsNull(self.llbuilder, val, noname())
920         }
921     }
922
923     pub fn is_not_null(&self, val: ValueRef) -> ValueRef {
924         self.count_insn("isnotnull");
925         unsafe {
926             llvm::LLVMBuildIsNotNull(self.llbuilder, val, noname())
927         }
928     }
929
930     pub fn ptrdiff(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
931         self.count_insn("ptrdiff");
932         unsafe {
933             llvm::LLVMBuildPtrDiff(self.llbuilder, lhs, rhs, noname())
934         }
935     }
936
937     pub fn trap(&self) {
938         unsafe {
939             let bb: BasicBlockRef = llvm::LLVMGetInsertBlock(self.llbuilder);
940             let fn_: ValueRef = llvm::LLVMGetBasicBlockParent(bb);
941             let m: ModuleRef = llvm::LLVMGetGlobalParent(fn_);
942             let p = "llvm.trap\0".as_ptr();
943             let t: ValueRef = llvm::LLVMGetNamedFunction(m, p as *const _);
944             assert!((t as isize != 0));
945             let args: &[ValueRef] = &[];
946             self.count_insn("trap");
947             llvm::LLVMBuildCall(
948                 self.llbuilder, t, args.as_ptr(), args.len() as c_uint, noname());
949         }
950     }
951
952     pub fn landing_pad(&self, ty: Type, pers_fn: ValueRef, num_clauses: usize) -> ValueRef {
953         self.count_insn("landingpad");
954         unsafe {
955             llvm::LLVMBuildLandingPad(
956                 self.llbuilder, ty.to_ref(), pers_fn, num_clauses as c_uint, noname())
957         }
958     }
959
960     pub fn set_cleanup(&self, landing_pad: ValueRef) {
961         self.count_insn("setcleanup");
962         unsafe {
963             llvm::LLVMSetCleanup(landing_pad, llvm::True);
964         }
965     }
966
967     pub fn resume(&self, exn: ValueRef) -> ValueRef {
968         self.count_insn("resume");
969         unsafe {
970             llvm::LLVMBuildResume(self.llbuilder, exn)
971         }
972     }
973
974     // Atomic Operations
975     pub fn atomic_cmpxchg(&self, dst: ValueRef,
976                          cmp: ValueRef, src: ValueRef,
977                          order: AtomicOrdering,
978                          failure_order: AtomicOrdering) -> ValueRef {
979         unsafe {
980             llvm::LLVMBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
981                                          order, failure_order)
982         }
983     }
984     pub fn atomic_rmw(&self, op: AtomicBinOp,
985                      dst: ValueRef, src: ValueRef,
986                      order: AtomicOrdering) -> ValueRef {
987         unsafe {
988             llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False)
989         }
990     }
991
992     pub fn atomic_fence(&self, order: AtomicOrdering, scope: SynchronizationScope) {
993         unsafe {
994             llvm::LLVMBuildAtomicFence(self.llbuilder, order, scope);
995         }
996     }
997 }