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, LayoutTyper};
17 use abi::{Abi, FnType, ArgType};
19 use base::{self, Lifetime};
22 use common::{self, Funclet};
23 use common::{C_bool, C_str_slice, C_struct, C_u32, C_uint, C_undef};
25 use machine::llalign_of_min;
32 use rustc_data_structures::indexed_vec::IndexVec;
33 use syntax::symbol::Symbol;
37 use super::{MirContext, LocalRef};
38 use super::analyze::CleanupKind;
39 use super::constant::Const;
40 use super::lvalue::{Alignment, LvalueRef};
41 use super::operand::OperandRef;
42 use super::operand::OperandValue::{Pair, Ref, Immediate};
44 impl<'a, 'tcx> MirContext<'a, 'tcx> {
45 pub fn trans_block(&mut self, bb: mir::BasicBlock,
46 funclets: &IndexVec<mir::BasicBlock, Option<Funclet>>) {
47 let mut bcx = self.get_builder(bb);
48 let data = &self.mir[bb];
50 debug!("trans_block({:?}={:?})", bb, data);
52 let funclet = match self.cleanup_kinds[bb] {
53 CleanupKind::Internal { funclet } => funclets[funclet].as_ref(),
54 _ => funclets[bb].as_ref(),
57 // Create the cleanup bundle, if needed.
58 let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
59 let cleanup_bundle = funclet.map(|l| l.bundle());
61 let funclet_br = |this: &Self, bcx: Builder, bb: mir::BasicBlock| {
62 let lltarget = this.blocks[bb];
63 if let Some(cp) = cleanup_pad {
64 match this.cleanup_kinds[bb] {
65 CleanupKind::Funclet => {
66 // micro-optimization: generate a `ret` rather than a jump
68 bcx.cleanup_ret(cp, Some(lltarget));
70 CleanupKind::Internal { .. } => bcx.br(lltarget),
71 CleanupKind::NotCleanup => bug!("jump from cleanup bb to bb {:?}", bb)
78 let llblock = |this: &mut Self, target: mir::BasicBlock| {
79 let lltarget = this.blocks[target];
81 if let Some(cp) = cleanup_pad {
82 match this.cleanup_kinds[target] {
83 CleanupKind::Funclet => {
84 // MSVC cross-funclet jump - need a trampoline
86 debug!("llblock: creating cleanup trampoline for {:?}", target);
87 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
88 let trampoline = this.new_block(name);
89 trampoline.cleanup_ret(cp, Some(lltarget));
92 CleanupKind::Internal { .. } => lltarget,
93 CleanupKind::NotCleanup =>
94 bug!("jump from cleanup bb {:?} to bb {:?}", bb, target)
97 if let (CleanupKind::NotCleanup, CleanupKind::Funclet) =
98 (this.cleanup_kinds[bb], this.cleanup_kinds[target])
100 // jump *into* cleanup - need a landing pad if GNU
101 this.landing_pad_to(target)
108 for statement in &data.statements {
109 bcx = self.trans_statement(bcx, statement);
112 let terminator = data.terminator();
113 debug!("trans_block: terminator: {:?}", terminator);
115 let span = terminator.source_info.span;
116 self.set_debug_loc(&bcx, terminator.source_info);
117 match terminator.kind {
118 mir::TerminatorKind::Resume => {
119 if let Some(cleanup_pad) = cleanup_pad {
120 bcx.cleanup_ret(cleanup_pad, None);
122 let ps = self.get_personality_slot(&bcx);
123 let lp = bcx.load(ps, None);
124 Lifetime::End.call(&bcx, ps);
125 if !bcx.sess().target.target.options.custom_unwind_resume {
128 let exc_ptr = bcx.extract_value(lp, 0);
129 bcx.call(bcx.ccx.eh_unwind_resume(), &[exc_ptr], cleanup_bundle);
135 mir::TerminatorKind::Goto { target } => {
136 funclet_br(self, bcx, target);
139 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
140 let discr = self.trans_operand(&bcx, discr);
141 if switch_ty == bcx.tcx().types.bool {
142 let lltrue = llblock(self, targets[0]);
143 let llfalse = llblock(self, targets[1]);
144 if let [ConstInt::U8(0)] = values[..] {
145 bcx.cond_br(discr.immediate(), llfalse, lltrue);
147 bcx.cond_br(discr.immediate(), lltrue, llfalse);
150 let (otherwise, targets) = targets.split_last().unwrap();
151 let switch = bcx.switch(discr.immediate(),
152 llblock(self, *otherwise), values.len());
153 for (value, target) in values.iter().zip(targets) {
154 let val = Const::from_constint(bcx.ccx, value);
155 let llbb = llblock(self, *target);
156 bcx.add_case(switch, val.llval, llbb)
161 mir::TerminatorKind::Return => {
162 let ret = self.fn_ty.ret;
163 if ret.is_ignore() || ret.is_indirect() {
168 let llval = if let Some(cast_ty) = ret.cast {
169 let op = match self.locals[mir::RETURN_POINTER] {
170 LocalRef::Operand(Some(op)) => op,
171 LocalRef::Operand(None) => bug!("use of return before def"),
172 LocalRef::Lvalue(tr_lvalue) => {
174 val: Ref(tr_lvalue.llval, tr_lvalue.alignment),
175 ty: tr_lvalue.ty.to_ty(bcx.tcx())
179 let llslot = match op.val {
180 Immediate(_) | Pair(..) => {
181 let llscratch = bcx.alloca(ret.memory_ty(bcx.ccx), "ret", None);
182 self.store_operand(&bcx, llscratch, None, op);
185 Ref(llval, align) => {
186 assert_eq!(align, Alignment::AbiAligned,
187 "return pointer is unaligned!");
192 bcx.pointercast(llslot, cast_ty.ptr_to()),
193 Some(ret.layout.align(bcx.ccx).abi() as u32));
196 let op = self.trans_consume(&bcx, &mir::Lvalue::Local(mir::RETURN_POINTER));
197 if let Ref(llval, align) = op.val {
198 base::load_ty(&bcx, llval, align, op.ty)
200 op.pack_if_pair(&bcx).immediate()
206 mir::TerminatorKind::Unreachable => {
210 mir::TerminatorKind::Drop { ref location, target, unwind } => {
211 let ty = location.ty(&self.mir, bcx.tcx()).to_ty(bcx.tcx());
212 let ty = self.monomorphize(&ty);
213 let drop_fn = monomorphize::resolve_drop_in_place(bcx.ccx.shared(), ty);
215 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
216 // we don't actually need to drop anything.
217 funclet_br(self, bcx, target);
221 let lvalue = self.trans_lvalue(&bcx, location);
222 let (drop_fn, need_extra) = match ty.sty {
223 ty::TyDynamic(..) => (meth::DESTRUCTOR.get_fn(&bcx, lvalue.llextra),
225 ty::TyArray(ety, _) | ty::TySlice(ety) => {
226 // FIXME: handle panics
227 let drop_fn = monomorphize::resolve_drop_in_place(
228 bcx.ccx.shared(), ety);
229 let drop_fn = callee::get_fn(bcx.ccx, drop_fn);
230 let bcx = tvec::slice_for_each(
232 lvalue.project_index(&bcx, C_uint(bcx.ccx, 0u64)),
235 |bcx, llval, loop_bb| {
236 self.set_debug_loc(&bcx, terminator.source_info);
237 if let Some(unwind) = unwind {
242 llblock(self, unwind),
246 bcx.call(drop_fn, &[llval], cleanup_bundle);
250 funclet_br(self, bcx, target);
253 _ => (callee::get_fn(bcx.ccx, drop_fn), lvalue.has_extra())
255 let args = &[lvalue.llval, lvalue.llextra][..1 + need_extra as usize];
256 if let Some(unwind) = unwind {
261 llblock(self, unwind),
265 bcx.call(drop_fn, args, cleanup_bundle);
266 funclet_br(self, bcx, target);
270 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
271 let cond = self.trans_operand(&bcx, cond).immediate();
272 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
274 // This case can currently arise only from functions marked
275 // with #[rustc_inherit_overflow_checks] and inlined from
276 // another crate (mostly core::num generic/#[inline] fns),
277 // while the current crate doesn't use overflow checks.
278 // NOTE: Unlike binops, negation doesn't have its own
279 // checked operation, just a comparison with the minimum
280 // value, so we have to check for the assert message.
281 if !bcx.ccx.check_overflow() {
282 use rustc_const_math::ConstMathErr::Overflow;
283 use rustc_const_math::Op::Neg;
285 if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
286 const_cond = Some(expected);
290 // Don't translate the panic block if success if known.
291 if const_cond == Some(expected) {
292 funclet_br(self, bcx, target);
296 // Pass the condition through llvm.expect for branch hinting.
297 let expect = bcx.ccx.get_intrinsic(&"llvm.expect.i1");
298 let cond = bcx.call(expect, &[cond, C_bool(bcx.ccx, expected)], None);
300 // Create the failure block and the conditional branch to it.
301 let lltarget = llblock(self, target);
302 let panic_block = self.new_block("panic");
304 bcx.cond_br(cond, lltarget, panic_block.llbb());
306 bcx.cond_br(cond, panic_block.llbb(), lltarget);
309 // After this point, bcx is the block for the call to panic.
311 self.set_debug_loc(&bcx, terminator.source_info);
313 // Get the location information.
314 let loc = bcx.sess().codemap().lookup_char_pos(span.lo);
315 let filename = Symbol::intern(&loc.file.name).as_str();
316 let filename = C_str_slice(bcx.ccx, filename);
317 let line = C_u32(bcx.ccx, loc.line as u32);
319 // Put together the arguments to the panic entry point.
320 let (lang_item, args, const_err) = match *msg {
321 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
322 let len = self.trans_operand(&mut bcx, len).immediate();
323 let index = self.trans_operand(&mut bcx, index).immediate();
325 let const_err = common::const_to_opt_u128(len, false)
326 .and_then(|len| common::const_to_opt_u128(index, false)
327 .map(|index| ErrKind::IndexOutOfBounds {
332 let file_line = C_struct(bcx.ccx, &[filename, line], false);
333 let align = llalign_of_min(bcx.ccx, common::val_ty(file_line));
334 let file_line = consts::addr_of(bcx.ccx,
337 "panic_bounds_check_loc");
338 (lang_items::PanicBoundsCheckFnLangItem,
339 vec![file_line, index, len],
342 mir::AssertMessage::Math(ref err) => {
343 let msg_str = Symbol::intern(err.description()).as_str();
344 let msg_str = C_str_slice(bcx.ccx, msg_str);
345 let msg_file_line = C_struct(bcx.ccx,
346 &[msg_str, filename, line],
348 let align = llalign_of_min(bcx.ccx, common::val_ty(msg_file_line));
349 let msg_file_line = consts::addr_of(bcx.ccx,
353 (lang_items::PanicFnLangItem,
355 Some(ErrKind::Math(err.clone())))
359 // If we know we always panic, and the error message
360 // is also constant, then we can produce a warning.
361 if const_cond == Some(!expected) {
362 if let Some(err) = const_err {
363 let err = ConstEvalErr{ span: span, kind: err };
364 let mut diag = bcx.tcx().sess.struct_span_warn(
365 span, "this expression will panic at run-time");
366 err.note(bcx.tcx(), span, "expression", &mut diag);
371 // Obtain the panic entry point.
372 let def_id = common::langcall(bcx.tcx(), Some(span), "", lang_item);
373 let instance = ty::Instance::mono(bcx.tcx(), def_id);
374 let llfn = callee::get_fn(bcx.ccx, instance);
376 // Translate the actual panic invoke/call.
377 if let Some(unwind) = cleanup {
380 self.unreachable_block(),
381 llblock(self, unwind),
384 bcx.call(llfn, &args, cleanup_bundle);
389 mir::TerminatorKind::DropAndReplace { .. } => {
390 bug!("undesugared DropAndReplace in trans: {:?}", data);
393 mir::TerminatorKind::Call { ref func, ref args, ref destination, ref cleanup } => {
394 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
395 let callee = self.trans_operand(&bcx, func);
397 let (instance, mut llfn, sig) = match callee.ty.sty {
398 ty::TyFnDef(def_id, substs, sig) => {
399 (Some(monomorphize::resolve(bcx.ccx.shared(), def_id, substs)),
403 ty::TyFnPtr(sig) => {
405 Some(callee.immediate()),
408 _ => bug!("{} is not callable", callee.ty)
410 let def = instance.map(|i| i.def);
411 let sig = bcx.tcx().erase_late_bound_regions_and_normalize(&sig);
414 // Handle intrinsics old trans wants Expr's for, ourselves.
415 let intrinsic = match def {
416 Some(ty::InstanceDef::Intrinsic(def_id))
417 => Some(bcx.tcx().item_name(def_id).as_str()),
420 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
422 if intrinsic == Some("transmute") {
423 let &(ref dest, target) = destination.as_ref().unwrap();
424 self.trans_transmute(&bcx, &args[0], dest);
425 funclet_br(self, bcx, target);
429 let extra_args = &args[sig.inputs().len()..];
430 let extra_args = extra_args.iter().map(|op_arg| {
431 let op_ty = op_arg.ty(&self.mir, bcx.tcx());
432 self.monomorphize(&op_ty)
433 }).collect::<Vec<_>>();
435 let fn_ty = match def {
436 Some(ty::InstanceDef::Virtual(..)) => {
437 FnType::new_vtable(bcx.ccx, sig, &extra_args)
439 Some(ty::InstanceDef::DropGlue(_, None)) => {
440 // empty drop glue - a nop.
441 let &(_, target) = destination.as_ref().unwrap();
442 funclet_br(self, bcx, target);
445 _ => FnType::new(bcx.ccx, sig, &extra_args)
448 // The arguments we'll be passing. Plus one to account for outptr, if used.
449 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
450 let mut llargs = Vec::with_capacity(arg_count);
452 // Prepare the return value destination
453 let ret_dest = if let Some((ref dest, _)) = *destination {
454 let is_intrinsic = intrinsic.is_some();
455 self.make_return_dest(&bcx, dest, &fn_ty.ret, &mut llargs,
461 // Split the rust-call tupled arguments off.
462 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
463 let (tup, args) = args.split_last().unwrap();
469 let is_shuffle = intrinsic.map_or(false, |name| {
470 name.starts_with("simd_shuffle")
473 for arg in first_args {
474 // The indices passed to simd_shuffle* in the
475 // third argument must be constant. This is
476 // checked by const-qualification, which also
477 // promotes any complex rvalues to constants.
478 if is_shuffle && idx == 2 {
480 mir::Operand::Consume(_) => {
481 span_bug!(span, "shuffle indices must be constant");
483 mir::Operand::Constant(ref constant) => {
484 let val = self.trans_constant(&bcx, constant);
485 llargs.push(val.llval);
492 let op = self.trans_operand(&bcx, arg);
493 self.trans_argument(&bcx, op, &mut llargs, &fn_ty,
494 &mut idx, &mut llfn, &def);
496 if let Some(tup) = untuple {
497 self.trans_arguments_untupled(&bcx, tup, &mut llargs, &fn_ty,
498 &mut idx, &mut llfn, &def)
501 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
502 use intrinsic::trans_intrinsic_call;
504 let (dest, llargs) = match ret_dest {
505 _ if fn_ty.ret.is_indirect() => {
506 (llargs[0], &llargs[1..])
508 ReturnDest::Nothing => {
509 (C_undef(fn_ty.ret.memory_ty(bcx.ccx).ptr_to()), &llargs[..])
511 ReturnDest::IndirectOperand(dst, _) |
512 ReturnDest::Store(dst) => (dst, &llargs[..]),
513 ReturnDest::DirectOperand(_) =>
514 bug!("Cannot use direct operand with an intrinsic call")
517 let callee_ty = common::instance_ty(
518 bcx.ccx.shared(), instance.as_ref().unwrap());
519 trans_intrinsic_call(&bcx, callee_ty, &fn_ty, &llargs, dest,
520 terminator.source_info.span);
522 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
523 // Make a fake operand for store_return
524 let op = OperandRef {
525 val: Ref(dst, Alignment::AbiAligned),
528 self.store_return(&bcx, ret_dest, &fn_ty.ret, op);
531 if let Some((_, target)) = *destination {
532 funclet_br(self, bcx, target);
540 let fn_ptr = match (llfn, instance) {
541 (Some(llfn), _) => llfn,
542 (None, Some(instance)) => callee::get_fn(bcx.ccx, instance),
543 _ => span_bug!(span, "no llfn for call"),
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 let Some((_, target)) = *destination {
561 let ret_bcx = self.get_builder(target);
562 self.set_debug_loc(&ret_bcx, terminator.source_info);
563 let op = OperandRef {
564 val: Immediate(invokeret),
567 self.store_return(&ret_bcx, ret_dest, &fn_ty.ret, op);
570 let llret = bcx.call(fn_ptr, &llargs, cleanup_bundle);
571 fn_ty.apply_attrs_callsite(llret);
572 if let Some((_, target)) = *destination {
573 let op = OperandRef {
574 val: Immediate(llret),
577 self.store_return(&bcx, ret_dest, &fn_ty.ret, op);
578 funclet_br(self, bcx, target);
587 fn trans_argument(&mut self,
588 bcx: &Builder<'a, 'tcx>,
589 op: OperandRef<'tcx>,
590 llargs: &mut Vec<ValueRef>,
591 fn_ty: &FnType<'tcx>,
592 next_idx: &mut usize,
593 llfn: &mut Option<ValueRef>,
594 def: &Option<ty::InstanceDef<'tcx>>) {
595 if let Pair(a, b) = op.val {
596 // Treat the values in a fat pointer separately.
597 if common::type_is_fat_ptr(bcx.ccx, op.ty) {
598 let (ptr, meta) = (a, b);
600 if let Some(ty::InstanceDef::Virtual(_, idx)) = *def {
601 let llmeth = meth::VirtualIndex::from_index(idx).get_fn(bcx, meta);
602 let llty = fn_ty.llvm_type(bcx.ccx).ptr_to();
603 *llfn = Some(bcx.pointercast(llmeth, llty));
607 let imm_op = |x| OperandRef {
609 // We won't be checking the type again.
610 ty: bcx.tcx().types.err
612 self.trans_argument(bcx, imm_op(ptr), llargs, fn_ty, next_idx, llfn, def);
613 self.trans_argument(bcx, imm_op(meta), llargs, fn_ty, next_idx, llfn, def);
618 let arg = &fn_ty.args[*next_idx];
621 // Fill padding with undef value, where applicable.
622 if let Some(ty) = arg.pad {
623 llargs.push(C_undef(ty));
630 // Force by-ref if we have to load through a cast pointer.
631 let (mut llval, align, by_ref) = match op.val {
632 Immediate(_) | Pair(..) => {
633 if arg.is_indirect() || arg.cast.is_some() {
634 let llscratch = bcx.alloca(arg.memory_ty(bcx.ccx), "arg", None);
635 self.store_operand(bcx, llscratch, None, op);
636 (llscratch, Alignment::AbiAligned, true)
638 (op.pack_if_pair(bcx).immediate(), Alignment::AbiAligned, false)
641 Ref(llval, Alignment::Packed) if arg.is_indirect() => {
642 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
643 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
644 // have scary latent bugs around.
646 let llscratch = bcx.alloca(arg.memory_ty(bcx.ccx), "arg", None);
647 base::memcpy_ty(bcx, llscratch, llval, op.ty, Some(1));
648 (llscratch, Alignment::AbiAligned, true)
650 Ref(llval, align) => (llval, align, true)
653 if by_ref && !arg.is_indirect() {
654 // Have to load the argument, maybe while casting it.
655 if arg.layout.ty == bcx.tcx().types.bool {
656 // We store bools as i8 so we need to truncate to i1.
657 llval = bcx.load_range_assert(llval, 0, 2, llvm::False, None);
658 llval = bcx.trunc(llval, Type::i1(bcx.ccx));
659 } else if let Some(ty) = arg.cast {
660 llval = bcx.load(bcx.pointercast(llval, ty.ptr_to()),
661 align.min_with(arg.layout.align(bcx.ccx).abi() as u32));
663 llval = bcx.load(llval, align.to_align());
670 fn trans_arguments_untupled(&mut self,
671 bcx: &Builder<'a, 'tcx>,
672 operand: &mir::Operand<'tcx>,
673 llargs: &mut Vec<ValueRef>,
674 fn_ty: &FnType<'tcx>,
675 next_idx: &mut usize,
676 llfn: &mut Option<ValueRef>,
677 def: &Option<ty::InstanceDef<'tcx>>) {
678 let tuple = self.trans_operand(bcx, operand);
680 let arg_types = match tuple.ty.sty {
681 ty::TyTuple(ref tys, _) => tys,
682 _ => span_bug!(self.mir.span,
683 "bad final argument to \"rust-call\" fn {:?}", tuple.ty)
686 // Handle both by-ref and immediate tuples.
688 Ref(llval, align) => {
689 for (n, &ty) in arg_types.iter().enumerate() {
690 let ptr = LvalueRef::new_sized_ty(llval, tuple.ty, align);
691 let (ptr, align) = ptr.trans_field_ptr(bcx, n);
692 let val = if common::type_is_fat_ptr(bcx.ccx, ty) {
693 let (lldata, llextra) = base::load_fat_ptr(bcx, ptr, align, ty);
694 Pair(lldata, llextra)
696 // trans_argument will load this if it needs to
699 let op = OperandRef {
703 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, llfn, def);
707 Immediate(llval) => {
708 let l = bcx.ccx.layout_of(tuple.ty);
709 let v = if let layout::Univariant { ref variant, .. } = *l {
712 bug!("Not a tuple.");
714 for (n, &ty) in arg_types.iter().enumerate() {
715 let mut elem = bcx.extract_value(
716 llval, adt::struct_llfields_index(v, n));
717 // Truncate bools to i1, if needed
718 if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
719 elem = bcx.trunc(elem, Type::i1(bcx.ccx));
721 // If the tuple is immediate, the elements are as well
722 let op = OperandRef {
723 val: Immediate(elem),
726 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, llfn, def);
731 for (n, &ty) in arg_types.iter().enumerate() {
732 let mut elem = elems[n];
733 // Truncate bools to i1, if needed
734 if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
735 elem = bcx.trunc(elem, Type::i1(bcx.ccx));
737 // Pair is always made up of immediates
738 let op = OperandRef {
739 val: Immediate(elem),
742 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, llfn, def);
749 fn get_personality_slot(&mut self, bcx: &Builder<'a, 'tcx>) -> ValueRef {
751 if let Some(slot) = self.llpersonalityslot {
754 let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
755 let slot = bcx.alloca(llretty, "personalityslot", None);
756 self.llpersonalityslot = Some(slot);
761 /// Return the landingpad wrapper around the given basic block
763 /// No-op in MSVC SEH scheme.
764 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> BasicBlockRef {
765 if let Some(block) = self.landing_pads[target_bb] {
769 let block = self.blocks[target_bb];
770 let landing_pad = self.landing_pad_uncached(block);
771 self.landing_pads[target_bb] = Some(landing_pad);
775 fn landing_pad_uncached(&mut self, target_bb: BasicBlockRef) -> BasicBlockRef {
776 if base::wants_msvc_seh(self.ccx.sess()) {
780 let bcx = self.new_block("cleanup");
783 let llpersonality = self.ccx.eh_personality();
784 let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
785 let llretval = bcx.landing_pad(llretty, llpersonality, 1, self.llfn);
786 bcx.set_cleanup(llretval);
787 let slot = self.get_personality_slot(&bcx);
788 Lifetime::Start.call(&bcx, slot);
789 bcx.store(llretval, slot, None);
794 fn unreachable_block(&mut self) -> BasicBlockRef {
795 self.unreachable_block.unwrap_or_else(|| {
796 let bl = self.new_block("unreachable");
798 self.unreachable_block = Some(bl.llbb());
803 pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
804 Builder::new_block(self.ccx, self.llfn, name)
807 pub fn get_builder(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> {
808 let builder = Builder::with_ccx(self.ccx);
809 builder.position_at_end(self.blocks[bb]);
813 fn make_return_dest(&mut self, bcx: &Builder<'a, 'tcx>,
814 dest: &mir::Lvalue<'tcx>, fn_ret_ty: &ArgType,
815 llargs: &mut Vec<ValueRef>, is_intrinsic: bool) -> ReturnDest {
816 // If the return is ignored, we can just return a do-nothing ReturnDest
817 if fn_ret_ty.is_ignore() {
818 return ReturnDest::Nothing;
820 let dest = if let mir::Lvalue::Local(index) = *dest {
821 let ret_ty = self.monomorphized_lvalue_ty(dest);
822 match self.locals[index] {
823 LocalRef::Lvalue(dest) => dest,
824 LocalRef::Operand(None) => {
825 // Handle temporary lvalues, specifically Operand ones, as
826 // they don't have allocas
827 return if fn_ret_ty.is_indirect() {
828 // Odd, but possible, case, we have an operand temporary,
829 // but the calling convention has an indirect return.
830 let tmp = LvalueRef::alloca(bcx, ret_ty, "tmp_ret");
831 llargs.push(tmp.llval);
832 ReturnDest::IndirectOperand(tmp.llval, index)
833 } else if is_intrinsic {
834 // Currently, intrinsics always need a location to store
835 // the result. so we create a temporary alloca for the
837 let tmp = LvalueRef::alloca(bcx, ret_ty, "tmp_ret");
838 ReturnDest::IndirectOperand(tmp.llval, index)
840 ReturnDest::DirectOperand(index)
843 LocalRef::Operand(Some(_)) => {
844 bug!("lvalue local already assigned to");
848 self.trans_lvalue(bcx, dest)
850 if fn_ret_ty.is_indirect() {
851 match dest.alignment {
852 Alignment::AbiAligned => {
853 llargs.push(dest.llval);
856 Alignment::Packed => {
857 // Currently, MIR code generation does not create calls
858 // that store directly to fields of packed structs (in
859 // fact, the calls it creates write only to temps),
861 // If someone changes that, please update this code path
862 // to create a temporary.
863 span_bug!(self.mir.span, "can't directly store to unaligned value");
867 ReturnDest::Store(dest.llval)
871 fn trans_transmute(&mut self, bcx: &Builder<'a, 'tcx>,
872 src: &mir::Operand<'tcx>,
873 dst: &mir::Lvalue<'tcx>) {
874 if let mir::Lvalue::Local(index) = *dst {
875 match self.locals[index] {
876 LocalRef::Lvalue(lvalue) => self.trans_transmute_into(bcx, src, &lvalue),
877 LocalRef::Operand(None) => {
878 let lvalue_ty = self.monomorphized_lvalue_ty(dst);
879 assert!(!lvalue_ty.has_erasable_regions());
880 let lvalue = LvalueRef::alloca(bcx, lvalue_ty, "transmute_temp");
881 self.trans_transmute_into(bcx, src, &lvalue);
882 let op = self.trans_load(bcx, lvalue.llval, lvalue.alignment, lvalue_ty);
883 self.locals[index] = LocalRef::Operand(Some(op));
885 LocalRef::Operand(Some(_)) => {
886 let ty = self.monomorphized_lvalue_ty(dst);
887 assert!(common::type_is_zero_size(bcx.ccx, ty),
888 "assigning to initialized SSAtemp");
892 let dst = self.trans_lvalue(bcx, dst);
893 self.trans_transmute_into(bcx, src, &dst);
897 fn trans_transmute_into(&mut self, bcx: &Builder<'a, 'tcx>,
898 src: &mir::Operand<'tcx>,
899 dst: &LvalueRef<'tcx>) {
900 let val = self.trans_operand(bcx, src);
901 let llty = type_of::type_of(bcx.ccx, val.ty);
902 let cast_ptr = bcx.pointercast(dst.llval, llty.ptr_to());
903 let in_type = val.ty;
904 let out_type = dst.ty.to_ty(bcx.tcx());
905 let llalign = cmp::min(bcx.ccx.align_of(in_type), bcx.ccx.align_of(out_type));
906 self.store_operand(bcx, cast_ptr, Some(llalign), val);
910 // Stores the return value of a function call into it's final location.
911 fn store_return(&mut self,
912 bcx: &Builder<'a, 'tcx>,
914 ret_ty: &ArgType<'tcx>,
915 op: OperandRef<'tcx>) {
916 use self::ReturnDest::*;
920 Store(dst) => ret_ty.store(bcx, op.immediate(), dst),
921 IndirectOperand(tmp, index) => {
922 let op = self.trans_load(bcx, tmp, Alignment::AbiAligned, op.ty);
923 self.locals[index] = LocalRef::Operand(Some(op));
925 DirectOperand(index) => {
926 // If there is a cast, we have to store and reload.
927 let op = if ret_ty.cast.is_some() {
928 let tmp = LvalueRef::alloca(bcx, op.ty, "tmp_ret");
929 ret_ty.store(bcx, op.immediate(), tmp.llval);
930 self.trans_load(bcx, tmp.llval, tmp.alignment, op.ty)
932 op.unpack_if_pair(bcx)
934 self.locals[index] = LocalRef::Operand(Some(op));
941 // Do nothing, the return value is indirect or ignored
943 // Store the return value to the pointer
945 // Stores an indirect return value to an operand local lvalue
946 IndirectOperand(ValueRef, mir::Local),
947 // Stores a direct return value to an operand local lvalue
948 DirectOperand(mir::Local)