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::ty::{self, TypeFoldable};
14 use rustc::ty::layout::{self, LayoutOf};
16 use abi::{Abi, FnType, ArgType, PassMode};
20 use common::{self, C_bool, C_str_slice, C_struct, C_u32, C_uint_big, C_undef};
24 use type_of::LayoutLlvmExt;
27 use syntax::symbol::Symbol;
30 use super::{FunctionCx, LocalRef};
31 use super::place::PlaceRef;
32 use super::operand::OperandRef;
33 use super::operand::OperandValue::{Pair, Ref, Immediate};
35 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
36 pub fn trans_block(&mut self, bb: mir::BasicBlock) {
37 let mut bx = self.build_block(bb);
38 let data = &self.mir[bb];
40 debug!("trans_block({:?}={:?})", bb, data);
42 for statement in &data.statements {
43 bx = self.trans_statement(bx, statement);
46 self.trans_terminator(bx, bb, data.terminator());
49 fn trans_terminator(&mut self,
50 mut bx: Builder<'a, 'tcx>,
52 terminator: &mir::Terminator<'tcx>)
54 debug!("trans_terminator: {:?}", terminator);
56 // Create the cleanup bundle, if needed.
58 let span = terminator.source_info.span;
59 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
60 let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());
62 let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
63 let cleanup_bundle = funclet.map(|l| l.bundle());
65 let lltarget = |this: &mut Self, target: mir::BasicBlock| {
66 let lltarget = this.blocks[target];
67 let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
68 match (funclet_bb, target_funclet) {
69 (None, None) => (lltarget, false),
71 if f == t_f || !base::wants_msvc_seh(tcx.sess)
74 // jump *into* cleanup - need a landing pad if GNU
75 (this.landing_pad_to(target), false)
77 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
78 (Some(_), Some(_)) => {
79 (this.landing_pad_to(target), true)
84 let llblock = |this: &mut Self, target: mir::BasicBlock| {
85 let (lltarget, is_cleanupret) = lltarget(this, target);
87 // MSVC cross-funclet jump - need a trampoline
89 debug!("llblock: creating cleanup trampoline for {:?}", target);
90 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
91 let trampoline = this.new_block(name);
92 trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
99 let funclet_br = |this: &mut Self, bx: Builder, target: mir::BasicBlock| {
100 let (lltarget, is_cleanupret) = lltarget(this, target);
102 // micro-optimization: generate a `ret` rather than a jump
104 bx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
112 bx: Builder<'a, 'tcx>,
116 destination: Option<(ReturnDest<'tcx>, mir::BasicBlock)>,
117 cleanup: Option<mir::BasicBlock>
119 if let Some(cleanup) = cleanup {
120 let ret_bx = if let Some((_, target)) = destination {
123 this.unreachable_block()
125 let invokeret = bx.invoke(fn_ptr,
128 llblock(this, cleanup),
130 fn_ty.apply_attrs_callsite(invokeret);
132 if let Some((ret_dest, target)) = destination {
133 let ret_bx = this.build_block(target);
134 this.set_debug_loc(&ret_bx, terminator.source_info);
135 this.store_return(&ret_bx, ret_dest, &fn_ty.ret, invokeret);
138 let llret = bx.call(fn_ptr, &llargs, cleanup_bundle);
139 fn_ty.apply_attrs_callsite(llret);
140 if this.mir[bb].is_cleanup {
141 // Cleanup is always the cold path. Don't inline
142 // drop glue. Also, when there is a deeply-nested
143 // struct, there are "symmetry" issues that cause
144 // exponential inlining - see issue #41696.
145 llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
148 if let Some((ret_dest, target)) = destination {
149 this.store_return(&bx, ret_dest, &fn_ty.ret, llret);
150 funclet_br(this, bx, target);
157 self.set_debug_loc(&bx, terminator.source_info);
158 match terminator.kind {
159 mir::TerminatorKind::Resume => {
160 if let Some(cleanup_pad) = cleanup_pad {
161 bx.cleanup_ret(cleanup_pad, None);
163 let slot = self.get_personality_slot(&bx);
164 let lp0 = slot.project_field(&bx, 0).load(&bx).immediate();
165 let lp1 = slot.project_field(&bx, 1).load(&bx).immediate();
166 slot.storage_dead(&bx);
168 if !bx.sess().target.target.options.custom_unwind_resume {
169 let mut lp = C_undef(self.landing_pad_type());
170 lp = bx.insert_value(lp, lp0, 0);
171 lp = bx.insert_value(lp, lp1, 1);
174 bx.call(bx.cx.eh_unwind_resume(), &[lp0], cleanup_bundle);
180 mir::TerminatorKind::Abort => {
181 // Call core::intrinsics::abort()
182 let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
183 bx.call(fnname, &[], None);
187 mir::TerminatorKind::Goto { target } => {
188 funclet_br(self, bx, target);
191 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
192 let discr = self.trans_operand(&bx, discr);
193 if switch_ty == bx.tcx().types.bool {
194 let lltrue = llblock(self, targets[0]);
195 let llfalse = llblock(self, targets[1]);
196 if let [0] = values[..] {
197 bx.cond_br(discr.immediate(), llfalse, lltrue);
199 assert_eq!(&values[..], &[1]);
200 bx.cond_br(discr.immediate(), lltrue, llfalse);
203 let (otherwise, targets) = targets.split_last().unwrap();
204 let switch = bx.switch(discr.immediate(),
205 llblock(self, *otherwise), values.len());
206 let switch_llty = bx.cx.layout_of(switch_ty).immediate_llvm_type(bx.cx);
207 for (&value, target) in values.iter().zip(targets) {
208 let llval = C_uint_big(switch_llty, value);
209 let llbb = llblock(self, *target);
210 bx.add_case(switch, llval, llbb)
215 mir::TerminatorKind::Return => {
216 let llval = match self.fn_ty.ret.mode {
217 PassMode::Ignore | PassMode::Indirect(_) => {
222 PassMode::Direct(_) | PassMode::Pair(..) => {
223 let op = self.trans_consume(&bx, &mir::Place::Local(mir::RETURN_PLACE));
224 if let Ref(llval, align) = op.val {
225 bx.load(llval, align)
227 op.immediate_or_packed_pair(&bx)
231 PassMode::Cast(cast_ty) => {
232 let op = match self.locals[mir::RETURN_PLACE] {
233 LocalRef::Operand(Some(op)) => op,
234 LocalRef::Operand(None) => bug!("use of return before def"),
235 LocalRef::Place(tr_place) => {
237 val: Ref(tr_place.llval, tr_place.align),
238 layout: tr_place.layout
242 let llslot = match op.val {
243 Immediate(_) | Pair(..) => {
244 let scratch = PlaceRef::alloca(&bx, self.fn_ty.ret.layout, "ret");
245 op.val.store(&bx, scratch);
248 Ref(llval, align) => {
249 assert_eq!(align.abi(), op.layout.align.abi(),
250 "return place is unaligned!");
255 bx.pointercast(llslot, cast_ty.llvm_type(bx.cx).ptr_to()),
256 self.fn_ty.ret.layout.align)
262 mir::TerminatorKind::Unreachable => {
266 mir::TerminatorKind::Drop { ref location, target, unwind } => {
267 let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
268 let ty = self.monomorphize(&ty);
269 let drop_fn = monomorphize::resolve_drop_in_place(bx.cx.tcx, ty);
271 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
272 // we don't actually need to drop anything.
273 funclet_br(self, bx, target);
277 let place = self.trans_place(&bx, location);
278 let mut args: &[_] = &[place.llval, place.llextra];
279 args = &args[..1 + place.has_extra() as usize];
280 let (drop_fn, fn_ty) = match ty.sty {
281 ty::TyDynamic(..) => {
282 let fn_ty = drop_fn.ty(bx.cx.tcx);
283 let sig = common::ty_fn_sig(bx.cx, fn_ty);
284 let sig = bx.tcx().erase_late_bound_regions_and_normalize(&sig);
285 let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
287 (meth::DESTRUCTOR.get_fn(&bx, place.llextra, &fn_ty), fn_ty)
290 (callee::get_fn(bx.cx, drop_fn),
291 FnType::of_instance(bx.cx, &drop_fn))
294 do_call(self, bx, fn_ty, drop_fn, args,
295 Some((ReturnDest::Nothing, target)),
299 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
300 let cond = self.trans_operand(&bx, cond).immediate();
301 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
303 // This case can currently arise only from functions marked
304 // with #[rustc_inherit_overflow_checks] and inlined from
305 // another crate (mostly core::num generic/#[inline] fns),
306 // while the current crate doesn't use overflow checks.
307 // NOTE: Unlike binops, negation doesn't have its own
308 // checked operation, just a comparison with the minimum
309 // value, so we have to check for the assert message.
310 if !bx.cx.check_overflow {
311 use rustc_const_math::ConstMathErr::Overflow;
312 use rustc_const_math::Op::Neg;
314 if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
315 const_cond = Some(expected);
319 // Don't translate the panic block if success if known.
320 if const_cond == Some(expected) {
321 funclet_br(self, bx, target);
325 // Pass the condition through llvm.expect for branch hinting.
326 let expect = bx.cx.get_intrinsic(&"llvm.expect.i1");
327 let cond = bx.call(expect, &[cond, C_bool(bx.cx, expected)], None);
329 // Create the failure block and the conditional branch to it.
330 let lltarget = llblock(self, target);
331 let panic_block = self.new_block("panic");
333 bx.cond_br(cond, lltarget, panic_block.llbb());
335 bx.cond_br(cond, panic_block.llbb(), lltarget);
338 // After this point, bx is the block for the call to panic.
340 self.set_debug_loc(&bx, terminator.source_info);
342 // Get the location information.
343 let loc = bx.sess().codemap().lookup_char_pos(span.lo());
344 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
345 let filename = C_str_slice(bx.cx, filename);
346 let line = C_u32(bx.cx, loc.line as u32);
347 let col = C_u32(bx.cx, loc.col.to_usize() as u32 + 1);
348 let align = tcx.data_layout.aggregate_align
349 .max(tcx.data_layout.i32_align)
350 .max(tcx.data_layout.pointer_align);
352 // Put together the arguments to the panic entry point.
353 let (lang_item, args) = match *msg {
354 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
355 let len = self.trans_operand(&mut bx, len).immediate();
356 let index = self.trans_operand(&mut bx, index).immediate();
358 let file_line_col = C_struct(bx.cx, &[filename, line, col], false);
359 let file_line_col = consts::addr_of(bx.cx,
362 "panic_bounds_check_loc");
363 (lang_items::PanicBoundsCheckFnLangItem,
364 vec![file_line_col, index, len])
366 mir::AssertMessage::Math(ref err) => {
367 let msg_str = Symbol::intern(err.description()).as_str();
368 let msg_str = C_str_slice(bx.cx, msg_str);
369 let msg_file_line_col = C_struct(bx.cx,
370 &[msg_str, filename, line, col],
372 let msg_file_line_col = consts::addr_of(bx.cx,
376 (lang_items::PanicFnLangItem,
377 vec![msg_file_line_col])
379 mir::AssertMessage::GeneratorResumedAfterReturn |
380 mir::AssertMessage::GeneratorResumedAfterPanic => {
381 let str = if let mir::AssertMessage::GeneratorResumedAfterReturn = *msg {
382 "generator resumed after completion"
384 "generator resumed after panicking"
386 let msg_str = Symbol::intern(str).as_str();
387 let msg_str = C_str_slice(bx.cx, msg_str);
388 let msg_file_line_col = C_struct(bx.cx,
389 &[msg_str, filename, line, col],
391 let msg_file_line_col = consts::addr_of(bx.cx,
395 (lang_items::PanicFnLangItem,
396 vec![msg_file_line_col])
400 // Obtain the panic entry point.
401 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
402 let instance = ty::Instance::mono(bx.tcx(), def_id);
403 let fn_ty = FnType::of_instance(bx.cx, &instance);
404 let llfn = callee::get_fn(bx.cx, instance);
406 // Translate the actual panic invoke/call.
407 do_call(self, bx, fn_ty, llfn, &args, None, cleanup);
410 mir::TerminatorKind::DropAndReplace { .. } => {
411 bug!("undesugared DropAndReplace in trans: {:?}", terminator);
414 mir::TerminatorKind::Call { ref func, ref args, ref destination, cleanup } => {
415 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
416 let callee = self.trans_operand(&bx, func);
418 let (instance, mut llfn) = match callee.layout.ty.sty {
419 ty::TyFnDef(def_id, substs) => {
420 (Some(ty::Instance::resolve(bx.cx.tcx,
421 ty::ParamEnv::reveal_all(),
427 (None, Some(callee.immediate()))
429 _ => bug!("{} is not callable", callee.layout.ty)
431 let def = instance.map(|i| i.def);
432 let sig = callee.layout.ty.fn_sig(bx.tcx());
433 let sig = bx.tcx().erase_late_bound_regions_and_normalize(&sig);
436 // Handle intrinsics old trans wants Expr's for, ourselves.
437 let intrinsic = match def {
438 Some(ty::InstanceDef::Intrinsic(def_id))
439 => Some(bx.tcx().item_name(def_id)),
442 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
444 if intrinsic == Some("transmute") {
445 let &(ref dest, target) = destination.as_ref().unwrap();
446 self.trans_transmute(&bx, &args[0], dest);
447 funclet_br(self, bx, target);
451 let extra_args = &args[sig.inputs().len()..];
452 let extra_args = extra_args.iter().map(|op_arg| {
453 let op_ty = op_arg.ty(self.mir, bx.tcx());
454 self.monomorphize(&op_ty)
455 }).collect::<Vec<_>>();
457 let fn_ty = match def {
458 Some(ty::InstanceDef::Virtual(..)) => {
459 FnType::new_vtable(bx.cx, sig, &extra_args)
461 Some(ty::InstanceDef::DropGlue(_, None)) => {
462 // empty drop glue - a nop.
463 let &(_, target) = destination.as_ref().unwrap();
464 funclet_br(self, bx, target);
467 _ => FnType::new(bx.cx, sig, &extra_args)
470 // The arguments we'll be passing. Plus one to account for outptr, if used.
471 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
472 let mut llargs = Vec::with_capacity(arg_count);
474 // Prepare the return value destination
475 let ret_dest = if let Some((ref dest, _)) = *destination {
476 let is_intrinsic = intrinsic.is_some();
477 self.make_return_dest(&bx, dest, &fn_ty.ret, &mut llargs,
483 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
484 use intrinsic::trans_intrinsic_call;
486 let dest = match ret_dest {
487 _ if fn_ty.ret.is_indirect() => llargs[0],
488 ReturnDest::Nothing => {
489 C_undef(fn_ty.ret.memory_ty(bx.cx).ptr_to())
491 ReturnDest::IndirectOperand(dst, _) |
492 ReturnDest::Store(dst) => dst.llval,
493 ReturnDest::DirectOperand(_) =>
494 bug!("Cannot use direct operand with an intrinsic call")
497 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
498 // The indices passed to simd_shuffle* in the
499 // third argument must be constant. This is
500 // checked by const-qualification, which also
501 // promotes any complex rvalues to constants.
502 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
504 mir::Operand::Copy(_) |
505 mir::Operand::Move(_) => {
506 span_bug!(span, "shuffle indices must be constant");
508 mir::Operand::Constant(ref constant) => {
509 let (llval, ty) = self.simd_shuffle_indices(
514 val: Immediate(llval),
515 layout: bx.cx.layout_of(ty)
521 self.trans_operand(&bx, arg)
525 let callee_ty = instance.as_ref().unwrap().ty(bx.cx.tcx);
526 trans_intrinsic_call(&bx, callee_ty, &fn_ty, &args, dest,
527 terminator.source_info.span);
529 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
530 self.store_return(&bx, ret_dest, &fn_ty.ret, dst.llval);
533 if let Some((_, target)) = *destination {
534 funclet_br(self, bx, target);
542 // Split the rust-call tupled arguments off.
543 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
544 let (tup, args) = args.split_last().unwrap();
550 for (i, arg) in first_args.iter().enumerate() {
551 let mut op = self.trans_operand(&bx, arg);
552 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
553 if let Pair(data_ptr, meta) = op.val {
554 llfn = Some(meth::VirtualIndex::from_index(idx)
555 .get_fn(&bx, meta, &fn_ty));
556 llargs.push(data_ptr);
561 // The callee needs to own the argument memory if we pass it
562 // by-ref, so make a local copy of non-immediate constants.
563 match (arg, op.val) {
564 (&mir::Operand::Copy(_), Ref(..)) |
565 (&mir::Operand::Constant(_), Ref(..)) => {
566 let tmp = PlaceRef::alloca(&bx, op.layout, "const");
567 op.val.store(&bx, tmp);
568 op.val = Ref(tmp.llval, tmp.align);
573 self.trans_argument(&bx, op, &mut llargs, &fn_ty.args[i]);
575 if let Some(tup) = untuple {
576 self.trans_arguments_untupled(&bx, tup, &mut llargs,
577 &fn_ty.args[first_args.len()..])
580 let fn_ptr = match (llfn, instance) {
581 (Some(llfn), _) => llfn,
582 (None, Some(instance)) => callee::get_fn(bx.cx, instance),
583 _ => span_bug!(span, "no llfn for call"),
586 do_call(self, bx, fn_ty, fn_ptr, &llargs,
587 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
590 mir::TerminatorKind::GeneratorDrop |
591 mir::TerminatorKind::Yield { .. } => bug!("generator ops in trans"),
592 mir::TerminatorKind::FalseEdges { .. } |
593 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in trans"),
597 fn trans_argument(&mut self,
598 bx: &Builder<'a, 'tcx>,
599 op: OperandRef<'tcx>,
600 llargs: &mut Vec<ValueRef>,
601 arg: &ArgType<'tcx>) {
602 // Fill padding with undef value, where applicable.
603 if let Some(ty) = arg.pad {
604 llargs.push(C_undef(ty.llvm_type(bx.cx)));
611 if let PassMode::Pair(..) = arg.mode {
618 _ => bug!("trans_argument: {:?} invalid for pair arugment", op)
622 // Force by-ref if we have to load through a cast pointer.
623 let (mut llval, align, by_ref) = match op.val {
624 Immediate(_) | Pair(..) => {
626 PassMode::Indirect(_) | PassMode::Cast(_) => {
627 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
628 op.val.store(bx, scratch);
629 (scratch.llval, scratch.align, true)
632 (op.immediate_or_packed_pair(bx), arg.layout.align, false)
636 Ref(llval, align) => {
637 if arg.is_indirect() && align.abi() < arg.layout.align.abi() {
638 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
639 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
640 // have scary latent bugs around.
642 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
643 base::memcpy_ty(bx, scratch.llval, llval, op.layout, align);
644 (scratch.llval, scratch.align, true)
651 if by_ref && !arg.is_indirect() {
652 // Have to load the argument, maybe while casting it.
653 if let PassMode::Cast(ty) = arg.mode {
654 llval = bx.load(bx.pointercast(llval, ty.llvm_type(bx.cx).ptr_to()),
655 align.min(arg.layout.align));
657 // We can't use `PlaceRef::load` here because the argument
658 // may have a type we don't treat as immediate, but the ABI
659 // used for this call is passing it by-value. In that case,
660 // the load would just produce `OperandValue::Ref` instead
661 // of the `OperandValue::Immediate` we need for the call.
662 llval = bx.load(llval, align);
663 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
664 if scalar.is_bool() {
665 bx.range_metadata(llval, 0..2);
668 // We store bools as i8 so we need to truncate to i1.
669 llval = base::to_immediate(bx, llval, arg.layout);
676 fn trans_arguments_untupled(&mut self,
677 bx: &Builder<'a, 'tcx>,
678 operand: &mir::Operand<'tcx>,
679 llargs: &mut Vec<ValueRef>,
680 args: &[ArgType<'tcx>]) {
681 let tuple = self.trans_operand(bx, operand);
683 // Handle both by-ref and immediate tuples.
684 if let Ref(llval, align) = tuple.val {
685 let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
686 for i in 0..tuple.layout.fields.count() {
687 let field_ptr = tuple_ptr.project_field(bx, i);
688 self.trans_argument(bx, field_ptr.load(bx), llargs, &args[i]);
691 // If the tuple is immediate, the elements are as well.
692 for i in 0..tuple.layout.fields.count() {
693 let op = tuple.extract_field(bx, i);
694 self.trans_argument(bx, op, llargs, &args[i]);
699 fn get_personality_slot(&mut self, bx: &Builder<'a, 'tcx>) -> PlaceRef<'tcx> {
701 if let Some(slot) = self.personality_slot {
704 let layout = cx.layout_of(cx.tcx.intern_tup(&[
705 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
708 let slot = PlaceRef::alloca(bx, layout, "personalityslot");
709 self.personality_slot = Some(slot);
714 /// Return the landingpad wrapper around the given basic block
716 /// No-op in MSVC SEH scheme.
717 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> BasicBlockRef {
718 if let Some(block) = self.landing_pads[target_bb] {
722 let block = self.blocks[target_bb];
723 let landing_pad = self.landing_pad_uncached(block);
724 self.landing_pads[target_bb] = Some(landing_pad);
728 fn landing_pad_uncached(&mut self, target_bb: BasicBlockRef) -> BasicBlockRef {
729 if base::wants_msvc_seh(self.cx.sess()) {
730 span_bug!(self.mir.span, "landing pad was not inserted?")
733 let bx = self.new_block("cleanup");
735 let llpersonality = self.cx.eh_personality();
736 let llretty = self.landing_pad_type();
737 let lp = bx.landing_pad(llretty, llpersonality, 1);
740 let slot = self.get_personality_slot(&bx);
741 slot.storage_live(&bx);
742 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&bx, slot);
748 fn landing_pad_type(&self) -> Type {
750 Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)], false)
753 fn unreachable_block(&mut self) -> BasicBlockRef {
754 self.unreachable_block.unwrap_or_else(|| {
755 let bl = self.new_block("unreachable");
757 self.unreachable_block = Some(bl.llbb());
762 pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
763 Builder::new_block(self.cx, self.llfn, name)
766 pub fn build_block(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> {
767 let bx = Builder::with_cx(self.cx);
768 bx.position_at_end(self.blocks[bb]);
772 fn make_return_dest(&mut self, bx: &Builder<'a, 'tcx>,
773 dest: &mir::Place<'tcx>, fn_ret: &ArgType<'tcx>,
774 llargs: &mut Vec<ValueRef>, is_intrinsic: bool)
775 -> ReturnDest<'tcx> {
776 // If the return is ignored, we can just return a do-nothing ReturnDest
777 if fn_ret.is_ignore() {
778 return ReturnDest::Nothing;
780 let dest = if let mir::Place::Local(index) = *dest {
781 match self.locals[index] {
782 LocalRef::Place(dest) => dest,
783 LocalRef::Operand(None) => {
784 // Handle temporary places, specifically Operand ones, as
785 // they don't have allocas
786 return if fn_ret.is_indirect() {
787 // Odd, but possible, case, we have an operand temporary,
788 // but the calling convention has an indirect return.
789 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
790 tmp.storage_live(bx);
791 llargs.push(tmp.llval);
792 ReturnDest::IndirectOperand(tmp, index)
793 } else if is_intrinsic {
794 // Currently, intrinsics always need a location to store
795 // the result. so we create a temporary alloca for the
797 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
798 tmp.storage_live(bx);
799 ReturnDest::IndirectOperand(tmp, index)
801 ReturnDest::DirectOperand(index)
804 LocalRef::Operand(Some(_)) => {
805 bug!("place local already assigned to");
809 self.trans_place(bx, dest)
811 if fn_ret.is_indirect() {
812 if dest.align.abi() < dest.layout.align.abi() {
813 // Currently, MIR code generation does not create calls
814 // that store directly to fields of packed structs (in
815 // fact, the calls it creates write only to temps),
817 // If someone changes that, please update this code path
818 // to create a temporary.
819 span_bug!(self.mir.span, "can't directly store to unaligned value");
821 llargs.push(dest.llval);
824 ReturnDest::Store(dest)
828 fn trans_transmute(&mut self, bx: &Builder<'a, 'tcx>,
829 src: &mir::Operand<'tcx>,
830 dst: &mir::Place<'tcx>) {
831 if let mir::Place::Local(index) = *dst {
832 match self.locals[index] {
833 LocalRef::Place(place) => self.trans_transmute_into(bx, src, place),
834 LocalRef::Operand(None) => {
835 let dst_layout = bx.cx.layout_of(self.monomorphized_place_ty(dst));
836 assert!(!dst_layout.ty.has_erasable_regions());
837 let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
838 place.storage_live(bx);
839 self.trans_transmute_into(bx, src, place);
840 let op = place.load(bx);
841 place.storage_dead(bx);
842 self.locals[index] = LocalRef::Operand(Some(op));
844 LocalRef::Operand(Some(op)) => {
845 assert!(op.layout.is_zst(),
846 "assigning to initialized SSAtemp");
850 let dst = self.trans_place(bx, dst);
851 self.trans_transmute_into(bx, src, dst);
855 fn trans_transmute_into(&mut self, bx: &Builder<'a, 'tcx>,
856 src: &mir::Operand<'tcx>,
857 dst: PlaceRef<'tcx>) {
858 let src = self.trans_operand(bx, src);
859 let llty = src.layout.llvm_type(bx.cx);
860 let cast_ptr = bx.pointercast(dst.llval, llty.ptr_to());
861 let align = src.layout.align.min(dst.layout.align);
862 src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
866 // Stores the return value of a function call into it's final location.
867 fn store_return(&mut self,
868 bx: &Builder<'a, 'tcx>,
869 dest: ReturnDest<'tcx>,
870 ret_ty: &ArgType<'tcx>,
872 use self::ReturnDest::*;
876 Store(dst) => ret_ty.store(bx, llval, dst),
877 IndirectOperand(tmp, index) => {
878 let op = tmp.load(bx);
879 tmp.storage_dead(bx);
880 self.locals[index] = LocalRef::Operand(Some(op));
882 DirectOperand(index) => {
883 // If there is a cast, we have to store and reload.
884 let op = if let PassMode::Cast(_) = ret_ty.mode {
885 let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
886 tmp.storage_live(bx);
887 ret_ty.store(bx, llval, tmp);
888 let op = tmp.load(bx);
889 tmp.storage_dead(bx);
892 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
894 self.locals[index] = LocalRef::Operand(Some(op));
900 enum ReturnDest<'tcx> {
901 // Do nothing, the return value is indirect or ignored
903 // Store the return value to the pointer
904 Store(PlaceRef<'tcx>),
905 // Stores an indirect return value to an operand local place
906 IndirectOperand(PlaceRef<'tcx>, mir::Local),
907 // Stores a direct return value to an operand local place
908 DirectOperand(mir::Local)