]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/block.rs
Refactor how SwitchInt stores jump targets
[rust.git] / compiler / rustc_codegen_ssa / src / mir / block.rs
1 use super::operand::OperandRef;
2 use super::operand::OperandValue::{Immediate, Pair, Ref};
3 use super::place::PlaceRef;
4 use super::{FunctionCx, LocalRef};
5
6 use crate::base;
7 use crate::common::{self, IntPredicate};
8 use crate::meth;
9 use crate::traits::*;
10 use crate::MemFlags;
11
12 use rustc_ast as ast;
13 use rustc_hir::lang_items::LangItem;
14 use rustc_index::vec::Idx;
15 use rustc_middle::mir::interpret::ConstValue;
16 use rustc_middle::mir::AssertKind;
17 use rustc_middle::mir::{self, SwitchTargets};
18 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
19 use rustc_middle::ty::print::with_no_trimmed_paths;
20 use rustc_middle::ty::{self, Instance, Ty, TypeFoldable};
21 use rustc_span::source_map::Span;
22 use rustc_span::{sym, Symbol};
23 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode};
24 use rustc_target::abi::{self, LayoutOf};
25 use rustc_target::spec::abi::Abi;
26
27 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
28 /// e.g., creating a basic block, calling a function, etc.
29 struct TerminatorCodegenHelper<'tcx> {
30     bb: mir::BasicBlock,
31     terminator: &'tcx mir::Terminator<'tcx>,
32     funclet_bb: Option<mir::BasicBlock>,
33 }
34
35 impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
36     /// Returns the associated funclet from `FunctionCx::funclets` for the
37     /// `funclet_bb` member if it is not `None`.
38     fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
39         &self,
40         fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
41     ) -> Option<&'b Bx::Funclet> {
42         match self.funclet_bb {
43             Some(funcl) => fx.funclets[funcl].as_ref(),
44             None => None,
45         }
46     }
47
48     fn lltarget<Bx: BuilderMethods<'a, 'tcx>>(
49         &self,
50         fx: &mut FunctionCx<'a, 'tcx, Bx>,
51         target: mir::BasicBlock,
52     ) -> (Bx::BasicBlock, bool) {
53         let span = self.terminator.source_info.span;
54         let lltarget = fx.blocks[target];
55         let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
56         match (self.funclet_bb, target_funclet) {
57             (None, None) => (lltarget, false),
58             (Some(f), Some(t_f)) if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) => {
59                 (lltarget, false)
60             }
61             // jump *into* cleanup - need a landing pad if GNU
62             (None, Some(_)) => (fx.landing_pad_to(target), false),
63             (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
64             (Some(_), Some(_)) => (fx.landing_pad_to(target), true),
65         }
66     }
67
68     /// Create a basic block.
69     fn llblock<Bx: BuilderMethods<'a, 'tcx>>(
70         &self,
71         fx: &mut FunctionCx<'a, 'tcx, Bx>,
72         target: mir::BasicBlock,
73     ) -> Bx::BasicBlock {
74         let (lltarget, is_cleanupret) = self.lltarget(fx, target);
75         if is_cleanupret {
76             // MSVC cross-funclet jump - need a trampoline
77
78             debug!("llblock: creating cleanup trampoline for {:?}", target);
79             let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
80             let mut trampoline = fx.new_block(name);
81             trampoline.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
82             trampoline.llbb()
83         } else {
84             lltarget
85         }
86     }
87
88     fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
89         &self,
90         fx: &mut FunctionCx<'a, 'tcx, Bx>,
91         bx: &mut Bx,
92         target: mir::BasicBlock,
93     ) {
94         let (lltarget, is_cleanupret) = self.lltarget(fx, target);
95         if is_cleanupret {
96             // micro-optimization: generate a `ret` rather than a jump
97             // to a trampoline.
98             bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
99         } else {
100             bx.br(lltarget);
101         }
102     }
103
104     /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
105     /// return destination `destination` and the cleanup function `cleanup`.
106     fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
107         &self,
108         fx: &mut FunctionCx<'a, 'tcx, Bx>,
109         bx: &mut Bx,
110         fn_abi: FnAbi<'tcx, Ty<'tcx>>,
111         fn_ptr: Bx::Value,
112         llargs: &[Bx::Value],
113         destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
114         cleanup: Option<mir::BasicBlock>,
115     ) {
116         // If there is a cleanup block and the function we're calling can unwind, then
117         // do an invoke, otherwise do a call.
118         if let Some(cleanup) = cleanup.filter(|_| fn_abi.can_unwind) {
119             let ret_bx = if let Some((_, target)) = destination {
120                 fx.blocks[target]
121             } else {
122                 fx.unreachable_block()
123             };
124             let invokeret =
125                 bx.invoke(fn_ptr, &llargs, ret_bx, self.llblock(fx, cleanup), self.funclet(fx));
126             bx.apply_attrs_callsite(&fn_abi, invokeret);
127
128             if let Some((ret_dest, target)) = destination {
129                 let mut ret_bx = fx.build_block(target);
130                 fx.set_debug_loc(&mut ret_bx, self.terminator.source_info);
131                 fx.store_return(&mut ret_bx, ret_dest, &fn_abi.ret, invokeret);
132             }
133         } else {
134             let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
135             bx.apply_attrs_callsite(&fn_abi, llret);
136             if fx.mir[self.bb].is_cleanup {
137                 // Cleanup is always the cold path. Don't inline
138                 // drop glue. Also, when there is a deeply-nested
139                 // struct, there are "symmetry" issues that cause
140                 // exponential inlining - see issue #41696.
141                 bx.do_not_inline(llret);
142             }
143
144             if let Some((ret_dest, target)) = destination {
145                 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
146                 self.funclet_br(fx, bx, target);
147             } else {
148                 bx.unreachable();
149             }
150         }
151     }
152
153     // Generate sideeffect intrinsic if jumping to any of the targets can form
154     // a loop.
155     fn maybe_sideeffect<Bx: BuilderMethods<'a, 'tcx>>(
156         &self,
157         mir: &'tcx mir::Body<'tcx>,
158         bx: &mut Bx,
159         targets: &[mir::BasicBlock],
160     ) {
161         if bx.tcx().sess.opts.debugging_opts.insert_sideeffect {
162             if targets.iter().any(|&target| {
163                 target <= self.bb
164                     && target.start_location().is_predecessor_of(self.bb.start_location(), mir)
165             }) {
166                 bx.sideeffect();
167             }
168         }
169     }
170 }
171
172 /// Codegen implementations for some terminator variants.
173 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
174     /// Generates code for a `Resume` terminator.
175     fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, mut bx: Bx) {
176         if let Some(funclet) = helper.funclet(self) {
177             bx.cleanup_ret(funclet, None);
178         } else {
179             let slot = self.get_personality_slot(&mut bx);
180             let lp0 = slot.project_field(&mut bx, 0);
181             let lp0 = bx.load_operand(lp0).immediate();
182             let lp1 = slot.project_field(&mut bx, 1);
183             let lp1 = bx.load_operand(lp1).immediate();
184             slot.storage_dead(&mut bx);
185
186             let mut lp = bx.const_undef(self.landing_pad_type());
187             lp = bx.insert_value(lp, lp0, 0);
188             lp = bx.insert_value(lp, lp1, 1);
189             bx.resume(lp);
190         }
191     }
192
193     fn codegen_switchint_terminator(
194         &mut self,
195         helper: TerminatorCodegenHelper<'tcx>,
196         mut bx: Bx,
197         discr: &mir::Operand<'tcx>,
198         switch_ty: Ty<'tcx>,
199         targets: &SwitchTargets<'tcx>,
200     ) {
201         let discr = self.codegen_operand(&mut bx, &discr);
202         // `switch_ty` is redundant, sanity-check that.
203         assert_eq!(discr.layout.ty, switch_ty);
204         helper.maybe_sideeffect(self.mir, &mut bx, targets.all_targets());
205
206         let mut target_iter = targets.iter();
207         if target_iter.len() == 1 {
208             // If there are two targets (one conditional, one fallback), emit br instead of switch
209             let (test_value, target) = target_iter.next().unwrap();
210             let lltrue = helper.llblock(self, target);
211             let llfalse = helper.llblock(self, targets.otherwise());
212             if switch_ty == bx.tcx().types.bool {
213                 // Don't generate trivial icmps when switching on bool
214                 match test_value {
215                     0 => bx.cond_br(discr.immediate(), llfalse, lltrue),
216                     1 => bx.cond_br(discr.immediate(), lltrue, llfalse),
217                     _ => bug!(),
218                 }
219             } else {
220                 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
221                 let llval = bx.const_uint_big(switch_llty, test_value);
222                 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
223                 bx.cond_br(cmp, lltrue, llfalse);
224             }
225         } else {
226             bx.switch(
227                 discr.immediate(),
228                 helper.llblock(self, targets.otherwise()),
229                 target_iter.map(|(value, target)| (value, helper.llblock(self, target))),
230             );
231         }
232     }
233
234     fn codegen_return_terminator(&mut self, mut bx: Bx) {
235         // Call `va_end` if this is the definition of a C-variadic function.
236         if self.fn_abi.c_variadic {
237             // The `VaList` "spoofed" argument is just after all the real arguments.
238             let va_list_arg_idx = self.fn_abi.args.len();
239             match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
240                 LocalRef::Place(va_list) => {
241                     bx.va_end(va_list.llval);
242                 }
243                 _ => bug!("C-variadic function must have a `VaList` place"),
244             }
245         }
246         if self.fn_abi.ret.layout.abi.is_uninhabited() {
247             // Functions with uninhabited return values are marked `noreturn`,
248             // so we should make sure that we never actually do.
249             // We play it safe by using a well-defined `abort`, but we could go for immediate UB
250             // if that turns out to be helpful.
251             bx.abort();
252             // `abort` does not terminate the block, so we still need to generate
253             // an `unreachable` terminator after it.
254             bx.unreachable();
255             return;
256         }
257         let llval = match self.fn_abi.ret.mode {
258             PassMode::Ignore | PassMode::Indirect(..) => {
259                 bx.ret_void();
260                 return;
261             }
262
263             PassMode::Direct(_) | PassMode::Pair(..) => {
264                 let op = self.codegen_consume(&mut bx, mir::Place::return_place().as_ref());
265                 if let Ref(llval, _, align) = op.val {
266                     bx.load(llval, align)
267                 } else {
268                     op.immediate_or_packed_pair(&mut bx)
269                 }
270             }
271
272             PassMode::Cast(cast_ty) => {
273                 let op = match self.locals[mir::RETURN_PLACE] {
274                     LocalRef::Operand(Some(op)) => op,
275                     LocalRef::Operand(None) => bug!("use of return before def"),
276                     LocalRef::Place(cg_place) => OperandRef {
277                         val: Ref(cg_place.llval, None, cg_place.align),
278                         layout: cg_place.layout,
279                     },
280                     LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
281                 };
282                 let llslot = match op.val {
283                     Immediate(_) | Pair(..) => {
284                         let scratch = PlaceRef::alloca(&mut bx, self.fn_abi.ret.layout);
285                         op.val.store(&mut bx, scratch);
286                         scratch.llval
287                     }
288                     Ref(llval, _, align) => {
289                         assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
290                         llval
291                     }
292                 };
293                 let addr = bx.pointercast(llslot, bx.type_ptr_to(bx.cast_backend_type(&cast_ty)));
294                 bx.load(addr, self.fn_abi.ret.layout.align.abi)
295             }
296         };
297         bx.ret(llval);
298     }
299
300     fn codegen_drop_terminator(
301         &mut self,
302         helper: TerminatorCodegenHelper<'tcx>,
303         mut bx: Bx,
304         location: mir::Place<'tcx>,
305         target: mir::BasicBlock,
306         unwind: Option<mir::BasicBlock>,
307     ) {
308         let ty = location.ty(self.mir, bx.tcx()).ty;
309         let ty = self.monomorphize(&ty);
310         let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
311
312         if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
313             // we don't actually need to drop anything.
314             helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
315             helper.funclet_br(self, &mut bx, target);
316             return;
317         }
318
319         let place = self.codegen_place(&mut bx, location.as_ref());
320         let (args1, args2);
321         let mut args = if let Some(llextra) = place.llextra {
322             args2 = [place.llval, llextra];
323             &args2[..]
324         } else {
325             args1 = [place.llval];
326             &args1[..]
327         };
328         let (drop_fn, fn_abi) = match ty.kind() {
329             // FIXME(eddyb) perhaps move some of this logic into
330             // `Instance::resolve_drop_in_place`?
331             ty::Dynamic(..) => {
332                 let virtual_drop = Instance {
333                     def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
334                     substs: drop_fn.substs,
335                 };
336                 let fn_abi = FnAbi::of_instance(&bx, virtual_drop, &[]);
337                 let vtable = args[1];
338                 args = &args[..1];
339                 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_abi), fn_abi)
340             }
341             _ => (bx.get_fn_addr(drop_fn), FnAbi::of_instance(&bx, drop_fn, &[])),
342         };
343         helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
344         helper.do_call(
345             self,
346             &mut bx,
347             fn_abi,
348             drop_fn,
349             args,
350             Some((ReturnDest::Nothing, target)),
351             unwind,
352         );
353     }
354
355     fn codegen_assert_terminator(
356         &mut self,
357         helper: TerminatorCodegenHelper<'tcx>,
358         mut bx: Bx,
359         terminator: &mir::Terminator<'tcx>,
360         cond: &mir::Operand<'tcx>,
361         expected: bool,
362         msg: &mir::AssertMessage<'tcx>,
363         target: mir::BasicBlock,
364         cleanup: Option<mir::BasicBlock>,
365     ) {
366         let span = terminator.source_info.span;
367         let cond = self.codegen_operand(&mut bx, cond).immediate();
368         let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
369
370         // This case can currently arise only from functions marked
371         // with #[rustc_inherit_overflow_checks] and inlined from
372         // another crate (mostly core::num generic/#[inline] fns),
373         // while the current crate doesn't use overflow checks.
374         // NOTE: Unlike binops, negation doesn't have its own
375         // checked operation, just a comparison with the minimum
376         // value, so we have to check for the assert message.
377         if !bx.check_overflow() {
378             if let AssertKind::OverflowNeg(_) = *msg {
379                 const_cond = Some(expected);
380             }
381         }
382
383         // Don't codegen the panic block if success if known.
384         if const_cond == Some(expected) {
385             helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
386             helper.funclet_br(self, &mut bx, target);
387             return;
388         }
389
390         // Pass the condition through llvm.expect for branch hinting.
391         let cond = bx.expect(cond, expected);
392
393         // Create the failure block and the conditional branch to it.
394         let lltarget = helper.llblock(self, target);
395         let panic_block = self.new_block("panic");
396         helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
397         if expected {
398             bx.cond_br(cond, lltarget, panic_block.llbb());
399         } else {
400             bx.cond_br(cond, panic_block.llbb(), lltarget);
401         }
402
403         // After this point, bx is the block for the call to panic.
404         bx = panic_block;
405         self.set_debug_loc(&mut bx, terminator.source_info);
406
407         // Get the location information.
408         let location = self.get_caller_location(&mut bx, span).immediate();
409
410         // Put together the arguments to the panic entry point.
411         let (lang_item, args) = match msg {
412             AssertKind::BoundsCheck { ref len, ref index } => {
413                 let len = self.codegen_operand(&mut bx, len).immediate();
414                 let index = self.codegen_operand(&mut bx, index).immediate();
415                 // It's `fn panic_bounds_check(index: usize, len: usize)`,
416                 // and `#[track_caller]` adds an implicit third argument.
417                 (LangItem::PanicBoundsCheck, vec![index, len, location])
418             }
419             _ => {
420                 let msg_str = Symbol::intern(msg.description());
421                 let msg = bx.const_str(msg_str);
422                 // It's `pub fn panic(expr: &str)`, with the wide reference being passed
423                 // as two arguments, and `#[track_caller]` adds an implicit third argument.
424                 (LangItem::Panic, vec![msg.0, msg.1, location])
425             }
426         };
427
428         // Obtain the panic entry point.
429         let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
430         let instance = ty::Instance::mono(bx.tcx(), def_id);
431         let fn_abi = FnAbi::of_instance(&bx, instance, &[]);
432         let llfn = bx.get_fn_addr(instance);
433
434         // Codegen the actual panic invoke/call.
435         helper.do_call(self, &mut bx, fn_abi, llfn, &args, None, cleanup);
436     }
437
438     /// Returns `true` if this is indeed a panic intrinsic and codegen is done.
439     fn codegen_panic_intrinsic(
440         &mut self,
441         helper: &TerminatorCodegenHelper<'tcx>,
442         bx: &mut Bx,
443         intrinsic: Option<Symbol>,
444         instance: Option<Instance<'tcx>>,
445         span: Span,
446         destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
447         cleanup: Option<mir::BasicBlock>,
448     ) -> bool {
449         // Emit a panic or a no-op for `assert_*` intrinsics.
450         // These are intrinsics that compile to panics so that we can get a message
451         // which mentions the offending type, even from a const context.
452         #[derive(Debug, PartialEq)]
453         enum AssertIntrinsic {
454             Inhabited,
455             ZeroValid,
456             UninitValid,
457         };
458         let panic_intrinsic = intrinsic.and_then(|i| match i {
459             sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
460             sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
461             sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid),
462             _ => None,
463         });
464         if let Some(intrinsic) = panic_intrinsic {
465             use AssertIntrinsic::*;
466             let ty = instance.unwrap().substs.type_at(0);
467             let layout = bx.layout_of(ty);
468             let do_panic = match intrinsic {
469                 Inhabited => layout.abi.is_uninhabited(),
470                 // We unwrap as the error type is `!`.
471                 ZeroValid => !layout.might_permit_raw_init(bx, /*zero:*/ true).unwrap(),
472                 // We unwrap as the error type is `!`.
473                 UninitValid => !layout.might_permit_raw_init(bx, /*zero:*/ false).unwrap(),
474             };
475             if do_panic {
476                 let msg_str = with_no_trimmed_paths(|| {
477                     if layout.abi.is_uninhabited() {
478                         // Use this error even for the other intrinsics as it is more precise.
479                         format!("attempted to instantiate uninhabited type `{}`", ty)
480                     } else if intrinsic == ZeroValid {
481                         format!("attempted to zero-initialize type `{}`, which is invalid", ty)
482                     } else {
483                         format!("attempted to leave type `{}` uninitialized, which is invalid", ty)
484                     }
485                 });
486                 let msg = bx.const_str(Symbol::intern(&msg_str));
487                 let location = self.get_caller_location(bx, span).immediate();
488
489                 // Obtain the panic entry point.
490                 // FIXME: dedup this with `codegen_assert_terminator` above.
491                 let def_id = common::langcall(bx.tcx(), Some(span), "", LangItem::Panic);
492                 let instance = ty::Instance::mono(bx.tcx(), def_id);
493                 let fn_abi = FnAbi::of_instance(bx, instance, &[]);
494                 let llfn = bx.get_fn_addr(instance);
495
496                 if let Some((_, target)) = destination.as_ref() {
497                     helper.maybe_sideeffect(self.mir, bx, &[*target]);
498                 }
499                 // Codegen the actual panic invoke/call.
500                 helper.do_call(
501                     self,
502                     bx,
503                     fn_abi,
504                     llfn,
505                     &[msg.0, msg.1, location],
506                     destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
507                     cleanup,
508                 );
509             } else {
510                 // a NOP
511                 let target = destination.as_ref().unwrap().1;
512                 helper.maybe_sideeffect(self.mir, bx, &[target]);
513                 helper.funclet_br(self, bx, target)
514             }
515             true
516         } else {
517             false
518         }
519     }
520
521     fn codegen_call_terminator(
522         &mut self,
523         helper: TerminatorCodegenHelper<'tcx>,
524         mut bx: Bx,
525         terminator: &mir::Terminator<'tcx>,
526         func: &mir::Operand<'tcx>,
527         args: &Vec<mir::Operand<'tcx>>,
528         destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
529         cleanup: Option<mir::BasicBlock>,
530         fn_span: Span,
531     ) {
532         let span = terminator.source_info.span;
533         // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
534         let callee = self.codegen_operand(&mut bx, func);
535
536         let (instance, mut llfn) = match *callee.layout.ty.kind() {
537             ty::FnDef(def_id, substs) => (
538                 Some(
539                     ty::Instance::resolve(bx.tcx(), ty::ParamEnv::reveal_all(), def_id, substs)
540                         .unwrap()
541                         .unwrap()
542                         .polymorphize(bx.tcx()),
543                 ),
544                 None,
545             ),
546             ty::FnPtr(_) => (None, Some(callee.immediate())),
547             _ => bug!("{} is not callable", callee.layout.ty),
548         };
549         let def = instance.map(|i| i.def);
550
551         if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
552             // Empty drop glue; a no-op.
553             let &(_, target) = destination.as_ref().unwrap();
554             helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
555             helper.funclet_br(self, &mut bx, target);
556             return;
557         }
558
559         // FIXME(eddyb) avoid computing this if possible, when `instance` is
560         // available - right now `sig` is only needed for getting the `abi`
561         // and figuring out how many extra args were passed to a C-variadic `fn`.
562         let sig = callee.layout.ty.fn_sig(bx.tcx());
563         let abi = sig.abi();
564
565         // Handle intrinsics old codegen wants Expr's for, ourselves.
566         let intrinsic = match def {
567             Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
568             _ => None,
569         };
570
571         let extra_args = &args[sig.inputs().skip_binder().len()..];
572         let extra_args = extra_args
573             .iter()
574             .map(|op_arg| {
575                 let op_ty = op_arg.ty(self.mir, bx.tcx());
576                 self.monomorphize(&op_ty)
577             })
578             .collect::<Vec<_>>();
579
580         let fn_abi = match instance {
581             Some(instance) => FnAbi::of_instance(&bx, instance, &extra_args),
582             None => FnAbi::of_fn_ptr(&bx, sig, &extra_args),
583         };
584
585         if intrinsic == Some(sym::transmute) {
586             if let Some(destination_ref) = destination.as_ref() {
587                 let &(dest, target) = destination_ref;
588                 self.codegen_transmute(&mut bx, &args[0], dest);
589                 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
590                 helper.funclet_br(self, &mut bx, target);
591             } else {
592                 // If we are trying to transmute to an uninhabited type,
593                 // it is likely there is no allotted destination. In fact,
594                 // transmuting to an uninhabited type is UB, which means
595                 // we can do what we like. Here, we declare that transmuting
596                 // into an uninhabited type is impossible, so anything following
597                 // it must be unreachable.
598                 assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited);
599                 bx.unreachable();
600             }
601             return;
602         }
603
604         if self.codegen_panic_intrinsic(
605             &helper,
606             &mut bx,
607             intrinsic,
608             instance,
609             span,
610             destination,
611             cleanup,
612         ) {
613             return;
614         }
615
616         // The arguments we'll be passing. Plus one to account for outptr, if used.
617         let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
618         let mut llargs = Vec::with_capacity(arg_count);
619
620         // Prepare the return value destination
621         let ret_dest = if let Some((dest, _)) = *destination {
622             let is_intrinsic = intrinsic.is_some();
623             self.make_return_dest(&mut bx, dest, &fn_abi.ret, &mut llargs, is_intrinsic)
624         } else {
625             ReturnDest::Nothing
626         };
627
628         if intrinsic == Some(sym::caller_location) {
629             if let Some((_, target)) = destination.as_ref() {
630                 let location = self.get_caller_location(&mut bx, fn_span);
631
632                 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
633                     location.val.store(&mut bx, tmp);
634                 }
635                 self.store_return(&mut bx, ret_dest, &fn_abi.ret, location.immediate());
636
637                 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
638                 helper.funclet_br(self, &mut bx, *target);
639             }
640             return;
641         }
642
643         if intrinsic.is_some() && intrinsic != Some(sym::drop_in_place) {
644             let intrinsic = intrinsic.unwrap();
645             let dest = match ret_dest {
646                 _ if fn_abi.ret.is_indirect() => llargs[0],
647                 ReturnDest::Nothing => {
648                     bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
649                 }
650                 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
651                 ReturnDest::DirectOperand(_) => {
652                     bug!("Cannot use direct operand with an intrinsic call")
653                 }
654             };
655
656             let args: Vec<_> = args
657                 .iter()
658                 .enumerate()
659                 .map(|(i, arg)| {
660                     // The indices passed to simd_shuffle* in the
661                     // third argument must be constant. This is
662                     // checked by const-qualification, which also
663                     // promotes any complex rvalues to constants.
664                     if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
665                         if let mir::Operand::Constant(constant) = arg {
666                             let c = self.eval_mir_constant(constant);
667                             let (llval, ty) = self.simd_shuffle_indices(
668                                 &bx,
669                                 constant.span,
670                                 constant.literal.ty,
671                                 c,
672                             );
673                             return OperandRef { val: Immediate(llval), layout: bx.layout_of(ty) };
674                         } else {
675                             span_bug!(span, "shuffle indices must be constant");
676                         }
677                     }
678
679                     self.codegen_operand(&mut bx, arg)
680                 })
681                 .collect();
682
683             Self::codegen_intrinsic_call(
684                 &mut bx,
685                 *instance.as_ref().unwrap(),
686                 &fn_abi,
687                 &args,
688                 dest,
689                 terminator.source_info.span,
690             );
691
692             if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
693                 self.store_return(&mut bx, ret_dest, &fn_abi.ret, dst.llval);
694             }
695
696             if let Some((_, target)) = *destination {
697                 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
698                 helper.funclet_br(self, &mut bx, target);
699             } else {
700                 bx.unreachable();
701             }
702
703             return;
704         }
705
706         // Split the rust-call tupled arguments off.
707         let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
708             let (tup, args) = args.split_last().unwrap();
709             (args, Some(tup))
710         } else {
711             (&args[..], None)
712         };
713
714         'make_args: for (i, arg) in first_args.iter().enumerate() {
715             let mut op = self.codegen_operand(&mut bx, arg);
716
717             if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
718                 if let Pair(..) = op.val {
719                     // In the case of Rc<Self>, we need to explicitly pass a
720                     // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
721                     // that is understood elsewhere in the compiler as a method on
722                     // `dyn Trait`.
723                     // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
724                     // we get a value of a built-in pointer type
725                     'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
726                         && !op.layout.ty.is_region_ptr()
727                     {
728                         for i in 0..op.layout.fields.count() {
729                             let field = op.extract_field(&mut bx, i);
730                             if !field.layout.is_zst() {
731                                 // we found the one non-zero-sized field that is allowed
732                                 // now find *its* non-zero-sized field, or stop if it's a
733                                 // pointer
734                                 op = field;
735                                 continue 'descend_newtypes;
736                             }
737                         }
738
739                         span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
740                     }
741
742                     // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
743                     // data pointer and vtable. Look up the method in the vtable, and pass
744                     // the data pointer as the first argument
745                     match op.val {
746                         Pair(data_ptr, meta) => {
747                             llfn = Some(
748                                 meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi),
749                             );
750                             llargs.push(data_ptr);
751                             continue 'make_args;
752                         }
753                         other => bug!("expected a Pair, got {:?}", other),
754                     }
755                 } else if let Ref(data_ptr, Some(meta), _) = op.val {
756                     // by-value dynamic dispatch
757                     llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi));
758                     llargs.push(data_ptr);
759                     continue;
760                 } else {
761                     span_bug!(span, "can't codegen a virtual call on {:?}", op);
762                 }
763             }
764
765             // The callee needs to own the argument memory if we pass it
766             // by-ref, so make a local copy of non-immediate constants.
767             match (arg, op.val) {
768                 (&mir::Operand::Copy(_), Ref(_, None, _))
769                 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
770                     let tmp = PlaceRef::alloca(&mut bx, op.layout);
771                     op.val.store(&mut bx, tmp);
772                     op.val = Ref(tmp.llval, None, tmp.align);
773                 }
774                 _ => {}
775             }
776
777             self.codegen_argument(&mut bx, op, &mut llargs, &fn_abi.args[i]);
778         }
779         if let Some(tup) = untuple {
780             self.codegen_arguments_untupled(
781                 &mut bx,
782                 tup,
783                 &mut llargs,
784                 &fn_abi.args[first_args.len()..],
785             )
786         }
787
788         let needs_location =
789             instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
790         if needs_location {
791             assert_eq!(
792                 fn_abi.args.len(),
793                 args.len() + 1,
794                 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR",
795             );
796             let location = self.get_caller_location(&mut bx, fn_span);
797             debug!(
798                 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
799                 terminator, location, fn_span
800             );
801
802             let last_arg = fn_abi.args.last().unwrap();
803             self.codegen_argument(&mut bx, location, &mut llargs, last_arg);
804         }
805
806         let fn_ptr = match (llfn, instance) {
807             (Some(llfn), _) => llfn,
808             (None, Some(instance)) => bx.get_fn_addr(instance),
809             _ => span_bug!(span, "no llfn for call"),
810         };
811
812         if let Some((_, target)) = destination.as_ref() {
813             helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
814         }
815         helper.do_call(
816             self,
817             &mut bx,
818             fn_abi,
819             fn_ptr,
820             &llargs,
821             destination.as_ref().map(|&(_, target)| (ret_dest, target)),
822             cleanup,
823         );
824     }
825
826     fn codegen_asm_terminator(
827         &mut self,
828         helper: TerminatorCodegenHelper<'tcx>,
829         mut bx: Bx,
830         terminator: &mir::Terminator<'tcx>,
831         template: &[ast::InlineAsmTemplatePiece],
832         operands: &[mir::InlineAsmOperand<'tcx>],
833         options: ast::InlineAsmOptions,
834         line_spans: &[Span],
835         destination: Option<mir::BasicBlock>,
836     ) {
837         let span = terminator.source_info.span;
838
839         let operands: Vec<_> = operands
840             .iter()
841             .map(|op| match *op {
842                 mir::InlineAsmOperand::In { reg, ref value } => {
843                     let value = self.codegen_operand(&mut bx, value);
844                     InlineAsmOperandRef::In { reg, value }
845                 }
846                 mir::InlineAsmOperand::Out { reg, late, ref place } => {
847                     let place = place.map(|place| self.codegen_place(&mut bx, place.as_ref()));
848                     InlineAsmOperandRef::Out { reg, late, place }
849                 }
850                 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
851                     let in_value = self.codegen_operand(&mut bx, in_value);
852                     let out_place =
853                         out_place.map(|out_place| self.codegen_place(&mut bx, out_place.as_ref()));
854                     InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
855                 }
856                 mir::InlineAsmOperand::Const { ref value } => {
857                     if let mir::Operand::Constant(constant) = value {
858                         let const_value = self
859                             .eval_mir_constant(constant)
860                             .unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
861                         let ty = constant.literal.ty;
862                         let size = bx.layout_of(ty).size;
863                         let scalar = match const_value {
864                             ConstValue::Scalar(s) => s,
865                             _ => span_bug!(
866                                 span,
867                                 "expected Scalar for promoted asm const, but got {:#?}",
868                                 const_value
869                             ),
870                         };
871                         let value = scalar.assert_bits(size);
872                         let string = match ty.kind() {
873                             ty::Uint(_) => value.to_string(),
874                             ty::Int(int_ty) => {
875                                 match int_ty.normalize(bx.tcx().sess.target.ptr_width) {
876                                     ast::IntTy::I8 => (value as i8).to_string(),
877                                     ast::IntTy::I16 => (value as i16).to_string(),
878                                     ast::IntTy::I32 => (value as i32).to_string(),
879                                     ast::IntTy::I64 => (value as i64).to_string(),
880                                     ast::IntTy::I128 => (value as i128).to_string(),
881                                     ast::IntTy::Isize => unreachable!(),
882                                 }
883                             }
884                             ty::Float(ast::FloatTy::F32) => {
885                                 f32::from_bits(value as u32).to_string()
886                             }
887                             ty::Float(ast::FloatTy::F64) => {
888                                 f64::from_bits(value as u64).to_string()
889                             }
890                             _ => span_bug!(span, "asm const has bad type {}", ty),
891                         };
892                         InlineAsmOperandRef::Const { string }
893                     } else {
894                         span_bug!(span, "asm const is not a constant");
895                     }
896                 }
897                 mir::InlineAsmOperand::SymFn { ref value } => {
898                     let literal = self.monomorphize(&value.literal);
899                     if let ty::FnDef(def_id, substs) = *literal.ty.kind() {
900                         let instance = ty::Instance::resolve_for_fn_ptr(
901                             bx.tcx(),
902                             ty::ParamEnv::reveal_all(),
903                             def_id,
904                             substs,
905                         )
906                         .unwrap();
907                         InlineAsmOperandRef::SymFn { instance }
908                     } else {
909                         span_bug!(span, "invalid type for asm sym (fn)");
910                     }
911                 }
912                 mir::InlineAsmOperand::SymStatic { def_id } => {
913                     InlineAsmOperandRef::SymStatic { def_id }
914                 }
915             })
916             .collect();
917
918         bx.codegen_inline_asm(template, &operands, options, line_spans);
919
920         if let Some(target) = destination {
921             helper.funclet_br(self, &mut bx, target);
922         } else {
923             bx.unreachable();
924         }
925     }
926 }
927
928 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
929     pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
930         let mut bx = self.build_block(bb);
931         let mir = self.mir;
932         let data = &mir[bb];
933
934         debug!("codegen_block({:?}={:?})", bb, data);
935
936         for statement in &data.statements {
937             bx = self.codegen_statement(bx, statement);
938         }
939
940         self.codegen_terminator(bx, bb, data.terminator());
941     }
942
943     fn codegen_terminator(
944         &mut self,
945         mut bx: Bx,
946         bb: mir::BasicBlock,
947         terminator: &'tcx mir::Terminator<'tcx>,
948     ) {
949         debug!("codegen_terminator: {:?}", terminator);
950
951         // Create the cleanup bundle, if needed.
952         let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
953         let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
954
955         self.set_debug_loc(&mut bx, terminator.source_info);
956         match terminator.kind {
957             mir::TerminatorKind::Resume => self.codegen_resume_terminator(helper, bx),
958
959             mir::TerminatorKind::Abort => {
960                 bx.abort();
961                 // `abort` does not terminate the block, so we still need to generate
962                 // an `unreachable` terminator after it.
963                 bx.unreachable();
964             }
965
966             mir::TerminatorKind::Goto { target } => {
967                 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
968                 helper.funclet_br(self, &mut bx, target);
969             }
970
971             mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref targets } => {
972                 self.codegen_switchint_terminator(helper, bx, discr, switch_ty, targets);
973             }
974
975             mir::TerminatorKind::Return => {
976                 self.codegen_return_terminator(bx);
977             }
978
979             mir::TerminatorKind::Unreachable => {
980                 bx.unreachable();
981             }
982
983             mir::TerminatorKind::Drop { place, target, unwind } => {
984                 self.codegen_drop_terminator(helper, bx, place, target, unwind);
985             }
986
987             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
988                 self.codegen_assert_terminator(
989                     helper, bx, terminator, cond, expected, msg, target, cleanup,
990                 );
991             }
992
993             mir::TerminatorKind::DropAndReplace { .. } => {
994                 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
995             }
996
997             mir::TerminatorKind::Call {
998                 ref func,
999                 ref args,
1000                 ref destination,
1001                 cleanup,
1002                 from_hir_call: _,
1003                 fn_span,
1004             } => {
1005                 self.codegen_call_terminator(
1006                     helper,
1007                     bx,
1008                     terminator,
1009                     func,
1010                     args,
1011                     destination,
1012                     cleanup,
1013                     fn_span,
1014                 );
1015             }
1016             mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
1017                 bug!("generator ops in codegen")
1018             }
1019             mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1020                 bug!("borrowck false edges in codegen")
1021             }
1022
1023             mir::TerminatorKind::InlineAsm {
1024                 template,
1025                 ref operands,
1026                 options,
1027                 line_spans,
1028                 destination,
1029             } => {
1030                 self.codegen_asm_terminator(
1031                     helper,
1032                     bx,
1033                     terminator,
1034                     template,
1035                     operands,
1036                     options,
1037                     line_spans,
1038                     destination,
1039                 );
1040             }
1041         }
1042     }
1043
1044     fn codegen_argument(
1045         &mut self,
1046         bx: &mut Bx,
1047         op: OperandRef<'tcx, Bx::Value>,
1048         llargs: &mut Vec<Bx::Value>,
1049         arg: &ArgAbi<'tcx, Ty<'tcx>>,
1050     ) {
1051         // Fill padding with undef value, where applicable.
1052         if let Some(ty) = arg.pad {
1053             llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
1054         }
1055
1056         if arg.is_ignore() {
1057             return;
1058         }
1059
1060         if let PassMode::Pair(..) = arg.mode {
1061             match op.val {
1062                 Pair(a, b) => {
1063                     llargs.push(a);
1064                     llargs.push(b);
1065                     return;
1066                 }
1067                 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1068             }
1069         } else if arg.is_unsized_indirect() {
1070             match op.val {
1071                 Ref(a, Some(b), _) => {
1072                     llargs.push(a);
1073                     llargs.push(b);
1074                     return;
1075                 }
1076                 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1077             }
1078         }
1079
1080         // Force by-ref if we have to load through a cast pointer.
1081         let (mut llval, align, by_ref) = match op.val {
1082             Immediate(_) | Pair(..) => match arg.mode {
1083                 PassMode::Indirect(..) | PassMode::Cast(_) => {
1084                     let scratch = PlaceRef::alloca(bx, arg.layout);
1085                     op.val.store(bx, scratch);
1086                     (scratch.llval, scratch.align, true)
1087                 }
1088                 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1089             },
1090             Ref(llval, _, align) => {
1091                 if arg.is_indirect() && align < arg.layout.align.abi {
1092                     // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
1093                     // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
1094                     // have scary latent bugs around.
1095
1096                     let scratch = PlaceRef::alloca(bx, arg.layout);
1097                     base::memcpy_ty(
1098                         bx,
1099                         scratch.llval,
1100                         scratch.align,
1101                         llval,
1102                         align,
1103                         op.layout,
1104                         MemFlags::empty(),
1105                     );
1106                     (scratch.llval, scratch.align, true)
1107                 } else {
1108                     (llval, align, true)
1109                 }
1110             }
1111         };
1112
1113         if by_ref && !arg.is_indirect() {
1114             // Have to load the argument, maybe while casting it.
1115             if let PassMode::Cast(ty) = arg.mode {
1116                 let addr = bx.pointercast(llval, bx.type_ptr_to(bx.cast_backend_type(&ty)));
1117                 llval = bx.load(addr, align.min(arg.layout.align.abi));
1118             } else {
1119                 // We can't use `PlaceRef::load` here because the argument
1120                 // may have a type we don't treat as immediate, but the ABI
1121                 // used for this call is passing it by-value. In that case,
1122                 // the load would just produce `OperandValue::Ref` instead
1123                 // of the `OperandValue::Immediate` we need for the call.
1124                 llval = bx.load(llval, align);
1125                 if let abi::Abi::Scalar(ref scalar) = arg.layout.abi {
1126                     if scalar.is_bool() {
1127                         bx.range_metadata(llval, 0..2);
1128                     }
1129                 }
1130                 // We store bools as `i8` so we need to truncate to `i1`.
1131                 llval = bx.to_immediate(llval, arg.layout);
1132             }
1133         }
1134
1135         llargs.push(llval);
1136     }
1137
1138     fn codegen_arguments_untupled(
1139         &mut self,
1140         bx: &mut Bx,
1141         operand: &mir::Operand<'tcx>,
1142         llargs: &mut Vec<Bx::Value>,
1143         args: &[ArgAbi<'tcx, Ty<'tcx>>],
1144     ) {
1145         let tuple = self.codegen_operand(bx, operand);
1146
1147         // Handle both by-ref and immediate tuples.
1148         if let Ref(llval, None, align) = tuple.val {
1149             let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
1150             for i in 0..tuple.layout.fields.count() {
1151                 let field_ptr = tuple_ptr.project_field(bx, i);
1152                 let field = bx.load_operand(field_ptr);
1153                 self.codegen_argument(bx, field, llargs, &args[i]);
1154             }
1155         } else if let Ref(_, Some(_), _) = tuple.val {
1156             bug!("closure arguments must be sized")
1157         } else {
1158             // If the tuple is immediate, the elements are as well.
1159             for i in 0..tuple.layout.fields.count() {
1160                 let op = tuple.extract_field(bx, i);
1161                 self.codegen_argument(bx, op, llargs, &args[i]);
1162             }
1163         }
1164     }
1165
1166     fn get_caller_location(&mut self, bx: &mut Bx, span: Span) -> OperandRef<'tcx, Bx::Value> {
1167         self.caller_location.unwrap_or_else(|| {
1168             let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1169             let caller = bx.tcx().sess.source_map().lookup_char_pos(topmost.lo());
1170             let const_loc = bx.tcx().const_caller_location((
1171                 Symbol::intern(&caller.file.name.to_string()),
1172                 caller.line as u32,
1173                 caller.col_display as u32 + 1,
1174             ));
1175             OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1176         })
1177     }
1178
1179     fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1180         let cx = bx.cx();
1181         if let Some(slot) = self.personality_slot {
1182             slot
1183         } else {
1184             let layout = cx.layout_of(
1185                 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1186             );
1187             let slot = PlaceRef::alloca(bx, layout);
1188             self.personality_slot = Some(slot);
1189             slot
1190         }
1191     }
1192
1193     /// Returns the landing-pad wrapper around the given basic block.
1194     ///
1195     /// No-op in MSVC SEH scheme.
1196     fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> Bx::BasicBlock {
1197         if let Some(block) = self.landing_pads[target_bb] {
1198             return block;
1199         }
1200
1201         let block = self.blocks[target_bb];
1202         let landing_pad = self.landing_pad_uncached(block);
1203         self.landing_pads[target_bb] = Some(landing_pad);
1204         landing_pad
1205     }
1206
1207     fn landing_pad_uncached(&mut self, target_bb: Bx::BasicBlock) -> Bx::BasicBlock {
1208         if base::wants_msvc_seh(self.cx.sess()) {
1209             span_bug!(self.mir.span, "landing pad was not inserted?")
1210         }
1211
1212         let mut bx = self.new_block("cleanup");
1213
1214         let llpersonality = self.cx.eh_personality();
1215         let llretty = self.landing_pad_type();
1216         let lp = bx.landing_pad(llretty, llpersonality, 1);
1217         bx.set_cleanup(lp);
1218
1219         let slot = self.get_personality_slot(&mut bx);
1220         slot.storage_live(&mut bx);
1221         Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1222
1223         bx.br(target_bb);
1224         bx.llbb()
1225     }
1226
1227     fn landing_pad_type(&self) -> Bx::Type {
1228         let cx = self.cx;
1229         cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1230     }
1231
1232     fn unreachable_block(&mut self) -> Bx::BasicBlock {
1233         self.unreachable_block.unwrap_or_else(|| {
1234             let mut bx = self.new_block("unreachable");
1235             bx.unreachable();
1236             self.unreachable_block = Some(bx.llbb());
1237             bx.llbb()
1238         })
1239     }
1240
1241     pub fn new_block(&self, name: &str) -> Bx {
1242         Bx::new_block(self.cx, self.llfn, name)
1243     }
1244
1245     pub fn build_block(&self, bb: mir::BasicBlock) -> Bx {
1246         let mut bx = Bx::with_cx(self.cx);
1247         bx.position_at_end(self.blocks[bb]);
1248         bx
1249     }
1250
1251     fn make_return_dest(
1252         &mut self,
1253         bx: &mut Bx,
1254         dest: mir::Place<'tcx>,
1255         fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1256         llargs: &mut Vec<Bx::Value>,
1257         is_intrinsic: bool,
1258     ) -> ReturnDest<'tcx, Bx::Value> {
1259         // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1260         if fn_ret.is_ignore() {
1261             return ReturnDest::Nothing;
1262         }
1263         let dest = if let Some(index) = dest.as_local() {
1264             match self.locals[index] {
1265                 LocalRef::Place(dest) => dest,
1266                 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1267                 LocalRef::Operand(None) => {
1268                     // Handle temporary places, specifically `Operand` ones, as
1269                     // they don't have `alloca`s.
1270                     return if fn_ret.is_indirect() {
1271                         // Odd, but possible, case, we have an operand temporary,
1272                         // but the calling convention has an indirect return.
1273                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1274                         tmp.storage_live(bx);
1275                         llargs.push(tmp.llval);
1276                         ReturnDest::IndirectOperand(tmp, index)
1277                     } else if is_intrinsic {
1278                         // Currently, intrinsics always need a location to store
1279                         // the result, so we create a temporary `alloca` for the
1280                         // result.
1281                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1282                         tmp.storage_live(bx);
1283                         ReturnDest::IndirectOperand(tmp, index)
1284                     } else {
1285                         ReturnDest::DirectOperand(index)
1286                     };
1287                 }
1288                 LocalRef::Operand(Some(_)) => {
1289                     bug!("place local already assigned to");
1290                 }
1291             }
1292         } else {
1293             self.codegen_place(
1294                 bx,
1295                 mir::PlaceRef { local: dest.local, projection: &dest.projection },
1296             )
1297         };
1298         if fn_ret.is_indirect() {
1299             if dest.align < dest.layout.align.abi {
1300                 // Currently, MIR code generation does not create calls
1301                 // that store directly to fields of packed structs (in
1302                 // fact, the calls it creates write only to temps).
1303                 //
1304                 // If someone changes that, please update this code path
1305                 // to create a temporary.
1306                 span_bug!(self.mir.span, "can't directly store to unaligned value");
1307             }
1308             llargs.push(dest.llval);
1309             ReturnDest::Nothing
1310         } else {
1311             ReturnDest::Store(dest)
1312         }
1313     }
1314
1315     fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: mir::Place<'tcx>) {
1316         if let Some(index) = dst.as_local() {
1317             match self.locals[index] {
1318                 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1319                 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1320                 LocalRef::Operand(None) => {
1321                     let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst.as_ref()));
1322                     assert!(!dst_layout.ty.has_erasable_regions());
1323                     let place = PlaceRef::alloca(bx, dst_layout);
1324                     place.storage_live(bx);
1325                     self.codegen_transmute_into(bx, src, place);
1326                     let op = bx.load_operand(place);
1327                     place.storage_dead(bx);
1328                     self.locals[index] = LocalRef::Operand(Some(op));
1329                     self.debug_introduce_local(bx, index);
1330                 }
1331                 LocalRef::Operand(Some(op)) => {
1332                     assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
1333                 }
1334             }
1335         } else {
1336             let dst = self.codegen_place(bx, dst.as_ref());
1337             self.codegen_transmute_into(bx, src, dst);
1338         }
1339     }
1340
1341     fn codegen_transmute_into(
1342         &mut self,
1343         bx: &mut Bx,
1344         src: &mir::Operand<'tcx>,
1345         dst: PlaceRef<'tcx, Bx::Value>,
1346     ) {
1347         let src = self.codegen_operand(bx, src);
1348         let llty = bx.backend_type(src.layout);
1349         let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1350         let align = src.layout.align.abi.min(dst.align);
1351         src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1352     }
1353
1354     // Stores the return value of a function call into it's final location.
1355     fn store_return(
1356         &mut self,
1357         bx: &mut Bx,
1358         dest: ReturnDest<'tcx, Bx::Value>,
1359         ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1360         llval: Bx::Value,
1361     ) {
1362         use self::ReturnDest::*;
1363
1364         match dest {
1365             Nothing => (),
1366             Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1367             IndirectOperand(tmp, index) => {
1368                 let op = bx.load_operand(tmp);
1369                 tmp.storage_dead(bx);
1370                 self.locals[index] = LocalRef::Operand(Some(op));
1371                 self.debug_introduce_local(bx, index);
1372             }
1373             DirectOperand(index) => {
1374                 // If there is a cast, we have to store and reload.
1375                 let op = if let PassMode::Cast(_) = ret_abi.mode {
1376                     let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1377                     tmp.storage_live(bx);
1378                     bx.store_arg(&ret_abi, llval, tmp);
1379                     let op = bx.load_operand(tmp);
1380                     tmp.storage_dead(bx);
1381                     op
1382                 } else {
1383                     OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1384                 };
1385                 self.locals[index] = LocalRef::Operand(Some(op));
1386                 self.debug_introduce_local(bx, index);
1387             }
1388         }
1389     }
1390 }
1391
1392 enum ReturnDest<'tcx, V> {
1393     // Do nothing; the return value is indirect or ignored.
1394     Nothing,
1395     // Store the return value to the pointer.
1396     Store(PlaceRef<'tcx, V>),
1397     // Store an indirect return value to an operand local place.
1398     IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1399     // Store a direct return value to an operand local place.
1400     DirectOperand(mir::Local),
1401 }