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, BasicBlockRef};
12 use rustc::middle::lang_items;
13 use rustc::middle::const_val::{ConstEvalErr, ConstInt, ErrKind};
14 use rustc::ty::{self, TypeFoldable};
15 use rustc::ty::layout::{self, LayoutOf};
18 use abi::{Abi, FnType, ArgType, PassMode};
22 use common::{self, C_bool, C_str_slice, C_struct, C_u32, C_undef};
26 use type_of::LayoutLlvmExt;
29 use syntax::symbol::Symbol;
32 use super::{FunctionCx, LocalRef};
33 use super::constant::Const;
34 use super::place::PlaceRef;
35 use super::operand::OperandRef;
36 use super::operand::OperandValue::{Pair, Ref, Immediate};
38 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
39 pub fn trans_block(&mut self, bb: mir::BasicBlock) {
40 let mut bx = self.build_block(bb);
41 let data = &self.mir[bb];
43 debug!("trans_block({:?}={:?})", bb, data);
45 for statement in &data.statements {
46 bx = self.trans_statement(bx, statement);
49 self.trans_terminator(bx, bb, data.terminator());
52 fn trans_terminator(&mut self,
53 mut bx: Builder<'a, 'tcx>,
55 terminator: &mir::Terminator<'tcx>)
57 debug!("trans_terminator: {:?}", terminator);
59 // Create the cleanup bundle, if needed.
61 let span = terminator.source_info.span;
62 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
63 let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());
65 let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
66 let cleanup_bundle = funclet.map(|l| l.bundle());
68 let lltarget = |this: &mut Self, target: mir::BasicBlock| {
69 let lltarget = this.blocks[target];
70 let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
71 match (funclet_bb, target_funclet) {
72 (None, None) => (lltarget, false),
74 if f == t_f || !base::wants_msvc_seh(tcx.sess)
77 // jump *into* cleanup - need a landing pad if GNU
78 (this.landing_pad_to(target), false)
80 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
81 (Some(_), Some(_)) => {
82 (this.landing_pad_to(target), true)
87 let llblock = |this: &mut Self, target: mir::BasicBlock| {
88 let (lltarget, is_cleanupret) = lltarget(this, target);
90 // MSVC cross-funclet jump - need a trampoline
92 debug!("llblock: creating cleanup trampoline for {:?}", target);
93 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
94 let trampoline = this.new_block(name);
95 trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
102 let funclet_br = |this: &mut Self, bx: Builder, target: mir::BasicBlock| {
103 let (lltarget, is_cleanupret) = lltarget(this, target);
105 // micro-optimization: generate a `ret` rather than a jump
107 bx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
115 bx: Builder<'a, 'tcx>,
119 destination: Option<(ReturnDest<'tcx>, mir::BasicBlock)>,
120 cleanup: Option<mir::BasicBlock>
122 if let Some(cleanup) = cleanup {
123 let ret_bx = if let Some((_, target)) = destination {
126 this.unreachable_block()
128 let invokeret = bx.invoke(fn_ptr,
131 llblock(this, cleanup),
133 fn_ty.apply_attrs_callsite(invokeret);
135 if let Some((ret_dest, target)) = destination {
136 let ret_bx = this.build_block(target);
137 this.set_debug_loc(&ret_bx, terminator.source_info);
138 this.store_return(&ret_bx, ret_dest, &fn_ty.ret, invokeret);
141 let llret = bx.call(fn_ptr, &llargs, cleanup_bundle);
142 fn_ty.apply_attrs_callsite(llret);
143 if this.mir[bb].is_cleanup {
144 // Cleanup is always the cold path. Don't inline
145 // drop glue. Also, when there is a deeply-nested
146 // struct, there are "symmetry" issues that cause
147 // exponential inlining - see issue #41696.
148 llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
151 if let Some((ret_dest, target)) = destination {
152 this.store_return(&bx, ret_dest, &fn_ty.ret, llret);
153 funclet_br(this, bx, target);
160 self.set_debug_loc(&bx, terminator.source_info);
161 match terminator.kind {
162 mir::TerminatorKind::Resume => {
163 if let Some(cleanup_pad) = cleanup_pad {
164 bx.cleanup_ret(cleanup_pad, None);
166 let slot = self.get_personality_slot(&bx);
167 let lp0 = slot.project_field(&bx, 0).load(&bx).immediate();
168 let lp1 = slot.project_field(&bx, 1).load(&bx).immediate();
169 slot.storage_dead(&bx);
171 if !bx.sess().target.target.options.custom_unwind_resume {
172 let mut lp = C_undef(self.landing_pad_type());
173 lp = bx.insert_value(lp, lp0, 0);
174 lp = bx.insert_value(lp, lp1, 1);
177 bx.call(bx.cx.eh_unwind_resume(), &[lp0], cleanup_bundle);
183 mir::TerminatorKind::Abort => {
184 // Call core::intrinsics::abort()
185 let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
186 bx.call(fnname, &[], None);
190 mir::TerminatorKind::Goto { target } => {
191 funclet_br(self, bx, target);
194 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
195 let discr = self.trans_operand(&bx, discr);
196 if switch_ty == bx.tcx().types.bool {
197 let lltrue = llblock(self, targets[0]);
198 let llfalse = llblock(self, targets[1]);
199 if let [ConstInt::U8(0)] = values[..] {
200 bx.cond_br(discr.immediate(), llfalse, lltrue);
202 bx.cond_br(discr.immediate(), lltrue, llfalse);
205 let (otherwise, targets) = targets.split_last().unwrap();
206 let switch = bx.switch(discr.immediate(),
207 llblock(self, *otherwise), values.len());
208 for (value, target) in values.iter().zip(targets) {
209 let val = Const::from_constint(bx.cx, value);
210 let llbb = llblock(self, *target);
211 bx.add_case(switch, val.llval, llbb)
216 mir::TerminatorKind::Return => {
217 let llval = match self.fn_ty.ret.mode {
218 PassMode::Ignore | PassMode::Indirect(_) => {
223 PassMode::Direct(_) | PassMode::Pair(..) => {
224 let op = self.trans_consume(&bx, &mir::Place::Local(mir::RETURN_PLACE));
225 if let Ref(llval, align) = op.val {
226 bx.load(llval, align)
228 op.immediate_or_packed_pair(&bx)
232 PassMode::Cast(cast_ty) => {
233 let op = match self.locals[mir::RETURN_PLACE] {
234 LocalRef::Operand(Some(op)) => op,
235 LocalRef::Operand(None) => bug!("use of return before def"),
236 LocalRef::Place(tr_place) => {
238 val: Ref(tr_place.llval, tr_place.align),
239 layout: tr_place.layout
243 let llslot = match op.val {
244 Immediate(_) | Pair(..) => {
245 let scratch = PlaceRef::alloca(&bx, self.fn_ty.ret.layout, "ret");
246 op.val.store(&bx, scratch);
249 Ref(llval, align) => {
250 assert_eq!(align.abi(), op.layout.align.abi(),
251 "return place is unaligned!");
256 bx.pointercast(llslot, cast_ty.llvm_type(bx.cx).ptr_to()),
257 self.fn_ty.ret.layout.align)
263 mir::TerminatorKind::Unreachable => {
267 mir::TerminatorKind::Drop { ref location, target, unwind } => {
268 let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
269 let ty = self.monomorphize(&ty);
270 let drop_fn = monomorphize::resolve_drop_in_place(bx.cx.tcx, ty);
272 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
273 // we don't actually need to drop anything.
274 funclet_br(self, bx, target);
278 let place = self.trans_place(&bx, location);
279 let mut args: &[_] = &[place.llval, place.llextra];
280 args = &args[..1 + place.has_extra() as usize];
281 let (drop_fn, fn_ty) = match ty.sty {
282 ty::TyDynamic(..) => {
283 let fn_ty = drop_fn.ty(bx.cx.tcx);
284 let sig = common::ty_fn_sig(bx.cx, fn_ty);
285 let sig = bx.tcx().erase_late_bound_regions_and_normalize(&sig);
286 let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
288 (meth::DESTRUCTOR.get_fn(&bx, place.llextra, &fn_ty), fn_ty)
291 (callee::get_fn(bx.cx, drop_fn),
292 FnType::of_instance(bx.cx, &drop_fn))
295 do_call(self, bx, fn_ty, drop_fn, args,
296 Some((ReturnDest::Nothing, target)),
300 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
301 let cond = self.trans_operand(&bx, cond).immediate();
302 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
304 // This case can currently arise only from functions marked
305 // with #[rustc_inherit_overflow_checks] and inlined from
306 // another crate (mostly core::num generic/#[inline] fns),
307 // while the current crate doesn't use overflow checks.
308 // NOTE: Unlike binops, negation doesn't have its own
309 // checked operation, just a comparison with the minimum
310 // value, so we have to check for the assert message.
311 if !bx.cx.check_overflow {
312 use rustc_const_math::ConstMathErr::Overflow;
313 use rustc_const_math::Op::Neg;
315 if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
316 const_cond = Some(expected);
320 // Don't translate the panic block if success if known.
321 if const_cond == Some(expected) {
322 funclet_br(self, bx, target);
326 // Pass the condition through llvm.expect for branch hinting.
327 let expect = bx.cx.get_intrinsic(&"llvm.expect.i1");
328 let cond = bx.call(expect, &[cond, C_bool(bx.cx, expected)], None);
330 // Create the failure block and the conditional branch to it.
331 let lltarget = llblock(self, target);
332 let panic_block = self.new_block("panic");
334 bx.cond_br(cond, lltarget, panic_block.llbb());
336 bx.cond_br(cond, panic_block.llbb(), lltarget);
339 // After this point, bx is the block for the call to panic.
341 self.set_debug_loc(&bx, terminator.source_info);
343 // Get the location information.
344 let loc = bx.sess().codemap().lookup_char_pos(span.lo());
345 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
346 let filename = C_str_slice(bx.cx, filename);
347 let line = C_u32(bx.cx, loc.line as u32);
348 let col = C_u32(bx.cx, loc.col.to_usize() as u32 + 1);
349 let align = tcx.data_layout.aggregate_align
350 .max(tcx.data_layout.i32_align)
351 .max(tcx.data_layout.pointer_align);
353 // Put together the arguments to the panic entry point.
354 let (lang_item, args, const_err) = match *msg {
355 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
356 let len = self.trans_operand(&mut bx, len).immediate();
357 let index = self.trans_operand(&mut bx, index).immediate();
359 let const_err = common::const_to_opt_u128(len, false)
360 .and_then(|len| common::const_to_opt_u128(index, false)
361 .map(|index| ErrKind::IndexOutOfBounds {
366 let file_line_col = C_struct(bx.cx, &[filename, line, col], false);
367 let file_line_col = consts::addr_of(bx.cx,
370 "panic_bounds_check_loc");
371 (lang_items::PanicBoundsCheckFnLangItem,
372 vec![file_line_col, index, len],
375 mir::AssertMessage::Math(ref err) => {
376 let msg_str = Symbol::intern(err.description()).as_str();
377 let msg_str = C_str_slice(bx.cx, msg_str);
378 let msg_file_line_col = C_struct(bx.cx,
379 &[msg_str, filename, line, col],
381 let msg_file_line_col = consts::addr_of(bx.cx,
385 (lang_items::PanicFnLangItem,
386 vec![msg_file_line_col],
387 Some(ErrKind::Math(err.clone())))
389 mir::AssertMessage::GeneratorResumedAfterReturn |
390 mir::AssertMessage::GeneratorResumedAfterPanic => {
391 let str = if let mir::AssertMessage::GeneratorResumedAfterReturn = *msg {
392 "generator resumed after completion"
394 "generator resumed after panicking"
396 let msg_str = Symbol::intern(str).as_str();
397 let msg_str = C_str_slice(bx.cx, msg_str);
398 let msg_file_line_col = C_struct(bx.cx,
399 &[msg_str, filename, line, col],
401 let msg_file_line_col = consts::addr_of(bx.cx,
405 (lang_items::PanicFnLangItem,
406 vec![msg_file_line_col],
411 // If we know we always panic, and the error message
412 // is also constant, then we can produce a warning.
413 if const_cond == Some(!expected) {
414 if let Some(err) = const_err {
415 let err = ConstEvalErr{ span: span, kind: err };
416 let mut diag = bx.tcx().sess.struct_span_warn(
417 span, "this expression will panic at run-time");
418 err.note(bx.tcx(), span, "expression", &mut diag);
423 // Obtain the panic entry point.
424 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
425 let instance = ty::Instance::mono(bx.tcx(), def_id);
426 let fn_ty = FnType::of_instance(bx.cx, &instance);
427 let llfn = callee::get_fn(bx.cx, instance);
429 // Translate the actual panic invoke/call.
430 do_call(self, bx, fn_ty, llfn, &args, None, cleanup);
433 mir::TerminatorKind::DropAndReplace { .. } => {
434 bug!("undesugared DropAndReplace in trans: {:?}", terminator);
437 mir::TerminatorKind::Call { ref func, ref args, ref destination, cleanup } => {
438 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
439 let callee = self.trans_operand(&bx, func);
441 let (instance, mut llfn) = match callee.layout.ty.sty {
442 ty::TyFnDef(def_id, substs) => {
443 (Some(ty::Instance::resolve(bx.cx.tcx,
444 ty::ParamEnv::empty(traits::Reveal::All),
450 (None, Some(callee.immediate()))
452 _ => bug!("{} is not callable", callee.layout.ty)
454 let def = instance.map(|i| i.def);
455 let sig = callee.layout.ty.fn_sig(bx.tcx());
456 let sig = bx.tcx().erase_late_bound_regions_and_normalize(&sig);
459 // Handle intrinsics old trans wants Expr's for, ourselves.
460 let intrinsic = match def {
461 Some(ty::InstanceDef::Intrinsic(def_id))
462 => Some(bx.tcx().item_name(def_id)),
465 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
467 if intrinsic == Some("transmute") {
468 let &(ref dest, target) = destination.as_ref().unwrap();
469 self.trans_transmute(&bx, &args[0], dest);
470 funclet_br(self, bx, target);
474 let extra_args = &args[sig.inputs().len()..];
475 let extra_args = extra_args.iter().map(|op_arg| {
476 let op_ty = op_arg.ty(self.mir, bx.tcx());
477 self.monomorphize(&op_ty)
478 }).collect::<Vec<_>>();
480 let fn_ty = match def {
481 Some(ty::InstanceDef::Virtual(..)) => {
482 FnType::new_vtable(bx.cx, sig, &extra_args)
484 Some(ty::InstanceDef::DropGlue(_, None)) => {
485 // empty drop glue - a nop.
486 let &(_, target) = destination.as_ref().unwrap();
487 funclet_br(self, bx, target);
490 _ => FnType::new(bx.cx, sig, &extra_args)
493 // The arguments we'll be passing. Plus one to account for outptr, if used.
494 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
495 let mut llargs = Vec::with_capacity(arg_count);
497 // Prepare the return value destination
498 let ret_dest = if let Some((ref dest, _)) = *destination {
499 let is_intrinsic = intrinsic.is_some();
500 self.make_return_dest(&bx, dest, &fn_ty.ret, &mut llargs,
506 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
507 use intrinsic::trans_intrinsic_call;
509 let dest = match ret_dest {
510 _ if fn_ty.ret.is_indirect() => llargs[0],
511 ReturnDest::Nothing => {
512 C_undef(fn_ty.ret.memory_ty(bx.cx).ptr_to())
514 ReturnDest::IndirectOperand(dst, _) |
515 ReturnDest::Store(dst) => dst.llval,
516 ReturnDest::DirectOperand(_) =>
517 bug!("Cannot use direct operand with an intrinsic call")
520 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
521 // The indices passed to simd_shuffle* in the
522 // third argument must be constant. This is
523 // checked by const-qualification, which also
524 // promotes any complex rvalues to constants.
525 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
527 mir::Operand::Copy(_) |
528 mir::Operand::Move(_) => {
529 span_bug!(span, "shuffle indices must be constant");
531 mir::Operand::Constant(ref constant) => {
532 let val = self.trans_constant(&bx, constant);
534 val: Immediate(val.llval),
535 layout: bx.cx.layout_of(val.ty)
541 self.trans_operand(&bx, arg)
545 let callee_ty = instance.as_ref().unwrap().ty(bx.cx.tcx);
546 trans_intrinsic_call(&bx, callee_ty, &fn_ty, &args, dest,
547 terminator.source_info.span);
549 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
550 self.store_return(&bx, ret_dest, &fn_ty.ret, dst.llval);
553 if let Some((_, target)) = *destination {
554 funclet_br(self, bx, target);
562 // Split the rust-call tupled arguments off.
563 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
564 let (tup, args) = args.split_last().unwrap();
570 for (i, arg) in first_args.iter().enumerate() {
571 let mut op = self.trans_operand(&bx, arg);
572 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
573 if let Pair(data_ptr, meta) = op.val {
574 llfn = Some(meth::VirtualIndex::from_index(idx)
575 .get_fn(&bx, meta, &fn_ty));
576 llargs.push(data_ptr);
581 // The callee needs to own the argument memory if we pass it
582 // by-ref, so make a local copy of non-immediate constants.
583 match (arg, op.val) {
584 (&mir::Operand::Copy(_), Ref(..)) |
585 (&mir::Operand::Constant(_), Ref(..)) => {
586 let tmp = PlaceRef::alloca(&bx, op.layout, "const");
587 op.val.store(&bx, tmp);
588 op.val = Ref(tmp.llval, tmp.align);
593 self.trans_argument(&bx, op, &mut llargs, &fn_ty.args[i]);
595 if let Some(tup) = untuple {
596 self.trans_arguments_untupled(&bx, tup, &mut llargs,
597 &fn_ty.args[first_args.len()..])
600 let fn_ptr = match (llfn, instance) {
601 (Some(llfn), _) => llfn,
602 (None, Some(instance)) => callee::get_fn(bx.cx, instance),
603 _ => span_bug!(span, "no llfn for call"),
606 do_call(self, bx, fn_ty, fn_ptr, &llargs,
607 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
610 mir::TerminatorKind::GeneratorDrop |
611 mir::TerminatorKind::Yield { .. } |
612 mir::TerminatorKind::FalseEdges { .. } => bug!("generator ops in trans"),
616 fn trans_argument(&mut self,
617 bx: &Builder<'a, 'tcx>,
618 op: OperandRef<'tcx>,
619 llargs: &mut Vec<ValueRef>,
620 arg: &ArgType<'tcx>) {
621 // Fill padding with undef value, where applicable.
622 if let Some(ty) = arg.pad {
623 llargs.push(C_undef(ty.llvm_type(bx.cx)));
630 if let PassMode::Pair(..) = arg.mode {
637 _ => bug!("trans_argument: {:?} invalid for pair arugment", op)
641 // Force by-ref if we have to load through a cast pointer.
642 let (mut llval, align, by_ref) = match op.val {
643 Immediate(_) | Pair(..) => {
645 PassMode::Indirect(_) | PassMode::Cast(_) => {
646 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
647 op.val.store(bx, scratch);
648 (scratch.llval, scratch.align, true)
651 (op.immediate_or_packed_pair(bx), arg.layout.align, false)
655 Ref(llval, align) => {
656 if arg.is_indirect() && align.abi() < arg.layout.align.abi() {
657 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
658 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
659 // have scary latent bugs around.
661 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
662 base::memcpy_ty(bx, scratch.llval, llval, op.layout, align);
663 (scratch.llval, scratch.align, true)
670 if by_ref && !arg.is_indirect() {
671 // Have to load the argument, maybe while casting it.
672 if let PassMode::Cast(ty) = arg.mode {
673 llval = bx.load(bx.pointercast(llval, ty.llvm_type(bx.cx).ptr_to()),
674 align.min(arg.layout.align));
676 // We can't use `PlaceRef::load` here because the argument
677 // may have a type we don't treat as immediate, but the ABI
678 // used for this call is passing it by-value. In that case,
679 // the load would just produce `OperandValue::Ref` instead
680 // of the `OperandValue::Immediate` we need for the call.
681 llval = bx.load(llval, align);
682 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
683 if scalar.is_bool() {
684 bx.range_metadata(llval, 0..2);
687 // We store bools as i8 so we need to truncate to i1.
688 llval = base::to_immediate(bx, llval, arg.layout);
695 fn trans_arguments_untupled(&mut self,
696 bx: &Builder<'a, 'tcx>,
697 operand: &mir::Operand<'tcx>,
698 llargs: &mut Vec<ValueRef>,
699 args: &[ArgType<'tcx>]) {
700 let tuple = self.trans_operand(bx, operand);
702 // Handle both by-ref and immediate tuples.
703 if let Ref(llval, align) = tuple.val {
704 let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
705 for i in 0..tuple.layout.fields.count() {
706 let field_ptr = tuple_ptr.project_field(bx, i);
707 self.trans_argument(bx, field_ptr.load(bx), llargs, &args[i]);
710 // If the tuple is immediate, the elements are as well.
711 for i in 0..tuple.layout.fields.count() {
712 let op = tuple.extract_field(bx, i);
713 self.trans_argument(bx, op, llargs, &args[i]);
718 fn get_personality_slot(&mut self, bx: &Builder<'a, 'tcx>) -> PlaceRef<'tcx> {
720 if let Some(slot) = self.personality_slot {
723 let layout = cx.layout_of(cx.tcx.intern_tup(&[
724 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
727 let slot = PlaceRef::alloca(bx, layout, "personalityslot");
728 self.personality_slot = Some(slot);
733 /// Return the landingpad wrapper around the given basic block
735 /// No-op in MSVC SEH scheme.
736 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> BasicBlockRef {
737 if let Some(block) = self.landing_pads[target_bb] {
741 let block = self.blocks[target_bb];
742 let landing_pad = self.landing_pad_uncached(block);
743 self.landing_pads[target_bb] = Some(landing_pad);
747 fn landing_pad_uncached(&mut self, target_bb: BasicBlockRef) -> BasicBlockRef {
748 if base::wants_msvc_seh(self.cx.sess()) {
749 span_bug!(self.mir.span, "landing pad was not inserted?")
752 let bx = self.new_block("cleanup");
754 let llpersonality = self.cx.eh_personality();
755 let llretty = self.landing_pad_type();
756 let lp = bx.landing_pad(llretty, llpersonality, 1);
759 let slot = self.get_personality_slot(&bx);
760 slot.storage_live(&bx);
761 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&bx, slot);
767 fn landing_pad_type(&self) -> Type {
769 Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)], false)
772 fn unreachable_block(&mut self) -> BasicBlockRef {
773 self.unreachable_block.unwrap_or_else(|| {
774 let bl = self.new_block("unreachable");
776 self.unreachable_block = Some(bl.llbb());
781 pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
782 Builder::new_block(self.cx, self.llfn, name)
785 pub fn build_block(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> {
786 let bx = Builder::with_cx(self.cx);
787 bx.position_at_end(self.blocks[bb]);
791 fn make_return_dest(&mut self, bx: &Builder<'a, 'tcx>,
792 dest: &mir::Place<'tcx>, fn_ret: &ArgType<'tcx>,
793 llargs: &mut Vec<ValueRef>, is_intrinsic: bool)
794 -> ReturnDest<'tcx> {
795 // If the return is ignored, we can just return a do-nothing ReturnDest
796 if fn_ret.is_ignore() {
797 return ReturnDest::Nothing;
799 let dest = if let mir::Place::Local(index) = *dest {
800 match self.locals[index] {
801 LocalRef::Place(dest) => dest,
802 LocalRef::Operand(None) => {
803 // Handle temporary places, specifically Operand ones, as
804 // they don't have allocas
805 return if fn_ret.is_indirect() {
806 // Odd, but possible, case, we have an operand temporary,
807 // but the calling convention has an indirect return.
808 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
809 tmp.storage_live(bx);
810 llargs.push(tmp.llval);
811 ReturnDest::IndirectOperand(tmp, index)
812 } else if is_intrinsic {
813 // Currently, intrinsics always need a location to store
814 // the result. so we create a temporary alloca for the
816 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
817 tmp.storage_live(bx);
818 ReturnDest::IndirectOperand(tmp, index)
820 ReturnDest::DirectOperand(index)
823 LocalRef::Operand(Some(_)) => {
824 bug!("place local already assigned to");
828 self.trans_place(bx, dest)
830 if fn_ret.is_indirect() {
831 if dest.align.abi() < dest.layout.align.abi() {
832 // Currently, MIR code generation does not create calls
833 // that store directly to fields of packed structs (in
834 // fact, the calls it creates write only to temps),
836 // If someone changes that, please update this code path
837 // to create a temporary.
838 span_bug!(self.mir.span, "can't directly store to unaligned value");
840 llargs.push(dest.llval);
843 ReturnDest::Store(dest)
847 fn trans_transmute(&mut self, bx: &Builder<'a, 'tcx>,
848 src: &mir::Operand<'tcx>,
849 dst: &mir::Place<'tcx>) {
850 if let mir::Place::Local(index) = *dst {
851 match self.locals[index] {
852 LocalRef::Place(place) => self.trans_transmute_into(bx, src, place),
853 LocalRef::Operand(None) => {
854 let dst_layout = bx.cx.layout_of(self.monomorphized_place_ty(dst));
855 assert!(!dst_layout.ty.has_erasable_regions());
856 let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
857 place.storage_live(bx);
858 self.trans_transmute_into(bx, src, place);
859 let op = place.load(bx);
860 place.storage_dead(bx);
861 self.locals[index] = LocalRef::Operand(Some(op));
863 LocalRef::Operand(Some(op)) => {
864 assert!(op.layout.is_zst(),
865 "assigning to initialized SSAtemp");
869 let dst = self.trans_place(bx, dst);
870 self.trans_transmute_into(bx, src, dst);
874 fn trans_transmute_into(&mut self, bx: &Builder<'a, 'tcx>,
875 src: &mir::Operand<'tcx>,
876 dst: PlaceRef<'tcx>) {
877 let src = self.trans_operand(bx, src);
878 let llty = src.layout.llvm_type(bx.cx);
879 let cast_ptr = bx.pointercast(dst.llval, llty.ptr_to());
880 let align = src.layout.align.min(dst.layout.align);
881 src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
885 // Stores the return value of a function call into it's final location.
886 fn store_return(&mut self,
887 bx: &Builder<'a, 'tcx>,
888 dest: ReturnDest<'tcx>,
889 ret_ty: &ArgType<'tcx>,
891 use self::ReturnDest::*;
895 Store(dst) => ret_ty.store(bx, llval, dst),
896 IndirectOperand(tmp, index) => {
897 let op = tmp.load(bx);
898 tmp.storage_dead(bx);
899 self.locals[index] = LocalRef::Operand(Some(op));
901 DirectOperand(index) => {
902 // If there is a cast, we have to store and reload.
903 let op = if let PassMode::Cast(_) = ret_ty.mode {
904 let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
905 tmp.storage_live(bx);
906 ret_ty.store(bx, llval, tmp);
907 let op = tmp.load(bx);
908 tmp.storage_dead(bx);
911 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
913 self.locals[index] = LocalRef::Operand(Some(op));
919 enum ReturnDest<'tcx> {
920 // Do nothing, the return value is indirect or ignored
922 // Store the return value to the pointer
923 Store(PlaceRef<'tcx>),
924 // Stores an indirect return value to an operand local place
925 IndirectOperand(PlaceRef<'tcx>, mir::Local),
926 // Stores a direct return value to an operand local place
927 DirectOperand(mir::Local)