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::{AtomicBinOp, AtomicOrdering, SynchronizationScope, AsmDialect};
15 use llvm::{Opcode, IntPredicate, RealPredicate, False, OperandBundleDef};
16 use llvm::{ValueRef, BasicBlockRef, BuilderRef, ModuleRef};
19 use machine::llalign_of_pref;
22 use util::nodemap::FnvHashMap;
23 use libc::{c_uint, c_char};
25 use std::ffi::CString;
29 pub struct Builder<'a, 'tcx: 'a> {
30 pub llbuilder: BuilderRef,
31 pub ccx: &'a CrateContext<'a, 'tcx>,
34 // This is a really awful way to get a zero-length c-string, but better (and a
35 // lot more efficient) than doing str::as_c_str("", ...) every time.
36 pub fn noname() -> *const c_char {
37 static CNULL: c_char = 0;
41 impl<'a, 'tcx> Builder<'a, 'tcx> {
42 pub fn new(ccx: &'a CrateContext<'a, 'tcx>) -> Builder<'a, 'tcx> {
44 llbuilder: ccx.raw_builder(),
49 pub fn count_insn(&self, category: &str) {
50 if self.ccx.sess().trans_stats() {
51 self.ccx.stats().n_llvm_insns.set(self.ccx
56 self.ccx.count_llvm_insn();
57 if self.ccx.sess().count_llvm_insns() {
58 base::with_insn_ctxt(|v| {
59 let mut h = self.ccx.stats().llvm_insns.borrow_mut();
61 // Build version of path with cycles removed.
63 // Pass 1: scan table mapping str -> rightmost pos.
64 let mut mm = FnvHashMap();
72 // Pass 2: concat strings for each elt, skipping
73 // forwards over any cycles by advancing to rightmost
74 // occurrence of each element in path.
75 let mut s = String::from(".");
87 let n = match h.get(&s) {
96 pub fn position_before(&self, insn: ValueRef) {
98 llvm::LLVMPositionBuilderBefore(self.llbuilder, insn);
102 pub fn position_at_end(&self, llbb: BasicBlockRef) {
104 llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
108 pub fn position_at_start(&self, llbb: BasicBlockRef) {
110 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
114 pub fn ret_void(&self) {
115 self.count_insn("retvoid");
117 llvm::LLVMBuildRetVoid(self.llbuilder);
121 pub fn ret(&self, v: ValueRef) {
122 self.count_insn("ret");
124 llvm::LLVMBuildRet(self.llbuilder, v);
128 pub fn aggregate_ret(&self, ret_vals: &[ValueRef]) {
130 llvm::LLVMBuildAggregateRet(self.llbuilder,
132 ret_vals.len() as c_uint);
136 pub fn br(&self, dest: BasicBlockRef) {
137 self.count_insn("br");
139 llvm::LLVMBuildBr(self.llbuilder, dest);
143 pub fn cond_br(&self, cond: ValueRef, then_llbb: BasicBlockRef, else_llbb: BasicBlockRef) {
144 self.count_insn("condbr");
146 llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
150 pub fn switch(&self, v: ValueRef, else_llbb: BasicBlockRef, num_cases: usize) -> ValueRef {
152 llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint)
156 pub fn indirect_br(&self, addr: ValueRef, num_dests: usize) {
157 self.count_insn("indirectbr");
159 llvm::LLVMBuildIndirectBr(self.llbuilder, addr, num_dests as c_uint);
167 catch: BasicBlockRef,
168 bundle: Option<&OperandBundleDef>) -> ValueRef {
169 self.count_insn("invoke");
171 debug!("Invoke {:?} with args ({})",
174 .map(|&v| format!("{:?}", Value(v)))
175 .collect::<Vec<String>>()
178 check_call("invoke", llfn, args);
180 let bundle = bundle.as_ref().map(|b| b.raw()).unwrap_or(ptr::null_mut());
183 llvm::LLVMRustBuildInvoke(self.llbuilder,
186 args.len() as c_uint,
194 pub fn unreachable(&self) {
195 self.count_insn("unreachable");
197 llvm::LLVMBuildUnreachable(self.llbuilder);
202 pub fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
203 self.count_insn("add");
205 llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
209 pub fn nswadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
210 self.count_insn("nswadd");
212 llvm::LLVMBuildNSWAdd(self.llbuilder, lhs, rhs, noname())
216 pub fn nuwadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
217 self.count_insn("nuwadd");
219 llvm::LLVMBuildNUWAdd(self.llbuilder, lhs, rhs, noname())
223 pub fn fadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
224 self.count_insn("fadd");
226 llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
230 pub fn fadd_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
231 self.count_insn("fadd");
233 let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname());
234 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
239 pub fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
240 self.count_insn("sub");
242 llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
246 pub fn nswsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
247 self.count_insn("nwsub");
249 llvm::LLVMBuildNSWSub(self.llbuilder, lhs, rhs, noname())
253 pub fn nuwsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
254 self.count_insn("nuwsub");
256 llvm::LLVMBuildNUWSub(self.llbuilder, lhs, rhs, noname())
260 pub fn fsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
261 self.count_insn("sub");
263 llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
267 pub fn fsub_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
268 self.count_insn("sub");
270 let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname());
271 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
276 pub fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
277 self.count_insn("mul");
279 llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
283 pub fn nswmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
284 self.count_insn("nswmul");
286 llvm::LLVMBuildNSWMul(self.llbuilder, lhs, rhs, noname())
290 pub fn nuwmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
291 self.count_insn("nuwmul");
293 llvm::LLVMBuildNUWMul(self.llbuilder, lhs, rhs, noname())
297 pub fn fmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
298 self.count_insn("fmul");
300 llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
304 pub fn fmul_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
305 self.count_insn("fmul");
307 let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname());
308 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
314 pub fn udiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
315 self.count_insn("udiv");
317 llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
321 pub fn sdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
322 self.count_insn("sdiv");
324 llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
328 pub fn exactsdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
329 self.count_insn("exactsdiv");
331 llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
335 pub fn fdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
336 self.count_insn("fdiv");
338 llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
342 pub fn fdiv_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
343 self.count_insn("fdiv");
345 let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname());
346 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
351 pub fn urem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
352 self.count_insn("urem");
354 llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
358 pub fn srem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
359 self.count_insn("srem");
361 llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
365 pub fn frem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
366 self.count_insn("frem");
368 llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
372 pub fn frem_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
373 self.count_insn("frem");
375 let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname());
376 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
381 pub fn shl(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
382 self.count_insn("shl");
384 llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
388 pub fn lshr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
389 self.count_insn("lshr");
391 llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
395 pub fn ashr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
396 self.count_insn("ashr");
398 llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
402 pub fn and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
403 self.count_insn("and");
405 llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
409 pub fn or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
410 self.count_insn("or");
412 llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
416 pub fn xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
417 self.count_insn("xor");
419 llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
423 pub fn binop(&self, op: Opcode, lhs: ValueRef, rhs: ValueRef)
425 self.count_insn("binop");
427 llvm::LLVMBuildBinOp(self.llbuilder, op, lhs, rhs, noname())
431 pub fn neg(&self, v: ValueRef) -> ValueRef {
432 self.count_insn("neg");
434 llvm::LLVMBuildNeg(self.llbuilder, v, noname())
438 pub fn nswneg(&self, v: ValueRef) -> ValueRef {
439 self.count_insn("nswneg");
441 llvm::LLVMBuildNSWNeg(self.llbuilder, v, noname())
445 pub fn nuwneg(&self, v: ValueRef) -> ValueRef {
446 self.count_insn("nuwneg");
448 llvm::LLVMBuildNUWNeg(self.llbuilder, v, noname())
451 pub fn fneg(&self, v: ValueRef) -> ValueRef {
452 self.count_insn("fneg");
454 llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
458 pub fn not(&self, v: ValueRef) -> ValueRef {
459 self.count_insn("not");
461 llvm::LLVMBuildNot(self.llbuilder, v, noname())
465 pub fn alloca(&self, ty: Type, name: &str) -> ValueRef {
466 self.count_insn("alloca");
469 llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), noname())
471 let name = CString::new(name).unwrap();
472 llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(),
478 pub fn free(&self, ptr: ValueRef) {
479 self.count_insn("free");
481 llvm::LLVMBuildFree(self.llbuilder, ptr);
485 pub fn load(&self, ptr: ValueRef) -> ValueRef {
486 self.count_insn("load");
488 llvm::LLVMBuildLoad(self.llbuilder, ptr, noname())
492 pub fn volatile_load(&self, ptr: ValueRef) -> ValueRef {
493 self.count_insn("load.volatile");
495 let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
496 llvm::LLVMSetVolatile(insn, llvm::True);
501 pub fn atomic_load(&self, ptr: ValueRef, order: AtomicOrdering) -> ValueRef {
502 self.count_insn("load.atomic");
504 let ty = Type::from_ref(llvm::LLVMTypeOf(ptr));
505 let align = llalign_of_pref(self.ccx, ty.element_type());
506 llvm::LLVMBuildAtomicLoad(self.llbuilder, ptr, noname(), order,
512 pub fn load_range_assert(&self, ptr: ValueRef, lo: u64,
513 hi: u64, signed: llvm::Bool) -> ValueRef {
514 let value = self.load(ptr);
517 let t = llvm::LLVMGetElementType(llvm::LLVMTypeOf(ptr));
518 let min = llvm::LLVMConstInt(t, lo, signed);
519 let max = llvm::LLVMConstInt(t, hi, signed);
523 llvm::LLVMSetMetadata(value, llvm::MD_range as c_uint,
524 llvm::LLVMMDNodeInContext(self.ccx.llcx(),
532 pub fn load_nonnull(&self, ptr: ValueRef) -> ValueRef {
533 let value = self.load(ptr);
535 llvm::LLVMSetMetadata(value, llvm::MD_nonnull as c_uint,
536 llvm::LLVMMDNodeInContext(self.ccx.llcx(), ptr::null(), 0));
542 pub fn store(&self, val: ValueRef, ptr: ValueRef) -> ValueRef {
543 debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
544 assert!(!self.llbuilder.is_null());
545 self.count_insn("store");
547 llvm::LLVMBuildStore(self.llbuilder, val, ptr)
551 pub fn volatile_store(&self, val: ValueRef, ptr: ValueRef) -> ValueRef {
552 debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
553 assert!(!self.llbuilder.is_null());
554 self.count_insn("store.volatile");
556 let insn = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
557 llvm::LLVMSetVolatile(insn, llvm::True);
562 pub fn atomic_store(&self, val: ValueRef, ptr: ValueRef, order: AtomicOrdering) {
563 debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
564 self.count_insn("store.atomic");
566 let ty = Type::from_ref(llvm::LLVMTypeOf(ptr));
567 let align = llalign_of_pref(self.ccx, ty.element_type());
568 llvm::LLVMBuildAtomicStore(self.llbuilder, val, ptr, order, align as c_uint);
572 pub fn gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
573 self.count_insn("gep");
575 llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
576 indices.len() as c_uint, noname())
580 // Simple wrapper around GEP that takes an array of ints and wraps them
583 pub fn gepi(&self, base: ValueRef, ixs: &[usize]) -> ValueRef {
584 // Small vector optimization. This should catch 100% of the cases that
587 let mut small_vec = [ C_i32(self.ccx, 0); 16 ];
588 for (small_vec_e, &ix) in small_vec.iter_mut().zip(ixs) {
589 *small_vec_e = C_i32(self.ccx, ix as i32);
591 self.inbounds_gep(base, &small_vec[..ixs.len()])
593 let v = ixs.iter().map(|i| C_i32(self.ccx, *i as i32)).collect::<Vec<ValueRef>>();
594 self.count_insn("gepi");
595 self.inbounds_gep(base, &v[..])
599 pub fn inbounds_gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
600 self.count_insn("inboundsgep");
602 llvm::LLVMBuildInBoundsGEP(
603 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
607 pub fn struct_gep(&self, ptr: ValueRef, idx: usize) -> ValueRef {
608 self.count_insn("structgep");
610 llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
614 pub fn global_string(&self, _str: *const c_char) -> ValueRef {
615 self.count_insn("globalstring");
617 llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname())
621 pub fn global_string_ptr(&self, _str: *const c_char) -> ValueRef {
622 self.count_insn("globalstringptr");
624 llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname())
629 pub fn trunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
630 self.count_insn("trunc");
632 llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
636 pub fn zext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
637 self.count_insn("zext");
639 llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty.to_ref(), noname())
643 pub fn sext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
644 self.count_insn("sext");
646 llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty.to_ref(), noname())
650 pub fn fptoui(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
651 self.count_insn("fptoui");
653 llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty.to_ref(), noname())
657 pub fn fptosi(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
658 self.count_insn("fptosi");
660 llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty.to_ref(),noname())
664 pub fn uitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
665 self.count_insn("uitofp");
667 llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
671 pub fn sitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
672 self.count_insn("sitofp");
674 llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
678 pub fn fptrunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
679 self.count_insn("fptrunc");
681 llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
685 pub fn fpext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
686 self.count_insn("fpext");
688 llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty.to_ref(), noname())
692 pub fn ptrtoint(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
693 self.count_insn("ptrtoint");
695 llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty.to_ref(), noname())
699 pub fn inttoptr(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
700 self.count_insn("inttoptr");
702 llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty.to_ref(), noname())
706 pub fn bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
707 self.count_insn("bitcast");
709 llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
713 pub fn zext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
714 self.count_insn("zextorbitcast");
716 llvm::LLVMBuildZExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
720 pub fn sext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
721 self.count_insn("sextorbitcast");
723 llvm::LLVMBuildSExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
727 pub fn trunc_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
728 self.count_insn("truncorbitcast");
730 llvm::LLVMBuildTruncOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
734 pub fn cast(&self, op: Opcode, val: ValueRef, dest_ty: Type) -> ValueRef {
735 self.count_insn("cast");
737 llvm::LLVMBuildCast(self.llbuilder, op, val, dest_ty.to_ref(), noname())
741 pub fn pointercast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
742 self.count_insn("pointercast");
744 llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty.to_ref(), noname())
748 pub fn intcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
749 self.count_insn("intcast");
751 llvm::LLVMBuildIntCast(self.llbuilder, val, dest_ty.to_ref(), noname())
755 pub fn fpcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
756 self.count_insn("fpcast");
758 llvm::LLVMBuildFPCast(self.llbuilder, val, dest_ty.to_ref(), noname())
764 pub fn icmp(&self, op: IntPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
765 self.count_insn("icmp");
767 llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
771 pub fn fcmp(&self, op: RealPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
772 self.count_insn("fcmp");
774 llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
778 /* Miscellaneous instructions */
779 pub fn empty_phi(&self, ty: Type) -> ValueRef {
780 self.count_insn("emptyphi");
782 llvm::LLVMBuildPhi(self.llbuilder, ty.to_ref(), noname())
786 pub fn phi(&self, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef {
787 assert_eq!(vals.len(), bbs.len());
788 let phi = self.empty_phi(ty);
789 self.count_insn("addincoming");
791 llvm::LLVMAddIncoming(phi, vals.as_ptr(),
793 vals.len() as c_uint);
798 pub fn add_span_comment(&self, sp: Span, text: &str) {
799 if self.ccx.sess().asm_comments() {
800 let s = format!("{} ({})",
802 self.ccx.sess().codemap().span_to_string(sp));
803 debug!("{}", &s[..]);
804 self.add_comment(&s[..]);
808 pub fn add_comment(&self, text: &str) {
809 if self.ccx.sess().asm_comments() {
810 let sanitized = text.replace("$", "");
811 let comment_text = format!("{} {}", "#",
812 sanitized.replace("\n", "\n\t# "));
813 self.count_insn("inlineasm");
814 let comment_text = CString::new(comment_text).unwrap();
816 llvm::LLVMConstInlineAsm(Type::func(&[], &Type::void(self.ccx)).to_ref(),
817 comment_text.as_ptr(), noname(), False,
820 self.call(asm, &[], None);
824 pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
825 inputs: &[ValueRef], output: Type,
826 volatile: bool, alignstack: bool,
827 dia: AsmDialect) -> ValueRef {
828 self.count_insn("inlineasm");
830 let volatile = if volatile { llvm::True }
831 else { llvm::False };
832 let alignstack = if alignstack { llvm::True }
833 else { llvm::False };
835 let argtys = inputs.iter().map(|v| {
836 debug!("Asm Input Type: {:?}", Value(*v));
838 }).collect::<Vec<_>>();
840 debug!("Asm Output Type: {:?}", output);
841 let fty = Type::func(&argtys[..], &output);
843 let v = llvm::LLVMInlineAsm(
844 fty.to_ref(), asm, cons, volatile, alignstack, dia as c_uint);
845 self.call(v, inputs, None)
849 pub fn call(&self, llfn: ValueRef, args: &[ValueRef],
850 bundle: Option<&OperandBundleDef>) -> ValueRef {
851 self.count_insn("call");
853 debug!("Call {:?} with args ({})",
856 .map(|&v| format!("{:?}", Value(v)))
857 .collect::<Vec<String>>()
860 check_call("call", llfn, args);
862 let bundle = bundle.as_ref().map(|b| b.raw()).unwrap_or(ptr::null_mut());
865 llvm::LLVMRustBuildCall(self.llbuilder, llfn, args.as_ptr(),
866 args.len() as c_uint, bundle, noname())
870 pub fn select(&self, cond: ValueRef, then_val: ValueRef, else_val: ValueRef) -> ValueRef {
871 self.count_insn("select");
873 llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
877 pub fn va_arg(&self, list: ValueRef, ty: Type) -> ValueRef {
878 self.count_insn("vaarg");
880 llvm::LLVMBuildVAArg(self.llbuilder, list, ty.to_ref(), noname())
884 pub fn extract_element(&self, vec: ValueRef, idx: ValueRef) -> ValueRef {
885 self.count_insn("extractelement");
887 llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
891 pub fn insert_element(&self, vec: ValueRef, elt: ValueRef, idx: ValueRef) -> ValueRef {
892 self.count_insn("insertelement");
894 llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
898 pub fn shuffle_vector(&self, v1: ValueRef, v2: ValueRef, mask: ValueRef) -> ValueRef {
899 self.count_insn("shufflevector");
901 llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
905 pub fn vector_splat(&self, num_elts: usize, elt: ValueRef) -> ValueRef {
907 let elt_ty = val_ty(elt);
908 let undef = llvm::LLVMGetUndef(Type::vector(&elt_ty, num_elts as u64).to_ref());
909 let vec = self.insert_element(undef, elt, C_i32(self.ccx, 0));
910 let vec_i32_ty = Type::vector(&Type::i32(self.ccx), num_elts as u64);
911 self.shuffle_vector(vec, undef, C_null(vec_i32_ty))
915 pub fn extract_value(&self, agg_val: ValueRef, idx: usize) -> ValueRef {
916 self.count_insn("extractvalue");
918 llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
922 pub fn insert_value(&self, agg_val: ValueRef, elt: ValueRef,
923 idx: usize) -> ValueRef {
924 self.count_insn("insertvalue");
926 llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
931 pub fn is_null(&self, val: ValueRef) -> ValueRef {
932 self.count_insn("isnull");
934 llvm::LLVMBuildIsNull(self.llbuilder, val, noname())
938 pub fn is_not_null(&self, val: ValueRef) -> ValueRef {
939 self.count_insn("isnotnull");
941 llvm::LLVMBuildIsNotNull(self.llbuilder, val, noname())
945 pub fn ptrdiff(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
946 self.count_insn("ptrdiff");
948 llvm::LLVMBuildPtrDiff(self.llbuilder, lhs, rhs, noname())
954 let bb: BasicBlockRef = llvm::LLVMGetInsertBlock(self.llbuilder);
955 let fn_: ValueRef = llvm::LLVMGetBasicBlockParent(bb);
956 let m: ModuleRef = llvm::LLVMGetGlobalParent(fn_);
957 let p = "llvm.trap\0".as_ptr();
958 let t: ValueRef = llvm::LLVMGetNamedFunction(m, p as *const _);
959 assert!((t as isize != 0));
960 let args: &[ValueRef] = &[];
961 self.count_insn("trap");
962 llvm::LLVMRustBuildCall(self.llbuilder, t,
963 args.as_ptr(), args.len() as c_uint,
969 pub fn landing_pad(&self, ty: Type, pers_fn: ValueRef,
971 llfn: ValueRef) -> ValueRef {
972 self.count_insn("landingpad");
974 llvm::LLVMRustBuildLandingPad(self.llbuilder, ty.to_ref(), pers_fn,
975 num_clauses as c_uint, noname(), llfn)
979 pub fn add_clause(&self, landing_pad: ValueRef, clause: ValueRef) {
981 llvm::LLVMAddClause(landing_pad, clause);
985 pub fn set_cleanup(&self, landing_pad: ValueRef) {
986 self.count_insn("setcleanup");
988 llvm::LLVMSetCleanup(landing_pad, llvm::True);
992 pub fn resume(&self, exn: ValueRef) -> ValueRef {
993 self.count_insn("resume");
995 llvm::LLVMBuildResume(self.llbuilder, exn)
999 pub fn cleanup_pad(&self,
1000 parent: Option<ValueRef>,
1001 args: &[ValueRef]) -> ValueRef {
1002 self.count_insn("cleanuppad");
1003 let parent = parent.unwrap_or(ptr::null_mut());
1004 let name = CString::new("cleanuppad").unwrap();
1006 llvm::LLVMRustBuildCleanupPad(self.llbuilder,
1008 args.len() as c_uint,
1012 assert!(!ret.is_null(), "LLVM does not have support for cleanuppad");
1016 pub fn cleanup_ret(&self, cleanup: ValueRef,
1017 unwind: Option<BasicBlockRef>) -> ValueRef {
1018 self.count_insn("cleanupret");
1019 let unwind = unwind.unwrap_or(ptr::null_mut());
1021 llvm::LLVMRustBuildCleanupRet(self.llbuilder, cleanup, unwind)
1023 assert!(!ret.is_null(), "LLVM does not have support for cleanupret");
1027 pub fn catch_pad(&self,
1029 args: &[ValueRef]) -> ValueRef {
1030 self.count_insn("catchpad");
1031 let name = CString::new("catchpad").unwrap();
1033 llvm::LLVMRustBuildCatchPad(self.llbuilder, parent,
1034 args.len() as c_uint, args.as_ptr(),
1037 assert!(!ret.is_null(), "LLVM does not have support for catchpad");
1041 pub fn catch_ret(&self, pad: ValueRef, unwind: BasicBlockRef) -> ValueRef {
1042 self.count_insn("catchret");
1044 llvm::LLVMRustBuildCatchRet(self.llbuilder, pad, unwind)
1046 assert!(!ret.is_null(), "LLVM does not have support for catchret");
1050 pub fn catch_switch(&self,
1051 parent: Option<ValueRef>,
1052 unwind: Option<BasicBlockRef>,
1053 num_handlers: usize) -> ValueRef {
1054 self.count_insn("catchswitch");
1055 let parent = parent.unwrap_or(ptr::null_mut());
1056 let unwind = unwind.unwrap_or(ptr::null_mut());
1057 let name = CString::new("catchswitch").unwrap();
1059 llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind,
1060 num_handlers as c_uint,
1063 assert!(!ret.is_null(), "LLVM does not have support for catchswitch");
1067 pub fn add_handler(&self, catch_switch: ValueRef, handler: BasicBlockRef) {
1069 llvm::LLVMRustAddHandler(catch_switch, handler);
1073 pub fn set_personality_fn(&self, personality: ValueRef) {
1075 llvm::LLVMRustSetPersonalityFn(self.llbuilder, personality);
1079 // Atomic Operations
1080 pub fn atomic_cmpxchg(&self, dst: ValueRef,
1081 cmp: ValueRef, src: ValueRef,
1082 order: AtomicOrdering,
1083 failure_order: AtomicOrdering,
1084 weak: llvm::Bool) -> ValueRef {
1086 llvm::LLVMBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
1087 order, failure_order, weak)
1090 pub fn atomic_rmw(&self, op: AtomicBinOp,
1091 dst: ValueRef, src: ValueRef,
1092 order: AtomicOrdering) -> ValueRef {
1094 llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False)
1098 pub fn atomic_fence(&self, order: AtomicOrdering, scope: SynchronizationScope) {
1100 llvm::LLVMBuildAtomicFence(self.llbuilder, order, scope);
1105 fn check_call(typ: &str, llfn: ValueRef, args: &[ValueRef]) {
1106 if cfg!(debug_assertions) {
1107 let mut fn_ty = val_ty(llfn);
1108 // Strip off pointers
1109 while fn_ty.kind() == llvm::TypeKind::Pointer {
1110 fn_ty = fn_ty.element_type();
1113 assert!(fn_ty.kind() == llvm::TypeKind::Function,
1114 "builder::{} not passed a function", typ);
1116 let param_tys = fn_ty.func_params();
1118 let iter = param_tys.into_iter()
1119 .zip(args.iter().map(|&v| val_ty(v)));
1120 for (i, (expected_ty, actual_ty)) in iter.enumerate() {
1121 if expected_ty != actual_ty {
1122 bug!("Type mismatch in function call of {:?}. \
1123 Expected {:?} for param {}, got {:?}",
1125 expected_ty, i, actual_ty);