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};
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::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);
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(&bcx, ty, discr_lvalue.llval, None, true);
152 let mut bb_hist = FxHashMap();
153 for target in targets {
154 *bb_hist.entry(target).or_insert(0) += 1;
156 let (default_bb, default_blk) = match bb_hist.iter().max_by_key(|&(_, c)| c) {
157 // If a single target basic blocks is predominant, promote that to be the
158 // default case for the switch instruction to reduce the size of the generated
159 // code. This is especially helpful in cases like an if-let on a huge enum.
160 // Note: This optimization is only valid for exhaustive matches.
161 Some((&&bb, &c)) if c > targets.len() / 2 => {
162 (Some(bb), llblock(self, bb))
164 // We're generating an exhaustive switch, so the else branch
165 // can't be hit. Branching to an unreachable instruction
166 // lets LLVM know this
167 _ => (None, self.unreachable_block())
169 let switch = bcx.switch(discr, default_blk, targets.len());
170 assert_eq!(adt_def.variants.len(), targets.len());
171 for (adt_variant, &target) in adt_def.variants.iter().zip(targets) {
172 if default_bb != Some(target) {
173 let llbb = llblock(self, target);
174 let llval = adt::trans_case(&bcx, ty, Disr::from(adt_variant.disr_val));
175 bcx.add_case(switch, llval, llbb)
180 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
181 let (otherwise, targets) = targets.split_last().unwrap();
182 let discr = bcx.load(self.trans_lvalue(&bcx, discr).llval);
183 let discr = base::to_immediate(&bcx, discr, switch_ty);
184 let switch = bcx.switch(discr, llblock(self, *otherwise), values.len());
185 for (value, target) in values.iter().zip(targets) {
186 let val = Const::from_constval(bcx.ccx, value.clone(), switch_ty);
187 let llbb = llblock(self, *target);
188 bcx.add_case(switch, val.llval, llbb)
192 mir::TerminatorKind::Return => {
193 let ret = self.fn_ty.ret;
194 if ret.is_ignore() || ret.is_indirect() {
199 let llval = if let Some(cast_ty) = ret.cast {
200 let op = match self.locals[mir::RETURN_POINTER] {
201 LocalRef::Operand(Some(op)) => op,
202 LocalRef::Operand(None) => bug!("use of return before def"),
203 LocalRef::Lvalue(tr_lvalue) => {
205 val: Ref(tr_lvalue.llval),
206 ty: tr_lvalue.ty.to_ty(bcx.tcx())
210 let llslot = match op.val {
211 Immediate(_) | Pair(..) => {
212 let llscratch = bcx.alloca(ret.original_ty, "ret");
213 self.store_operand(&bcx, llscratch, op, None);
218 let load = bcx.load(bcx.pointercast(llslot, cast_ty.ptr_to()));
219 let llalign = llalign_of_min(bcx.ccx, ret.ty);
221 llvm::LLVMSetAlignment(load, llalign);
225 let op = self.trans_consume(&bcx, &mir::Lvalue::Local(mir::RETURN_POINTER));
226 if let Ref(llval) = op.val {
227 base::load_ty(&bcx, llval, op.ty)
229 op.pack_if_pair(&bcx).immediate()
235 mir::TerminatorKind::Unreachable => {
239 mir::TerminatorKind::Drop { ref location, target, unwind } => {
240 let ty = location.ty(&self.mir, bcx.tcx()).to_ty(bcx.tcx());
241 let ty = self.monomorphize(&ty);
243 // Double check for necessity to drop
244 if !bcx.ccx.shared().type_needs_drop(ty) {
245 funclet_br(self, bcx, target);
249 let mut lvalue = self.trans_lvalue(&bcx, location);
250 let drop_fn = glue::get_drop_glue(bcx.ccx, ty);
251 let drop_ty = glue::get_drop_glue_type(bcx.ccx.shared(), ty);
252 if bcx.ccx.shared().type_is_sized(ty) && drop_ty != ty {
253 lvalue.llval = bcx.pointercast(
254 lvalue.llval, type_of::type_of(bcx.ccx, drop_ty).ptr_to());
256 let args = &[lvalue.llval, lvalue.llextra][..1 + lvalue.has_extra() as usize];
257 if let Some(unwind) = unwind {
262 llblock(self, unwind),
266 bcx.call(drop_fn, args, cleanup_bundle);
267 funclet_br(self, bcx, target);
271 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
272 let cond = self.trans_operand(&bcx, cond).immediate();
273 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
275 // This case can currently arise only from functions marked
276 // with #[rustc_inherit_overflow_checks] and inlined from
277 // another crate (mostly core::num generic/#[inline] fns),
278 // while the current crate doesn't use overflow checks.
279 // NOTE: Unlike binops, negation doesn't have its own
280 // checked operation, just a comparison with the minimum
281 // value, so we have to check for the assert message.
282 if !bcx.ccx.check_overflow() {
283 use rustc_const_math::ConstMathErr::Overflow;
284 use rustc_const_math::Op::Neg;
286 if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
287 const_cond = Some(expected);
291 // Don't translate the panic block if success if known.
292 if const_cond == Some(expected) {
293 funclet_br(self, bcx, target);
297 // Pass the condition through llvm.expect for branch hinting.
298 let expect = bcx.ccx.get_intrinsic(&"llvm.expect.i1");
299 let cond = bcx.call(expect, &[cond, C_bool(bcx.ccx, expected)], None);
301 // Create the failure block and the conditional branch to it.
302 let lltarget = llblock(self, target);
303 let panic_block = self.new_block("panic");
305 bcx.cond_br(cond, lltarget, panic_block.llbb());
307 bcx.cond_br(cond, panic_block.llbb(), lltarget);
310 // After this point, bcx is the block for the call to panic.
312 self.set_debug_loc(&bcx, terminator.source_info);
314 // Get the location information.
315 let loc = bcx.sess().codemap().lookup_char_pos(span.lo);
316 let filename = Symbol::intern(&loc.file.name).as_str();
317 let filename = C_str_slice(bcx.ccx, filename);
318 let line = C_u32(bcx.ccx, loc.line as u32);
320 // Put together the arguments to the panic entry point.
321 let (lang_item, args, const_err) = match *msg {
322 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
323 let len = self.trans_operand(&mut bcx, len).immediate();
324 let index = self.trans_operand(&mut bcx, index).immediate();
326 let const_err = common::const_to_opt_u128(len, false)
327 .and_then(|len| common::const_to_opt_u128(index, false)
328 .map(|index| ErrKind::IndexOutOfBounds {
333 let file_line = C_struct(bcx.ccx, &[filename, line], false);
334 let align = llalign_of_min(bcx.ccx, common::val_ty(file_line));
335 let file_line = consts::addr_of(bcx.ccx,
338 "panic_bounds_check_loc");
339 (lang_items::PanicBoundsCheckFnLangItem,
340 vec![file_line, index, len],
343 mir::AssertMessage::Math(ref err) => {
344 let msg_str = Symbol::intern(err.description()).as_str();
345 let msg_str = C_str_slice(bcx.ccx, msg_str);
346 let msg_file_line = C_struct(bcx.ccx,
347 &[msg_str, filename, line],
349 let align = llalign_of_min(bcx.ccx, common::val_ty(msg_file_line));
350 let msg_file_line = consts::addr_of(bcx.ccx,
354 (lang_items::PanicFnLangItem,
356 Some(ErrKind::Math(err.clone())))
360 // If we know we always panic, and the error message
361 // is also constant, then we can produce a warning.
362 if const_cond == Some(!expected) {
363 if let Some(err) = const_err {
364 let err = ConstEvalErr{ span: span, kind: err };
365 let mut diag = bcx.tcx().sess.struct_span_warn(
366 span, "this expression will panic at run-time");
367 note_const_eval_err(bcx.tcx(), &err, span, "expression", &mut diag);
372 // Obtain the panic entry point.
373 let def_id = common::langcall(bcx.tcx(), Some(span), "", lang_item);
374 let callee = Callee::def(bcx.ccx, def_id,
375 bcx.ccx.empty_substs_for_def_id(def_id));
376 let llfn = callee.reify(bcx.ccx);
378 // Translate the actual panic invoke/call.
379 if let Some(unwind) = cleanup {
382 self.unreachable_block(),
383 llblock(self, unwind),
386 bcx.call(llfn, &args, cleanup_bundle);
391 mir::TerminatorKind::DropAndReplace { .. } => {
392 bug!("undesugared DropAndReplace in trans: {:?}", data);
395 mir::TerminatorKind::Call { ref func, ref args, ref destination, ref cleanup } => {
396 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
397 let callee = self.trans_operand(&bcx, func);
399 let (mut callee, abi, sig) = match callee.ty.sty {
400 ty::TyFnDef(def_id, substs, f) => {
401 (Callee::def(bcx.ccx, def_id, substs), f.abi, &f.sig)
405 data: Fn(callee.immediate()),
409 _ => bug!("{} is not callable", callee.ty)
412 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 (&callee.ty.sty, &callee.data) {
416 (&ty::TyFnDef(def_id, ..), &Intrinsic) => {
417 Some(bcx.tcx().item_name(def_id).as_str())
421 let mut intrinsic = intrinsic.as_ref().map(|s| &s[..]);
423 if intrinsic == Some("move_val_init") {
424 let &(_, target) = destination.as_ref().unwrap();
425 // The first argument is a thin destination pointer.
426 let llptr = self.trans_operand(&bcx, &args[0]).immediate();
427 let val = self.trans_operand(&bcx, &args[1]);
428 self.store_operand(&bcx, llptr, val, None);
429 funclet_br(self, bcx, target);
433 if intrinsic == Some("transmute") {
434 let &(ref dest, target) = destination.as_ref().unwrap();
435 self.with_lvalue_ref(&bcx, dest, |this, dest| {
436 this.trans_transmute(&bcx, &args[0], dest);
439 funclet_br(self, bcx, target);
443 let extra_args = &args[sig.inputs().len()..];
444 let extra_args = extra_args.iter().map(|op_arg| {
445 let op_ty = op_arg.ty(&self.mir, bcx.tcx());
446 self.monomorphize(&op_ty)
447 }).collect::<Vec<_>>();
448 let fn_ty = callee.direct_fn_type(bcx.ccx, &extra_args);
450 if intrinsic == Some("drop_in_place") {
451 let &(_, target) = destination.as_ref().unwrap();
452 let ty = if let ty::TyFnDef(_, substs, _) = callee.ty.sty {
455 bug!("Unexpected ty: {}", callee.ty);
458 // Double check for necessity to drop
459 if !bcx.ccx.shared().type_needs_drop(ty) {
460 funclet_br(self, bcx, target);
464 let drop_fn = glue::get_drop_glue(bcx.ccx, ty);
465 let llty = fn_ty.llvm_type(bcx.ccx).ptr_to();
466 callee.data = Fn(bcx.pointercast(drop_fn, llty));
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 = if let Intrinsic = callee.data {
481 self.make_return_dest(&bcx, dest, &fn_ty.ret, &mut llargs, is_intrinsic)
486 // Split the rust-call tupled arguments off.
487 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
488 let (tup, args) = args.split_last().unwrap();
494 let is_shuffle = intrinsic.map_or(false, |name| {
495 name.starts_with("simd_shuffle")
498 for arg in first_args {
499 // The indices passed to simd_shuffle* in the
500 // third argument must be constant. This is
501 // checked by const-qualification, which also
502 // promotes any complex rvalues to constants.
503 if is_shuffle && idx == 2 {
505 mir::Operand::Consume(_) => {
506 span_bug!(span, "shuffle indices must be constant");
508 mir::Operand::Constant(ref constant) => {
509 let val = self.trans_constant(&bcx, constant);
510 llargs.push(val.llval);
517 let op = self.trans_operand(&bcx, arg);
518 self.trans_argument(&bcx, op, &mut llargs, &fn_ty,
519 &mut idx, &mut callee.data);
521 if let Some(tup) = untuple {
522 self.trans_arguments_untupled(&bcx, tup, &mut llargs, &fn_ty,
523 &mut idx, &mut callee.data)
526 let fn_ptr = match callee.data {
527 NamedTupleConstructor(_) => {
528 // FIXME translate this like mir::Rvalue::Aggregate.
529 callee.reify(bcx.ccx)
532 use intrinsic::trans_intrinsic_call;
534 let (dest, llargs) = match ret_dest {
535 _ if fn_ty.ret.is_indirect() => {
536 (llargs[0], &llargs[1..])
538 ReturnDest::Nothing => {
539 (C_undef(fn_ty.ret.original_ty.ptr_to()), &llargs[..])
541 ReturnDest::IndirectOperand(dst, _) |
542 ReturnDest::Store(dst) => (dst, &llargs[..]),
543 ReturnDest::DirectOperand(_) =>
544 bug!("Cannot use direct operand with an intrinsic call")
547 trans_intrinsic_call(&bcx, callee.ty, &fn_ty, &llargs, dest,
548 terminator.source_info.span);
550 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
551 // Make a fake operand for store_return
552 let op = OperandRef {
556 self.store_return(&bcx, ret_dest, fn_ty.ret, op);
559 if let Some((_, target)) = *destination {
560 funclet_br(self, bcx, target);
568 Virtual(_) => bug!("Virtual fn ptr not extracted")
571 // Many different ways to call a function handled here
572 if let &Some(cleanup) = cleanup {
573 let ret_bcx = if let Some((_, target)) = *destination {
576 self.unreachable_block()
578 let invokeret = bcx.invoke(fn_ptr,
581 llblock(self, cleanup),
583 fn_ty.apply_attrs_callsite(invokeret);
585 if let Some((_, target)) = *destination {
586 let ret_bcx = self.get_builder(target);
587 self.set_debug_loc(&ret_bcx, terminator.source_info);
588 let op = OperandRef {
589 val: Immediate(invokeret),
592 self.store_return(&ret_bcx, ret_dest, fn_ty.ret, op);
595 let llret = bcx.call(fn_ptr, &llargs, cleanup_bundle);
596 fn_ty.apply_attrs_callsite(llret);
597 if let Some((_, target)) = *destination {
598 let op = OperandRef {
599 val: Immediate(llret),
602 self.store_return(&bcx, ret_dest, fn_ty.ret, op);
603 funclet_br(self, bcx, target);
612 fn trans_argument(&mut self,
613 bcx: &Builder<'a, 'tcx>,
614 op: OperandRef<'tcx>,
615 llargs: &mut Vec<ValueRef>,
617 next_idx: &mut usize,
618 callee: &mut CalleeData) {
619 if let Pair(a, b) = op.val {
620 // Treat the values in a fat pointer separately.
621 if common::type_is_fat_ptr(bcx.ccx, op.ty) {
622 let (ptr, meta) = (a, b);
624 if let Virtual(idx) = *callee {
625 let llfn = meth::get_virtual_method(bcx, meta, idx);
626 let llty = fn_ty.llvm_type(bcx.ccx).ptr_to();
627 *callee = Fn(bcx.pointercast(llfn, llty));
631 let imm_op = |x| OperandRef {
633 // We won't be checking the type again.
634 ty: bcx.tcx().types.err
636 self.trans_argument(bcx, imm_op(ptr), llargs, fn_ty, next_idx, callee);
637 self.trans_argument(bcx, imm_op(meta), llargs, fn_ty, next_idx, callee);
642 let arg = &fn_ty.args[*next_idx];
645 // Fill padding with undef value, where applicable.
646 if let Some(ty) = arg.pad {
647 llargs.push(C_undef(ty));
654 // Force by-ref if we have to load through a cast pointer.
655 let (mut llval, by_ref) = match op.val {
656 Immediate(_) | Pair(..) => {
657 if arg.is_indirect() || arg.cast.is_some() {
658 let llscratch = bcx.alloca(arg.original_ty, "arg");
659 self.store_operand(bcx, llscratch, op, None);
662 (op.pack_if_pair(bcx).immediate(), false)
665 Ref(llval) => (llval, true)
668 if by_ref && !arg.is_indirect() {
669 // Have to load the argument, maybe while casting it.
670 if arg.original_ty == Type::i1(bcx.ccx) {
671 // We store bools as i8 so we need to truncate to i1.
672 llval = bcx.load_range_assert(llval, 0, 2, llvm::False);
673 llval = bcx.trunc(llval, arg.original_ty);
674 } else if let Some(ty) = arg.cast {
675 llval = bcx.load(bcx.pointercast(llval, ty.ptr_to()));
676 let llalign = llalign_of_min(bcx.ccx, arg.ty);
678 llvm::LLVMSetAlignment(llval, llalign);
681 llval = bcx.load(llval);
688 fn trans_arguments_untupled(&mut self,
689 bcx: &Builder<'a, 'tcx>,
690 operand: &mir::Operand<'tcx>,
691 llargs: &mut Vec<ValueRef>,
693 next_idx: &mut usize,
694 callee: &mut CalleeData) {
695 let tuple = self.trans_operand(bcx, operand);
697 let arg_types = match tuple.ty.sty {
698 ty::TyTuple(ref tys, _) => tys,
699 _ => span_bug!(self.mir.span,
700 "bad final argument to \"rust-call\" fn {:?}", tuple.ty)
703 // Handle both by-ref and immediate tuples.
706 for (n, &ty) in arg_types.iter().enumerate() {
707 let ptr = LvalueRef::new_sized_ty(llval, tuple.ty);
708 let ptr = ptr.trans_field_ptr(bcx, n);
709 let val = if common::type_is_fat_ptr(bcx.ccx, ty) {
710 let (lldata, llextra) = base::load_fat_ptr(bcx, ptr, ty);
711 Pair(lldata, llextra)
713 // trans_argument will load this if it needs to
716 let op = OperandRef {
720 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
724 Immediate(llval) => {
725 let l = bcx.ccx.layout_of(tuple.ty);
726 let v = if let layout::Univariant { ref variant, .. } = *l {
729 bug!("Not a tuple.");
731 for (n, &ty) in arg_types.iter().enumerate() {
732 let mut elem = bcx.extract_value(llval, v.memory_index[n] as usize);
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 // If the tuple is immediate, the elements are as well
738 let op = OperandRef {
739 val: Immediate(elem),
742 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
747 for (n, &ty) in arg_types.iter().enumerate() {
748 let mut elem = elems[n];
749 // Truncate bools to i1, if needed
750 if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx) {
751 elem = bcx.trunc(elem, Type::i1(bcx.ccx));
753 // Pair is always made up of immediates
754 let op = OperandRef {
755 val: Immediate(elem),
758 self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
765 fn get_personality_slot(&mut self, bcx: &Builder<'a, 'tcx>) -> ValueRef {
767 if let Some(slot) = self.llpersonalityslot {
770 let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
771 let slot = bcx.alloca(llretty, "personalityslot");
772 self.llpersonalityslot = Some(slot);
773 Lifetime::Start.call(bcx, slot);
778 /// Return the landingpad wrapper around the given basic block
780 /// No-op in MSVC SEH scheme.
781 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> BasicBlockRef {
782 if let Some(block) = self.landing_pads[target_bb] {
786 if base::wants_msvc_seh(self.ccx.sess()) {
787 return self.blocks[target_bb];
790 let target = self.get_builder(target_bb);
792 let bcx = self.new_block("cleanup");
793 self.landing_pads[target_bb] = Some(bcx.llbb());
796 let llpersonality = self.ccx.eh_personality();
797 let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
798 let llretval = bcx.landing_pad(llretty, llpersonality, 1, self.llfn);
799 bcx.set_cleanup(llretval);
800 let slot = self.get_personality_slot(&bcx);
801 bcx.store(llretval, slot, None);
802 bcx.br(target.llbb());
806 fn unreachable_block(&mut self) -> BasicBlockRef {
807 self.unreachable_block.unwrap_or_else(|| {
808 let bl = self.new_block("unreachable");
810 self.unreachable_block = Some(bl.llbb());
815 pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
816 Builder::new_block(self.ccx, self.llfn, name)
819 pub fn get_builder(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> {
820 let builder = Builder::with_ccx(self.ccx);
821 builder.position_at_end(self.blocks[bb]);
825 fn make_return_dest(&mut self, bcx: &Builder<'a, 'tcx>,
826 dest: &mir::Lvalue<'tcx>, fn_ret_ty: &ArgType,
827 llargs: &mut Vec<ValueRef>, is_intrinsic: bool) -> ReturnDest {
828 // If the return is ignored, we can just return a do-nothing ReturnDest
829 if fn_ret_ty.is_ignore() {
830 return ReturnDest::Nothing;
832 let dest = if let mir::Lvalue::Local(index) = *dest {
833 let ret_ty = self.monomorphized_lvalue_ty(dest);
834 match self.locals[index] {
835 LocalRef::Lvalue(dest) => dest,
836 LocalRef::Operand(None) => {
837 // Handle temporary lvalues, specifically Operand ones, as
838 // they don't have allocas
839 return if fn_ret_ty.is_indirect() {
840 // Odd, but possible, case, we have an operand temporary,
841 // but the calling convention has an indirect return.
842 let tmp = bcx.alloca_ty(ret_ty, "tmp_ret");
844 ReturnDest::IndirectOperand(tmp, index)
845 } else if is_intrinsic {
846 // Currently, intrinsics always need a location to store
847 // the result. so we create a temporary alloca for the
849 let tmp = bcx.alloca_ty(ret_ty, "tmp_ret");
850 ReturnDest::IndirectOperand(tmp, index)
852 ReturnDest::DirectOperand(index)
855 LocalRef::Operand(Some(_)) => {
856 bug!("lvalue local already assigned to");
860 self.trans_lvalue(bcx, dest)
862 if fn_ret_ty.is_indirect() {
863 llargs.push(dest.llval);
866 ReturnDest::Store(dest.llval)
870 fn trans_transmute(&mut self, bcx: &Builder<'a, 'tcx>,
871 src: &mir::Operand<'tcx>, dst: LvalueRef<'tcx>) {
872 let mut val = self.trans_operand(bcx, src);
873 if let ty::TyFnDef(def_id, substs, _) = val.ty.sty {
874 let llouttype = type_of::type_of(bcx.ccx, dst.ty.to_ty(bcx.tcx()));
875 let out_type_size = llbitsize_of_real(bcx.ccx, llouttype);
876 if out_type_size != 0 {
877 // FIXME #19925 Remove this hack after a release cycle.
878 let f = Callee::def(bcx.ccx, def_id, substs);
879 let ty = match f.ty.sty {
880 ty::TyFnDef(.., f) => bcx.tcx().mk_fn_ptr(f),
884 val: Immediate(f.reify(bcx.ccx)),
890 let llty = type_of::type_of(bcx.ccx, val.ty);
891 let cast_ptr = bcx.pointercast(dst.llval, llty.ptr_to());
892 let in_type = val.ty;
893 let out_type = dst.ty.to_ty(bcx.tcx());;
894 let llalign = cmp::min(align_of(bcx.ccx, in_type), align_of(bcx.ccx, out_type));
895 self.store_operand(bcx, cast_ptr, val, Some(llalign));
899 // Stores the return value of a function call into it's final location.
900 fn store_return(&mut self,
901 bcx: &Builder<'a, 'tcx>,
904 op: OperandRef<'tcx>) {
905 use self::ReturnDest::*;
909 Store(dst) => ret_ty.store(bcx, op.immediate(), dst),
910 IndirectOperand(tmp, index) => {
911 let op = self.trans_load(bcx, tmp, op.ty);
912 self.locals[index] = LocalRef::Operand(Some(op));
914 DirectOperand(index) => {
915 // If there is a cast, we have to store and reload.
916 let op = if ret_ty.cast.is_some() {
917 let tmp = bcx.alloca_ty(op.ty, "tmp_ret");
918 ret_ty.store(bcx, op.immediate(), tmp);
919 self.trans_load(bcx, tmp, op.ty)
921 op.unpack_if_pair(bcx)
923 self.locals[index] = LocalRef::Operand(Some(op));
930 // Do nothing, the return value is indirect or ignored
932 // Store the return value to the pointer
934 // Stores an indirect return value to an operand local lvalue
935 IndirectOperand(ValueRef, mir::Local),
936 // Stores a direct return value to an operand local lvalue
937 DirectOperand(mir::Local)