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