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