]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/block.rs
Unignore u128 test for stage 0,1
[rust.git] / src / librustc_trans / mir / block.rs
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.
4 //
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.
10
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};
15 use rustc::mir;
16 use abi::{Abi, FnType, ArgType};
17 use adt;
18 use base::{self, Lifetime};
19 use callee::{Callee, CalleeData, Fn, Intrinsic, NamedTupleConstructor, Virtual};
20 use builder::Builder;
21 use common::{self, Funclet};
22 use common::{C_bool, C_str_slice, C_struct, C_u32, C_undef};
23 use consts;
24 use Disr;
25 use machine::{llalign_of_min, llbitsize_of_real};
26 use meth;
27 use type_of::{self, align_of};
28 use glue;
29 use type_::Type;
30
31 use rustc_data_structures::indexed_vec::IndexVec;
32 use rustc_data_structures::fx::FxHashMap;
33 use syntax::symbol::Symbol;
34
35 use std::cmp;
36
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};
43
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];
49
50         debug!("trans_block({:?}={:?})", bb, data);
51
52         let funclet = match self.cleanup_kinds[bb] {
53             CleanupKind::Internal { funclet } => funclets[funclet].as_ref(),
54             _ => funclets[bb].as_ref(),
55         };
56
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());
60
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
67                         // to a return block
68                         bcx.cleanup_ret(cp, Some(lltarget));
69                     }
70                     CleanupKind::Internal { .. } => bcx.br(lltarget),
71                     CleanupKind::NotCleanup => bug!("jump from cleanup bb to bb {:?}", bb)
72                 }
73             } else {
74                 bcx.br(lltarget);
75             }
76         };
77
78         let llblock = |this: &mut Self, target: mir::BasicBlock| {
79             let lltarget = this.blocks[target];
80
81             if let Some(cp) = cleanup_pad {
82                 match this.cleanup_kinds[target] {
83                     CleanupKind::Funclet => {
84                         // MSVC cross-funclet jump - need a trampoline
85
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));
90                         trampoline.llbb()
91                     }
92                     CleanupKind::Internal { .. } => lltarget,
93                     CleanupKind::NotCleanup =>
94                         bug!("jump from cleanup bb {:?} to bb {:?}", bb, target)
95                 }
96             } else {
97                 if let (CleanupKind::NotCleanup, CleanupKind::Funclet) =
98                     (this.cleanup_kinds[bb], this.cleanup_kinds[target])
99                 {
100                     // jump *into* cleanup - need a landing pad if GNU
101                     this.landing_pad_to(target)
102                 } else {
103                     lltarget
104                 }
105             }
106         };
107
108         for statement in &data.statements {
109             bcx = self.trans_statement(bcx, statement);
110         }
111
112         let terminator = data.terminator();
113         debug!("trans_block: terminator: {:?}", terminator);
114
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);
121                 } else {
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 {
126                         bcx.resume(lp);
127                     } else {
128                         let exc_ptr = bcx.extract_value(lp, 0);
129                         bcx.call(bcx.ccx.eh_unwind_resume(), &[exc_ptr], cleanup_bundle);
130                         bcx.unreachable();
131                     }
132                 }
133             }
134
135             mir::TerminatorKind::Goto { target } => {
136                 funclet_br(self, bcx, target);
137             }
138
139             mir::TerminatorKind::If { ref cond, targets: (true_bb, false_bb) } => {
140                 let cond = self.trans_operand(&bcx, cond);
141
142                 let lltrue = llblock(self, true_bb);
143                 let llfalse = llblock(self, false_bb);
144                 bcx.cond_br(cond.immediate(), lltrue, llfalse);
145             }
146
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);
151
152                 let mut bb_hist = FxHashMap();
153                 for target in targets {
154                     *bb_hist.entry(target).or_insert(0) += 1;
155                 }
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))
163                     }
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())
168                 };
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)
176                     }
177                 }
178             }
179
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)
189                 }
190             }
191
192             mir::TerminatorKind::Return => {
193                 let ret = self.fn_ty.ret;
194                 if ret.is_ignore() || ret.is_indirect() {
195                     bcx.ret_void();
196                     return;
197                 }
198
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) => {
204                             OperandRef {
205                                 val: Ref(tr_lvalue.llval),
206                                 ty: tr_lvalue.ty.to_ty(bcx.tcx())
207                             }
208                         }
209                     };
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);
214                             llscratch
215                         }
216                         Ref(llval) => llval
217                     };
218                     let load = bcx.load(bcx.pointercast(llslot, cast_ty.ptr_to()));
219                     let llalign = llalign_of_min(bcx.ccx, ret.ty);
220                     unsafe {
221                         llvm::LLVMSetAlignment(load, llalign);
222                     }
223                     load
224                 } else {
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)
228                     } else {
229                         op.pack_if_pair(&bcx).immediate()
230                     }
231                 };
232                 bcx.ret(llval);
233             }
234
235             mir::TerminatorKind::Unreachable => {
236                 bcx.unreachable();
237             }
238
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);
242
243                 // Double check for necessity to drop
244                 if !bcx.ccx.shared().type_needs_drop(ty) {
245                     funclet_br(self, bcx, target);
246                     return;
247                 }
248
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());
255                 }
256                 let args = &[lvalue.llval, lvalue.llextra][..1 + lvalue.has_extra() as usize];
257                 if let Some(unwind) = unwind {
258                     bcx.invoke(
259                         drop_fn,
260                         args,
261                         self.blocks[target],
262                         llblock(self, unwind),
263                         cleanup_bundle
264                     );
265                 } else {
266                     bcx.call(drop_fn, args, cleanup_bundle);
267                     funclet_br(self, bcx, target);
268                 }
269             }
270
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);
274
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;
285
286                     if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
287                         const_cond = Some(expected);
288                     }
289                 }
290
291                 // Don't translate the panic block if success if known.
292                 if const_cond == Some(expected) {
293                     funclet_br(self, bcx, target);
294                     return;
295                 }
296
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);
300
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");
304                 if expected {
305                     bcx.cond_br(cond, lltarget, panic_block.llbb());
306                 } else {
307                     bcx.cond_br(cond, panic_block.llbb(), lltarget);
308                 }
309
310                 // After this point, bcx is the block for the call to panic.
311                 bcx = panic_block;
312                 self.set_debug_loc(&bcx, terminator.source_info);
313
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);
319
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();
325
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 {
329                                     len: len as u64,
330                                     index: index as u64
331                                 }));
332
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,
336                                                         file_line,
337                                                         align,
338                                                         "panic_bounds_check_loc");
339                         (lang_items::PanicBoundsCheckFnLangItem,
340                          vec![file_line, index, len],
341                          const_err)
342                     }
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],
348                                                      false);
349                         let align = llalign_of_min(bcx.ccx, common::val_ty(msg_file_line));
350                         let msg_file_line = consts::addr_of(bcx.ccx,
351                                                             msg_file_line,
352                                                             align,
353                                                             "panic_loc");
354                         (lang_items::PanicFnLangItem,
355                          vec![msg_file_line],
356                          Some(ErrKind::Math(err.clone())))
357                     }
358                 };
359
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);
368                         diag.emit();
369                     }
370                 }
371
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);
377
378                 // Translate the actual panic invoke/call.
379                 if let Some(unwind) = cleanup {
380                     bcx.invoke(llfn,
381                                &args,
382                                self.unreachable_block(),
383                                llblock(self, unwind),
384                                cleanup_bundle);
385                 } else {
386                     bcx.call(llfn, &args, cleanup_bundle);
387                     bcx.unreachable();
388                 }
389             }
390
391             mir::TerminatorKind::DropAndReplace { .. } => {
392                 bug!("undesugared DropAndReplace in trans: {:?}", data);
393             }
394
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);
398
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)
402                     }
403                     ty::TyFnPtr(f) => {
404                         (Callee {
405                             data: Fn(callee.immediate()),
406                             ty: callee.ty
407                         }, f.abi, &f.sig)
408                     }
409                     _ => bug!("{} is not callable", callee.ty)
410                 };
411
412                 let sig = bcx.tcx().erase_late_bound_regions_and_normalize(sig);
413
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())
418                     }
419                     _ => None
420                 };
421                 let mut intrinsic = intrinsic.as_ref().map(|s| &s[..]);
422
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);
430                     return;
431                 }
432
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);
437                     });
438
439                     funclet_br(self, bcx, target);
440                     return;
441                 }
442
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);
449
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 {
453                         substs.type_at(0)
454                     } else {
455                         bug!("Unexpected ty: {}", callee.ty);
456                     };
457
458                     // Double check for necessity to drop
459                     if !bcx.ccx.shared().type_needs_drop(ty) {
460                         funclet_br(self, bcx, target);
461                         return;
462                     }
463
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));
467                     intrinsic = None;
468                 }
469
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);
473
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 {
477                         true
478                     } else {
479                         false
480                     };
481                     self.make_return_dest(&bcx, dest, &fn_ty.ret, &mut llargs, is_intrinsic)
482                 } else {
483                     ReturnDest::Nothing
484                 };
485
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();
489                     (args, Some(tup))
490                 } else {
491                     (&args[..], None)
492                 };
493
494                 let is_shuffle = intrinsic.map_or(false, |name| {
495                     name.starts_with("simd_shuffle")
496                 });
497                 let mut idx = 0;
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 {
504                         match *arg {
505                             mir::Operand::Consume(_) => {
506                                 span_bug!(span, "shuffle indices must be constant");
507                             }
508                             mir::Operand::Constant(ref constant) => {
509                                 let val = self.trans_constant(&bcx, constant);
510                                 llargs.push(val.llval);
511                                 idx += 1;
512                                 continue;
513                             }
514                         }
515                     }
516
517                     let op = self.trans_operand(&bcx, arg);
518                     self.trans_argument(&bcx, op, &mut llargs, &fn_ty,
519                                         &mut idx, &mut callee.data);
520                 }
521                 if let Some(tup) = untuple {
522                     self.trans_arguments_untupled(&bcx, tup, &mut llargs, &fn_ty,
523                                                   &mut idx, &mut callee.data)
524                 }
525
526                 let fn_ptr = match callee.data {
527                     NamedTupleConstructor(_) => {
528                         // FIXME translate this like mir::Rvalue::Aggregate.
529                         callee.reify(bcx.ccx)
530                     }
531                     Intrinsic => {
532                         use intrinsic::trans_intrinsic_call;
533
534                         let (dest, llargs) = match ret_dest {
535                             _ if fn_ty.ret.is_indirect() => {
536                                 (llargs[0], &llargs[1..])
537                             }
538                             ReturnDest::Nothing => {
539                                 (C_undef(fn_ty.ret.original_ty.ptr_to()), &llargs[..])
540                             }
541                             ReturnDest::IndirectOperand(dst, _) |
542                             ReturnDest::Store(dst) => (dst, &llargs[..]),
543                             ReturnDest::DirectOperand(_) =>
544                                 bug!("Cannot use direct operand with an intrinsic call")
545                         };
546
547                         trans_intrinsic_call(&bcx, callee.ty, &fn_ty, &llargs, dest,
548                             terminator.source_info.span);
549
550                         if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
551                             // Make a fake operand for store_return
552                             let op = OperandRef {
553                                 val: Ref(dst),
554                                 ty: sig.output(),
555                             };
556                             self.store_return(&bcx, ret_dest, fn_ty.ret, op);
557                         }
558
559                         if let Some((_, target)) = *destination {
560                             funclet_br(self, bcx, target);
561                         } else {
562                             bcx.unreachable();
563                         }
564
565                         return;
566                     }
567                     Fn(f) => f,
568                     Virtual(_) => bug!("Virtual fn ptr not extracted")
569                 };
570
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 {
574                         self.blocks[target]
575                     } else {
576                         self.unreachable_block()
577                     };
578                     let invokeret = bcx.invoke(fn_ptr,
579                                                &llargs,
580                                                ret_bcx,
581                                                llblock(self, cleanup),
582                                                cleanup_bundle);
583                     fn_ty.apply_attrs_callsite(invokeret);
584
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),
590                             ty: sig.output(),
591                         };
592                         self.store_return(&ret_bcx, ret_dest, fn_ty.ret, op);
593                     }
594                 } else {
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),
600                             ty: sig.output(),
601                         };
602                         self.store_return(&bcx, ret_dest, fn_ty.ret, op);
603                         funclet_br(self, bcx, target);
604                     } else {
605                         bcx.unreachable();
606                     }
607                 }
608             }
609         }
610     }
611
612     fn trans_argument(&mut self,
613                       bcx: &Builder<'a, 'tcx>,
614                       op: OperandRef<'tcx>,
615                       llargs: &mut Vec<ValueRef>,
616                       fn_ty: &FnType,
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);
623                 if *next_idx == 0 {
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));
628                     }
629                 }
630
631                 let imm_op = |x| OperandRef {
632                     val: Immediate(x),
633                     // We won't be checking the type again.
634                     ty: bcx.tcx().types.err
635                 };
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);
638                 return;
639             }
640         }
641
642         let arg = &fn_ty.args[*next_idx];
643         *next_idx += 1;
644
645         // Fill padding with undef value, where applicable.
646         if let Some(ty) = arg.pad {
647             llargs.push(C_undef(ty));
648         }
649
650         if arg.is_ignore() {
651             return;
652         }
653
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);
660                     (llscratch, true)
661                 } else {
662                     (op.pack_if_pair(bcx).immediate(), false)
663                 }
664             }
665             Ref(llval) => (llval, true)
666         };
667
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);
677                 unsafe {
678                     llvm::LLVMSetAlignment(llval, llalign);
679                 }
680             } else {
681                 llval = bcx.load(llval);
682             }
683         }
684
685         llargs.push(llval);
686     }
687
688     fn trans_arguments_untupled(&mut self,
689                                 bcx: &Builder<'a, 'tcx>,
690                                 operand: &mir::Operand<'tcx>,
691                                 llargs: &mut Vec<ValueRef>,
692                                 fn_ty: &FnType,
693                                 next_idx: &mut usize,
694                                 callee: &mut CalleeData) {
695         let tuple = self.trans_operand(bcx, operand);
696
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)
701         };
702
703         // Handle both by-ref and immediate tuples.
704         match tuple.val {
705             Ref(llval) => {
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)
712                     } else {
713                         // trans_argument will load this if it needs to
714                         Ref(ptr)
715                     };
716                     let op = OperandRef {
717                         val: val,
718                         ty: ty
719                     };
720                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
721                 }
722
723             }
724             Immediate(llval) => {
725                 let l = bcx.ccx.layout_of(tuple.ty);
726                 let v = if let layout::Univariant { ref variant, .. } = *l {
727                     variant
728                 } else {
729                     bug!("Not a tuple.");
730                 };
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));
736                     }
737                     // If the tuple is immediate, the elements are as well
738                     let op = OperandRef {
739                         val: Immediate(elem),
740                         ty: ty
741                     };
742                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
743                 }
744             }
745             Pair(a, b) => {
746                 let elems = [a, b];
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));
752                     }
753                     // Pair is always made up of immediates
754                     let op = OperandRef {
755                         val: Immediate(elem),
756                         ty: ty
757                     };
758                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
759                 }
760             }
761         }
762
763     }
764
765     fn get_personality_slot(&mut self, bcx: &Builder<'a, 'tcx>) -> ValueRef {
766         let ccx = bcx.ccx;
767         if let Some(slot) = self.llpersonalityslot {
768             slot
769         } else {
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);
774             slot
775         }
776     }
777
778     /// Return the landingpad wrapper around the given basic block
779     ///
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] {
783             return block;
784         }
785
786         if base::wants_msvc_seh(self.ccx.sess()) {
787             return self.blocks[target_bb];
788         }
789
790         let target = self.get_builder(target_bb);
791
792         let bcx = self.new_block("cleanup");
793         self.landing_pads[target_bb] = Some(bcx.llbb());
794
795         let ccx = bcx.ccx;
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());
803         bcx.llbb()
804     }
805
806     fn unreachable_block(&mut self) -> BasicBlockRef {
807         self.unreachable_block.unwrap_or_else(|| {
808             let bl = self.new_block("unreachable");
809             bl.unreachable();
810             self.unreachable_block = Some(bl.llbb());
811             bl.llbb()
812         })
813     }
814
815     pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
816         Builder::new_block(self.ccx, self.llfn, name)
817     }
818
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]);
822         builder
823     }
824
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;
831         }
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");
843                         llargs.push(tmp);
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
848                         // result
849                         let tmp = bcx.alloca_ty(ret_ty, "tmp_ret");
850                         ReturnDest::IndirectOperand(tmp, index)
851                     } else {
852                         ReturnDest::DirectOperand(index)
853                     };
854                 }
855                 LocalRef::Operand(Some(_)) => {
856                     bug!("lvalue local already assigned to");
857                 }
858             }
859         } else {
860             self.trans_lvalue(bcx, dest)
861         };
862         if fn_ret_ty.is_indirect() {
863             llargs.push(dest.llval);
864             ReturnDest::Nothing
865         } else {
866             ReturnDest::Store(dest.llval)
867         }
868     }
869
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),
881                     _ => f.ty
882                 };
883                 val = OperandRef {
884                     val: Immediate(f.reify(bcx.ccx)),
885                     ty: ty
886                 };
887             }
888         }
889
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));
896     }
897
898
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>,
902                     dest: ReturnDest,
903                     ret_ty: ArgType,
904                     op: OperandRef<'tcx>) {
905         use self::ReturnDest::*;
906
907         match dest {
908             Nothing => (),
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));
913             }
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)
920                 } else {
921                     op.unpack_if_pair(bcx)
922                 };
923                 self.locals[index] = LocalRef::Operand(Some(op));
924             }
925         }
926     }
927 }
928
929 enum ReturnDest {
930     // Do nothing, the return value is indirect or ignored
931     Nothing,
932     // Store the return value to the pointer
933     Store(ValueRef),
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)
938 }