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_const_eval::{ErrKind, ConstEvalErr, note_const_eval_err};
13 use rustc::middle::lang_items;
14 use rustc::ty::{self, layout, TypeFoldable};
16 use abi::{Abi, FnType, ArgType};
18 use base::{self, Lifetime};
19 use callee::{Callee, CalleeData, Fn, Intrinsic, NamedTupleConstructor, Virtual};
21 use common::{self, Funclet};
22 use common::{C_bool, C_str_slice, C_struct, C_u32, C_undef};
25 use machine::{llalign_of_min, llbitsize_of_real};
27 use type_of::{self, align_of};
31 use rustc_data_structures::indexed_vec::IndexVec;
32 use rustc_data_structures::fx::FxHashMap;
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::If { ref cond, targets: (true_bb, false_bb) } => {
140 let cond = self.trans_operand(&bcx, cond);
142 let lltrue = llblock(self, true_bb);
143 let llfalse = llblock(self, false_bb);
144 bcx.cond_br(cond.immediate(), lltrue, llfalse);
147 mir::TerminatorKind::Switch { ref discr, ref adt_def, ref targets } => {
148 let discr_lvalue = self.trans_lvalue(&bcx, discr);
149 let ty = discr_lvalue.ty.to_ty(bcx.tcx());
150 let discr = adt::trans_get_discr(
151 &bcx, ty, discr_lvalue.llval, discr_lvalue.alignment,
154 let mut bb_hist = FxHashMap();
155 for target in targets {
156 *bb_hist.entry(target).or_insert(0) += 1;
158 let (default_bb, default_blk) = match bb_hist.iter().max_by_key(|&(_, c)| c) {
159 // If a single target basic blocks is predominant, promote that to be the
160 // default case for the switch instruction to reduce the size of the generated
161 // code. This is especially helpful in cases like an if-let on a huge enum.
162 // Note: This optimization is only valid for exhaustive matches.
163 Some((&&bb, &c)) if c > targets.len() / 2 => {
164 (Some(bb), llblock(self, bb))
166 // We're generating an exhaustive switch, so the else branch
167 // can't be hit. Branching to an unreachable instruction
168 // lets LLVM know this
169 _ => (None, self.unreachable_block())
171 let switch = bcx.switch(discr, default_blk, targets.len());
172 assert_eq!(adt_def.variants.len(), targets.len());
173 for (adt_variant, &target) in adt_def.variants.iter().zip(targets) {
174 if default_bb != Some(target) {
175 let llbb = llblock(self, target);
176 let llval = adt::trans_case(&bcx, ty, Disr::from(adt_variant.disr_val));
177 bcx.add_case(switch, llval, llbb)
182 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
183 let (otherwise, targets) = targets.split_last().unwrap();
184 let lv = self.trans_lvalue(&bcx, discr);
185 let discr = bcx.load(lv.llval, lv.alignment.to_align());
186 let discr = base::to_immediate(&bcx, discr, switch_ty);
187 let switch = bcx.switch(discr, llblock(self, *otherwise), values.len());
188 for (value, target) in values.iter().zip(targets) {
189 let val = Const::from_constval(bcx.ccx, value.clone(), switch_ty);
190 let llbb = llblock(self, *target);
191 bcx.add_case(switch, val.llval, llbb)
195 mir::TerminatorKind::Return => {
196 let ret = self.fn_ty.ret;
197 if ret.is_ignore() || ret.is_indirect() {
202 let llval = if let Some(cast_ty) = ret.cast {
203 let op = match self.locals[mir::RETURN_POINTER] {
204 LocalRef::Operand(Some(op)) => op,
205 LocalRef::Operand(None) => bug!("use of return before def"),
206 LocalRef::Lvalue(tr_lvalue) => {
208 val: Ref(tr_lvalue.llval, tr_lvalue.alignment),
209 ty: tr_lvalue.ty.to_ty(bcx.tcx())
213 let llslot = match op.val {
214 Immediate(_) | Pair(..) => {
215 let llscratch = bcx.alloca(ret.original_ty, "ret");
216 self.store_operand(&bcx, llscratch, None, op);
219 Ref(llval, align) => {
220 assert_eq!(align, Alignment::AbiAligned,
221 "return pointer is unaligned!");
226 bcx.pointercast(llslot, cast_ty.ptr_to()),
227 Some(llalign_of_min(bcx.ccx, ret.ty)));
230 let op = self.trans_consume(&bcx, &mir::Lvalue::Local(mir::RETURN_POINTER));
231 if let Ref(llval, align) = op.val {
232 base::load_ty(&bcx, llval, align, op.ty)
234 op.pack_if_pair(&bcx).immediate()
240 mir::TerminatorKind::Unreachable => {
244 mir::TerminatorKind::Drop { ref location, target, unwind } => {
245 let ty = location.ty(&self.mir, bcx.tcx()).to_ty(bcx.tcx());
246 let ty = self.monomorphize(&ty);
248 // Double check for necessity to drop
249 if !bcx.ccx.shared().type_needs_drop(ty) {
250 funclet_br(self, bcx, target);
254 let mut lvalue = self.trans_lvalue(&bcx, location);
255 let drop_fn = glue::get_drop_glue(bcx.ccx, ty);
256 let drop_ty = glue::get_drop_glue_type(bcx.ccx.shared(), ty);
257 if bcx.ccx.shared().type_is_sized(ty) && drop_ty != ty {
258 lvalue.llval = bcx.pointercast(
259 lvalue.llval, type_of::type_of(bcx.ccx, drop_ty).ptr_to());
261 let args = &[lvalue.llval, lvalue.llextra][..1 + lvalue.has_extra() as usize];
262 if let Some(unwind) = unwind {
267 llblock(self, unwind),
271 bcx.call(drop_fn, args, cleanup_bundle);
272 funclet_br(self, bcx, target);
276 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
277 let cond = self.trans_operand(&bcx, cond).immediate();
278 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
280 // This case can currently arise only from functions marked
281 // with #[rustc_inherit_overflow_checks] and inlined from
282 // another crate (mostly core::num generic/#[inline] fns),
283 // while the current crate doesn't use overflow checks.
284 // NOTE: Unlike binops, negation doesn't have its own
285 // checked operation, just a comparison with the minimum
286 // value, so we have to check for the assert message.
287 if !bcx.ccx.check_overflow() {
288 use rustc_const_math::ConstMathErr::Overflow;
289 use rustc_const_math::Op::Neg;
291 if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
292 const_cond = Some(expected);
296 // Don't translate the panic block if success if known.
297 if const_cond == Some(expected) {
298 funclet_br(self, bcx, target);
302 // Pass the condition through llvm.expect for branch hinting.
303 let expect = bcx.ccx.get_intrinsic(&"llvm.expect.i1");
304 let cond = bcx.call(expect, &[cond, C_bool(bcx.ccx, expected)], None);
306 // Create the failure block and the conditional branch to it.
307 let lltarget = llblock(self, target);
308 let panic_block = self.new_block("panic");
310 bcx.cond_br(cond, lltarget, panic_block.llbb());
312 bcx.cond_br(cond, panic_block.llbb(), lltarget);
315 // After this point, bcx is the block for the call to panic.
317 self.set_debug_loc(&bcx, terminator.source_info);
319 // Get the location information.
320 let loc = bcx.sess().codemap().lookup_char_pos(span.lo);
321 let filename = Symbol::intern(&loc.file.name).as_str();
322 let filename = C_str_slice(bcx.ccx, filename);
323 let line = C_u32(bcx.ccx, loc.line as u32);
325 // Put together the arguments to the panic entry point.
326 let (lang_item, args, const_err) = match *msg {
327 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
328 let len = self.trans_operand(&mut bcx, len).immediate();
329 let index = self.trans_operand(&mut bcx, index).immediate();
331 let const_err = common::const_to_opt_u128(len, false)
332 .and_then(|len| common::const_to_opt_u128(index, false)
333 .map(|index| ErrKind::IndexOutOfBounds {
338 let file_line = C_struct(bcx.ccx, &[filename, line], false);
339 let align = llalign_of_min(bcx.ccx, common::val_ty(file_line));
340 let file_line = consts::addr_of(bcx.ccx,
343 "panic_bounds_check_loc");
344 (lang_items::PanicBoundsCheckFnLangItem,
345 vec![file_line, index, len],
348 mir::AssertMessage::Math(ref err) => {
349 let msg_str = Symbol::intern(err.description()).as_str();
350 let msg_str = C_str_slice(bcx.ccx, msg_str);
351 let msg_file_line = C_struct(bcx.ccx,
352 &[msg_str, filename, line],
354 let align = llalign_of_min(bcx.ccx, common::val_ty(msg_file_line));
355 let msg_file_line = consts::addr_of(bcx.ccx,
359 (lang_items::PanicFnLangItem,
361 Some(ErrKind::Math(err.clone())))
365 // If we know we always panic, and the error message
366 // is also constant, then we can produce a warning.
367 if const_cond == Some(!expected) {
368 if let Some(err) = const_err {
369 let err = ConstEvalErr{ span: span, kind: err };
370 let mut diag = bcx.tcx().sess.struct_span_warn(
371 span, "this expression will panic at run-time");
372 note_const_eval_err(bcx.tcx(), &err, span, "expression", &mut diag);
377 // Obtain the panic entry point.
378 let def_id = common::langcall(bcx.tcx(), Some(span), "", lang_item);
379 let callee = Callee::def(bcx.ccx, def_id,
380 bcx.ccx.empty_substs_for_def_id(def_id));
381 let llfn = callee.reify(bcx.ccx);
383 // Translate the actual panic invoke/call.
384 if let Some(unwind) = cleanup {
387 self.unreachable_block(),
388 llblock(self, unwind),
391 bcx.call(llfn, &args, cleanup_bundle);
396 mir::TerminatorKind::DropAndReplace { .. } => {
397 bug!("undesugared DropAndReplace in trans: {:?}", data);
400 mir::TerminatorKind::Call { ref func, ref args, ref destination, ref cleanup } => {
401 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
402 let callee = self.trans_operand(&bcx, func);
404 let (mut callee, abi, sig) = match callee.ty.sty {
405 ty::TyFnDef(def_id, substs, f) => {
406 (Callee::def(bcx.ccx, def_id, substs), f.abi, &f.sig)
410 data: Fn(callee.immediate()),
414 _ => bug!("{} is not callable", callee.ty)
417 let sig = bcx.tcx().erase_late_bound_regions_and_normalize(sig);
419 // Handle intrinsics old trans wants Expr's for, ourselves.
420 let intrinsic = match (&callee.ty.sty, &callee.data) {
421 (&ty::TyFnDef(def_id, ..), &Intrinsic) => {
422 Some(bcx.tcx().item_name(def_id).as_str())
426 let mut intrinsic = intrinsic.as_ref().map(|s| &s[..]);
428 if intrinsic == Some("move_val_init") {
429 let &(_, target) = destination.as_ref().unwrap();
430 // The first argument is a thin destination pointer.
431 let llptr = self.trans_operand(&bcx, &args[0]).immediate();
432 let val = self.trans_operand(&bcx, &args[1]);
433 self.store_operand(&bcx, llptr, None, val);
434 funclet_br(self, bcx, target);
438 if intrinsic == Some("transmute") {
439 let &(ref dest, target) = destination.as_ref().unwrap();
440 self.trans_transmute(&bcx, &args[0], dest);
441 funclet_br(self, bcx, target);
445 let extra_args = &args[sig.inputs().len()..];
446 let extra_args = extra_args.iter().map(|op_arg| {
447 let op_ty = op_arg.ty(&self.mir, bcx.tcx());
448 self.monomorphize(&op_ty)
449 }).collect::<Vec<_>>();
450 let fn_ty = callee.direct_fn_type(bcx.ccx, &extra_args);
452 if intrinsic == Some("drop_in_place") {
453 let &(_, target) = destination.as_ref().unwrap();
454 let ty = if let ty::TyFnDef(_, substs, _) = callee.ty.sty {
457 bug!("Unexpected ty: {}", callee.ty);
460 // Double check for necessity to drop
461 if !bcx.ccx.shared().type_needs_drop(ty) {
462 funclet_br(self, bcx, target);
466 let drop_fn = glue::get_drop_glue(bcx.ccx, ty);
467 let llty = fn_ty.llvm_type(bcx.ccx).ptr_to();
468 callee.data = Fn(bcx.pointercast(drop_fn, llty));
472 // The arguments we'll be passing. Plus one to account for outptr, if used.
473 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
474 let mut llargs = Vec::with_capacity(arg_count);
476 // Prepare the return value destination
477 let ret_dest = if let Some((ref dest, _)) = *destination {
478 let is_intrinsic = if let Intrinsic = callee.data {
483 self.make_return_dest(&bcx, dest, &fn_ty.ret, &mut llargs, is_intrinsic)
488 // Split the rust-call tupled arguments off.
489 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
490 let (tup, args) = args.split_last().unwrap();
496 let is_shuffle = intrinsic.map_or(false, |name| {
497 name.starts_with("simd_shuffle")
500 for arg in first_args {
501 // The indices passed to simd_shuffle* in the
502 // third argument must be constant. This is
503 // checked by const-qualification, which also
504 // promotes any complex rvalues to constants.
505 if is_shuffle && idx == 2 {
507 mir::Operand::Consume(_) => {
508 span_bug!(span, "shuffle indices must be constant");
510 mir::Operand::Constant(ref constant) => {
511 let val = self.trans_constant(&bcx, constant);
512 llargs.push(val.llval);
519 let op = self.trans_operand(&bcx, arg);
520 self.trans_argument(&bcx, op, &mut llargs, &fn_ty,
521 &mut idx, &mut callee.data);
523 if let Some(tup) = untuple {
524 self.trans_arguments_untupled(&bcx, tup, &mut llargs, &fn_ty,
525 &mut idx, &mut callee.data)
528 let fn_ptr = match callee.data {
529 NamedTupleConstructor(_) => {
530 // FIXME translate this like mir::Rvalue::Aggregate.
531 callee.reify(bcx.ccx)
534 use intrinsic::trans_intrinsic_call;
536 let (dest, llargs) = match ret_dest {
537 _ if fn_ty.ret.is_indirect() => {
538 (llargs[0], &llargs[1..])
540 ReturnDest::Nothing => {
541 (C_undef(fn_ty.ret.original_ty.ptr_to()), &llargs[..])
543 ReturnDest::IndirectOperand(dst, _) |
544 ReturnDest::Store(dst) => (dst, &llargs[..]),
545 ReturnDest::DirectOperand(_) =>
546 bug!("Cannot use direct operand with an intrinsic call")
549 trans_intrinsic_call(&bcx, callee.ty, &fn_ty, &llargs, dest,
550 terminator.source_info.span);
552 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
553 // Make a fake operand for store_return
554 let op = OperandRef {
555 val: Ref(dst, Alignment::AbiAligned),
558 self.store_return(&bcx, ret_dest, fn_ty.ret, op);
561 if let Some((_, target)) = *destination {
562 funclet_br(self, bcx, target);
570 Virtual(_) => bug!("Virtual fn ptr not extracted")
573 // Many different ways to call a function handled here
574 if let &Some(cleanup) = cleanup {
575 let ret_bcx = if let Some((_, target)) = *destination {
578 self.unreachable_block()
580 let invokeret = bcx.invoke(fn_ptr,
583 llblock(self, cleanup),
585 fn_ty.apply_attrs_callsite(invokeret);
587 if let Some((_, target)) = *destination {
588 let ret_bcx = self.get_builder(target);
589 self.set_debug_loc(&ret_bcx, terminator.source_info);
590 let op = OperandRef {
591 val: Immediate(invokeret),
594 self.store_return(&ret_bcx, ret_dest, fn_ty.ret, op);
597 let llret = bcx.call(fn_ptr, &llargs, cleanup_bundle);
598 fn_ty.apply_attrs_callsite(llret);
599 if let Some((_, target)) = *destination {
600 let op = OperandRef {
601 val: Immediate(llret),
604 self.store_return(&bcx, ret_dest, fn_ty.ret, op);
605 funclet_br(self, bcx, target);
614 fn trans_argument(&mut self,
615 bcx: &Builder<'a, 'tcx>,
616 op: OperandRef<'tcx>,
617 llargs: &mut Vec<ValueRef>,
619 next_idx: &mut usize,
620 callee: &mut CalleeData) {
621 if let Pair(a, b) = op.val {
622 // Treat the values in a fat pointer separately.
623 if common::type_is_fat_ptr(bcx.ccx, op.ty) {
624 let (ptr, meta) = (a, b);
626 if let Virtual(idx) = *callee {
627 let llfn = meth::get_virtual_method(bcx, meta, idx);
628 let llty = fn_ty.llvm_type(bcx.ccx).ptr_to();
629 *callee = Fn(bcx.pointercast(llfn, llty));
633 let imm_op = |x| OperandRef {
635 // We won't be checking the type again.
636 ty: bcx.tcx().types.err
638 self.trans_argument(bcx, imm_op(ptr), llargs, fn_ty, next_idx, callee);
639 self.trans_argument(bcx, imm_op(meta), llargs, fn_ty, next_idx, callee);
644 let arg = &fn_ty.args[*next_idx];
647 // Fill padding with undef value, where applicable.
648 if let Some(ty) = arg.pad {
649 llargs.push(C_undef(ty));
656 // Force by-ref if we have to load through a cast pointer.
657 let (mut llval, align, by_ref) = match op.val {
658 Immediate(_) | Pair(..) => {
659 if arg.is_indirect() || arg.cast.is_some() {
660 let llscratch = bcx.alloca(arg.original_ty, "arg");
661 self.store_operand(bcx, llscratch, None, op);
662 (llscratch, Alignment::AbiAligned, true)
664 (op.pack_if_pair(bcx).immediate(), Alignment::AbiAligned, false)
667 Ref(llval, Alignment::Packed) if arg.is_indirect() => {
668 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
669 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
670 // have scary latent bugs around.
672 let llscratch = bcx.alloca(arg.original_ty, "arg");
673 base::memcpy_ty(bcx, llscratch, llval, op.ty, Some(1));
674 (llscratch, Alignment::AbiAligned, true)
676 Ref(llval, align) => (llval, align, true)
679 if by_ref && !arg.is_indirect() {
680 // Have to load the argument, maybe while casting it.
681 if arg.original_ty == Type::i1(bcx.ccx) {
682 // We store bools as i8 so we need to truncate to i1.
683 llval = bcx.load_range_assert(llval, 0, 2, llvm::False, None);
684 llval = bcx.trunc(llval, arg.original_ty);
685 } else if let Some(ty) = arg.cast {
686 llval = bcx.load(bcx.pointercast(llval, ty.ptr_to()),
687 align.min_with(llalign_of_min(bcx.ccx, arg.ty)));
689 llval = bcx.load(llval, align.to_align());
696 fn trans_arguments_untupled(&mut self,
697 bcx: &Builder<'a, 'tcx>,
698 operand: &mir::Operand<'tcx>,
699 llargs: &mut Vec<ValueRef>,
701 next_idx: &mut usize,
702 callee: &mut CalleeData) {
703 let tuple = self.trans_operand(bcx, operand);
705 let arg_types = match tuple.ty.sty {
706 ty::TyTuple(ref tys, _) => tys,
707 _ => span_bug!(self.mir.span,
708 "bad final argument to \"rust-call\" fn {:?}", tuple.ty)
711 // Handle both by-ref and immediate tuples.
713 Ref(llval, align) => {
714 for (n, &ty) in arg_types.iter().enumerate() {
715 let ptr = LvalueRef::new_sized_ty(llval, tuple.ty, align);
716 let (ptr, align) = ptr.trans_field_ptr(bcx, n);
717 let val = if common::type_is_fat_ptr(bcx.ccx, ty) {
718 let (lldata, llextra) = base::load_fat_ptr(bcx, ptr, align, ty);
719 Pair(lldata, llextra)
721 // trans_argument will load this if it needs to
724 let op = OperandRef {
728 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
732 Immediate(llval) => {
733 let l = bcx.ccx.layout_of(tuple.ty);
734 let v = if let layout::Univariant { ref variant, .. } = *l {
737 bug!("Not a tuple.");
739 for (n, &ty) in arg_types.iter().enumerate() {
740 let mut elem = bcx.extract_value(llval, v.memory_index[n] as usize);
741 // Truncate bools to i1, if needed
742 if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
743 elem = bcx.trunc(elem, Type::i1(bcx.ccx));
745 // If the tuple is immediate, the elements are as well
746 let op = OperandRef {
747 val: Immediate(elem),
750 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
755 for (n, &ty) in arg_types.iter().enumerate() {
756 let mut elem = elems[n];
757 // Truncate bools to i1, if needed
758 if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
759 elem = bcx.trunc(elem, Type::i1(bcx.ccx));
761 // Pair is always made up of immediates
762 let op = OperandRef {
763 val: Immediate(elem),
766 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
773 fn get_personality_slot(&mut self, bcx: &Builder<'a, 'tcx>) -> ValueRef {
775 if let Some(slot) = self.llpersonalityslot {
778 let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
779 let slot = bcx.alloca(llretty, "personalityslot");
780 self.llpersonalityslot = Some(slot);
781 Lifetime::Start.call(bcx, slot);
786 /// Return the landingpad wrapper around the given basic block
788 /// No-op in MSVC SEH scheme.
789 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> BasicBlockRef {
790 if let Some(block) = self.landing_pads[target_bb] {
794 if base::wants_msvc_seh(self.ccx.sess()) {
795 return self.blocks[target_bb];
798 let target = self.get_builder(target_bb);
800 let bcx = self.new_block("cleanup");
801 self.landing_pads[target_bb] = Some(bcx.llbb());
804 let llpersonality = self.ccx.eh_personality();
805 let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
806 let llretval = bcx.landing_pad(llretty, llpersonality, 1, self.llfn);
807 bcx.set_cleanup(llretval);
808 let slot = self.get_personality_slot(&bcx);
809 bcx.store(llretval, slot, None);
810 bcx.br(target.llbb());
814 fn unreachable_block(&mut self) -> BasicBlockRef {
815 self.unreachable_block.unwrap_or_else(|| {
816 let bl = self.new_block("unreachable");
818 self.unreachable_block = Some(bl.llbb());
823 pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
824 Builder::new_block(self.ccx, self.llfn, name)
827 pub fn get_builder(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> {
828 let builder = Builder::with_ccx(self.ccx);
829 builder.position_at_end(self.blocks[bb]);
833 fn make_return_dest(&mut self, bcx: &Builder<'a, 'tcx>,
834 dest: &mir::Lvalue<'tcx>, fn_ret_ty: &ArgType,
835 llargs: &mut Vec<ValueRef>, is_intrinsic: bool) -> ReturnDest {
836 // If the return is ignored, we can just return a do-nothing ReturnDest
837 if fn_ret_ty.is_ignore() {
838 return ReturnDest::Nothing;
840 let dest = if let mir::Lvalue::Local(index) = *dest {
841 let ret_ty = self.monomorphized_lvalue_ty(dest);
842 match self.locals[index] {
843 LocalRef::Lvalue(dest) => dest,
844 LocalRef::Operand(None) => {
845 // Handle temporary lvalues, specifically Operand ones, as
846 // they don't have allocas
847 return if fn_ret_ty.is_indirect() {
848 // Odd, but possible, case, we have an operand temporary,
849 // but the calling convention has an indirect return.
850 let tmp = LvalueRef::alloca(bcx, ret_ty, "tmp_ret");
851 llargs.push(tmp.llval);
852 ReturnDest::IndirectOperand(tmp.llval, index)
853 } else if is_intrinsic {
854 // Currently, intrinsics always need a location to store
855 // the result. so we create a temporary alloca for the
857 let tmp = LvalueRef::alloca(bcx, ret_ty, "tmp_ret");
858 ReturnDest::IndirectOperand(tmp.llval, index)
860 ReturnDest::DirectOperand(index)
863 LocalRef::Operand(Some(_)) => {
864 bug!("lvalue local already assigned to");
868 self.trans_lvalue(bcx, dest)
870 if fn_ret_ty.is_indirect() {
871 llargs.push(dest.llval);
874 ReturnDest::Store(dest.llval)
878 fn trans_transmute(&mut self, bcx: &Builder<'a, 'tcx>,
879 src: &mir::Operand<'tcx>,
880 dst: &mir::Lvalue<'tcx>) {
881 if let mir::Lvalue::Local(index) = *dst {
882 match self.locals[index] {
883 LocalRef::Lvalue(lvalue) => self.trans_transmute_into(bcx, src, &lvalue),
884 LocalRef::Operand(None) => {
885 let lvalue_ty = self.monomorphized_lvalue_ty(dst);
886 assert!(!lvalue_ty.has_erasable_regions());
887 let lvalue = LvalueRef::alloca(bcx, lvalue_ty, "transmute_temp");
888 self.trans_transmute_into(bcx, src, &lvalue);
889 let op = self.trans_load(bcx, lvalue.llval, lvalue.alignment, lvalue_ty);
890 self.locals[index] = LocalRef::Operand(Some(op));
892 LocalRef::Operand(Some(_)) => {
893 let ty = self.monomorphized_lvalue_ty(dst);
894 assert!(common::type_is_zero_size(bcx.ccx, ty),
895 "assigning to initialized SSAtemp");
899 let dst = self.trans_lvalue(bcx, dst);
900 self.trans_transmute_into(bcx, src, &dst);
904 fn trans_transmute_into(&mut self, bcx: &Builder<'a, 'tcx>,
905 src: &mir::Operand<'tcx>,
906 dst: &LvalueRef<'tcx>) {
907 let mut val = self.trans_operand(bcx, src);
908 if let ty::TyFnDef(def_id, substs, _) = val.ty.sty {
909 let llouttype = type_of::type_of(bcx.ccx, dst.ty.to_ty(bcx.tcx()));
910 let out_type_size = llbitsize_of_real(bcx.ccx, llouttype);
911 if out_type_size != 0 {
912 // FIXME #19925 Remove this hack after a release cycle.
913 let f = Callee::def(bcx.ccx, def_id, substs);
914 let ty = match f.ty.sty {
915 ty::TyFnDef(.., f) => bcx.tcx().mk_fn_ptr(f),
919 val: Immediate(f.reify(bcx.ccx)),
925 let llty = type_of::type_of(bcx.ccx, val.ty);
926 let cast_ptr = bcx.pointercast(dst.llval, llty.ptr_to());
927 let in_type = val.ty;
928 let out_type = dst.ty.to_ty(bcx.tcx());;
929 let llalign = cmp::min(align_of(bcx.ccx, in_type), align_of(bcx.ccx, out_type));
930 self.store_operand(bcx, cast_ptr, Some(llalign), val);
934 // Stores the return value of a function call into it's final location.
935 fn store_return(&mut self,
936 bcx: &Builder<'a, 'tcx>,
939 op: OperandRef<'tcx>) {
940 use self::ReturnDest::*;
944 Store(dst) => ret_ty.store(bcx, op.immediate(), dst),
945 IndirectOperand(tmp, index) => {
946 let op = self.trans_load(bcx, tmp, Alignment::AbiAligned, op.ty);
947 self.locals[index] = LocalRef::Operand(Some(op));
949 DirectOperand(index) => {
950 // If there is a cast, we have to store and reload.
951 let op = if ret_ty.cast.is_some() {
952 let tmp = LvalueRef::alloca(bcx, op.ty, "tmp_ret");
953 ret_ty.store(bcx, op.immediate(), tmp.llval);
954 self.trans_load(bcx, tmp.llval, tmp.alignment, op.ty)
956 op.unpack_if_pair(bcx)
958 self.locals[index] = LocalRef::Operand(Some(op));
965 // Do nothing, the return value is indirect or ignored
967 // Store the return value to the pointer
969 // Stores an indirect return value to an operand local lvalue
970 IndirectOperand(ValueRef, mir::Local),
971 // Stores a direct return value to an operand local lvalue
972 DirectOperand(mir::Local)