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