]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/block.rs
Changed issue number to 36105
[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};
12 use rustc_const_eval::ErrKind;
13 use rustc::middle::lang_items;
14 use rustc::ty;
15 use rustc::mir::repr as mir;
16 use abi::{Abi, FnType, ArgType};
17 use adt;
18 use base;
19 use build;
20 use callee::{Callee, CalleeData, Fn, Intrinsic, NamedTupleConstructor, Virtual};
21 use common::{self, Block, BlockAndBuilder, LandingPad};
22 use common::{C_bool, C_str_slice, C_struct, C_u32, C_undef};
23 use consts;
24 use debuginfo::DebugLoc;
25 use Disr;
26 use machine::{llalign_of_min, llbitsize_of_real};
27 use meth;
28 use type_of;
29 use glue;
30 use type_::Type;
31
32 use rustc_data_structures::fnv::FnvHashMap;
33 use syntax::parse::token;
34
35 use super::{MirContext, LocalRef};
36 use super::analyze::CleanupKind;
37 use super::constant::Const;
38 use super::lvalue::{LvalueRef, load_fat_ptr};
39 use super::operand::OperandRef;
40 use super::operand::OperandValue::*;
41
42 impl<'bcx, 'tcx> MirContext<'bcx, 'tcx> {
43     pub fn trans_block(&mut self, bb: mir::BasicBlock) {
44         let mut bcx = self.bcx(bb);
45         let mir = self.mir.clone();
46         let data = &mir[bb];
47
48         debug!("trans_block({:?}={:?})", bb, data);
49
50         // Create the cleanup bundle, if needed.
51         let cleanup_pad = bcx.lpad().and_then(|lp| lp.cleanuppad());
52         let cleanup_bundle = bcx.lpad().and_then(|l| l.bundle());
53
54         let funclet_br = |this: &Self, bcx: BlockAndBuilder, bb: mir::BasicBlock| {
55             let lltarget = this.blocks[bb].llbb;
56             if let Some(cp) = cleanup_pad {
57                 match this.cleanup_kinds[bb] {
58                     CleanupKind::Funclet => {
59                         // micro-optimization: generate a `ret` rather than a jump
60                         // to a return block
61                         bcx.cleanup_ret(cp, Some(lltarget));
62                     }
63                     CleanupKind::Internal { .. } => bcx.br(lltarget),
64                     CleanupKind::NotCleanup => bug!("jump from cleanup bb to bb {:?}", bb)
65                 }
66             } else {
67                 bcx.br(lltarget);
68             }
69         };
70
71         let llblock = |this: &mut Self, target: mir::BasicBlock| {
72             let lltarget = this.blocks[target].llbb;
73
74             if let Some(cp) = cleanup_pad {
75                 match this.cleanup_kinds[target] {
76                     CleanupKind::Funclet => {
77                         // MSVC cross-funclet jump - need a trampoline
78
79                         debug!("llblock: creating cleanup trampoline for {:?}", target);
80                         let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
81                         let trampoline = this.fcx.new_block(name, None).build();
82                         trampoline.set_personality_fn(this.fcx.eh_personality());
83                         trampoline.cleanup_ret(cp, Some(lltarget));
84                         trampoline.llbb()
85                     }
86                     CleanupKind::Internal { .. } => lltarget,
87                     CleanupKind::NotCleanup =>
88                         bug!("jump from cleanup bb {:?} to bb {:?}", bb, target)
89                 }
90             } else {
91                 if let (CleanupKind::NotCleanup, CleanupKind::Funclet) =
92                     (this.cleanup_kinds[bb], this.cleanup_kinds[target])
93                 {
94                     // jump *into* cleanup - need a landing pad if GNU
95                     this.landing_pad_to(target).llbb
96                 } else {
97                     lltarget
98                 }
99             }
100         };
101
102         for statement in &data.statements {
103             bcx = self.trans_statement(bcx, statement);
104         }
105
106         let terminator = data.terminator();
107         debug!("trans_block: terminator: {:?}", terminator);
108
109         let span = terminator.source_info.span;
110         let debug_loc = self.debug_loc(terminator.source_info);
111         debug_loc.apply_to_bcx(&bcx);
112         debug_loc.apply(bcx.fcx());
113         match terminator.kind {
114             mir::TerminatorKind::Resume => {
115                 if let Some(cleanup_pad) = cleanup_pad {
116                     bcx.cleanup_ret(cleanup_pad, None);
117                 } else {
118                     let ps = self.get_personality_slot(&bcx);
119                     let lp = bcx.load(ps);
120                     bcx.with_block(|bcx| {
121                         base::call_lifetime_end(bcx, ps);
122                         base::trans_unwind_resume(bcx, lp);
123                     });
124                 }
125             }
126
127             mir::TerminatorKind::Goto { target } => {
128                 funclet_br(self, bcx, target);
129             }
130
131             mir::TerminatorKind::If { ref cond, targets: (true_bb, false_bb) } => {
132                 let cond = self.trans_operand(&bcx, cond);
133
134                 let lltrue = llblock(self, true_bb);
135                 let llfalse = llblock(self, false_bb);
136                 bcx.cond_br(cond.immediate(), lltrue, llfalse);
137             }
138
139             mir::TerminatorKind::Switch { ref discr, ref adt_def, ref targets } => {
140                 let discr_lvalue = self.trans_lvalue(&bcx, discr);
141                 let ty = discr_lvalue.ty.to_ty(bcx.tcx());
142                 let repr = adt::represent_type(bcx.ccx(), ty);
143                 let discr = bcx.with_block(|bcx|
144                     adt::trans_get_discr(bcx, &repr, discr_lvalue.llval, None, true)
145                 );
146
147                 let mut bb_hist = FnvHashMap();
148                 for target in targets {
149                     *bb_hist.entry(target).or_insert(0) += 1;
150                 }
151                 let (default_bb, default_blk) = match bb_hist.iter().max_by_key(|&(_, c)| c) {
152                     // If a single target basic blocks is predominant, promote that to be the
153                     // default case for the switch instruction to reduce the size of the generated
154                     // code. This is especially helpful in cases like an if-let on a huge enum.
155                     // Note: This optimization is only valid for exhaustive matches.
156                     Some((&&bb, &c)) if c > targets.len() / 2 => {
157                         (Some(bb), llblock(self, bb))
158                     }
159                     // We're generating an exhaustive switch, so the else branch
160                     // can't be hit.  Branching to an unreachable instruction
161                     // lets LLVM know this
162                     _ => (None, self.unreachable_block().llbb)
163                 };
164                 let switch = bcx.switch(discr, default_blk, targets.len());
165                 assert_eq!(adt_def.variants.len(), targets.len());
166                 for (adt_variant, &target) in adt_def.variants.iter().zip(targets) {
167                     if default_bb != Some(target) {
168                         let llbb = llblock(self, target);
169                         let llval = bcx.with_block(|bcx| adt::trans_case(
170                                 bcx, &repr, Disr::from(adt_variant.disr_val)));
171                         build::AddCase(switch, llval, llbb)
172                     }
173                 }
174             }
175
176             mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
177                 let (otherwise, targets) = targets.split_last().unwrap();
178                 let discr = bcx.load(self.trans_lvalue(&bcx, discr).llval);
179                 let discr = bcx.with_block(|bcx| base::to_immediate(bcx, discr, switch_ty));
180                 let switch = bcx.switch(discr, llblock(self, *otherwise), values.len());
181                 for (value, target) in values.iter().zip(targets) {
182                     let val = Const::from_constval(bcx.ccx(), value.clone(), switch_ty);
183                     let llbb = llblock(self, *target);
184                     build::AddCase(switch, val.llval, llbb)
185                 }
186             }
187
188             mir::TerminatorKind::Return => {
189                 let ret = bcx.fcx().fn_ty.ret;
190                 if ret.is_ignore() || ret.is_indirect() {
191                     bcx.ret_void();
192                     return;
193                 }
194
195                 let llval = if let Some(cast_ty) = ret.cast {
196                     let index = mir.local_index(&mir::Lvalue::ReturnPointer).unwrap();
197                     let op = match self.locals[index] {
198                         LocalRef::Operand(Some(op)) => op,
199                         LocalRef::Operand(None) => bug!("use of return before def"),
200                         LocalRef::Lvalue(tr_lvalue) => {
201                             OperandRef {
202                                 val: Ref(tr_lvalue.llval),
203                                 ty: tr_lvalue.ty.to_ty(bcx.tcx())
204                             }
205                         }
206                     };
207                     let llslot = match op.val {
208                         Immediate(_) | Pair(..) => {
209                             let llscratch = build::AllocaFcx(bcx.fcx(), ret.original_ty, "ret");
210                             self.store_operand(&bcx, llscratch, op);
211                             llscratch
212                         }
213                         Ref(llval) => llval
214                     };
215                     let load = bcx.load(bcx.pointercast(llslot, cast_ty.ptr_to()));
216                     let llalign = llalign_of_min(bcx.ccx(), ret.ty);
217                     unsafe {
218                         llvm::LLVMSetAlignment(load, llalign);
219                     }
220                     load
221                 } else {
222                     let op = self.trans_consume(&bcx, &mir::Lvalue::ReturnPointer);
223                     op.pack_if_pair(&bcx).immediate()
224                 };
225                 bcx.ret(llval);
226             }
227
228             mir::TerminatorKind::Unreachable => {
229                 bcx.unreachable();
230             }
231
232             mir::TerminatorKind::Drop { ref location, target, unwind } => {
233                 let ty = location.ty(&mir, bcx.tcx()).to_ty(bcx.tcx());
234                 let ty = bcx.monomorphize(&ty);
235
236                 // Double check for necessity to drop
237                 if !glue::type_needs_drop(bcx.tcx(), ty) {
238                     funclet_br(self, bcx, target);
239                     return;
240                 }
241
242                 let lvalue = self.trans_lvalue(&bcx, location);
243                 let drop_fn = glue::get_drop_glue(bcx.ccx(), ty);
244                 let drop_ty = glue::get_drop_glue_type(bcx.tcx(), ty);
245                 let llvalue = if drop_ty != ty {
246                     bcx.pointercast(lvalue.llval, type_of::type_of(bcx.ccx(), drop_ty).ptr_to())
247                 } else {
248                     lvalue.llval
249                 };
250                 if let Some(unwind) = unwind {
251                     bcx.invoke(drop_fn,
252                                &[llvalue],
253                                self.blocks[target].llbb,
254                                llblock(self, unwind),
255                                cleanup_bundle);
256                 } else {
257                     bcx.call(drop_fn, &[llvalue], cleanup_bundle);
258                     funclet_br(self, bcx, target);
259                 }
260             }
261
262             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
263                 let cond = self.trans_operand(&bcx, cond).immediate();
264                 let mut const_cond = common::const_to_opt_uint(cond).map(|c| c == 1);
265
266                 // This case can currently arise only from functions marked
267                 // with #[rustc_inherit_overflow_checks] and inlined from
268                 // another crate (mostly core::num generic/#[inline] fns),
269                 // while the current crate doesn't use overflow checks.
270                 // NOTE: Unlike binops, negation doesn't have its own
271                 // checked operation, just a comparison with the minimum
272                 // value, so we have to check for the assert message.
273                 if !bcx.ccx().check_overflow() {
274                     use rustc_const_math::ConstMathErr::Overflow;
275                     use rustc_const_math::Op::Neg;
276
277                     if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
278                         const_cond = Some(expected);
279                     }
280                 }
281
282                 // Don't translate the panic block if success if known.
283                 if const_cond == Some(expected) {
284                     funclet_br(self, bcx, target);
285                     return;
286                 }
287
288                 // Pass the condition through llvm.expect for branch hinting.
289                 let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
290                 let cond = bcx.call(expect, &[cond, C_bool(bcx.ccx(), expected)], None);
291
292                 // Create the failure block and the conditional branch to it.
293                 let lltarget = llblock(self, target);
294                 let panic_block = self.fcx.new_block("panic", None);
295                 if expected {
296                     bcx.cond_br(cond, lltarget, panic_block.llbb);
297                 } else {
298                     bcx.cond_br(cond, panic_block.llbb, lltarget);
299                 }
300
301                 // After this point, bcx is the block for the call to panic.
302                 bcx = panic_block.build();
303                 debug_loc.apply_to_bcx(&bcx);
304
305                 // Get the location information.
306                 let loc = bcx.sess().codemap().lookup_char_pos(span.lo);
307                 let filename = token::intern_and_get_ident(&loc.file.name);
308                 let filename = C_str_slice(bcx.ccx(), filename);
309                 let line = C_u32(bcx.ccx(), loc.line as u32);
310
311                 // Put together the arguments to the panic entry point.
312                 let (lang_item, args, const_err) = match *msg {
313                     mir::AssertMessage::BoundsCheck { ref len, ref index } => {
314                         let len = self.trans_operand(&mut bcx, len).immediate();
315                         let index = self.trans_operand(&mut bcx, index).immediate();
316
317                         let const_err = common::const_to_opt_uint(len).and_then(|len| {
318                             common::const_to_opt_uint(index).map(|index| {
319                                 ErrKind::IndexOutOfBounds {
320                                     len: len,
321                                     index: index
322                                 }
323                             })
324                         });
325
326                         let file_line = C_struct(bcx.ccx(), &[filename, line], false);
327                         let align = llalign_of_min(bcx.ccx(), common::val_ty(file_line));
328                         let file_line = consts::addr_of(bcx.ccx(),
329                                                         file_line,
330                                                         align,
331                                                         "panic_bounds_check_loc");
332                         (lang_items::PanicBoundsCheckFnLangItem,
333                          vec![file_line, index, len],
334                          const_err)
335                     }
336                     mir::AssertMessage::Math(ref err) => {
337                         let msg_str = token::intern_and_get_ident(err.description());
338                         let msg_str = C_str_slice(bcx.ccx(), msg_str);
339                         let msg_file_line = C_struct(bcx.ccx(),
340                                                      &[msg_str, filename, line],
341                                                      false);
342                         let align = llalign_of_min(bcx.ccx(), common::val_ty(msg_file_line));
343                         let msg_file_line = consts::addr_of(bcx.ccx(),
344                                                             msg_file_line,
345                                                             align,
346                                                             "panic_loc");
347                         (lang_items::PanicFnLangItem,
348                          vec![msg_file_line],
349                          Some(ErrKind::Math(err.clone())))
350                     }
351                 };
352
353                 // If we know we always panic, and the error message
354                 // is also constant, then we can produce a warning.
355                 if const_cond == Some(!expected) {
356                     if let Some(err) = const_err {
357                         let _ = consts::const_err(bcx.ccx(), span,
358                                                   Err::<(), _>(err),
359                                                   consts::TrueConst::No);
360                     }
361                 }
362
363                 // Obtain the panic entry point.
364                 let def_id = common::langcall(bcx.tcx(), Some(span), "", lang_item);
365                 let callee = Callee::def(bcx.ccx(), def_id,
366                     bcx.ccx().empty_substs_for_def_id(def_id));
367                 let llfn = callee.reify(bcx.ccx()).val;
368
369                 // Translate the actual panic invoke/call.
370                 if let Some(unwind) = cleanup {
371                     bcx.invoke(llfn,
372                                &args,
373                                self.unreachable_block().llbb,
374                                llblock(self, unwind),
375                                cleanup_bundle);
376                 } else {
377                     bcx.call(llfn, &args, cleanup_bundle);
378                     bcx.unreachable();
379                 }
380             }
381
382             mir::TerminatorKind::DropAndReplace { .. } => {
383                 bug!("undesugared DropAndReplace in trans: {:?}", data);
384             }
385
386             mir::TerminatorKind::Call { ref func, ref args, ref destination, ref cleanup } => {
387                 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
388                 let callee = self.trans_operand(&bcx, func);
389
390                 let (mut callee, abi, sig) = match callee.ty.sty {
391                     ty::TyFnDef(def_id, substs, f) => {
392                         (Callee::def(bcx.ccx(), def_id, substs), f.abi, &f.sig)
393                     }
394                     ty::TyFnPtr(f) => {
395                         (Callee {
396                             data: Fn(callee.immediate()),
397                             ty: callee.ty
398                         }, f.abi, &f.sig)
399                     }
400                     _ => bug!("{} is not callable", callee.ty)
401                 };
402
403                 let sig = bcx.tcx().erase_late_bound_regions(sig);
404
405                 // Handle intrinsics old trans wants Expr's for, ourselves.
406                 let intrinsic = match (&callee.ty.sty, &callee.data) {
407                     (&ty::TyFnDef(def_id, _, _), &Intrinsic) => {
408                         Some(bcx.tcx().item_name(def_id).as_str())
409                     }
410                     _ => None
411                 };
412                 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
413
414                 if intrinsic == Some("move_val_init") {
415                     let &(_, target) = destination.as_ref().unwrap();
416                     // The first argument is a thin destination pointer.
417                     let llptr = self.trans_operand(&bcx, &args[0]).immediate();
418                     let val = self.trans_operand(&bcx, &args[1]);
419                     self.store_operand(&bcx, llptr, val);
420                     funclet_br(self, bcx, target);
421                     return;
422                 }
423
424                 if intrinsic == Some("transmute") {
425                     let &(ref dest, target) = destination.as_ref().unwrap();
426                     self.with_lvalue_ref(&bcx, dest, |this, dest| {
427                         this.trans_transmute(&bcx, &args[0], dest);
428                     });
429
430                     funclet_br(self, bcx, target);
431                     return;
432                 }
433
434                 let extra_args = &args[sig.inputs.len()..];
435                 let extra_args = extra_args.iter().map(|op_arg| {
436                     let op_ty = op_arg.ty(&self.mir, bcx.tcx());
437                     bcx.monomorphize(&op_ty)
438                 }).collect::<Vec<_>>();
439                 let fn_ty = callee.direct_fn_type(bcx.ccx(), &extra_args);
440
441                 // The arguments we'll be passing. Plus one to account for outptr, if used.
442                 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
443                 let mut llargs = Vec::with_capacity(arg_count);
444
445                 // Prepare the return value destination
446                 let ret_dest = if let Some((ref dest, _)) = *destination {
447                     let is_intrinsic = if let Intrinsic = callee.data {
448                         true
449                     } else {
450                         false
451                     };
452                     self.make_return_dest(&bcx, dest, &fn_ty.ret, &mut llargs, is_intrinsic)
453                 } else {
454                     ReturnDest::Nothing
455                 };
456
457                 // Split the rust-call tupled arguments off.
458                 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
459                     let (tup, args) = args.split_last().unwrap();
460                     (args, Some(tup))
461                 } else {
462                     (&args[..], None)
463                 };
464
465                 let is_shuffle = intrinsic.map_or(false, |name| {
466                     name.starts_with("simd_shuffle")
467                 });
468                 let mut idx = 0;
469                 for arg in first_args {
470                     // The indices passed to simd_shuffle* in the
471                     // third argument must be constant. This is
472                     // checked by const-qualification, which also
473                     // promotes any complex rvalues to constants.
474                     if is_shuffle && idx == 2 {
475                         match *arg {
476                             mir::Operand::Consume(_) => {
477                                 span_bug!(span, "shuffle indices must be constant");
478                             }
479                             mir::Operand::Constant(ref constant) => {
480                                 let val = self.trans_constant(&bcx, constant);
481                                 llargs.push(val.llval);
482                                 idx += 1;
483                                 continue;
484                             }
485                         }
486                     }
487
488                     let op = self.trans_operand(&bcx, arg);
489                     self.trans_argument(&bcx, op, &mut llargs, &fn_ty,
490                                         &mut idx, &mut callee.data);
491                 }
492                 if let Some(tup) = untuple {
493                     self.trans_arguments_untupled(&bcx, tup, &mut llargs, &fn_ty,
494                                                   &mut idx, &mut callee.data)
495                 }
496
497                 let fn_ptr = match callee.data {
498                     NamedTupleConstructor(_) => {
499                         // FIXME translate this like mir::Rvalue::Aggregate.
500                         callee.reify(bcx.ccx()).val
501                     }
502                     Intrinsic => {
503                         use callee::ArgVals;
504                         use expr::{Ignore, SaveIn};
505                         use intrinsic::trans_intrinsic_call;
506
507                         let (dest, llargs) = match ret_dest {
508                             _ if fn_ty.ret.is_indirect() => {
509                                 (SaveIn(llargs[0]), &llargs[1..])
510                             }
511                             ReturnDest::Nothing => (Ignore, &llargs[..]),
512                             ReturnDest::IndirectOperand(dst, _) |
513                             ReturnDest::Store(dst) => (SaveIn(dst), &llargs[..]),
514                             ReturnDest::DirectOperand(_) =>
515                                 bug!("Cannot use direct operand with an intrinsic call")
516                         };
517
518                         bcx.with_block(|bcx| {
519                             trans_intrinsic_call(bcx, callee.ty, &fn_ty,
520                                                            ArgVals(llargs), dest,
521                                                            debug_loc);
522                         });
523
524                         if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
525                             // Make a fake operand for store_return
526                             let op = OperandRef {
527                                 val: Ref(dst),
528                                 ty: sig.output,
529                             };
530                             self.store_return(&bcx, ret_dest, fn_ty.ret, op);
531                         }
532
533                         if let Some((_, target)) = *destination {
534                             funclet_br(self, bcx, target);
535                         } else {
536                             // trans_intrinsic_call already used Unreachable.
537                             // bcx.unreachable();
538                         }
539
540                         return;
541                     }
542                     Fn(f) => f,
543                     Virtual(_) => bug!("Virtual fn ptr not extracted")
544                 };
545
546                 // Many different ways to call a function handled here
547                 if let &Some(cleanup) = cleanup {
548                     let ret_bcx = if let Some((_, target)) = *destination {
549                         self.blocks[target]
550                     } else {
551                         self.unreachable_block()
552                     };
553                     let invokeret = bcx.invoke(fn_ptr,
554                                                &llargs,
555                                                ret_bcx.llbb,
556                                                llblock(self, cleanup),
557                                                cleanup_bundle);
558                     fn_ty.apply_attrs_callsite(invokeret);
559
560                     if destination.is_some() {
561                         let ret_bcx = ret_bcx.build();
562                         ret_bcx.at_start(|ret_bcx| {
563                             debug_loc.apply_to_bcx(ret_bcx);
564                             let op = OperandRef {
565                                 val: Immediate(invokeret),
566                                 ty: sig.output,
567                             };
568                             self.store_return(&ret_bcx, ret_dest, fn_ty.ret, op);
569                         });
570                     }
571                 } else {
572                     let llret = bcx.call(fn_ptr, &llargs, cleanup_bundle);
573                     fn_ty.apply_attrs_callsite(llret);
574                     if let Some((_, target)) = *destination {
575                         let op = OperandRef {
576                             val: Immediate(llret),
577                             ty: sig.output,
578                         };
579                         self.store_return(&bcx, ret_dest, fn_ty.ret, op);
580                         funclet_br(self, bcx, target);
581                     } else {
582                         bcx.unreachable();
583                     }
584                 }
585             }
586         }
587     }
588
589     fn trans_argument(&mut self,
590                       bcx: &BlockAndBuilder<'bcx, 'tcx>,
591                       op: OperandRef<'tcx>,
592                       llargs: &mut Vec<ValueRef>,
593                       fn_ty: &FnType,
594                       next_idx: &mut usize,
595                       callee: &mut CalleeData) {
596         if let Pair(a, b) = op.val {
597             // Treat the values in a fat pointer separately.
598             if common::type_is_fat_ptr(bcx.tcx(), op.ty) {
599                 let (ptr, meta) = (a, b);
600                 if *next_idx == 0 {
601                     if let Virtual(idx) = *callee {
602                         let llfn = bcx.with_block(|bcx| {
603                             meth::get_virtual_method(bcx, meta, idx)
604                         });
605                         let llty = fn_ty.llvm_type(bcx.ccx()).ptr_to();
606                         *callee = Fn(bcx.pointercast(llfn, llty));
607                     }
608                 }
609
610                 let imm_op = |x| OperandRef {
611                     val: Immediate(x),
612                     // We won't be checking the type again.
613                     ty: bcx.tcx().types.err
614                 };
615                 self.trans_argument(bcx, imm_op(ptr), llargs, fn_ty, next_idx, callee);
616                 self.trans_argument(bcx, imm_op(meta), llargs, fn_ty, next_idx, callee);
617                 return;
618             }
619         }
620
621         let arg = &fn_ty.args[*next_idx];
622         *next_idx += 1;
623
624         // Fill padding with undef value, where applicable.
625         if let Some(ty) = arg.pad {
626             llargs.push(C_undef(ty));
627         }
628
629         if arg.is_ignore() {
630             return;
631         }
632
633         // Force by-ref if we have to load through a cast pointer.
634         let (mut llval, by_ref) = match op.val {
635             Immediate(_) | Pair(..) => {
636                 if arg.is_indirect() || arg.cast.is_some() {
637                     let llscratch = build::AllocaFcx(bcx.fcx(), arg.original_ty, "arg");
638                     self.store_operand(bcx, llscratch, op);
639                     (llscratch, true)
640                 } else {
641                     (op.pack_if_pair(bcx).immediate(), false)
642                 }
643             }
644             Ref(llval) => (llval, true)
645         };
646
647         if by_ref && !arg.is_indirect() {
648             // Have to load the argument, maybe while casting it.
649             if arg.original_ty == Type::i1(bcx.ccx()) {
650                 // We store bools as i8 so we need to truncate to i1.
651                 llval = bcx.load_range_assert(llval, 0, 2, llvm::False);
652                 llval = bcx.trunc(llval, arg.original_ty);
653             } else if let Some(ty) = arg.cast {
654                 llval = bcx.load(bcx.pointercast(llval, ty.ptr_to()));
655                 let llalign = llalign_of_min(bcx.ccx(), arg.ty);
656                 unsafe {
657                     llvm::LLVMSetAlignment(llval, llalign);
658                 }
659             } else {
660                 llval = bcx.load(llval);
661             }
662         }
663
664         llargs.push(llval);
665     }
666
667     fn trans_arguments_untupled(&mut self,
668                                 bcx: &BlockAndBuilder<'bcx, 'tcx>,
669                                 operand: &mir::Operand<'tcx>,
670                                 llargs: &mut Vec<ValueRef>,
671                                 fn_ty: &FnType,
672                                 next_idx: &mut usize,
673                                 callee: &mut CalleeData) {
674         let tuple = self.trans_operand(bcx, operand);
675
676         let arg_types = match tuple.ty.sty {
677             ty::TyTuple(ref tys) => tys,
678             _ => span_bug!(self.mir.span,
679                            "bad final argument to \"rust-call\" fn {:?}", tuple.ty)
680         };
681
682         // Handle both by-ref and immediate tuples.
683         match tuple.val {
684             Ref(llval) => {
685                 let base_repr = adt::represent_type(bcx.ccx(), tuple.ty);
686                 let base = adt::MaybeSizedValue::sized(llval);
687                 for (n, &ty) in arg_types.iter().enumerate() {
688                     let ptr = adt::trans_field_ptr_builder(bcx, &base_repr, base, Disr(0), n);
689                     let val = if common::type_is_fat_ptr(bcx.tcx(), ty) {
690                         let (lldata, llextra) = load_fat_ptr(bcx, ptr);
691                         Pair(lldata, llextra)
692                     } else {
693                         // trans_argument will load this if it needs to
694                         Ref(ptr)
695                     };
696                     let op = OperandRef {
697                         val: val,
698                         ty: ty
699                     };
700                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
701                 }
702
703             }
704             Immediate(llval) => {
705                 for (n, &ty) in arg_types.iter().enumerate() {
706                     let mut elem = bcx.extract_value(llval, n);
707                     // Truncate bools to i1, if needed
708                     if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx()) {
709                         elem = bcx.trunc(elem, Type::i1(bcx.ccx()));
710                     }
711                     // If the tuple is immediate, the elements are as well
712                     let op = OperandRef {
713                         val: Immediate(elem),
714                         ty: ty
715                     };
716                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
717                 }
718             }
719             Pair(a, b) => {
720                 let elems = [a, b];
721                 for (n, &ty) in arg_types.iter().enumerate() {
722                     let mut elem = elems[n];
723                     // Truncate bools to i1, if needed
724                     if ty.is_bool() && common::val_ty(elem) != Type::i1(bcx.ccx()) {
725                         elem = bcx.trunc(elem, Type::i1(bcx.ccx()));
726                     }
727                     // Pair is always made up of immediates
728                     let op = OperandRef {
729                         val: Immediate(elem),
730                         ty: ty
731                     };
732                     self.trans_argument(bcx, op, llargs, fn_ty, next_idx, callee);
733                 }
734             }
735         }
736
737     }
738
739     fn get_personality_slot(&mut self, bcx: &BlockAndBuilder<'bcx, 'tcx>) -> ValueRef {
740         let ccx = bcx.ccx();
741         if let Some(slot) = self.llpersonalityslot {
742             slot
743         } else {
744             let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
745             bcx.with_block(|bcx| {
746                 let slot = base::alloca(bcx, llretty, "personalityslot");
747                 self.llpersonalityslot = Some(slot);
748                 base::call_lifetime_start(bcx, slot);
749                 slot
750             })
751         }
752     }
753
754     /// Return the landingpad wrapper around the given basic block
755     ///
756     /// No-op in MSVC SEH scheme.
757     fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> Block<'bcx, 'tcx>
758     {
759         if let Some(block) = self.landing_pads[target_bb] {
760             return block;
761         }
762
763         if base::wants_msvc_seh(self.fcx.ccx.sess()) {
764             return self.blocks[target_bb];
765         }
766
767         let target = self.bcx(target_bb);
768
769         let block = self.fcx.new_block("cleanup", None);
770         self.landing_pads[target_bb] = Some(block);
771
772         let bcx = block.build();
773         let ccx = bcx.ccx();
774         let llpersonality = self.fcx.eh_personality();
775         let llretty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)], false);
776         let llretval = bcx.landing_pad(llretty, llpersonality, 1, self.fcx.llfn);
777         bcx.set_cleanup(llretval);
778         let slot = self.get_personality_slot(&bcx);
779         bcx.store(llretval, slot);
780         bcx.br(target.llbb());
781         block
782     }
783
784     pub fn init_cpad(&mut self, bb: mir::BasicBlock) {
785         let bcx = self.bcx(bb);
786         let data = &self.mir[bb];
787         debug!("init_cpad({:?})", data);
788
789         match self.cleanup_kinds[bb] {
790             CleanupKind::NotCleanup => {
791                 bcx.set_lpad(None)
792             }
793             _ if !base::wants_msvc_seh(bcx.sess()) => {
794                 bcx.set_lpad(Some(LandingPad::gnu()))
795             }
796             CleanupKind::Internal { funclet } => {
797                 // FIXME: is this needed?
798                 bcx.set_personality_fn(self.fcx.eh_personality());
799                 bcx.set_lpad_ref(self.bcx(funclet).lpad());
800             }
801             CleanupKind::Funclet => {
802                 bcx.set_personality_fn(self.fcx.eh_personality());
803                 DebugLoc::None.apply_to_bcx(&bcx);
804                 let cleanup_pad = bcx.cleanup_pad(None, &[]);
805                 bcx.set_lpad(Some(LandingPad::msvc(cleanup_pad)));
806             }
807         };
808     }
809
810     fn unreachable_block(&mut self) -> Block<'bcx, 'tcx> {
811         self.unreachable_block.unwrap_or_else(|| {
812             let bl = self.fcx.new_block("unreachable", None);
813             bl.build().unreachable();
814             self.unreachable_block = Some(bl);
815             bl
816         })
817     }
818
819     fn bcx(&self, bb: mir::BasicBlock) -> BlockAndBuilder<'bcx, 'tcx> {
820         self.blocks[bb].build()
821     }
822
823     fn make_return_dest(&mut self, bcx: &BlockAndBuilder<'bcx, 'tcx>,
824                         dest: &mir::Lvalue<'tcx>, fn_ret_ty: &ArgType,
825                         llargs: &mut Vec<ValueRef>, is_intrinsic: bool) -> ReturnDest {
826         // If the return is ignored, we can just return a do-nothing ReturnDest
827         if fn_ret_ty.is_ignore() {
828             return ReturnDest::Nothing;
829         }
830         let dest = if let Some(index) = self.mir.local_index(dest) {
831             let ret_ty = self.monomorphized_lvalue_ty(dest);
832             match self.locals[index] {
833                 LocalRef::Lvalue(dest) => dest,
834                 LocalRef::Operand(None) => {
835                     // Handle temporary lvalues, specifically Operand ones, as
836                     // they don't have allocas
837                     return if fn_ret_ty.is_indirect() {
838                         // Odd, but possible, case, we have an operand temporary,
839                         // but the calling convention has an indirect return.
840                         let tmp = bcx.with_block(|bcx| {
841                             base::alloc_ty(bcx, ret_ty, "tmp_ret")
842                         });
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.with_block(|bcx| {
850                             base::alloc_ty(bcx, ret_ty, "tmp_ret")
851                         });
852                         ReturnDest::IndirectOperand(tmp, index)
853                     } else {
854                         ReturnDest::DirectOperand(index)
855                     };
856                 }
857                 LocalRef::Operand(Some(_)) => {
858                     bug!("lvalue local already assigned to");
859                 }
860             }
861         } else {
862             self.trans_lvalue(bcx, dest)
863         };
864         if fn_ret_ty.is_indirect() {
865             llargs.push(dest.llval);
866             ReturnDest::Nothing
867         } else {
868             ReturnDest::Store(dest.llval)
869         }
870     }
871
872     fn trans_transmute(&mut self, bcx: &BlockAndBuilder<'bcx, 'tcx>,
873                        src: &mir::Operand<'tcx>, dst: LvalueRef<'tcx>) {
874         let mut val = self.trans_operand(bcx, src);
875         if let ty::TyFnDef(def_id, substs, _) = val.ty.sty {
876             let llouttype = type_of::type_of(bcx.ccx(), dst.ty.to_ty(bcx.tcx()));
877             let out_type_size = llbitsize_of_real(bcx.ccx(), llouttype);
878             if out_type_size != 0 {
879                 // FIXME #19925 Remove this hack after a release cycle.
880                 let f = Callee::def(bcx.ccx(), def_id, substs);
881                 let datum = f.reify(bcx.ccx());
882                 val = OperandRef {
883                     val: Immediate(datum.val),
884                     ty: datum.ty
885                 };
886             }
887         }
888
889         let llty = type_of::type_of(bcx.ccx(), val.ty);
890         let cast_ptr = bcx.pointercast(dst.llval, llty.ptr_to());
891         self.store_operand(bcx, cast_ptr, val);
892     }
893
894
895     // Stores the return value of a function call into it's final location.
896     fn store_return(&mut self,
897                     bcx: &BlockAndBuilder<'bcx, 'tcx>,
898                     dest: ReturnDest,
899                     ret_ty: ArgType,
900                     op: OperandRef<'tcx>) {
901         use self::ReturnDest::*;
902
903         match dest {
904             Nothing => (),
905             Store(dst) => ret_ty.store(bcx, op.immediate(), dst),
906             IndirectOperand(tmp, index) => {
907                 let op = self.trans_load(bcx, tmp, op.ty);
908                 self.locals[index] = LocalRef::Operand(Some(op));
909             }
910             DirectOperand(index) => {
911                 // If there is a cast, we have to store and reload.
912                 let op = if ret_ty.cast.is_some() {
913                     let tmp = bcx.with_block(|bcx| {
914                         base::alloc_ty(bcx, op.ty, "tmp_ret")
915                     });
916                     ret_ty.store(bcx, op.immediate(), tmp);
917                     self.trans_load(bcx, tmp, op.ty)
918                 } else {
919                     op.unpack_if_pair(bcx)
920                 };
921                 self.locals[index] = LocalRef::Operand(Some(op));
922             }
923         }
924     }
925 }
926
927 enum ReturnDest {
928     // Do nothing, the return value is indirect or ignored
929     Nothing,
930     // Store the return value to the pointer
931     Store(ValueRef),
932     // Stores an indirect return value to an operand local lvalue
933     IndirectOperand(ValueRef, mir::Local),
934     // Stores a direct return value to an operand local lvalue
935     DirectOperand(mir::Local)
936 }