1 // Copyright 2012-2014 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 use llvm::{self, ValueRef};
12 use rustc_const_eval::ErrKind;
13 use rustc::middle::lang_items;
15 use rustc::mir::repr as mir;
16 use abi::{Abi, FnType, ArgType};
20 use callee::{Callee, CalleeData, Fn, Intrinsic, NamedTupleConstructor, Virtual};
21 use common::{self, Block, BlockAndBuilder, LandingPad};
22 use common::{C_bool, C_str_slice, C_struct, C_u32, C_undef};
24 use debuginfo::DebugLoc;
26 use machine::{llalign_of_min, llbitsize_of_real};
32 use rustc_data_structures::fnv::FnvHashMap;
33 use syntax::parse::token;
35 use super::{MirContext, LocalRef};
36 use super::analyze::CleanupKind;
37 use super::constant::Const;
38 use super::lvalue::{LvalueRef, load_fat_ptr};
39 use super::operand::OperandRef;
40 use super::operand::OperandValue::*;
42 impl<'bcx, 'tcx> MirContext<'bcx, 'tcx> {
43 pub fn trans_block(&mut self, bb: mir::BasicBlock) {
44 let mut bcx = self.bcx(bb);
45 let mir = self.mir.clone();
48 debug!("trans_block({:?}={:?})", bb, data);
50 // Create the cleanup bundle, if needed.
51 let cleanup_pad = bcx.lpad().and_then(|lp| lp.cleanuppad());
52 let cleanup_bundle = bcx.lpad().and_then(|l| l.bundle());
54 let funclet_br = |this: &Self, bcx: BlockAndBuilder, bb: mir::BasicBlock| {
55 let lltarget = this.blocks[bb].llbb;
56 if let Some(cp) = cleanup_pad {
57 match this.cleanup_kinds[bb] {
58 CleanupKind::Funclet => {
59 // micro-optimization: generate a `ret` rather than a jump
61 bcx.cleanup_ret(cp, Some(lltarget));
63 CleanupKind::Internal { .. } => bcx.br(lltarget),
64 CleanupKind::NotCleanup => bug!("jump from cleanup bb to bb {:?}", bb)
71 let llblock = |this: &mut Self, target: mir::BasicBlock| {
72 let lltarget = this.blocks[target].llbb;
74 if let Some(cp) = cleanup_pad {
75 match this.cleanup_kinds[target] {
76 CleanupKind::Funclet => {
77 // MSVC cross-funclet jump - need a trampoline
79 debug!("llblock: creating cleanup trampoline for {:?}", target);
80 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
81 let trampoline = this.fcx.new_block(name, None).build();
82 trampoline.set_personality_fn(this.fcx.eh_personality());
83 trampoline.cleanup_ret(cp, Some(lltarget));
86 CleanupKind::Internal { .. } => lltarget,
87 CleanupKind::NotCleanup =>
88 bug!("jump from cleanup bb {:?} to bb {:?}", bb, target)
91 if let (CleanupKind::NotCleanup, CleanupKind::Funclet) =
92 (this.cleanup_kinds[bb], this.cleanup_kinds[target])
94 // jump *into* cleanup - need a landing pad if GNU
95 this.landing_pad_to(target).llbb
102 for statement in &data.statements {
103 bcx = self.trans_statement(bcx, statement);
106 let terminator = data.terminator();
107 debug!("trans_block: terminator: {:?}", terminator);
109 let span = terminator.source_info.span;
110 let debug_loc = self.debug_loc(terminator.source_info);
111 debug_loc.apply_to_bcx(&bcx);
112 debug_loc.apply(bcx.fcx());
113 match terminator.kind {
114 mir::TerminatorKind::Resume => {
115 if let Some(cleanup_pad) = cleanup_pad {
116 bcx.cleanup_ret(cleanup_pad, None);
118 let ps = self.get_personality_slot(&bcx);
119 let lp = bcx.load(ps);
120 bcx.with_block(|bcx| {
121 base::call_lifetime_end(bcx, ps);
122 base::trans_unwind_resume(bcx, lp);
127 mir::TerminatorKind::Goto { target } => {
128 funclet_br(self, bcx, target);
131 mir::TerminatorKind::If { ref cond, targets: (true_bb, false_bb) } => {
132 let cond = self.trans_operand(&bcx, cond);
134 let lltrue = llblock(self, true_bb);
135 let llfalse = llblock(self, false_bb);
136 bcx.cond_br(cond.immediate(), lltrue, llfalse);
139 mir::TerminatorKind::Switch { ref discr, ref adt_def, ref targets } => {
140 let discr_lvalue = self.trans_lvalue(&bcx, discr);
141 let ty = discr_lvalue.ty.to_ty(bcx.tcx());
142 let repr = adt::represent_type(bcx.ccx(), ty);
143 let discr = bcx.with_block(|bcx|
144 adt::trans_get_discr(bcx, &repr, discr_lvalue.llval, None, true)
147 let mut bb_hist = FnvHashMap();
148 for target in targets {
149 *bb_hist.entry(target).or_insert(0) += 1;
151 let (default_bb, default_blk) = match bb_hist.iter().max_by_key(|&(_, c)| c) {
152 // If a single target basic blocks is predominant, promote that to be the
153 // default case for the switch instruction to reduce the size of the generated
154 // code. This is especially helpful in cases like an if-let on a huge enum.
155 // Note: This optimization is only valid for exhaustive matches.
156 Some((&&bb, &c)) if c > targets.len() / 2 => {
157 (Some(bb), llblock(self, bb))
159 // We're generating an exhaustive switch, so the else branch
160 // can't be hit. Branching to an unreachable instruction
161 // lets LLVM know this
162 _ => (None, self.unreachable_block().llbb)
164 let switch = bcx.switch(discr, default_blk, targets.len());
165 assert_eq!(adt_def.variants.len(), targets.len());
166 for (adt_variant, &target) in adt_def.variants.iter().zip(targets) {
167 if default_bb != Some(target) {
168 let llbb = llblock(self, target);
169 let llval = bcx.with_block(|bcx| adt::trans_case(
170 bcx, &repr, Disr::from(adt_variant.disr_val)));
171 build::AddCase(switch, llval, llbb)
176 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
177 let (otherwise, targets) = targets.split_last().unwrap();
178 let discr = bcx.load(self.trans_lvalue(&bcx, discr).llval);
179 let discr = bcx.with_block(|bcx| base::to_immediate(bcx, discr, switch_ty));
180 let switch = bcx.switch(discr, llblock(self, *otherwise), values.len());
181 for (value, target) in values.iter().zip(targets) {
182 let val = Const::from_constval(bcx.ccx(), value.clone(), switch_ty);
183 let llbb = llblock(self, *target);
184 build::AddCase(switch, val.llval, llbb)
188 mir::TerminatorKind::Return => {
189 let ret = bcx.fcx().fn_ty.ret;
190 if ret.is_ignore() || ret.is_indirect() {
195 let llval = if let Some(cast_ty) = ret.cast {
196 let index = mir.local_index(&mir::Lvalue::ReturnPointer).unwrap();
197 let op = match self.locals[index] {
198 LocalRef::Operand(Some(op)) => op,
199 LocalRef::Operand(None) => bug!("use of return before def"),
200 LocalRef::Lvalue(tr_lvalue) => {
202 val: Ref(tr_lvalue.llval),
203 ty: tr_lvalue.ty.to_ty(bcx.tcx())
207 let llslot = match op.val {
208 Immediate(_) | Pair(..) => {
209 let llscratch = build::AllocaFcx(bcx.fcx(), ret.original_ty, "ret");
210 self.store_operand(&bcx, llscratch, op);
215 let load = bcx.load(bcx.pointercast(llslot, cast_ty.ptr_to()));
216 let llalign = llalign_of_min(bcx.ccx(), ret.ty);
218 llvm::LLVMSetAlignment(load, llalign);
222 let op = self.trans_consume(&bcx, &mir::Lvalue::ReturnPointer);
223 op.pack_if_pair(&bcx).immediate()
228 mir::TerminatorKind::Unreachable => {
232 mir::TerminatorKind::Drop { ref location, target, unwind } => {
233 let ty = location.ty(&mir, bcx.tcx()).to_ty(bcx.tcx());
234 let ty = bcx.monomorphize(&ty);
236 // Double check for necessity to drop
237 if !glue::type_needs_drop(bcx.tcx(), ty) {
238 funclet_br(self, bcx, target);
242 let lvalue = self.trans_lvalue(&bcx, location);
243 let drop_fn = glue::get_drop_glue(bcx.ccx(), ty);
244 let drop_ty = glue::get_drop_glue_type(bcx.tcx(), ty);
245 let llvalue = if drop_ty != ty {
246 bcx.pointercast(lvalue.llval, type_of::type_of(bcx.ccx(), drop_ty).ptr_to())
250 if let Some(unwind) = unwind {
253 self.blocks[target].llbb,
254 llblock(self, unwind),
257 bcx.call(drop_fn, &[llvalue], cleanup_bundle);
258 funclet_br(self, bcx, target);
262 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
263 let cond = self.trans_operand(&bcx, cond).immediate();
264 let mut const_cond = common::const_to_opt_uint(cond).map(|c| c == 1);
266 // This case can currently arise only from functions marked
267 // with #[rustc_inherit_overflow_checks] and inlined from
268 // another crate (mostly core::num generic/#[inline] fns),
269 // while the current crate doesn't use overflow checks.
270 // NOTE: Unlike binops, negation doesn't have its own
271 // checked operation, just a comparison with the minimum
272 // value, so we have to check for the assert message.
273 if !bcx.ccx().check_overflow() {
274 use rustc_const_math::ConstMathErr::Overflow;
275 use rustc_const_math::Op::Neg;
277 if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
278 const_cond = Some(expected);
282 // Don't translate the panic block if success if known.
283 if const_cond == Some(expected) {
284 funclet_br(self, bcx, target);
288 // Pass the condition through llvm.expect for branch hinting.
289 let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
290 let cond = bcx.call(expect, &[cond, C_bool(bcx.ccx(), expected)], None);
292 // Create the failure block and the conditional branch to it.
293 let lltarget = llblock(self, target);
294 let panic_block = self.fcx.new_block("panic", None);
296 bcx.cond_br(cond, lltarget, panic_block.llbb);
298 bcx.cond_br(cond, panic_block.llbb, lltarget);
301 // After this point, bcx is the block for the call to panic.
302 bcx = panic_block.build();
303 debug_loc.apply_to_bcx(&bcx);
305 // Get the location information.
306 let loc = bcx.sess().codemap().lookup_char_pos(span.lo);
307 let filename = token::intern_and_get_ident(&loc.file.name);
308 let filename = C_str_slice(bcx.ccx(), filename);
309 let line = C_u32(bcx.ccx(), loc.line as u32);
311 // Put together the arguments to the panic entry point.
312 let (lang_item, args, const_err) = match *msg {
313 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
314 let len = self.trans_operand(&mut bcx, len).immediate();
315 let index = self.trans_operand(&mut bcx, index).immediate();
317 let const_err = common::const_to_opt_uint(len).and_then(|len| {
318 common::const_to_opt_uint(index).map(|index| {
319 ErrKind::IndexOutOfBounds {
326 let file_line = C_struct(bcx.ccx(), &[filename, line], false);
327 let align = llalign_of_min(bcx.ccx(), common::val_ty(file_line));
328 let file_line = consts::addr_of(bcx.ccx(),
331 "panic_bounds_check_loc");
332 (lang_items::PanicBoundsCheckFnLangItem,
333 vec![file_line, index, len],
336 mir::AssertMessage::Math(ref err) => {
337 let msg_str = token::intern_and_get_ident(err.description());
338 let msg_str = C_str_slice(bcx.ccx(), msg_str);
339 let msg_file_line = C_struct(bcx.ccx(),
340 &[msg_str, filename, line],
342 let align = llalign_of_min(bcx.ccx(), common::val_ty(msg_file_line));
343 let msg_file_line = consts::addr_of(bcx.ccx(),
347 (lang_items::PanicFnLangItem,
349 Some(ErrKind::Math(err.clone())))
353 // If we know we always panic, and the error message
354 // is also constant, then we can produce a warning.
355 if const_cond == Some(!expected) {
356 if let Some(err) = const_err {
357 let _ = consts::const_err(bcx.ccx(), span,
359 consts::TrueConst::No);
363 // Obtain the panic entry point.
364 let def_id = common::langcall(bcx.tcx(), Some(span), "", lang_item);
365 let callee = Callee::def(bcx.ccx(), def_id,
366 bcx.ccx().empty_substs_for_def_id(def_id));
367 let llfn = callee.reify(bcx.ccx()).val;
369 // Translate the actual panic invoke/call.
370 if let Some(unwind) = cleanup {
373 self.unreachable_block().llbb,
374 llblock(self, unwind),
377 bcx.call(llfn, &args, cleanup_bundle);
382 mir::TerminatorKind::DropAndReplace { .. } => {
383 bug!("undesugared DropAndReplace in trans: {:?}", data);
386 mir::TerminatorKind::Call { ref func, ref args, ref destination, ref cleanup } => {
387 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
388 let callee = self.trans_operand(&bcx, func);
390 let (mut callee, abi, sig) = match callee.ty.sty {
391 ty::TyFnDef(def_id, substs, f) => {
392 (Callee::def(bcx.ccx(), def_id, substs), f.abi, &f.sig)
396 data: Fn(callee.immediate()),
400 _ => bug!("{} is not callable", callee.ty)
403 let sig = bcx.tcx().erase_late_bound_regions(sig);
405 // Handle intrinsics old trans wants Expr's for, ourselves.
406 let intrinsic = match (&callee.ty.sty, &callee.data) {
407 (&ty::TyFnDef(def_id, _, _), &Intrinsic) => {
408 Some(bcx.tcx().item_name(def_id).as_str())
412 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
414 if intrinsic == Some("move_val_init") {
415 let &(_, target) = destination.as_ref().unwrap();
416 // The first argument is a thin destination pointer.
417 let llptr = self.trans_operand(&bcx, &args[0]).immediate();
418 let val = self.trans_operand(&bcx, &args[1]);
419 self.store_operand(&bcx, llptr, val);
420 funclet_br(self, bcx, target);
424 if intrinsic == Some("transmute") {
425 let &(ref dest, target) = destination.as_ref().unwrap();
426 self.with_lvalue_ref(&bcx, dest, |this, dest| {
427 this.trans_transmute(&bcx, &args[0], dest);
430 funclet_br(self, bcx, target);
434 let extra_args = &args[sig.inputs.len()..];
435 let extra_args = extra_args.iter().map(|op_arg| {
436 let op_ty = op_arg.ty(&self.mir, bcx.tcx());
437 bcx.monomorphize(&op_ty)
438 }).collect::<Vec<_>>();
439 let fn_ty = callee.direct_fn_type(bcx.ccx(), &extra_args);
441 // The arguments we'll be passing. Plus one to account for outptr, if used.
442 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
443 let mut llargs = Vec::with_capacity(arg_count);
445 // Prepare the return value destination
446 let ret_dest = if let Some((ref dest, _)) = *destination {
447 let is_intrinsic = if let Intrinsic = callee.data {
452 self.make_return_dest(&bcx, dest, &fn_ty.ret, &mut llargs, is_intrinsic)
457 // Split the rust-call tupled arguments off.
458 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
459 let (tup, args) = args.split_last().unwrap();
465 let is_shuffle = intrinsic.map_or(false, |name| {
466 name.starts_with("simd_shuffle")
469 for arg in first_args {
470 // The indices passed to simd_shuffle* in the
471 // third argument must be constant. This is
472 // checked by const-qualification, which also
473 // promotes any complex rvalues to constants.
474 if is_shuffle && idx == 2 {
476 mir::Operand::Consume(_) => {
477 span_bug!(span, "shuffle indices must be constant");
479 mir::Operand::Constant(ref constant) => {
480 let val = self.trans_constant(&bcx, constant);
481 llargs.push(val.llval);
488 let op = self.trans_operand(&bcx, arg);
489 self.trans_argument(&bcx, op, &mut llargs, &fn_ty,
490 &mut idx, &mut callee.data);
492 if let Some(tup) = untuple {
493 self.trans_arguments_untupled(&bcx, tup, &mut llargs, &fn_ty,
494 &mut idx, &mut callee.data)
497 let fn_ptr = match callee.data {
498 NamedTupleConstructor(_) => {
499 // FIXME translate this like mir::Rvalue::Aggregate.
500 callee.reify(bcx.ccx()).val
504 use expr::{Ignore, SaveIn};
505 use intrinsic::trans_intrinsic_call;
507 let (dest, llargs) = match ret_dest {
508 _ if fn_ty.ret.is_indirect() => {
509 (SaveIn(llargs[0]), &llargs[1..])
511 ReturnDest::Nothing => (Ignore, &llargs[..]),
512 ReturnDest::IndirectOperand(dst, _) |
513 ReturnDest::Store(dst) => (SaveIn(dst), &llargs[..]),
514 ReturnDest::DirectOperand(_) =>
515 bug!("Cannot use direct operand with an intrinsic call")
518 bcx.with_block(|bcx| {
519 trans_intrinsic_call(bcx, callee.ty, &fn_ty,
520 ArgVals(llargs), dest,
524 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
525 // Make a fake operand for store_return
526 let op = OperandRef {
528 ty: sig.output.unwrap()
530 self.store_return(&bcx, ret_dest, fn_ty.ret, op);
533 if let Some((_, target)) = *destination {
534 funclet_br(self, bcx, target);
536 // trans_intrinsic_call already used Unreachable.
537 // bcx.unreachable();
543 Virtual(_) => bug!("Virtual fn ptr not extracted")
546 // Many different ways to call a function handled here
547 if let &Some(cleanup) = cleanup {
548 let ret_bcx = if let Some((_, target)) = *destination {
551 self.unreachable_block()
553 let invokeret = bcx.invoke(fn_ptr,
556 llblock(self, cleanup),
558 fn_ty.apply_attrs_callsite(invokeret);
560 if destination.is_some() {
561 let ret_bcx = ret_bcx.build();
562 ret_bcx.at_start(|ret_bcx| {
563 debug_loc.apply_to_bcx(ret_bcx);
564 let op = OperandRef {
565 val: Immediate(invokeret),
566 ty: sig.output.unwrap()
568 self.store_return(&ret_bcx, ret_dest, fn_ty.ret, op);
572 let llret = bcx.call(fn_ptr, &llargs, cleanup_bundle);
573 fn_ty.apply_attrs_callsite(llret);
574 if let Some((_, target)) = *destination {
575 let op = OperandRef {
576 val: Immediate(llret),
577 ty: sig.output.unwrap()
579 self.store_return(&bcx, ret_dest, fn_ty.ret, op);
580 funclet_br(self, bcx, target);
589 fn trans_argument(&mut self,
590 bcx: &BlockAndBuilder<'bcx, 'tcx>,
591 op: OperandRef<'tcx>,
592 llargs: &mut Vec<ValueRef>,
594 next_idx: &mut usize,
595 callee: &mut CalleeData) {
596 if let Pair(a, b) = op.val {
597 // Treat the values in a fat pointer separately.
598 if common::type_is_fat_ptr(bcx.tcx(), op.ty) {
599 let (ptr, meta) = (a, b);
601 if let Virtual(idx) = *callee {
602 let llfn = bcx.with_block(|bcx| {
603 meth::get_virtual_method(bcx, meta, idx)
605 let llty = fn_ty.llvm_type(bcx.ccx()).ptr_to();
606 *callee = Fn(bcx.pointercast(llfn, llty));
610 let imm_op = |x| OperandRef {
612 // We won't be checking the type again.
613 ty: bcx.tcx().types.err
615 self.trans_argument(bcx, imm_op(ptr), llargs, fn_ty, next_idx, callee);
616 self.trans_argument(bcx, imm_op(meta), llargs, fn_ty, next_idx, callee);
621 let arg = &fn_ty.args[*next_idx];
624 // Fill padding with undef value, where applicable.
625 if let Some(ty) = arg.pad {
626 llargs.push(C_undef(ty));
633 // Force by-ref if we have to load through a cast pointer.
634 let (mut llval, by_ref) = match op.val {
635 Immediate(_) | Pair(..) => {
636 if arg.is_indirect() || arg.cast.is_some() {
637 let llscratch = build::AllocaFcx(bcx.fcx(), arg.original_ty, "arg");
638 self.store_operand(bcx, llscratch, op);
641 (op.pack_if_pair(bcx).immediate(), false)
644 Ref(llval) => (llval, true)
647 if by_ref && !arg.is_indirect() {
648 // Have to load the argument, maybe while casting it.
649 if arg.original_ty == Type::i1(bcx.ccx()) {
650 // We store bools as i8 so we need to truncate to i1.
651 llval = bcx.load_range_assert(llval, 0, 2, llvm::False);
652 llval = bcx.trunc(llval, arg.original_ty);
653 } else if let Some(ty) = arg.cast {
654 llval = bcx.load(bcx.pointercast(llval, ty.ptr_to()));
655 let llalign = llalign_of_min(bcx.ccx(), arg.ty);
657 llvm::LLVMSetAlignment(llval, llalign);
660 llval = bcx.load(llval);
667 fn trans_arguments_untupled(&mut self,
668 bcx: &BlockAndBuilder<'bcx, 'tcx>,
669 operand: &mir::Operand<'tcx>,
670 llargs: &mut Vec<ValueRef>,
672 next_idx: &mut usize,
673 callee: &mut CalleeData) {
674 let tuple = self.trans_operand(bcx, operand);
676 let arg_types = match tuple.ty.sty {
677 ty::TyTuple(ref tys) => tys,
678 _ => span_bug!(self.mir.span,
679 "bad final argument to \"rust-call\" fn {:?}", tuple.ty)
682 // Handle both by-ref and immediate tuples.
685 let base_repr = adt::represent_type(bcx.ccx(), tuple.ty);
686 let base = adt::MaybeSizedValue::sized(llval);
687 for (n, &ty) in arg_types.iter().enumerate() {
688 let ptr = adt::trans_field_ptr_builder(bcx, &base_repr, base, Disr(0), n);
689 let val = if common::type_is_fat_ptr(bcx.tcx(), ty) {
690 let (lldata, llextra) = load_fat_ptr(bcx, ptr);
691 Pair(lldata, llextra)
693 // trans_argument will load this if it needs to
696 let op = OperandRef {
700 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
704 Immediate(llval) => {
705 for (n, &ty) in arg_types.iter().enumerate() {
706 let mut elem = bcx.extract_value(llval, n);
707 // Truncate bools to i1, if needed
708 if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx()) {
709 elem = bcx.trunc(elem, Type::i1(bcx.ccx()));
711 // If the tuple is immediate, the elements are as well
712 let op = OperandRef {
713 val: Immediate(elem),
716 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
721 for (n, &ty) in arg_types.iter().enumerate() {
722 let mut elem = elems[n];
723 // Truncate bools to i1, if needed
724 if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx()) {
725 elem = bcx.trunc(elem, Type::i1(bcx.ccx()));
727 // Pair is always made up of immediates
728 let op = OperandRef {
729 val: Immediate(elem),
732 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
739 fn get_personality_slot(&mut self, bcx: &BlockAndBuilder<'bcx, 'tcx>) -> ValueRef {
741 if let Some(slot) = self.llpersonalityslot {
744 let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
745 bcx.with_block(|bcx| {
746 let slot = base::alloca(bcx, llretty, "personalityslot");
747 self.llpersonalityslot = Some(slot);
748 base::call_lifetime_start(bcx, slot);
754 /// Return the landingpad wrapper around the given basic block
756 /// No-op in MSVC SEH scheme.
757 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> Block<'bcx, 'tcx>
759 if let Some(block) = self.landing_pads[target_bb] {
763 if base::wants_msvc_seh(self.fcx.ccx.sess()) {
764 return self.blocks[target_bb];
767 let target = self.bcx(target_bb);
769 let block = self.fcx.new_block("cleanup", None);
770 self.landing_pads[target_bb] = Some(block);
772 let bcx = block.build();
774 let llpersonality = self.fcx.eh_personality();
775 let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
776 let llretval = bcx.landing_pad(llretty, llpersonality, 1, self.fcx.llfn);
777 bcx.set_cleanup(llretval);
778 let slot = self.get_personality_slot(&bcx);
779 bcx.store(llretval, slot);
780 bcx.br(target.llbb());
784 pub fn init_cpad(&mut self, bb: mir::BasicBlock) {
785 let bcx = self.bcx(bb);
786 let data = &self.mir[bb];
787 debug!("init_cpad({:?})", data);
789 match self.cleanup_kinds[bb] {
790 CleanupKind::NotCleanup => {
793 _ if !base::wants_msvc_seh(bcx.sess()) => {
794 bcx.set_lpad(Some(LandingPad::gnu()))
796 CleanupKind::Internal { funclet } => {
797 // FIXME: is this needed?
798 bcx.set_personality_fn(self.fcx.eh_personality());
799 bcx.set_lpad_ref(self.bcx(funclet).lpad());
801 CleanupKind::Funclet => {
802 bcx.set_personality_fn(self.fcx.eh_personality());
803 DebugLoc::None.apply_to_bcx(&bcx);
804 let cleanup_pad = bcx.cleanup_pad(None, &[]);
805 bcx.set_lpad(Some(LandingPad::msvc(cleanup_pad)));
810 fn unreachable_block(&mut self) -> Block<'bcx, 'tcx> {
811 self.unreachable_block.unwrap_or_else(|| {
812 let bl = self.fcx.new_block("unreachable", None);
813 bl.build().unreachable();
814 self.unreachable_block = Some(bl);
819 fn bcx(&self, bb: mir::BasicBlock) -> BlockAndBuilder<'bcx, 'tcx> {
820 self.blocks[bb].build()
823 fn make_return_dest(&mut self, bcx: &BlockAndBuilder<'bcx, 'tcx>,
824 dest: &mir::Lvalue<'tcx>, fn_ret_ty: &ArgType,
825 llargs: &mut Vec<ValueRef>, is_intrinsic: bool) -> ReturnDest {
826 // If the return is ignored, we can just return a do-nothing ReturnDest
827 if fn_ret_ty.is_ignore() {
828 return ReturnDest::Nothing;
830 let dest = if let Some(index) = self.mir.local_index(dest) {
831 let ret_ty = self.monomorphized_lvalue_ty(dest);
832 match self.locals[index] {
833 LocalRef::Lvalue(dest) => dest,
834 LocalRef::Operand(None) => {
835 // Handle temporary lvalues, specifically Operand ones, as
836 // they don't have allocas
837 return if fn_ret_ty.is_indirect() {
838 // Odd, but possible, case, we have an operand temporary,
839 // but the calling convention has an indirect return.
840 let tmp = bcx.with_block(|bcx| {
841 base::alloc_ty(bcx, ret_ty, "tmp_ret")
844 ReturnDest::IndirectOperand(tmp, index)
845 } else if is_intrinsic {
846 // Currently, intrinsics always need a location to store
847 // the result. so we create a temporary alloca for the
849 let tmp = bcx.with_block(|bcx| {
850 base::alloc_ty(bcx, ret_ty, "tmp_ret")
852 ReturnDest::IndirectOperand(tmp, index)
854 ReturnDest::DirectOperand(index)
857 LocalRef::Operand(Some(_)) => {
858 bug!("lvalue local already assigned to");
862 self.trans_lvalue(bcx, dest)
864 if fn_ret_ty.is_indirect() {
865 llargs.push(dest.llval);
868 ReturnDest::Store(dest.llval)
872 fn trans_transmute(&mut self, bcx: &BlockAndBuilder<'bcx, 'tcx>,
873 src: &mir::Operand<'tcx>, dst: LvalueRef<'tcx>) {
874 let mut val = self.trans_operand(bcx, src);
875 if let ty::TyFnDef(def_id, substs, _) = val.ty.sty {
876 let llouttype = type_of::type_of(bcx.ccx(), dst.ty.to_ty(bcx.tcx()));
877 let out_type_size = llbitsize_of_real(bcx.ccx(), llouttype);
878 if out_type_size != 0 {
879 // FIXME #19925 Remove this hack after a release cycle.
880 let f = Callee::def(bcx.ccx(), def_id, substs);
881 let datum = f.reify(bcx.ccx());
883 val: Immediate(datum.val),
889 let llty = type_of::type_of(bcx.ccx(), val.ty);
890 let cast_ptr = bcx.pointercast(dst.llval, llty.ptr_to());
891 self.store_operand(bcx, cast_ptr, val);
895 // Stores the return value of a function call into it's final location.
896 fn store_return(&mut self,
897 bcx: &BlockAndBuilder<'bcx, 'tcx>,
900 op: OperandRef<'tcx>) {
901 use self::ReturnDest::*;
905 Store(dst) => ret_ty.store(bcx, op.immediate(), dst),
906 IndirectOperand(tmp, index) => {
907 let op = self.trans_load(bcx, tmp, op.ty);
908 self.locals[index] = LocalRef::Operand(Some(op));
910 DirectOperand(index) => {
911 // If there is a cast, we have to store and reload.
912 let op = if ret_ty.cast.is_some() {
913 let tmp = bcx.with_block(|bcx| {
914 base::alloc_ty(bcx, op.ty, "tmp_ret")
916 ret_ty.store(bcx, op.immediate(), tmp);
917 self.trans_load(bcx, tmp, op.ty)
919 op.unpack_if_pair(bcx)
921 self.locals[index] = LocalRef::Operand(Some(op));
928 // Do nothing, the return value is indirect or ignored
930 // Store the return value to the pointer
932 // Stores an indirect return value to an operand local lvalue
933 IndirectOperand(ValueRef, mir::Local),
934 // Stores a direct return value to an operand local lvalue
935 DirectOperand(mir::Local)