]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/block.rs
Auto merge of #49891 - cuviper:compiletest-crash, r=alexcrichton
[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::middle::lang_items;
13 use rustc::ty::{self, Ty, TypeFoldable};
14 use rustc::ty::layout::{self, LayoutOf};
15 use rustc::mir;
16 use abi::{Abi, ArgType, ArgTypeExt, FnType, FnTypeExt, LlvmType, PassMode};
17 use base;
18 use callee;
19 use builder::Builder;
20 use common::{self, C_bool, C_str_slice, C_struct, C_u32, C_uint_big, C_undef};
21 use consts;
22 use meth;
23 use monomorphize;
24 use type_of::LayoutLlvmExt;
25 use type_::Type;
26
27 use syntax::symbol::Symbol;
28 use syntax_pos::Pos;
29
30 use super::{FunctionCx, LocalRef};
31 use super::place::PlaceRef;
32 use super::operand::OperandRef;
33 use super::operand::OperandValue::{Pair, Ref, Immediate};
34
35 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
36     pub fn trans_block(&mut self, bb: mir::BasicBlock) {
37         let mut bx = self.build_block(bb);
38         let data = &self.mir[bb];
39
40         debug!("trans_block({:?}={:?})", bb, data);
41
42         for statement in &data.statements {
43             bx = self.trans_statement(bx, statement);
44         }
45
46         self.trans_terminator(bx, bb, data.terminator());
47     }
48
49     fn trans_terminator(&mut self,
50                         mut bx: Builder<'a, 'tcx>,
51                         bb: mir::BasicBlock,
52                         terminator: &mir::Terminator<'tcx>)
53     {
54         debug!("trans_terminator: {:?}", terminator);
55
56         // Create the cleanup bundle, if needed.
57         let tcx = bx.tcx();
58         let span = terminator.source_info.span;
59         let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
60         let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());
61
62         let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
63         let cleanup_bundle = funclet.map(|l| l.bundle());
64
65         let lltarget = |this: &mut Self, target: mir::BasicBlock| {
66             let lltarget = this.blocks[target];
67             let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
68             match (funclet_bb, target_funclet) {
69                 (None, None) => (lltarget, false),
70                 (Some(f), Some(t_f))
71                     if f == t_f || !base::wants_msvc_seh(tcx.sess)
72                     => (lltarget, false),
73                 (None, Some(_)) => {
74                     // jump *into* cleanup - need a landing pad if GNU
75                     (this.landing_pad_to(target), false)
76                 }
77                 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
78                 (Some(_), Some(_)) => {
79                     (this.landing_pad_to(target), true)
80                 }
81             }
82         };
83
84         let llblock = |this: &mut Self, target: mir::BasicBlock| {
85             let (lltarget, is_cleanupret) = lltarget(this, target);
86             if is_cleanupret {
87                 // MSVC cross-funclet jump - need a trampoline
88
89                 debug!("llblock: creating cleanup trampoline for {:?}", target);
90                 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
91                 let trampoline = this.new_block(name);
92                 trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
93                 trampoline.llbb()
94             } else {
95                 lltarget
96             }
97         };
98
99         let funclet_br = |this: &mut Self, bx: Builder, target: mir::BasicBlock| {
100             let (lltarget, is_cleanupret) = lltarget(this, target);
101             if is_cleanupret {
102                 // micro-optimization: generate a `ret` rather than a jump
103                 // to a trampoline.
104                 bx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
105             } else {
106                 bx.br(lltarget);
107             }
108         };
109
110         let do_call = |
111             this: &mut Self,
112             bx: Builder<'a, 'tcx>,
113             fn_ty: FnType<'tcx, Ty<'tcx>>,
114             fn_ptr: ValueRef,
115             llargs: &[ValueRef],
116             destination: Option<(ReturnDest<'tcx>, mir::BasicBlock)>,
117             cleanup: Option<mir::BasicBlock>
118         | {
119             if let Some(cleanup) = cleanup {
120                 let ret_bx = if let Some((_, target)) = destination {
121                     this.blocks[target]
122                 } else {
123                     this.unreachable_block()
124                 };
125                 let invokeret = bx.invoke(fn_ptr,
126                                            &llargs,
127                                            ret_bx,
128                                            llblock(this, cleanup),
129                                            cleanup_bundle);
130                 fn_ty.apply_attrs_callsite(invokeret);
131
132                 if let Some((ret_dest, target)) = destination {
133                     let ret_bx = this.build_block(target);
134                     this.set_debug_loc(&ret_bx, terminator.source_info);
135                     this.store_return(&ret_bx, ret_dest, &fn_ty.ret, invokeret);
136                 }
137             } else {
138                 let llret = bx.call(fn_ptr, &llargs, cleanup_bundle);
139                 fn_ty.apply_attrs_callsite(llret);
140                 if this.mir[bb].is_cleanup {
141                     // Cleanup is always the cold path. Don't inline
142                     // drop glue. Also, when there is a deeply-nested
143                     // struct, there are "symmetry" issues that cause
144                     // exponential inlining - see issue #41696.
145                     llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
146                 }
147
148                 if let Some((ret_dest, target)) = destination {
149                     this.store_return(&bx, ret_dest, &fn_ty.ret, llret);
150                     funclet_br(this, bx, target);
151                 } else {
152                     bx.unreachable();
153                 }
154             }
155         };
156
157         self.set_debug_loc(&bx, terminator.source_info);
158         match terminator.kind {
159             mir::TerminatorKind::Resume => {
160                 if let Some(cleanup_pad) = cleanup_pad {
161                     bx.cleanup_ret(cleanup_pad, None);
162                 } else {
163                     let slot = self.get_personality_slot(&bx);
164                     let lp0 = slot.project_field(&bx, 0).load(&bx).immediate();
165                     let lp1 = slot.project_field(&bx, 1).load(&bx).immediate();
166                     slot.storage_dead(&bx);
167
168                     if !bx.sess().target.target.options.custom_unwind_resume {
169                         let mut lp = C_undef(self.landing_pad_type());
170                         lp = bx.insert_value(lp, lp0, 0);
171                         lp = bx.insert_value(lp, lp1, 1);
172                         bx.resume(lp);
173                     } else {
174                         bx.call(bx.cx.eh_unwind_resume(), &[lp0], cleanup_bundle);
175                         bx.unreachable();
176                     }
177                 }
178             }
179
180             mir::TerminatorKind::Abort => {
181                 // Call core::intrinsics::abort()
182                 let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
183                 bx.call(fnname, &[], None);
184                 bx.unreachable();
185             }
186
187             mir::TerminatorKind::Goto { target } => {
188                 funclet_br(self, bx, target);
189             }
190
191             mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
192                 let discr = self.trans_operand(&bx, discr);
193                 if switch_ty == bx.tcx().types.bool {
194                     let lltrue = llblock(self, targets[0]);
195                     let llfalse = llblock(self, targets[1]);
196                     if let [0] = values[..] {
197                         bx.cond_br(discr.immediate(), llfalse, lltrue);
198                     } else {
199                         assert_eq!(&values[..], &[1]);
200                         bx.cond_br(discr.immediate(), lltrue, llfalse);
201                     }
202                 } else {
203                     let (otherwise, targets) = targets.split_last().unwrap();
204                     let switch = bx.switch(discr.immediate(),
205                                             llblock(self, *otherwise), values.len());
206                     let switch_llty = bx.cx.layout_of(switch_ty).immediate_llvm_type(bx.cx);
207                     for (&value, target) in values.iter().zip(targets) {
208                         let llval = C_uint_big(switch_llty, value);
209                         let llbb = llblock(self, *target);
210                         bx.add_case(switch, llval, llbb)
211                     }
212                 }
213             }
214
215             mir::TerminatorKind::Return => {
216                 let llval = match self.fn_ty.ret.mode {
217                     PassMode::Ignore | PassMode::Indirect(_) => {
218                         bx.ret_void();
219                         return;
220                     }
221
222                     PassMode::Direct(_) | PassMode::Pair(..) => {
223                         let op = self.trans_consume(&bx, &mir::Place::Local(mir::RETURN_PLACE));
224                         if let Ref(llval, align) = op.val {
225                             bx.load(llval, align)
226                         } else {
227                             op.immediate_or_packed_pair(&bx)
228                         }
229                     }
230
231                     PassMode::Cast(cast_ty) => {
232                         let op = match self.locals[mir::RETURN_PLACE] {
233                             LocalRef::Operand(Some(op)) => op,
234                             LocalRef::Operand(None) => bug!("use of return before def"),
235                             LocalRef::Place(tr_place) => {
236                                 OperandRef {
237                                     val: Ref(tr_place.llval, tr_place.align),
238                                     layout: tr_place.layout
239                                 }
240                             }
241                         };
242                         let llslot = match op.val {
243                             Immediate(_) | Pair(..) => {
244                                 let scratch = PlaceRef::alloca(&bx, self.fn_ty.ret.layout, "ret");
245                                 op.val.store(&bx, scratch);
246                                 scratch.llval
247                             }
248                             Ref(llval, align) => {
249                                 assert_eq!(align.abi(), op.layout.align.abi(),
250                                            "return place is unaligned!");
251                                 llval
252                             }
253                         };
254                         bx.load(
255                             bx.pointercast(llslot, cast_ty.llvm_type(bx.cx).ptr_to()),
256                             self.fn_ty.ret.layout.align)
257                     }
258                 };
259                 bx.ret(llval);
260             }
261
262             mir::TerminatorKind::Unreachable => {
263                 bx.unreachable();
264             }
265
266             mir::TerminatorKind::Drop { ref location, target, unwind } => {
267                 let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
268                 let ty = self.monomorphize(&ty);
269                 let drop_fn = monomorphize::resolve_drop_in_place(bx.cx.tcx, ty);
270
271                 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
272                     // we don't actually need to drop anything.
273                     funclet_br(self, bx, target);
274                     return
275                 }
276
277                 let place = self.trans_place(&bx, location);
278                 let mut args: &[_] = &[place.llval, place.llextra];
279                 args = &args[..1 + place.has_extra() as usize];
280                 let (drop_fn, fn_ty) = match ty.sty {
281                     ty::TyDynamic(..) => {
282                         let fn_ty = drop_fn.ty(bx.cx.tcx);
283                         let sig = common::ty_fn_sig(bx.cx, fn_ty);
284                         let sig = bx.tcx().normalize_erasing_late_bound_regions(
285                             ty::ParamEnv::reveal_all(),
286                             &sig,
287                         );
288                         let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
289                         args = &args[..1];
290                         (meth::DESTRUCTOR.get_fn(&bx, place.llextra, &fn_ty), fn_ty)
291                     }
292                     _ => {
293                         (callee::get_fn(bx.cx, drop_fn),
294                          FnType::of_instance(bx.cx, &drop_fn))
295                     }
296                 };
297                 do_call(self, bx, fn_ty, drop_fn, args,
298                         Some((ReturnDest::Nothing, target)),
299                         unwind);
300             }
301
302             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
303                 let cond = self.trans_operand(&bx, cond).immediate();
304                 let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);
305
306                 // This case can currently arise only from functions marked
307                 // with #[rustc_inherit_overflow_checks] and inlined from
308                 // another crate (mostly core::num generic/#[inline] fns),
309                 // while the current crate doesn't use overflow checks.
310                 // NOTE: Unlike binops, negation doesn't have its own
311                 // checked operation, just a comparison with the minimum
312                 // value, so we have to check for the assert message.
313                 if !bx.cx.check_overflow {
314                     use rustc_const_math::ConstMathErr::Overflow;
315                     use rustc_const_math::Op::Neg;
316
317                     if let mir::AssertMessage::Math(Overflow(Neg)) = *msg {
318                         const_cond = Some(expected);
319                     }
320                 }
321
322                 // Don't translate the panic block if success if known.
323                 if const_cond == Some(expected) {
324                     funclet_br(self, bx, target);
325                     return;
326                 }
327
328                 // Pass the condition through llvm.expect for branch hinting.
329                 let expect = bx.cx.get_intrinsic(&"llvm.expect.i1");
330                 let cond = bx.call(expect, &[cond, C_bool(bx.cx, expected)], None);
331
332                 // Create the failure block and the conditional branch to it.
333                 let lltarget = llblock(self, target);
334                 let panic_block = self.new_block("panic");
335                 if expected {
336                     bx.cond_br(cond, lltarget, panic_block.llbb());
337                 } else {
338                     bx.cond_br(cond, panic_block.llbb(), lltarget);
339                 }
340
341                 // After this point, bx is the block for the call to panic.
342                 bx = panic_block;
343                 self.set_debug_loc(&bx, terminator.source_info);
344
345                 // Get the location information.
346                 let loc = bx.sess().codemap().lookup_char_pos(span.lo());
347                 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
348                 let filename = C_str_slice(bx.cx, filename);
349                 let line = C_u32(bx.cx, loc.line as u32);
350                 let col = C_u32(bx.cx, loc.col.to_usize() as u32 + 1);
351                 let align = tcx.data_layout.aggregate_align
352                     .max(tcx.data_layout.i32_align)
353                     .max(tcx.data_layout.pointer_align);
354
355                 // Put together the arguments to the panic entry point.
356                 let (lang_item, args) = match *msg {
357                     mir::AssertMessage::BoundsCheck { ref len, ref index } => {
358                         let len = self.trans_operand(&mut bx, len).immediate();
359                         let index = self.trans_operand(&mut bx, index).immediate();
360
361                         let file_line_col = C_struct(bx.cx, &[filename, line, col], false);
362                         let file_line_col = consts::addr_of(bx.cx,
363                                                             file_line_col,
364                                                             align,
365                                                             "panic_bounds_check_loc");
366                         (lang_items::PanicBoundsCheckFnLangItem,
367                          vec![file_line_col, index, len])
368                     }
369                     mir::AssertMessage::Math(ref err) => {
370                         let msg_str = Symbol::intern(err.description()).as_str();
371                         let msg_str = C_str_slice(bx.cx, msg_str);
372                         let msg_file_line_col = C_struct(bx.cx,
373                                                      &[msg_str, filename, line, col],
374                                                      false);
375                         let msg_file_line_col = consts::addr_of(bx.cx,
376                                                                 msg_file_line_col,
377                                                                 align,
378                                                                 "panic_loc");
379                         (lang_items::PanicFnLangItem,
380                          vec![msg_file_line_col])
381                     }
382                     mir::AssertMessage::GeneratorResumedAfterReturn |
383                     mir::AssertMessage::GeneratorResumedAfterPanic => {
384                         let str = if let mir::AssertMessage::GeneratorResumedAfterReturn = *msg {
385                             "generator resumed after completion"
386                         } else {
387                             "generator resumed after panicking"
388                         };
389                         let msg_str = Symbol::intern(str).as_str();
390                         let msg_str = C_str_slice(bx.cx, msg_str);
391                         let msg_file_line_col = C_struct(bx.cx,
392                                                      &[msg_str, filename, line, col],
393                                                      false);
394                         let msg_file_line_col = consts::addr_of(bx.cx,
395                                                                 msg_file_line_col,
396                                                                 align,
397                                                                 "panic_loc");
398                         (lang_items::PanicFnLangItem,
399                          vec![msg_file_line_col])
400                     }
401                 };
402
403                 // Obtain the panic entry point.
404                 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
405                 let instance = ty::Instance::mono(bx.tcx(), def_id);
406                 let fn_ty = FnType::of_instance(bx.cx, &instance);
407                 let llfn = callee::get_fn(bx.cx, instance);
408
409                 // Translate the actual panic invoke/call.
410                 do_call(self, bx, fn_ty, llfn, &args, None, cleanup);
411             }
412
413             mir::TerminatorKind::DropAndReplace { .. } => {
414                 bug!("undesugared DropAndReplace in trans: {:?}", terminator);
415             }
416
417             mir::TerminatorKind::Call { ref func, ref args, ref destination, cleanup } => {
418                 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
419                 let callee = self.trans_operand(&bx, func);
420
421                 let (instance, mut llfn) = match callee.layout.ty.sty {
422                     ty::TyFnDef(def_id, substs) => {
423                         (Some(ty::Instance::resolve(bx.cx.tcx,
424                                                     ty::ParamEnv::reveal_all(),
425                                                     def_id,
426                                                     substs).unwrap()),
427                          None)
428                     }
429                     ty::TyFnPtr(_) => {
430                         (None, Some(callee.immediate()))
431                     }
432                     _ => bug!("{} is not callable", callee.layout.ty)
433                 };
434                 let def = instance.map(|i| i.def);
435                 let sig = callee.layout.ty.fn_sig(bx.tcx());
436                 let sig = bx.tcx().normalize_erasing_late_bound_regions(
437                     ty::ParamEnv::reveal_all(),
438                     &sig,
439                 );
440                 let abi = sig.abi;
441
442                 // Handle intrinsics old trans wants Expr's for, ourselves.
443                 let intrinsic = match def {
444                     Some(ty::InstanceDef::Intrinsic(def_id))
445                         => Some(bx.tcx().item_name(def_id)),
446                     _ => None
447                 };
448                 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
449
450                 if intrinsic == Some("transmute") {
451                     let &(ref dest, target) = destination.as_ref().unwrap();
452                     self.trans_transmute(&bx, &args[0], dest);
453                     funclet_br(self, bx, target);
454                     return;
455                 }
456
457                 let extra_args = &args[sig.inputs().len()..];
458                 let extra_args = extra_args.iter().map(|op_arg| {
459                     let op_ty = op_arg.ty(self.mir, bx.tcx());
460                     self.monomorphize(&op_ty)
461                 }).collect::<Vec<_>>();
462
463                 let fn_ty = match def {
464                     Some(ty::InstanceDef::Virtual(..)) => {
465                         FnType::new_vtable(bx.cx, sig, &extra_args)
466                     }
467                     Some(ty::InstanceDef::DropGlue(_, None)) => {
468                         // empty drop glue - a nop.
469                         let &(_, target) = destination.as_ref().unwrap();
470                         funclet_br(self, bx, target);
471                         return;
472                     }
473                     _ => FnType::new(bx.cx, sig, &extra_args)
474                 };
475
476                 // The arguments we'll be passing. Plus one to account for outptr, if used.
477                 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
478                 let mut llargs = Vec::with_capacity(arg_count);
479
480                 // Prepare the return value destination
481                 let ret_dest = if let Some((ref dest, _)) = *destination {
482                     let is_intrinsic = intrinsic.is_some();
483                     self.make_return_dest(&bx, dest, &fn_ty.ret, &mut llargs,
484                                           is_intrinsic)
485                 } else {
486                     ReturnDest::Nothing
487                 };
488
489                 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
490                     use intrinsic::trans_intrinsic_call;
491
492                     let dest = match ret_dest {
493                         _ if fn_ty.ret.is_indirect() => llargs[0],
494                         ReturnDest::Nothing => {
495                             C_undef(fn_ty.ret.memory_ty(bx.cx).ptr_to())
496                         }
497                         ReturnDest::IndirectOperand(dst, _) |
498                         ReturnDest::Store(dst) => dst.llval,
499                         ReturnDest::DirectOperand(_) =>
500                             bug!("Cannot use direct operand with an intrinsic call")
501                     };
502
503                     let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
504                         // The indices passed to simd_shuffle* in the
505                         // third argument must be constant. This is
506                         // checked by const-qualification, which also
507                         // promotes any complex rvalues to constants.
508                         if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
509                             match *arg {
510                                 mir::Operand::Copy(_) |
511                                 mir::Operand::Move(_) => {
512                                     span_bug!(span, "shuffle indices must be constant");
513                                 }
514                                 mir::Operand::Constant(ref constant) => {
515                                     let (llval, ty) = self.simd_shuffle_indices(
516                                         &bx,
517                                         constant,
518                                     );
519                                     return OperandRef {
520                                         val: Immediate(llval),
521                                         layout: bx.cx.layout_of(ty)
522                                     };
523                                 }
524                             }
525                         }
526
527                         self.trans_operand(&bx, arg)
528                     }).collect();
529
530
531                     let callee_ty = instance.as_ref().unwrap().ty(bx.cx.tcx);
532                     trans_intrinsic_call(&bx, callee_ty, &fn_ty, &args, dest,
533                                          terminator.source_info.span);
534
535                     if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
536                         self.store_return(&bx, ret_dest, &fn_ty.ret, dst.llval);
537                     }
538
539                     if let Some((_, target)) = *destination {
540                         funclet_br(self, bx, target);
541                     } else {
542                         bx.unreachable();
543                     }
544
545                     return;
546                 }
547
548                 // Split the rust-call tupled arguments off.
549                 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
550                     let (tup, args) = args.split_last().unwrap();
551                     (args, Some(tup))
552                 } else {
553                     (&args[..], None)
554                 };
555
556                 for (i, arg) in first_args.iter().enumerate() {
557                     let mut op = self.trans_operand(&bx, arg);
558                     if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
559                         if let Pair(data_ptr, meta) = op.val {
560                             llfn = Some(meth::VirtualIndex::from_index(idx)
561                                 .get_fn(&bx, meta, &fn_ty));
562                             llargs.push(data_ptr);
563                             continue;
564                         }
565                     }
566
567                     // The callee needs to own the argument memory if we pass it
568                     // by-ref, so make a local copy of non-immediate constants.
569                     match (arg, op.val) {
570                         (&mir::Operand::Copy(_), Ref(..)) |
571                         (&mir::Operand::Constant(_), Ref(..)) => {
572                             let tmp = PlaceRef::alloca(&bx, op.layout, "const");
573                             op.val.store(&bx, tmp);
574                             op.val = Ref(tmp.llval, tmp.align);
575                         }
576                         _ => {}
577                     }
578
579                     self.trans_argument(&bx, op, &mut llargs, &fn_ty.args[i]);
580                 }
581                 if let Some(tup) = untuple {
582                     self.trans_arguments_untupled(&bx, tup, &mut llargs,
583                         &fn_ty.args[first_args.len()..])
584                 }
585
586                 let fn_ptr = match (llfn, instance) {
587                     (Some(llfn), _) => llfn,
588                     (None, Some(instance)) => callee::get_fn(bx.cx, instance),
589                     _ => span_bug!(span, "no llfn for call"),
590                 };
591
592                 do_call(self, bx, fn_ty, fn_ptr, &llargs,
593                         destination.as_ref().map(|&(_, target)| (ret_dest, target)),
594                         cleanup);
595             }
596             mir::TerminatorKind::GeneratorDrop |
597             mir::TerminatorKind::Yield { .. } => bug!("generator ops in trans"),
598             mir::TerminatorKind::FalseEdges { .. } |
599             mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in trans"),
600         }
601     }
602
603     fn trans_argument(&mut self,
604                       bx: &Builder<'a, 'tcx>,
605                       op: OperandRef<'tcx>,
606                       llargs: &mut Vec<ValueRef>,
607                       arg: &ArgType<'tcx, Ty<'tcx>>) {
608         // Fill padding with undef value, where applicable.
609         if let Some(ty) = arg.pad {
610             llargs.push(C_undef(ty.llvm_type(bx.cx)));
611         }
612
613         if arg.is_ignore() {
614             return;
615         }
616
617         if let PassMode::Pair(..) = arg.mode {
618             match op.val {
619                 Pair(a, b) => {
620                     llargs.push(a);
621                     llargs.push(b);
622                     return;
623                 }
624                 _ => bug!("trans_argument: {:?} invalid for pair arugment", op)
625             }
626         }
627
628         // Force by-ref if we have to load through a cast pointer.
629         let (mut llval, align, by_ref) = match op.val {
630             Immediate(_) | Pair(..) => {
631                 match arg.mode {
632                     PassMode::Indirect(_) | PassMode::Cast(_) => {
633                         let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
634                         op.val.store(bx, scratch);
635                         (scratch.llval, scratch.align, true)
636                     }
637                     _ => {
638                         (op.immediate_or_packed_pair(bx), arg.layout.align, false)
639                     }
640                 }
641             }
642             Ref(llval, align) => {
643                 if arg.is_indirect() && align.abi() < arg.layout.align.abi() {
644                     // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
645                     // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
646                     // have scary latent bugs around.
647
648                     let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
649                     base::memcpy_ty(bx, scratch.llval, llval, op.layout, align);
650                     (scratch.llval, scratch.align, true)
651                 } else {
652                     (llval, align, true)
653                 }
654             }
655         };
656
657         if by_ref && !arg.is_indirect() {
658             // Have to load the argument, maybe while casting it.
659             if let PassMode::Cast(ty) = arg.mode {
660                 llval = bx.load(bx.pointercast(llval, ty.llvm_type(bx.cx).ptr_to()),
661                                  align.min(arg.layout.align));
662             } else {
663                 // We can't use `PlaceRef::load` here because the argument
664                 // may have a type we don't treat as immediate, but the ABI
665                 // used for this call is passing it by-value. In that case,
666                 // the load would just produce `OperandValue::Ref` instead
667                 // of the `OperandValue::Immediate` we need for the call.
668                 llval = bx.load(llval, align);
669                 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
670                     if scalar.is_bool() {
671                         bx.range_metadata(llval, 0..2);
672                     }
673                 }
674                 // We store bools as i8 so we need to truncate to i1.
675                 llval = base::to_immediate(bx, llval, arg.layout);
676             }
677         }
678
679         llargs.push(llval);
680     }
681
682     fn trans_arguments_untupled(&mut self,
683                                 bx: &Builder<'a, 'tcx>,
684                                 operand: &mir::Operand<'tcx>,
685                                 llargs: &mut Vec<ValueRef>,
686                                 args: &[ArgType<'tcx, Ty<'tcx>>]) {
687         let tuple = self.trans_operand(bx, operand);
688
689         // Handle both by-ref and immediate tuples.
690         if let Ref(llval, align) = tuple.val {
691             let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
692             for i in 0..tuple.layout.fields.count() {
693                 let field_ptr = tuple_ptr.project_field(bx, i);
694                 self.trans_argument(bx, field_ptr.load(bx), llargs, &args[i]);
695             }
696         } else {
697             // If the tuple is immediate, the elements are as well.
698             for i in 0..tuple.layout.fields.count() {
699                 let op = tuple.extract_field(bx, i);
700                 self.trans_argument(bx, op, llargs, &args[i]);
701             }
702         }
703     }
704
705     fn get_personality_slot(&mut self, bx: &Builder<'a, 'tcx>) -> PlaceRef<'tcx> {
706         let cx = bx.cx;
707         if let Some(slot) = self.personality_slot {
708             slot
709         } else {
710             let layout = cx.layout_of(cx.tcx.intern_tup(&[
711                 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
712                 cx.tcx.types.i32
713             ]));
714             let slot = PlaceRef::alloca(bx, layout, "personalityslot");
715             self.personality_slot = Some(slot);
716             slot
717         }
718     }
719
720     /// Return the landingpad wrapper around the given basic block
721     ///
722     /// No-op in MSVC SEH scheme.
723     fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> BasicBlockRef {
724         if let Some(block) = self.landing_pads[target_bb] {
725             return block;
726         }
727
728         let block = self.blocks[target_bb];
729         let landing_pad = self.landing_pad_uncached(block);
730         self.landing_pads[target_bb] = Some(landing_pad);
731         landing_pad
732     }
733
734     fn landing_pad_uncached(&mut self, target_bb: BasicBlockRef) -> BasicBlockRef {
735         if base::wants_msvc_seh(self.cx.sess()) {
736             span_bug!(self.mir.span, "landing pad was not inserted?")
737         }
738
739         let bx = self.new_block("cleanup");
740
741         let llpersonality = self.cx.eh_personality();
742         let llretty = self.landing_pad_type();
743         let lp = bx.landing_pad(llretty, llpersonality, 1);
744         bx.set_cleanup(lp);
745
746         let slot = self.get_personality_slot(&bx);
747         slot.storage_live(&bx);
748         Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&bx, slot);
749
750         bx.br(target_bb);
751         bx.llbb()
752     }
753
754     fn landing_pad_type(&self) -> Type {
755         let cx = self.cx;
756         Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)], false)
757     }
758
759     fn unreachable_block(&mut self) -> BasicBlockRef {
760         self.unreachable_block.unwrap_or_else(|| {
761             let bl = self.new_block("unreachable");
762             bl.unreachable();
763             self.unreachable_block = Some(bl.llbb());
764             bl.llbb()
765         })
766     }
767
768     pub fn new_block(&self, name: &str) -> Builder<'a, 'tcx> {
769         Builder::new_block(self.cx, self.llfn, name)
770     }
771
772     pub fn build_block(&self, bb: mir::BasicBlock) -> Builder<'a, 'tcx> {
773         let bx = Builder::with_cx(self.cx);
774         bx.position_at_end(self.blocks[bb]);
775         bx
776     }
777
778     fn make_return_dest(&mut self, bx: &Builder<'a, 'tcx>,
779                         dest: &mir::Place<'tcx>, fn_ret: &ArgType<'tcx, Ty<'tcx>>,
780                         llargs: &mut Vec<ValueRef>, is_intrinsic: bool)
781                         -> ReturnDest<'tcx> {
782         // If the return is ignored, we can just return a do-nothing ReturnDest
783         if fn_ret.is_ignore() {
784             return ReturnDest::Nothing;
785         }
786         let dest = if let mir::Place::Local(index) = *dest {
787             match self.locals[index] {
788                 LocalRef::Place(dest) => dest,
789                 LocalRef::Operand(None) => {
790                     // Handle temporary places, specifically Operand ones, as
791                     // they don't have allocas
792                     return if fn_ret.is_indirect() {
793                         // Odd, but possible, case, we have an operand temporary,
794                         // but the calling convention has an indirect return.
795                         let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
796                         tmp.storage_live(bx);
797                         llargs.push(tmp.llval);
798                         ReturnDest::IndirectOperand(tmp, index)
799                     } else if is_intrinsic {
800                         // Currently, intrinsics always need a location to store
801                         // the result. so we create a temporary alloca for the
802                         // result
803                         let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
804                         tmp.storage_live(bx);
805                         ReturnDest::IndirectOperand(tmp, index)
806                     } else {
807                         ReturnDest::DirectOperand(index)
808                     };
809                 }
810                 LocalRef::Operand(Some(_)) => {
811                     bug!("place local already assigned to");
812                 }
813             }
814         } else {
815             self.trans_place(bx, dest)
816         };
817         if fn_ret.is_indirect() {
818             if dest.align.abi() < dest.layout.align.abi() {
819                 // Currently, MIR code generation does not create calls
820                 // that store directly to fields of packed structs (in
821                 // fact, the calls it creates write only to temps),
822                 //
823                 // If someone changes that, please update this code path
824                 // to create a temporary.
825                 span_bug!(self.mir.span, "can't directly store to unaligned value");
826             }
827             llargs.push(dest.llval);
828             ReturnDest::Nothing
829         } else {
830             ReturnDest::Store(dest)
831         }
832     }
833
834     fn trans_transmute(&mut self, bx: &Builder<'a, 'tcx>,
835                        src: &mir::Operand<'tcx>,
836                        dst: &mir::Place<'tcx>) {
837         if let mir::Place::Local(index) = *dst {
838             match self.locals[index] {
839                 LocalRef::Place(place) => self.trans_transmute_into(bx, src, place),
840                 LocalRef::Operand(None) => {
841                     let dst_layout = bx.cx.layout_of(self.monomorphized_place_ty(dst));
842                     assert!(!dst_layout.ty.has_erasable_regions());
843                     let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
844                     place.storage_live(bx);
845                     self.trans_transmute_into(bx, src, place);
846                     let op = place.load(bx);
847                     place.storage_dead(bx);
848                     self.locals[index] = LocalRef::Operand(Some(op));
849                 }
850                 LocalRef::Operand(Some(op)) => {
851                     assert!(op.layout.is_zst(),
852                             "assigning to initialized SSAtemp");
853                 }
854             }
855         } else {
856             let dst = self.trans_place(bx, dst);
857             self.trans_transmute_into(bx, src, dst);
858         }
859     }
860
861     fn trans_transmute_into(&mut self, bx: &Builder<'a, 'tcx>,
862                             src: &mir::Operand<'tcx>,
863                             dst: PlaceRef<'tcx>) {
864         let src = self.trans_operand(bx, src);
865         let llty = src.layout.llvm_type(bx.cx);
866         let cast_ptr = bx.pointercast(dst.llval, llty.ptr_to());
867         let align = src.layout.align.min(dst.layout.align);
868         src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
869     }
870
871
872     // Stores the return value of a function call into it's final location.
873     fn store_return(&mut self,
874                     bx: &Builder<'a, 'tcx>,
875                     dest: ReturnDest<'tcx>,
876                     ret_ty: &ArgType<'tcx, Ty<'tcx>>,
877                     llval: ValueRef) {
878         use self::ReturnDest::*;
879
880         match dest {
881             Nothing => (),
882             Store(dst) => ret_ty.store(bx, llval, dst),
883             IndirectOperand(tmp, index) => {
884                 let op = tmp.load(bx);
885                 tmp.storage_dead(bx);
886                 self.locals[index] = LocalRef::Operand(Some(op));
887             }
888             DirectOperand(index) => {
889                 // If there is a cast, we have to store and reload.
890                 let op = if let PassMode::Cast(_) = ret_ty.mode {
891                     let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
892                     tmp.storage_live(bx);
893                     ret_ty.store(bx, llval, tmp);
894                     let op = tmp.load(bx);
895                     tmp.storage_dead(bx);
896                     op
897                 } else {
898                     OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
899                 };
900                 self.locals[index] = LocalRef::Operand(Some(op));
901             }
902         }
903     }
904 }
905
906 enum ReturnDest<'tcx> {
907     // Do nothing, the return value is indirect or ignored
908     Nothing,
909     // Store the return value to the pointer
910     Store(PlaceRef<'tcx>),
911     // Stores an indirect return value to an operand local place
912     IndirectOperand(PlaceRef<'tcx>, mir::Local),
913     // Stores a direct return value to an operand local place
914     DirectOperand(mir::Local)
915 }