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, Ty, TypeFoldable};
15 use rustc::ty::layout::{self, LayoutTyper};
17 use abi::{Abi, FnType, ArgType};
19 use base::{self, Lifetime};
22 use common::{self, C_bool, C_str_slice, C_struct, C_u32, C_undef};
24 use machine::llalign_of_min;
30 use syntax::symbol::Symbol;
35 use super::{MirContext, LocalRef};
36 use super::constant::Const;
37 use super::lvalue::{Alignment, LvalueRef};
38 use super::operand::OperandRef;
39 use super::operand::OperandValue::{Pair, Ref, Immediate};
41 impl<'a, 'tcx> MirContext<'a, 'tcx> {
42 pub fn trans_block(&mut self, bb: mir::BasicBlock) {
43 let mut bcx = self.get_builder(bb);
44 let data = &self.mir[bb];
46 debug!("trans_block({:?}={:?})", bb, data);
48 for statement in &data.statements {
49 bcx = self.trans_statement(bcx, statement);
52 self.trans_terminator(bcx, bb, data.terminator());
55 fn trans_terminator(&mut self,
56 mut bcx: Builder<'a, 'tcx>,
58 terminator: &mir::Terminator<'tcx>)
60 debug!("trans_terminator: {:?}", terminator);
62 // Create the cleanup bundle, if needed.
64 let span = terminator.source_info.span;
65 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
66 let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());
68 let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
69 let cleanup_bundle = funclet.map(|l| l.bundle());
71 let lltarget = |this: &mut Self, target: mir::BasicBlock| {
72 let lltarget = this.blocks[target];
73 let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
74 match (funclet_bb, target_funclet) {
75 (None, None) => (lltarget, false),
77 if f == t_f || !base::wants_msvc_seh(tcx.sess)
80 // jump *into* cleanup - need a landing pad if GNU
81 (this.landing_pad_to(target), false)
83 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
84 (Some(_), Some(_)) => {
85 (this.landing_pad_to(target), true)
90 let llblock = |this: &mut Self, target: mir::BasicBlock| {
91 let (lltarget, is_cleanupret) = lltarget(this, target);
93 // MSVC cross-funclet jump - need a trampoline
95 debug!("llblock: creating cleanup trampoline for {:?}", target);
96 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
97 let trampoline = this.new_block(name);
98 trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
105 let funclet_br = |this: &mut Self, bcx: Builder, target: mir::BasicBlock| {
106 let (lltarget, is_cleanupret) = lltarget(this, target);
108 // micro-optimization: generate a `ret` rather than a jump
110 bcx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
118 bcx: Builder<'a, 'tcx>,
122 destination: Option<(ReturnDest, Ty<'tcx>, mir::BasicBlock)>,
123 cleanup: Option<mir::BasicBlock>
125 if let Some(cleanup) = cleanup {
126 let ret_bcx = if let Some((_, _, target)) = destination {
129 this.unreachable_block()
131 let invokeret = bcx.invoke(fn_ptr,
134 llblock(this, cleanup),
136 fn_ty.apply_attrs_callsite(invokeret);
138 if let Some((ret_dest, ret_ty, target)) = destination {
139 let ret_bcx = this.get_builder(target);
140 this.set_debug_loc(&ret_bcx, terminator.source_info);
141 let op = OperandRef {
142 val: Immediate(invokeret),
145 this.store_return(&ret_bcx, ret_dest, &fn_ty.ret, op);
148 let llret = bcx.call(fn_ptr, &llargs, cleanup_bundle);
149 fn_ty.apply_attrs_callsite(llret);
150 if this.mir[bb].is_cleanup {
151 // Cleanup is always the cold path. Don't inline
152 // drop glue. Also, when there is a deeply-nested
153 // struct, there are "symmetry" issues that cause
154 // exponential inlining - see issue #41696.
155 llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
158 if let Some((ret_dest, ret_ty, target)) = destination {
159 let op = OperandRef {
160 val: Immediate(llret),
163 this.store_return(&bcx, ret_dest, &fn_ty.ret, op);
164 funclet_br(this, bcx, target);
171 self.set_debug_loc(&bcx, terminator.source_info);
172 match terminator.kind {
173 mir::TerminatorKind::Resume => {
174 if let Some(cleanup_pad) = cleanup_pad {
175 bcx.cleanup_ret(cleanup_pad, None);
177 let ps = self.get_personality_slot(&bcx);
178 let lp = bcx.load(ps, None);
179 Lifetime::End.call(&bcx, ps);
180 if !bcx.sess().target.target.options.custom_unwind_resume {
183 let exc_ptr = bcx.extract_value(lp, 0);
184 bcx.call(bcx.ccx.eh_unwind_resume(), &[exc_ptr], cleanup_bundle);
190 mir::TerminatorKind::Goto { target } => {
191 funclet_br(self, bcx, target);
194 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
195 let discr = self.trans_operand(&bcx, discr);
196 if switch_ty == bcx.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 bcx.cond_br(discr.immediate(), llfalse, lltrue);
202 bcx.cond_br(discr.immediate(), lltrue, llfalse);
205 let (otherwise, targets) = targets.split_last().unwrap();
206 let switch = bcx.switch(discr.immediate(),
207 llblock(self, *otherwise), values.len());
208 for (value, target) in values.iter().zip(targets) {
209 let val = Const::from_constint(bcx.ccx, value);
210 let llbb = llblock(self, *target);
211 bcx.add_case(switch, val.llval, llbb)
216 mir::TerminatorKind::Return => {
217 let ret = self.fn_ty.ret;
218 if ret.is_ignore() || ret.is_indirect() {
223 let llval = if let Some(cast_ty) = ret.cast {
224 let op = match self.locals[mir::RETURN_POINTER] {
225 LocalRef::Operand(Some(op)) => op,
226 LocalRef::Operand(None) => bug!("use of return before def"),
227 LocalRef::Lvalue(tr_lvalue) => {
229 val: Ref(tr_lvalue.llval, tr_lvalue.alignment),
230 ty: tr_lvalue.ty.to_ty(bcx.tcx())
234 let llslot = match op.val {
235 Immediate(_) | Pair(..) => {
236 let llscratch = bcx.alloca(ret.memory_ty(bcx.ccx), "ret", None);
237 self.store_operand(&bcx, llscratch, None, op);
240 Ref(llval, align) => {
241 assert_eq!(align, Alignment::AbiAligned,
242 "return pointer is unaligned!");
247 bcx.pointercast(llslot, cast_ty.ptr_to()),
248 Some(ret.layout.align(bcx.ccx).abi() as u32));
251 let op = self.trans_consume(&bcx, &mir::Lvalue::Local(mir::RETURN_POINTER));
252 if let Ref(llval, align) = op.val {
253 base::load_ty(&bcx, llval, align, op.ty)
255 op.pack_if_pair(&bcx).immediate()
261 mir::TerminatorKind::Unreachable => {
265 mir::TerminatorKind::Drop { ref location, target, unwind } => {
266 let ty = location.ty(self.mir, bcx.tcx()).to_ty(bcx.tcx());
267 let ty = self.monomorphize(&ty);
268 let drop_fn = monomorphize::resolve_drop_in_place(bcx.ccx.shared(), ty);
270 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
271 // we don't actually need to drop anything.
272 funclet_br(self, bcx, target);
276 let lvalue = self.trans_lvalue(&bcx, location);
277 let fn_ty = FnType::of_instance(bcx.ccx, &drop_fn);
278 let (drop_fn, need_extra) = match ty.sty {
279 ty::TyDynamic(..) => (meth::DESTRUCTOR.get_fn(&bcx, lvalue.llextra),
281 _ => (callee::get_fn(bcx.ccx, drop_fn), lvalue.has_extra())
283 let args = &[lvalue.llval, lvalue.llextra][..1 + need_extra as usize];
284 do_call(self, bcx, fn_ty, drop_fn, args,
285 Some((ReturnDest::Nothing, tcx.mk_nil(), target)),
289 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
290 let cond = self.trans_operand(&bcx, cond).immediate();
291 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
293 // This case can currently arise only from functions marked
294 // with #[rustc_inherit_overflow_checks] and inlined from
295 // another crate (mostly core::num generic/#[inline] fns),
296 // while the current crate doesn't use overflow checks.
297 // NOTE: Unlike binops, negation doesn't have its own
298 // checked operation, just a comparison with the minimum
299 // value, so we have to check for the assert message.
300 if !bcx.ccx.check_overflow() {
301 use rustc_const_math::ConstMathErr::Overflow;
302 use rustc_const_math::Op::Neg;
304 if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
305 const_cond = Some(expected);
309 // Don't translate the panic block if success if known.
310 if const_cond == Some(expected) {
311 funclet_br(self, bcx, target);
315 // Pass the condition through llvm.expect for branch hinting.
316 let expect = bcx.ccx.get_intrinsic(&"llvm.expect.i1");
317 let cond = bcx.call(expect, &[cond, C_bool(bcx.ccx, expected)], None);
319 // Create the failure block and the conditional branch to it.
320 let lltarget = llblock(self, target);
321 let panic_block = self.new_block("panic");
323 bcx.cond_br(cond, lltarget, panic_block.llbb());
325 bcx.cond_br(cond, panic_block.llbb(), lltarget);
328 // After this point, bcx is the block for the call to panic.
330 self.set_debug_loc(&bcx, terminator.source_info);
332 // Get the location information.
333 let loc = bcx.sess().codemap().lookup_char_pos(span.lo());
334 let filename = Symbol::intern(&loc.file.name).as_str();
335 let filename = C_str_slice(bcx.ccx, filename);
336 let line = C_u32(bcx.ccx, loc.line as u32);
337 let col = C_u32(bcx.ccx, loc.col.to_usize() as u32 + 1);
339 // Put together the arguments to the panic entry point.
340 let (lang_item, args, const_err) = match *msg {
341 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
342 let len = self.trans_operand(&mut bcx, len).immediate();
343 let index = self.trans_operand(&mut bcx, index).immediate();
345 let const_err = common::const_to_opt_u128(len, false)
346 .and_then(|len| common::const_to_opt_u128(index, false)
347 .map(|index| ErrKind::IndexOutOfBounds {
352 let file_line_col = C_struct(bcx.ccx, &[filename, line, col], false);
353 let align = llalign_of_min(bcx.ccx, common::val_ty(file_line_col));
354 let file_line_col = consts::addr_of(bcx.ccx,
357 "panic_bounds_check_loc");
358 (lang_items::PanicBoundsCheckFnLangItem,
359 vec![file_line_col, index, len],
362 mir::AssertMessage::Math(ref err) => {
363 let msg_str = Symbol::intern(err.description()).as_str();
364 let msg_str = C_str_slice(bcx.ccx, msg_str);
365 let msg_file_line_col = C_struct(bcx.ccx,
366 &[msg_str, filename, line, col],
368 let align = llalign_of_min(bcx.ccx, common::val_ty(msg_file_line_col));
369 let msg_file_line_col = consts::addr_of(bcx.ccx,
373 (lang_items::PanicFnLangItem,
374 vec![msg_file_line_col],
375 Some(ErrKind::Math(err.clone())))
377 mir::AssertMessage::GeneratorResumedAfterReturn |
378 mir::AssertMessage::GeneratorResumedAfterPanic => {
379 let str = if let mir::AssertMessage::GeneratorResumedAfterReturn = *msg {
380 "generator resumed after completion"
382 "generator resumed after panicking"
384 let msg_str = Symbol::intern(str).as_str();
385 let msg_str = C_str_slice(bcx.ccx, msg_str);
386 let msg_file_line_col = C_struct(bcx.ccx,
387 &[msg_str, filename, line, col],
389 let align = llalign_of_min(bcx.ccx, common::val_ty(msg_file_line_col));
390 let msg_file_line_col = consts::addr_of(bcx.ccx,
394 (lang_items::PanicFnLangItem,
395 vec![msg_file_line_col],
400 // If we know we always panic, and the error message
401 // is also constant, then we can produce a warning.
402 if const_cond == Some(!expected) {
403 if let Some(err) = const_err {
404 let err = ConstEvalErr{ span: span, kind: err };
405 let mut diag = bcx.tcx().sess.struct_span_warn(
406 span, "this expression will panic at run-time");
407 err.note(bcx.tcx(), span, "expression", &mut diag);
412 // Obtain the panic entry point.
413 let def_id = common::langcall(bcx.tcx(), Some(span), "", lang_item);
414 let instance = ty::Instance::mono(bcx.tcx(), def_id);
415 let fn_ty = FnType::of_instance(bcx.ccx, &instance);
416 let llfn = callee::get_fn(bcx.ccx, instance);
418 // Translate the actual panic invoke/call.
419 do_call(self, bcx, fn_ty, llfn, &args, None, cleanup);
422 mir::TerminatorKind::DropAndReplace { .. } => {
423 bug!("undesugared DropAndReplace in trans: {:?}", terminator);
426 mir::TerminatorKind::Call { ref func, ref args, ref destination, cleanup } => {
427 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
428 let callee = self.trans_operand(&bcx, func);
430 let (instance, mut llfn) = match callee.ty.sty {
431 ty::TyFnDef(def_id, substs) => {
432 (Some(monomorphize::resolve(bcx.ccx.shared(), def_id, substs)),
436 (None, Some(callee.immediate()))
438 _ => bug!("{} is not callable", callee.ty)
440 let def = instance.map(|i| i.def);
441 let sig = callee.ty.fn_sig(bcx.tcx());
442 let sig = bcx.tcx().erase_late_bound_regions_and_normalize(&sig);
445 // Handle intrinsics old trans wants Expr's for, ourselves.
446 let intrinsic = match def {
447 Some(ty::InstanceDef::Intrinsic(def_id))
448 => Some(bcx.tcx().item_name(def_id)),
451 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
453 if intrinsic == Some("transmute") {
454 let &(ref dest, target) = destination.as_ref().unwrap();
455 self.trans_transmute(&bcx, &args[0], dest);
456 funclet_br(self, bcx, target);
460 let extra_args = &args[sig.inputs().len()..];
461 let extra_args = extra_args.iter().map(|op_arg| {
462 let op_ty = op_arg.ty(self.mir, bcx.tcx());
463 self.monomorphize(&op_ty)
464 }).collect::<Vec<_>>();
466 let fn_ty = match def {
467 Some(ty::InstanceDef::Virtual(..)) => {
468 FnType::new_vtable(bcx.ccx, sig, &extra_args)
470 Some(ty::InstanceDef::DropGlue(_, None)) => {
471 // empty drop glue - a nop.
472 let &(_, target) = destination.as_ref().unwrap();
473 funclet_br(self, bcx, target);
476 _ => FnType::new(bcx.ccx, sig, &extra_args)
479 // The arguments we'll be passing. Plus one to account for outptr, if used.
480 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
481 let mut llargs = Vec::with_capacity(arg_count);
483 // Prepare the return value destination
484 let ret_dest = if let Some((ref dest, _)) = *destination {
485 let is_intrinsic = intrinsic.is_some();
486 self.make_return_dest(&bcx, dest, &fn_ty.ret, &mut llargs,
492 // Split the rust-call tupled arguments off.
493 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
494 let (tup, args) = args.split_last().unwrap();
500 let is_shuffle = intrinsic.map_or(false, |name| {
501 name.starts_with("simd_shuffle")
504 for arg in first_args {
505 // The indices passed to simd_shuffle* in the
506 // third argument must be constant. This is
507 // checked by const-qualification, which also
508 // promotes any complex rvalues to constants.
509 if is_shuffle && idx == 2 {
511 mir::Operand::Consume(_) => {
512 span_bug!(span, "shuffle indices must be constant");
514 mir::Operand::Constant(ref constant) => {
515 let val = self.trans_constant(&bcx, constant);
516 llargs.push(val.llval);
523 let op = self.trans_operand(&bcx, arg);
524 self.trans_argument(&bcx, op, &mut llargs, &fn_ty,
525 &mut idx, &mut llfn, &def);
527 if let Some(tup) = untuple {
528 self.trans_arguments_untupled(&bcx, tup, &mut llargs, &fn_ty,
529 &mut idx, &mut llfn, &def)
532 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
533 use intrinsic::trans_intrinsic_call;
535 let (dest, llargs) = match ret_dest {
536 _ if fn_ty.ret.is_indirect() => {
537 (llargs[0], &llargs[1..])
539 ReturnDest::Nothing => {
540 (C_undef(fn_ty.ret.memory_ty(bcx.ccx).ptr_to()), &llargs[..])
542 ReturnDest::IndirectOperand(dst, _) |
543 ReturnDest::Store(dst) => (dst, &llargs[..]),
544 ReturnDest::DirectOperand(_) =>
545 bug!("Cannot use direct operand with an intrinsic call")
548 let callee_ty = common::instance_ty(
549 bcx.ccx.shared(), instance.as_ref().unwrap());
550 trans_intrinsic_call(&bcx, callee_ty, &fn_ty, &llargs, dest,
551 terminator.source_info.span);
553 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
554 // Make a fake operand for store_return
555 let op = OperandRef {
556 val: Ref(dst, Alignment::AbiAligned),
559 self.store_return(&bcx, ret_dest, &fn_ty.ret, op);
562 if let Some((_, target)) = *destination {
563 funclet_br(self, bcx, target);
571 let fn_ptr = match (llfn, instance) {
572 (Some(llfn), _) => llfn,
573 (None, Some(instance)) => callee::get_fn(bcx.ccx, instance),
574 _ => span_bug!(span, "no llfn for call"),
577 do_call(self, bcx, fn_ty, fn_ptr, &llargs,
578 destination.as_ref().map(|&(_, target)| (ret_dest, sig.output(), target)),
581 mir::TerminatorKind::GeneratorDrop |
582 mir::TerminatorKind::Yield { .. } => bug!("generator ops in trans"),
586 fn trans_argument(&mut self,
587 bcx: &Builder<'a, 'tcx>,
588 op: OperandRef<'tcx>,
589 llargs: &mut Vec<ValueRef>,
590 fn_ty: &FnType<'tcx>,
591 next_idx: &mut usize,
592 llfn: &mut Option<ValueRef>,
593 def: &Option<ty::InstanceDef<'tcx>>) {
594 if let Pair(a, b) = op.val {
595 // Treat the values in a fat pointer separately.
596 if common::type_is_fat_ptr(bcx.ccx, op.ty) {
597 let (ptr, meta) = (a, b);
599 if let Some(ty::InstanceDef::Virtual(_, idx)) = *def {
600 let llmeth = meth::VirtualIndex::from_index(idx).get_fn(bcx, meta);
601 let llty = fn_ty.llvm_type(bcx.ccx).ptr_to();
602 *llfn = Some(bcx.pointercast(llmeth, llty));
606 let imm_op = |x| OperandRef {
608 // We won't be checking the type again.
609 ty: bcx.tcx().types.err
611 self.trans_argument(bcx, imm_op(ptr), llargs, fn_ty, next_idx, llfn, def);
612 self.trans_argument(bcx, imm_op(meta), llargs, fn_ty, next_idx, llfn, def);
617 let arg = &fn_ty.args[*next_idx];
620 // Fill padding with undef value, where applicable.
621 if let Some(ty) = arg.pad {
622 llargs.push(C_undef(ty));
629 // Force by-ref if we have to load through a cast pointer.
630 let (mut llval, align, by_ref) = match op.val {
631 Immediate(_) | Pair(..) => {
632 if arg.is_indirect() || arg.cast.is_some() {
633 let llscratch = bcx.alloca(arg.memory_ty(bcx.ccx), "arg", None);
634 self.store_operand(bcx, llscratch, None, op);
635 (llscratch, Alignment::AbiAligned, true)
637 (op.pack_if_pair(bcx).immediate(), Alignment::AbiAligned, false)
640 Ref(llval, Alignment::Packed) if arg.is_indirect() => {
641 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
642 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
643 // have scary latent bugs around.
645 let llscratch = bcx.alloca(arg.memory_ty(bcx.ccx), "arg", None);
646 base::memcpy_ty(bcx, llscratch, llval, op.ty, Some(1));
647 (llscratch, Alignment::AbiAligned, true)
649 Ref(llval, align) => (llval, align, true)
652 if by_ref && !arg.is_indirect() {
653 // Have to load the argument, maybe while casting it.
654 if arg.layout.ty == bcx.tcx().types.bool {
655 // We store bools as i8 so we need to truncate to i1.
656 llval = bcx.load_range_assert(llval, 0, 2, llvm::False, None);
657 llval = bcx.trunc(llval, Type::i1(bcx.ccx));
658 } else if let Some(ty) = arg.cast {
659 llval = bcx.load(bcx.pointercast(llval, ty.ptr_to()),
660 align.min_with(arg.layout.align(bcx.ccx).abi() as u32));
662 llval = bcx.load(llval, align.to_align());
669 fn trans_arguments_untupled(&mut self,
670 bcx: &Builder<'a, 'tcx>,
671 operand: &mir::Operand<'tcx>,
672 llargs: &mut Vec<ValueRef>,
673 fn_ty: &FnType<'tcx>,
674 next_idx: &mut usize,
675 llfn: &mut Option<ValueRef>,
676 def: &Option<ty::InstanceDef<'tcx>>) {
677 let tuple = self.trans_operand(bcx, operand);
679 let arg_types = match tuple.ty.sty {
680 ty::TyTuple(ref tys, _) => tys,
681 _ => span_bug!(self.mir.span,
682 "bad final argument to \"rust-call\" fn {:?}", tuple.ty)
685 // Handle both by-ref and immediate tuples.
687 Ref(llval, align) => {
688 for (n, &ty) in arg_types.iter().enumerate() {
689 let ptr = LvalueRef::new_sized_ty(llval, tuple.ty, align);
690 let (ptr, align) = ptr.trans_field_ptr(bcx, n);
691 let val = if common::type_is_fat_ptr(bcx.ccx, ty) {
692 let (lldata, llextra) = base::load_fat_ptr(bcx, ptr, align, ty);
693 Pair(lldata, llextra)
695 // trans_argument will load this if it needs to
698 let op = OperandRef {
702 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, llfn, def);
706 Immediate(llval) => {
707 let l = bcx.ccx.layout_of(tuple.ty);
708 let v = if let layout::Univariant { ref variant, .. } = *l {
711 bug!("Not a tuple.");
713 for (n, &ty) in arg_types.iter().enumerate() {
714 let mut elem = bcx.extract_value(
715 llval, adt::struct_llfields_index(v, n));
716 // Truncate bools to i1, if needed
717 if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
718 elem = bcx.trunc(elem, Type::i1(bcx.ccx));
720 // If the tuple is immediate, the elements are as well
721 let op = OperandRef {
722 val: Immediate(elem),
725 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, llfn, def);
730 for (n, &ty) in arg_types.iter().enumerate() {
731 let mut elem = elems[n];
732 // Truncate bools to i1, if needed
733 if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
734 elem = bcx.trunc(elem, Type::i1(bcx.ccx));
736 // Pair is always made up of immediates
737 let op = OperandRef {
738 val: Immediate(elem),
741 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, llfn, def);
748 fn get_personality_slot(&mut self, bcx: &Builder<'a, 'tcx>) -> ValueRef {
750 if let Some(slot) = self.llpersonalityslot {
753 let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
754 let slot = bcx.alloca(llretty, "personalityslot", None);
755 self.llpersonalityslot = Some(slot);
760 /// Return the landingpad wrapper around the given basic block
762 /// No-op in MSVC SEH scheme.
763 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> BasicBlockRef {
764 if let Some(block) = self.landing_pads[target_bb] {
768 let block = self.blocks[target_bb];
769 let landing_pad = self.landing_pad_uncached(block);
770 self.landing_pads[target_bb] = Some(landing_pad);
774 fn landing_pad_uncached(&mut self, target_bb: BasicBlockRef) -> BasicBlockRef {
775 if base::wants_msvc_seh(self.ccx.sess()) {
776 span_bug!(self.mir.span, "landing pad was not inserted?")
779 let bcx = self.new_block("cleanup");
782 let llpersonality = self.ccx.eh_personality();
783 let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
784 let llretval = bcx.landing_pad(llretty, llpersonality, 1, self.llfn);
785 bcx.set_cleanup(llretval);
786 let slot = self.get_personality_slot(&bcx);
787 Lifetime::Start.call(&bcx, slot);
788 bcx.store(llretval, slot, None);
793 fn unreachable_block(&mut self) -> BasicBlockRef {
794 self.unreachable_block.unwrap_or_else(|| {
795 let bl = self.new_block("unreachable");
797 self.unreachable_block = Some(bl.llbb());
802 pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
803 Builder::new_block(self.ccx, self.llfn, name)
806 pub fn get_builder(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> {
807 let builder = Builder::with_ccx(self.ccx);
808 builder.position_at_end(self.blocks[bb]);
812 fn make_return_dest(&mut self, bcx: &Builder<'a, 'tcx>,
813 dest: &mir::Lvalue<'tcx>, fn_ret_ty: &ArgType,
814 llargs: &mut Vec<ValueRef>, is_intrinsic: bool) -> ReturnDest {
815 // If the return is ignored, we can just return a do-nothing ReturnDest
816 if fn_ret_ty.is_ignore() {
817 return ReturnDest::Nothing;
819 let dest = if let mir::Lvalue::Local(index) = *dest {
820 let ret_ty = self.monomorphized_lvalue_ty(dest);
821 match self.locals[index] {
822 LocalRef::Lvalue(dest) => dest,
823 LocalRef::Operand(None) => {
824 // Handle temporary lvalues, specifically Operand ones, as
825 // they don't have allocas
826 return if fn_ret_ty.is_indirect() {
827 // Odd, but possible, case, we have an operand temporary,
828 // but the calling convention has an indirect return.
829 let tmp = LvalueRef::alloca(bcx, ret_ty, "tmp_ret");
830 llargs.push(tmp.llval);
831 ReturnDest::IndirectOperand(tmp.llval, index)
832 } else if is_intrinsic {
833 // Currently, intrinsics always need a location to store
834 // the result. so we create a temporary alloca for the
836 let tmp = LvalueRef::alloca(bcx, ret_ty, "tmp_ret");
837 ReturnDest::IndirectOperand(tmp.llval, index)
839 ReturnDest::DirectOperand(index)
842 LocalRef::Operand(Some(_)) => {
843 bug!("lvalue local already assigned to");
847 self.trans_lvalue(bcx, dest)
849 if fn_ret_ty.is_indirect() {
850 match dest.alignment {
851 Alignment::AbiAligned => {
852 llargs.push(dest.llval);
855 Alignment::Packed => {
856 // Currently, MIR code generation does not create calls
857 // that store directly to fields of packed structs (in
858 // fact, the calls it creates write only to temps),
860 // If someone changes that, please update this code path
861 // to create a temporary.
862 span_bug!(self.mir.span, "can't directly store to unaligned value");
866 ReturnDest::Store(dest.llval)
870 fn trans_transmute(&mut self, bcx: &Builder<'a, 'tcx>,
871 src: &mir::Operand<'tcx>,
872 dst: &mir::Lvalue<'tcx>) {
873 if let mir::Lvalue::Local(index) = *dst {
874 match self.locals[index] {
875 LocalRef::Lvalue(lvalue) => self.trans_transmute_into(bcx, src, &lvalue),
876 LocalRef::Operand(None) => {
877 let lvalue_ty = self.monomorphized_lvalue_ty(dst);
878 assert!(!lvalue_ty.has_erasable_regions());
879 let lvalue = LvalueRef::alloca(bcx, lvalue_ty, "transmute_temp");
880 self.trans_transmute_into(bcx, src, &lvalue);
881 let op = self.trans_load(bcx, lvalue.llval, lvalue.alignment, lvalue_ty);
882 self.locals[index] = LocalRef::Operand(Some(op));
884 LocalRef::Operand(Some(_)) => {
885 let ty = self.monomorphized_lvalue_ty(dst);
886 assert!(common::type_is_zero_size(bcx.ccx, ty),
887 "assigning to initialized SSAtemp");
891 let dst = self.trans_lvalue(bcx, dst);
892 self.trans_transmute_into(bcx, src, &dst);
896 fn trans_transmute_into(&mut self, bcx: &Builder<'a, 'tcx>,
897 src: &mir::Operand<'tcx>,
898 dst: &LvalueRef<'tcx>) {
899 let val = self.trans_operand(bcx, src);
900 let llty = type_of::type_of(bcx.ccx, val.ty);
901 let cast_ptr = bcx.pointercast(dst.llval, llty.ptr_to());
902 let in_type = val.ty;
903 let out_type = dst.ty.to_ty(bcx.tcx());
904 let llalign = cmp::min(bcx.ccx.align_of(in_type), bcx.ccx.align_of(out_type));
905 self.store_operand(bcx, cast_ptr, Some(llalign), val);
909 // Stores the return value of a function call into it's final location.
910 fn store_return(&mut self,
911 bcx: &Builder<'a, 'tcx>,
913 ret_ty: &ArgType<'tcx>,
914 op: OperandRef<'tcx>) {
915 use self::ReturnDest::*;
919 Store(dst) => ret_ty.store(bcx, op.immediate(), dst),
920 IndirectOperand(tmp, index) => {
921 let op = self.trans_load(bcx, tmp, Alignment::AbiAligned, op.ty);
922 self.locals[index] = LocalRef::Operand(Some(op));
924 DirectOperand(index) => {
925 // If there is a cast, we have to store and reload.
926 let op = if ret_ty.cast.is_some() {
927 let tmp = LvalueRef::alloca(bcx, op.ty, "tmp_ret");
928 ret_ty.store(bcx, op.immediate(), tmp.llval);
929 self.trans_load(bcx, tmp.llval, tmp.alignment, op.ty)
931 op.unpack_if_pair(bcx)
933 self.locals[index] = LocalRef::Operand(Some(op));
940 // Do nothing, the return value is indirect or ignored
942 // Store the return value to the pointer
944 // Stores an indirect return value to an operand local lvalue
945 IndirectOperand(ValueRef, mir::Local),
946 // Stores a direct return value to an operand local lvalue
947 DirectOperand(mir::Local)