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.
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.
11 #![allow(dead_code)] // FFI wrappers
14 use llvm::{AtomicRmwBinOp, AtomicOrdering, SynchronizationScope, AsmDialect};
15 use llvm::{Opcode, IntPredicate, RealPredicate, False, OperandBundleDef};
16 use llvm::{ValueRef, BasicBlockRef, BuilderRef, ModuleRef};
20 use libc::{c_uint, c_char};
21 use rustc::ty::TyCtxt;
22 use rustc::ty::layout::{Align, Size};
23 use rustc::session::{config, Session};
26 use std::ffi::CString;
31 // All Builders must have an llfn associated with them
33 pub struct Builder<'a, 'tcx: 'a> {
34 pub llbuilder: BuilderRef,
35 pub ccx: &'a CrateContext<'a, 'tcx>,
38 impl<'a, 'tcx> Drop for Builder<'a, 'tcx> {
41 llvm::LLVMDisposeBuilder(self.llbuilder);
46 // This is a really awful way to get a zero-length c-string, but better (and a
47 // lot more efficient) than doing str::as_c_str("", ...) every time.
48 fn noname() -> *const c_char {
49 static CNULL: c_char = 0;
53 impl<'a, 'tcx> Builder<'a, 'tcx> {
54 pub fn new_block<'b>(ccx: &'a CrateContext<'a, 'tcx>, llfn: ValueRef, name: &'b str) -> Self {
55 let builder = Builder::with_ccx(ccx);
57 let name = CString::new(name).unwrap();
58 llvm::LLVMAppendBasicBlockInContext(
64 builder.position_at_end(llbb);
68 pub fn with_ccx(ccx: &'a CrateContext<'a, 'tcx>) -> Self {
69 // Create a fresh builder from the crate context.
70 let llbuilder = unsafe {
71 llvm::LLVMCreateBuilderInContext(ccx.llcx())
79 pub fn build_sibling_block<'b>(&self, name: &'b str) -> Builder<'a, 'tcx> {
80 Builder::new_block(self.ccx, self.llfn(), name)
83 pub fn sess(&self) -> &Session {
87 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
91 pub fn llfn(&self) -> ValueRef {
93 llvm::LLVMGetBasicBlockParent(self.llbb())
97 pub fn llbb(&self) -> BasicBlockRef {
99 llvm::LLVMGetInsertBlock(self.llbuilder)
103 fn count_insn(&self, category: &str) {
104 if self.ccx.sess().trans_stats() {
105 self.ccx.stats().borrow_mut().n_llvm_insns += 1;
107 if self.ccx.sess().count_llvm_insns() {
111 .entry(category.to_string())
116 pub fn set_value_name(&self, value: ValueRef, name: &str) {
117 let cname = CString::new(name.as_bytes()).unwrap();
119 llvm::LLVMSetValueName(value, cname.as_ptr());
123 pub fn position_before(&self, insn: ValueRef) {
125 llvm::LLVMPositionBuilderBefore(self.llbuilder, insn);
129 pub fn position_at_end(&self, llbb: BasicBlockRef) {
131 llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
135 pub fn position_at_start(&self, llbb: BasicBlockRef) {
137 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
141 pub fn ret_void(&self) {
142 self.count_insn("retvoid");
144 llvm::LLVMBuildRetVoid(self.llbuilder);
148 pub fn ret(&self, v: ValueRef) {
149 self.count_insn("ret");
151 llvm::LLVMBuildRet(self.llbuilder, v);
155 pub fn aggregate_ret(&self, ret_vals: &[ValueRef]) {
157 llvm::LLVMBuildAggregateRet(self.llbuilder,
159 ret_vals.len() as c_uint);
163 pub fn br(&self, dest: BasicBlockRef) {
164 self.count_insn("br");
166 llvm::LLVMBuildBr(self.llbuilder, dest);
170 pub fn cond_br(&self, cond: ValueRef, then_llbb: BasicBlockRef, else_llbb: BasicBlockRef) {
171 self.count_insn("condbr");
173 llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
177 pub fn switch(&self, v: ValueRef, else_llbb: BasicBlockRef, num_cases: usize) -> ValueRef {
179 llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint)
183 pub fn indirect_br(&self, addr: ValueRef, num_dests: usize) {
184 self.count_insn("indirectbr");
186 llvm::LLVMBuildIndirectBr(self.llbuilder, addr, num_dests as c_uint);
194 catch: BasicBlockRef,
195 bundle: Option<&OperandBundleDef>) -> ValueRef {
196 self.count_insn("invoke");
198 debug!("Invoke {:?} with args ({})",
201 .map(|&v| format!("{:?}", Value(v)))
202 .collect::<Vec<String>>()
205 let args = self.check_call("invoke", llfn, args);
206 let bundle = bundle.as_ref().map(|b| b.raw()).unwrap_or(ptr::null_mut());
209 llvm::LLVMRustBuildInvoke(self.llbuilder,
212 args.len() as c_uint,
220 pub fn unreachable(&self) {
221 self.count_insn("unreachable");
223 llvm::LLVMBuildUnreachable(self.llbuilder);
228 pub fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
229 self.count_insn("add");
231 llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
235 pub fn nswadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
236 self.count_insn("nswadd");
238 llvm::LLVMBuildNSWAdd(self.llbuilder, lhs, rhs, noname())
242 pub fn nuwadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
243 self.count_insn("nuwadd");
245 llvm::LLVMBuildNUWAdd(self.llbuilder, lhs, rhs, noname())
249 pub fn fadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
250 self.count_insn("fadd");
252 llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
256 pub fn fadd_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
257 self.count_insn("fadd");
259 let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname());
260 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
265 pub fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
266 self.count_insn("sub");
268 llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
272 pub fn nswsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
273 self.count_insn("nwsub");
275 llvm::LLVMBuildNSWSub(self.llbuilder, lhs, rhs, noname())
279 pub fn nuwsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
280 self.count_insn("nuwsub");
282 llvm::LLVMBuildNUWSub(self.llbuilder, lhs, rhs, noname())
286 pub fn fsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
287 self.count_insn("sub");
289 llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
293 pub fn fsub_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
294 self.count_insn("sub");
296 let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname());
297 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
302 pub fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
303 self.count_insn("mul");
305 llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
309 pub fn nswmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
310 self.count_insn("nswmul");
312 llvm::LLVMBuildNSWMul(self.llbuilder, lhs, rhs, noname())
316 pub fn nuwmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
317 self.count_insn("nuwmul");
319 llvm::LLVMBuildNUWMul(self.llbuilder, lhs, rhs, noname())
323 pub fn fmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
324 self.count_insn("fmul");
326 llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
330 pub fn fmul_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
331 self.count_insn("fmul");
333 let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname());
334 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
340 pub fn udiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
341 self.count_insn("udiv");
343 llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
347 pub fn sdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
348 self.count_insn("sdiv");
350 llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
354 pub fn exactsdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
355 self.count_insn("exactsdiv");
357 llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
361 pub fn fdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
362 self.count_insn("fdiv");
364 llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
368 pub fn fdiv_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
369 self.count_insn("fdiv");
371 let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname());
372 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
377 pub fn urem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
378 self.count_insn("urem");
380 llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
384 pub fn srem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
385 self.count_insn("srem");
387 llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
391 pub fn frem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
392 self.count_insn("frem");
394 llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
398 pub fn frem_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
399 self.count_insn("frem");
401 let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname());
402 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
407 pub fn shl(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
408 self.count_insn("shl");
410 llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
414 pub fn lshr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
415 self.count_insn("lshr");
417 llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
421 pub fn ashr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
422 self.count_insn("ashr");
424 llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
428 pub fn and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
429 self.count_insn("and");
431 llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
435 pub fn or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
436 self.count_insn("or");
438 llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
442 pub fn xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
443 self.count_insn("xor");
445 llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
449 pub fn binop(&self, op: Opcode, lhs: ValueRef, rhs: ValueRef)
451 self.count_insn("binop");
453 llvm::LLVMBuildBinOp(self.llbuilder, op, lhs, rhs, noname())
457 pub fn neg(&self, v: ValueRef) -> ValueRef {
458 self.count_insn("neg");
460 llvm::LLVMBuildNeg(self.llbuilder, v, noname())
464 pub fn nswneg(&self, v: ValueRef) -> ValueRef {
465 self.count_insn("nswneg");
467 llvm::LLVMBuildNSWNeg(self.llbuilder, v, noname())
471 pub fn nuwneg(&self, v: ValueRef) -> ValueRef {
472 self.count_insn("nuwneg");
474 llvm::LLVMBuildNUWNeg(self.llbuilder, v, noname())
477 pub fn fneg(&self, v: ValueRef) -> ValueRef {
478 self.count_insn("fneg");
480 llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
484 pub fn not(&self, v: ValueRef) -> ValueRef {
485 self.count_insn("not");
487 llvm::LLVMBuildNot(self.llbuilder, v, noname())
491 pub fn alloca(&self, ty: Type, name: &str, align: Align) -> ValueRef {
492 let builder = Builder::with_ccx(self.ccx);
493 builder.position_at_start(unsafe {
494 llvm::LLVMGetFirstBasicBlock(self.llfn())
496 builder.dynamic_alloca(ty, name, align)
499 pub fn dynamic_alloca(&self, ty: Type, name: &str, align: Align) -> ValueRef {
500 self.count_insn("alloca");
502 let alloca = if name.is_empty() {
503 llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), noname())
505 let name = CString::new(name).unwrap();
506 llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(),
509 llvm::LLVMSetAlignment(alloca, align.abi() as c_uint);
514 pub fn free(&self, ptr: ValueRef) {
515 self.count_insn("free");
517 llvm::LLVMBuildFree(self.llbuilder, ptr);
521 pub fn load(&self, ptr: ValueRef, align: Option<Align>) -> ValueRef {
522 self.count_insn("load");
524 let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
525 if let Some(align) = align {
526 llvm::LLVMSetAlignment(load, align.abi() as c_uint);
532 pub fn volatile_load(&self, ptr: ValueRef) -> ValueRef {
533 self.count_insn("load.volatile");
535 let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
536 llvm::LLVMSetVolatile(insn, llvm::True);
541 pub fn atomic_load(&self, ptr: ValueRef, order: AtomicOrdering, align: Align) -> ValueRef {
542 self.count_insn("load.atomic");
544 let load = llvm::LLVMRustBuildAtomicLoad(self.llbuilder, ptr, noname(), order);
545 // FIXME(eddyb) Isn't it UB to use `pref` instead of `abi` here?
546 // However, 64-bit atomic loads on `i686-apple-darwin` appear to
547 // require `___atomic_load` with ABI-alignment, so it's staying.
548 llvm::LLVMSetAlignment(load, align.pref() as c_uint);
554 pub fn range_metadata(&self, load: ValueRef, range: Range<u128>) {
556 let llty = val_ty(load);
558 C_uint_big(llty, range.start),
559 C_uint_big(llty, range.end)
562 llvm::LLVMSetMetadata(load, llvm::MD_range as c_uint,
563 llvm::LLVMMDNodeInContext(self.ccx.llcx(),
569 pub fn nonnull_metadata(&self, load: ValueRef) {
571 llvm::LLVMSetMetadata(load, llvm::MD_nonnull as c_uint,
572 llvm::LLVMMDNodeInContext(self.ccx.llcx(), ptr::null(), 0));
576 pub fn store(&self, val: ValueRef, ptr: ValueRef, align: Option<Align>) -> ValueRef {
577 debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
578 assert!(!self.llbuilder.is_null());
579 self.count_insn("store");
580 let ptr = self.check_store(val, ptr);
582 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
583 if let Some(align) = align {
584 llvm::LLVMSetAlignment(store, align.abi() as c_uint);
590 pub fn volatile_store(&self, val: ValueRef, ptr: ValueRef) -> ValueRef {
591 debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
592 assert!(!self.llbuilder.is_null());
593 self.count_insn("store.volatile");
594 let ptr = self.check_store(val, ptr);
596 let insn = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
597 llvm::LLVMSetVolatile(insn, llvm::True);
602 pub fn atomic_store(&self, val: ValueRef, ptr: ValueRef,
603 order: AtomicOrdering, align: Align) {
604 debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
605 self.count_insn("store.atomic");
606 let ptr = self.check_store(val, ptr);
608 let store = llvm::LLVMRustBuildAtomicStore(self.llbuilder, val, ptr, order);
609 // FIXME(eddyb) Isn't it UB to use `pref` instead of `abi` here?
610 // Also see `atomic_load` for more context.
611 llvm::LLVMSetAlignment(store, align.pref() as c_uint);
615 pub fn nontemporal_store(&self, val: ValueRef, ptr: ValueRef) -> ValueRef {
616 debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
617 assert!(!self.llbuilder.is_null());
618 self.count_insn("store.nontemporal");
619 let ptr = self.check_store(val, ptr);
621 let insn = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
623 // According to LLVM [1] building a nontemporal store must *always*
624 // point to a metadata value of the integer 1. Who knew?
626 // [1]: http://llvm.org/docs/LangRef.html#store-instruction
627 let one = C_i32(self.ccx, 1);
628 let node = llvm::LLVMMDNodeInContext(self.ccx.llcx(),
631 llvm::LLVMSetMetadata(insn,
632 llvm::MD_nontemporal as c_uint,
638 pub fn gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
639 self.count_insn("gep");
641 llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
642 indices.len() as c_uint, noname())
646 pub fn inbounds_gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
647 self.count_insn("inboundsgep");
649 llvm::LLVMBuildInBoundsGEP(
650 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
654 pub fn struct_gep(&self, ptr: ValueRef, idx: u64) -> ValueRef {
655 self.count_insn("structgep");
656 assert_eq!(idx as c_uint as u64, idx);
658 llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
662 pub fn global_string(&self, _str: *const c_char) -> ValueRef {
663 self.count_insn("globalstring");
665 llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname())
669 pub fn global_string_ptr(&self, _str: *const c_char) -> ValueRef {
670 self.count_insn("globalstringptr");
672 llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname())
677 pub fn trunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
678 self.count_insn("trunc");
680 llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
684 pub fn zext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
685 self.count_insn("zext");
687 llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty.to_ref(), noname())
691 pub fn sext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
692 self.count_insn("sext");
694 llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty.to_ref(), noname())
698 pub fn fptoui(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
699 self.count_insn("fptoui");
701 llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty.to_ref(), noname())
705 pub fn fptosi(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
706 self.count_insn("fptosi");
708 llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty.to_ref(),noname())
712 pub fn uitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
713 self.count_insn("uitofp");
715 llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
719 pub fn sitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
720 self.count_insn("sitofp");
722 llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
726 pub fn fptrunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
727 self.count_insn("fptrunc");
729 llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
733 pub fn fpext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
734 self.count_insn("fpext");
736 llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty.to_ref(), noname())
740 pub fn ptrtoint(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
741 self.count_insn("ptrtoint");
743 llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty.to_ref(), noname())
747 pub fn inttoptr(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
748 self.count_insn("inttoptr");
750 llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty.to_ref(), noname())
754 pub fn bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
755 self.count_insn("bitcast");
757 llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
761 pub fn zext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
762 self.count_insn("zextorbitcast");
764 llvm::LLVMBuildZExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
768 pub fn sext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
769 self.count_insn("sextorbitcast");
771 llvm::LLVMBuildSExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
775 pub fn trunc_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
776 self.count_insn("truncorbitcast");
778 llvm::LLVMBuildTruncOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
782 pub fn cast(&self, op: Opcode, val: ValueRef, dest_ty: Type) -> ValueRef {
783 self.count_insn("cast");
785 llvm::LLVMBuildCast(self.llbuilder, op, val, dest_ty.to_ref(), noname())
789 pub fn pointercast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
790 self.count_insn("pointercast");
792 llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty.to_ref(), noname())
796 pub fn intcast(&self, val: ValueRef, dest_ty: Type, is_signed: bool) -> ValueRef {
797 self.count_insn("intcast");
799 llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty.to_ref(), is_signed)
803 pub fn fpcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
804 self.count_insn("fpcast");
806 llvm::LLVMBuildFPCast(self.llbuilder, val, dest_ty.to_ref(), noname())
812 pub fn icmp(&self, op: IntPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
813 self.count_insn("icmp");
815 llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
819 pub fn fcmp(&self, op: RealPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
820 self.count_insn("fcmp");
822 llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
826 /* Miscellaneous instructions */
827 pub fn empty_phi(&self, ty: Type) -> ValueRef {
828 self.count_insn("emptyphi");
830 llvm::LLVMBuildPhi(self.llbuilder, ty.to_ref(), noname())
834 pub fn phi(&self, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef {
835 assert_eq!(vals.len(), bbs.len());
836 let phi = self.empty_phi(ty);
837 self.count_insn("addincoming");
839 llvm::LLVMAddIncoming(phi, vals.as_ptr(),
841 vals.len() as c_uint);
846 pub fn add_span_comment(&self, sp: Span, text: &str) {
847 if self.ccx.sess().asm_comments() {
848 let s = format!("{} ({})",
850 self.ccx.sess().codemap().span_to_string(sp));
852 self.add_comment(&s);
856 pub fn add_comment(&self, text: &str) {
857 if self.ccx.sess().asm_comments() {
858 let sanitized = text.replace("$", "");
859 let comment_text = format!("{} {}", "#",
860 sanitized.replace("\n", "\n\t# "));
861 self.count_insn("inlineasm");
862 let comment_text = CString::new(comment_text).unwrap();
864 llvm::LLVMConstInlineAsm(Type::func(&[], &Type::void(self.ccx)).to_ref(),
865 comment_text.as_ptr(), noname(), False,
868 self.call(asm, &[], None);
872 pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
873 inputs: &[ValueRef], output: Type,
874 volatile: bool, alignstack: bool,
875 dia: AsmDialect) -> ValueRef {
876 self.count_insn("inlineasm");
878 let volatile = if volatile { llvm::True }
879 else { llvm::False };
880 let alignstack = if alignstack { llvm::True }
881 else { llvm::False };
883 let argtys = inputs.iter().map(|v| {
884 debug!("Asm Input Type: {:?}", Value(*v));
886 }).collect::<Vec<_>>();
888 debug!("Asm Output Type: {:?}", output);
889 let fty = Type::func(&argtys[..], &output);
891 let v = llvm::LLVMRustInlineAsm(
892 fty.to_ref(), asm, cons, volatile, alignstack, dia);
893 self.call(v, inputs, None)
897 pub fn call(&self, llfn: ValueRef, args: &[ValueRef],
898 bundle: Option<&OperandBundleDef>) -> ValueRef {
899 self.count_insn("call");
901 debug!("Call {:?} with args ({})",
904 .map(|&v| format!("{:?}", Value(v)))
905 .collect::<Vec<String>>()
908 let args = self.check_call("call", llfn, args);
909 let bundle = bundle.as_ref().map(|b| b.raw()).unwrap_or(ptr::null_mut());
912 llvm::LLVMRustBuildCall(self.llbuilder, llfn, args.as_ptr(),
913 args.len() as c_uint, bundle, noname())
917 pub fn select(&self, cond: ValueRef, then_val: ValueRef, else_val: ValueRef) -> ValueRef {
918 self.count_insn("select");
920 llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
924 pub fn va_arg(&self, list: ValueRef, ty: Type) -> ValueRef {
925 self.count_insn("vaarg");
927 llvm::LLVMBuildVAArg(self.llbuilder, list, ty.to_ref(), noname())
931 pub fn extract_element(&self, vec: ValueRef, idx: ValueRef) -> ValueRef {
932 self.count_insn("extractelement");
934 llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
938 pub fn insert_element(&self, vec: ValueRef, elt: ValueRef, idx: ValueRef) -> ValueRef {
939 self.count_insn("insertelement");
941 llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
945 pub fn shuffle_vector(&self, v1: ValueRef, v2: ValueRef, mask: ValueRef) -> ValueRef {
946 self.count_insn("shufflevector");
948 llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
952 pub fn vector_splat(&self, num_elts: usize, elt: ValueRef) -> ValueRef {
954 let elt_ty = val_ty(elt);
955 let undef = llvm::LLVMGetUndef(Type::vector(&elt_ty, num_elts as u64).to_ref());
956 let vec = self.insert_element(undef, elt, C_i32(self.ccx, 0));
957 let vec_i32_ty = Type::vector(&Type::i32(self.ccx), num_elts as u64);
958 self.shuffle_vector(vec, undef, C_null(vec_i32_ty))
962 pub fn extract_value(&self, agg_val: ValueRef, idx: u64) -> ValueRef {
963 self.count_insn("extractvalue");
964 assert_eq!(idx as c_uint as u64, idx);
966 llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
970 pub fn insert_value(&self, agg_val: ValueRef, elt: ValueRef,
971 idx: u64) -> ValueRef {
972 self.count_insn("insertvalue");
973 assert_eq!(idx as c_uint as u64, idx);
975 llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
980 pub fn is_null(&self, val: ValueRef) -> ValueRef {
981 self.count_insn("isnull");
983 llvm::LLVMBuildIsNull(self.llbuilder, val, noname())
987 pub fn is_not_null(&self, val: ValueRef) -> ValueRef {
988 self.count_insn("isnotnull");
990 llvm::LLVMBuildIsNotNull(self.llbuilder, val, noname())
994 pub fn ptrdiff(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
995 self.count_insn("ptrdiff");
997 llvm::LLVMBuildPtrDiff(self.llbuilder, lhs, rhs, noname())
1001 pub fn trap(&self) {
1003 let bb: BasicBlockRef = llvm::LLVMGetInsertBlock(self.llbuilder);
1004 let fn_: ValueRef = llvm::LLVMGetBasicBlockParent(bb);
1005 let m: ModuleRef = llvm::LLVMGetGlobalParent(fn_);
1006 let p = "llvm.trap\0".as_ptr();
1007 let t: ValueRef = llvm::LLVMGetNamedFunction(m, p as *const _);
1008 assert!((t as isize != 0));
1009 let args: &[ValueRef] = &[];
1010 self.count_insn("trap");
1011 llvm::LLVMRustBuildCall(self.llbuilder, t,
1012 args.as_ptr(), args.len() as c_uint,
1018 pub fn landing_pad(&self, ty: Type, pers_fn: ValueRef,
1020 llfn: ValueRef) -> ValueRef {
1021 self.count_insn("landingpad");
1023 llvm::LLVMRustBuildLandingPad(self.llbuilder, ty.to_ref(), pers_fn,
1024 num_clauses as c_uint, noname(), llfn)
1028 pub fn add_clause(&self, landing_pad: ValueRef, clause: ValueRef) {
1030 llvm::LLVMAddClause(landing_pad, clause);
1034 pub fn set_cleanup(&self, landing_pad: ValueRef) {
1035 self.count_insn("setcleanup");
1037 llvm::LLVMSetCleanup(landing_pad, llvm::True);
1041 pub fn resume(&self, exn: ValueRef) -> ValueRef {
1042 self.count_insn("resume");
1044 llvm::LLVMBuildResume(self.llbuilder, exn)
1048 pub fn cleanup_pad(&self,
1049 parent: Option<ValueRef>,
1050 args: &[ValueRef]) -> ValueRef {
1051 self.count_insn("cleanuppad");
1052 let parent = parent.unwrap_or(ptr::null_mut());
1053 let name = CString::new("cleanuppad").unwrap();
1055 llvm::LLVMRustBuildCleanupPad(self.llbuilder,
1057 args.len() as c_uint,
1061 assert!(!ret.is_null(), "LLVM does not have support for cleanuppad");
1065 pub fn cleanup_ret(&self, cleanup: ValueRef,
1066 unwind: Option<BasicBlockRef>) -> ValueRef {
1067 self.count_insn("cleanupret");
1068 let unwind = unwind.unwrap_or(ptr::null_mut());
1070 llvm::LLVMRustBuildCleanupRet(self.llbuilder, cleanup, unwind)
1072 assert!(!ret.is_null(), "LLVM does not have support for cleanupret");
1076 pub fn catch_pad(&self,
1078 args: &[ValueRef]) -> ValueRef {
1079 self.count_insn("catchpad");
1080 let name = CString::new("catchpad").unwrap();
1082 llvm::LLVMRustBuildCatchPad(self.llbuilder, parent,
1083 args.len() as c_uint, args.as_ptr(),
1086 assert!(!ret.is_null(), "LLVM does not have support for catchpad");
1090 pub fn catch_ret(&self, pad: ValueRef, unwind: BasicBlockRef) -> ValueRef {
1091 self.count_insn("catchret");
1093 llvm::LLVMRustBuildCatchRet(self.llbuilder, pad, unwind)
1095 assert!(!ret.is_null(), "LLVM does not have support for catchret");
1099 pub fn catch_switch(&self,
1100 parent: Option<ValueRef>,
1101 unwind: Option<BasicBlockRef>,
1102 num_handlers: usize) -> ValueRef {
1103 self.count_insn("catchswitch");
1104 let parent = parent.unwrap_or(ptr::null_mut());
1105 let unwind = unwind.unwrap_or(ptr::null_mut());
1106 let name = CString::new("catchswitch").unwrap();
1108 llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind,
1109 num_handlers as c_uint,
1112 assert!(!ret.is_null(), "LLVM does not have support for catchswitch");
1116 pub fn add_handler(&self, catch_switch: ValueRef, handler: BasicBlockRef) {
1118 llvm::LLVMRustAddHandler(catch_switch, handler);
1122 pub fn set_personality_fn(&self, personality: ValueRef) {
1124 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1128 // Atomic Operations
1129 pub fn atomic_cmpxchg(&self, dst: ValueRef,
1130 cmp: ValueRef, src: ValueRef,
1131 order: AtomicOrdering,
1132 failure_order: AtomicOrdering,
1133 weak: llvm::Bool) -> ValueRef {
1135 llvm::LLVMRustBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
1136 order, failure_order, weak)
1139 pub fn atomic_rmw(&self, op: AtomicRmwBinOp,
1140 dst: ValueRef, src: ValueRef,
1141 order: AtomicOrdering) -> ValueRef {
1143 llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False)
1147 pub fn atomic_fence(&self, order: AtomicOrdering, scope: SynchronizationScope) {
1149 llvm::LLVMRustBuildAtomicFence(self.llbuilder, order, scope);
1153 pub fn add_case(&self, s: ValueRef, on_val: ValueRef, dest: BasicBlockRef) {
1155 llvm::LLVMAddCase(s, on_val, dest)
1159 pub fn add_incoming_to_phi(&self, phi: ValueRef, val: ValueRef, bb: BasicBlockRef) {
1161 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1165 pub fn set_invariant_load(&self, load: ValueRef) {
1167 llvm::LLVMSetMetadata(load, llvm::MD_invariant_load as c_uint,
1168 llvm::LLVMMDNodeInContext(self.ccx.llcx(), ptr::null(), 0));
1172 /// Returns the ptr value that should be used for storing `val`.
1173 fn check_store<'b>(&self,
1175 ptr: ValueRef) -> ValueRef {
1176 let dest_ptr_ty = val_ty(ptr);
1177 let stored_ty = val_ty(val);
1178 let stored_ptr_ty = stored_ty.ptr_to();
1180 assert_eq!(dest_ptr_ty.kind(), llvm::TypeKind::Pointer);
1182 if dest_ptr_ty == stored_ptr_ty {
1185 debug!("Type mismatch in store. \
1186 Expected {:?}, got {:?}; inserting bitcast",
1187 dest_ptr_ty, stored_ptr_ty);
1188 self.bitcast(ptr, stored_ptr_ty)
1192 /// Returns the args that should be used for a call to `llfn`.
1193 fn check_call<'b>(&self,
1196 args: &'b [ValueRef]) -> Cow<'b, [ValueRef]> {
1197 let mut fn_ty = val_ty(llfn);
1198 // Strip off pointers
1199 while fn_ty.kind() == llvm::TypeKind::Pointer {
1200 fn_ty = fn_ty.element_type();
1203 assert!(fn_ty.kind() == llvm::TypeKind::Function,
1204 "builder::{} not passed a function, but {:?}", typ, fn_ty);
1206 let param_tys = fn_ty.func_params();
1208 let all_args_match = param_tys.iter()
1209 .zip(args.iter().map(|&v| val_ty(v)))
1210 .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1213 return Cow::Borrowed(args);
1216 let casted_args: Vec<_> = param_tys.into_iter()
1219 .map(|(i, (expected_ty, &actual_val))| {
1220 let actual_ty = val_ty(actual_val);
1221 if expected_ty != actual_ty {
1222 debug!("Type mismatch in function call of {:?}. \
1223 Expected {:?} for param {}, got {:?}; injecting bitcast",
1225 expected_ty, i, actual_ty);
1226 self.bitcast(actual_val, expected_ty)
1233 return Cow::Owned(casted_args);
1236 pub fn lifetime_start(&self, ptr: ValueRef, size: Size) {
1237 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1240 pub fn lifetime_end(&self, ptr: ValueRef, size: Size) {
1241 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1244 /// If LLVM lifetime intrinsic support is enabled (i.e. optimizations
1245 /// on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
1246 /// and the intrinsic for `lt` and passes them to `emit`, which is in
1247 /// charge of generating code to call the passed intrinsic on whatever
1248 /// block of generated code is targetted for the intrinsic.
1250 /// If LLVM lifetime intrinsic support is disabled (i.e. optimizations
1251 /// off) or `ptr` is zero-sized, then no-op (does not call `emit`).
1252 fn call_lifetime_intrinsic(&self, intrinsic: &str, ptr: ValueRef, size: Size) {
1253 if self.ccx.sess().opts.optimize == config::OptLevel::No {
1257 let size = size.bytes();
1262 let lifetime_intrinsic = self.ccx.get_intrinsic(intrinsic);
1264 let ptr = self.pointercast(ptr, Type::i8p(self.ccx));
1265 self.call(lifetime_intrinsic, &[C_u64(self.ccx, size), ptr], None);