]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/block.rs
Auto merge of #105812 - ojeda:no-jump-tables, r=nikic
[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::{CachedLlbb, 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_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
14 use rustc_hir::lang_items::LangItem;
15 use rustc_index::vec::Idx;
16 use rustc_middle::mir::{self, AssertKind, SwitchTargets};
17 use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf};
18 use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
19 use rustc_middle::ty::{self, Instance, Ty, TypeVisitable};
20 use rustc_session::config::OptLevel;
21 use rustc_span::source_map::Span;
22 use rustc_span::{sym, Symbol};
23 use rustc_symbol_mangling::typeid::typeid_for_fnabi;
24 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode, Reg};
25 use rustc_target::abi::{self, HasDataLayout, WrappingRange};
26 use rustc_target::spec::abi::Abi;
27
28 // Indicates if we are in the middle of merging a BB's successor into it. This
29 // can happen when BB jumps directly to its successor and the successor has no
30 // other predecessors.
31 #[derive(Debug, PartialEq)]
32 enum MergingSucc {
33     False,
34     True,
35 }
36
37 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
38 /// e.g., creating a basic block, calling a function, etc.
39 struct TerminatorCodegenHelper<'tcx> {
40     bb: mir::BasicBlock,
41     terminator: &'tcx mir::Terminator<'tcx>,
42     funclet_bb: Option<mir::BasicBlock>,
43 }
44
45 impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
46     /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
47     /// either already previously cached, or newly created, by `landing_pad_for`.
48     fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
49         &self,
50         fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
51     ) -> Option<&'b Bx::Funclet> {
52         let funclet_bb = self.funclet_bb?;
53         if base::wants_msvc_seh(fx.cx.tcx().sess) {
54             // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
55             // it has to be now. This may not seem necessary, as RPO should lead
56             // to all the unwind edges being visited (and so to `landing_pad_for`
57             // getting called for them), before building any of the blocks inside
58             // the funclet itself - however, if MIR contains edges that end up not
59             // being needed in the LLVM IR after monomorphization, the funclet may
60             // be unreachable, and we don't have yet a way to skip building it in
61             // such an eventuality (which may be a better solution than this).
62             if fx.funclets[funclet_bb].is_none() {
63                 fx.landing_pad_for(funclet_bb);
64             }
65
66             Some(
67                 fx.funclets[funclet_bb]
68                     .as_ref()
69                     .expect("landing_pad_for didn't also create funclets entry"),
70             )
71         } else {
72             None
73         }
74     }
75
76     /// Get a basic block (creating it if necessary), possibly with cleanup
77     /// stuff in it or next to it.
78     fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
79         &self,
80         fx: &mut FunctionCx<'a, 'tcx, Bx>,
81         target: mir::BasicBlock,
82     ) -> Bx::BasicBlock {
83         let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
84         let mut lltarget = fx.llbb(target);
85         if needs_landing_pad {
86             lltarget = fx.landing_pad_for(target);
87         }
88         if is_cleanupret {
89             // MSVC cross-funclet jump - need a trampoline
90             debug_assert!(base::wants_msvc_seh(fx.cx.tcx().sess));
91             debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
92             let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
93             let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
94             let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
95             trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
96             trampoline_llbb
97         } else {
98             lltarget
99         }
100     }
101
102     fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
103         &self,
104         fx: &mut FunctionCx<'a, 'tcx, Bx>,
105         target: mir::BasicBlock,
106     ) -> (bool, bool) {
107         let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
108         let (needs_landing_pad, is_cleanupret) = match (self.funclet_bb, target_funclet) {
109             (None, None) => (false, false),
110             (None, Some(_)) => (true, false),
111             (Some(_), None) => {
112                 let span = self.terminator.source_info.span;
113                 span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
114             }
115             (Some(f), Some(t_f)) => {
116                 if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) {
117                     (false, false)
118                 } else {
119                     (true, true)
120                 }
121             }
122         };
123         (needs_landing_pad, is_cleanupret)
124     }
125
126     fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
127         &self,
128         fx: &mut FunctionCx<'a, 'tcx, Bx>,
129         bx: &mut Bx,
130         target: mir::BasicBlock,
131         mergeable_succ: bool,
132     ) -> MergingSucc {
133         let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
134         if mergeable_succ && !needs_landing_pad && !is_cleanupret {
135             // We can merge the successor into this bb, so no need for a `br`.
136             MergingSucc::True
137         } else {
138             let mut lltarget = fx.llbb(target);
139             if needs_landing_pad {
140                 lltarget = fx.landing_pad_for(target);
141             }
142             if is_cleanupret {
143                 // micro-optimization: generate a `ret` rather than a jump
144                 // to a trampoline.
145                 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
146             } else {
147                 bx.br(lltarget);
148             }
149             MergingSucc::False
150         }
151     }
152
153     /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
154     /// return destination `destination` and the cleanup function `cleanup`.
155     fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
156         &self,
157         fx: &mut FunctionCx<'a, 'tcx, Bx>,
158         bx: &mut Bx,
159         fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
160         fn_ptr: Bx::Value,
161         llargs: &[Bx::Value],
162         destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
163         cleanup: Option<mir::BasicBlock>,
164         copied_constant_arguments: &[PlaceRef<'tcx, <Bx as BackendTypes>::Value>],
165         mergeable_succ: bool,
166     ) -> MergingSucc {
167         // If there is a cleanup block and the function we're calling can unwind, then
168         // do an invoke, otherwise do a call.
169         let fn_ty = bx.fn_decl_backend_type(&fn_abi);
170
171         let unwind_block = if let Some(cleanup) = cleanup.filter(|_| fn_abi.can_unwind) {
172             Some(self.llbb_with_cleanup(fx, cleanup))
173         } else if fx.mir[self.bb].is_cleanup
174             && fn_abi.can_unwind
175             && !base::wants_msvc_seh(fx.cx.tcx().sess)
176         {
177             // Exception must not propagate out of the execution of a cleanup (doing so
178             // can cause undefined behaviour). We insert a double unwind guard for
179             // functions that can potentially unwind to protect against this.
180             //
181             // This is not necessary for SEH which does not use successive unwinding
182             // like Itanium EH. EH frames in SEH are different from normal function
183             // frames and SEH will abort automatically if an exception tries to
184             // propagate out from cleanup.
185             Some(fx.double_unwind_guard())
186         } else {
187             None
188         };
189
190         if let Some(unwind_block) = unwind_block {
191             let ret_llbb = if let Some((_, target)) = destination {
192                 fx.llbb(target)
193             } else {
194                 fx.unreachable_block()
195             };
196             let invokeret = bx.invoke(
197                 fn_ty,
198                 Some(&fn_abi),
199                 fn_ptr,
200                 &llargs,
201                 ret_llbb,
202                 unwind_block,
203                 self.funclet(fx),
204             );
205             if fx.mir[self.bb].is_cleanup {
206                 bx.do_not_inline(invokeret);
207             }
208
209             if let Some((ret_dest, target)) = destination {
210                 bx.switch_to_block(fx.llbb(target));
211                 fx.set_debug_loc(bx, self.terminator.source_info);
212                 for tmp in copied_constant_arguments {
213                     bx.lifetime_end(tmp.llval, tmp.layout.size);
214                 }
215                 fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
216             }
217             MergingSucc::False
218         } else {
219             let llret = bx.call(fn_ty, Some(&fn_abi), fn_ptr, &llargs, self.funclet(fx));
220             if fx.mir[self.bb].is_cleanup {
221                 // Cleanup is always the cold path. Don't inline
222                 // drop glue. Also, when there is a deeply-nested
223                 // struct, there are "symmetry" issues that cause
224                 // exponential inlining - see issue #41696.
225                 bx.do_not_inline(llret);
226             }
227
228             if let Some((ret_dest, target)) = destination {
229                 for tmp in copied_constant_arguments {
230                     bx.lifetime_end(tmp.llval, tmp.layout.size);
231                 }
232                 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
233                 self.funclet_br(fx, bx, target, mergeable_succ)
234             } else {
235                 bx.unreachable();
236                 MergingSucc::False
237             }
238         }
239     }
240
241     /// Generates inline assembly with optional `destination` and `cleanup`.
242     fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
243         &self,
244         fx: &mut FunctionCx<'a, 'tcx, Bx>,
245         bx: &mut Bx,
246         template: &[InlineAsmTemplatePiece],
247         operands: &[InlineAsmOperandRef<'tcx, Bx>],
248         options: InlineAsmOptions,
249         line_spans: &[Span],
250         destination: Option<mir::BasicBlock>,
251         cleanup: Option<mir::BasicBlock>,
252         instance: Instance<'_>,
253         mergeable_succ: bool,
254     ) -> MergingSucc {
255         if let Some(cleanup) = cleanup {
256             let ret_llbb = if let Some(target) = destination {
257                 fx.llbb(target)
258             } else {
259                 fx.unreachable_block()
260             };
261
262             bx.codegen_inline_asm(
263                 template,
264                 &operands,
265                 options,
266                 line_spans,
267                 instance,
268                 Some((ret_llbb, self.llbb_with_cleanup(fx, cleanup), self.funclet(fx))),
269             );
270             MergingSucc::False
271         } else {
272             bx.codegen_inline_asm(template, &operands, options, line_spans, instance, None);
273
274             if let Some(target) = destination {
275                 self.funclet_br(fx, bx, target, mergeable_succ)
276             } else {
277                 bx.unreachable();
278                 MergingSucc::False
279             }
280         }
281     }
282 }
283
284 /// Codegen implementations for some terminator variants.
285 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
286     /// Generates code for a `Resume` terminator.
287     fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
288         if let Some(funclet) = helper.funclet(self) {
289             bx.cleanup_ret(funclet, None);
290         } else {
291             let slot = self.get_personality_slot(bx);
292             let exn0 = slot.project_field(bx, 0);
293             let exn0 = bx.load_operand(exn0).immediate();
294             let exn1 = slot.project_field(bx, 1);
295             let exn1 = bx.load_operand(exn1).immediate();
296             slot.storage_dead(bx);
297
298             bx.resume(exn0, exn1);
299         }
300     }
301
302     fn codegen_switchint_terminator(
303         &mut self,
304         helper: TerminatorCodegenHelper<'tcx>,
305         bx: &mut Bx,
306         discr: &mir::Operand<'tcx>,
307         targets: &SwitchTargets,
308     ) {
309         let discr = self.codegen_operand(bx, &discr);
310         let switch_ty = discr.layout.ty;
311         let mut target_iter = targets.iter();
312         if target_iter.len() == 1 {
313             // If there are two targets (one conditional, one fallback), emit `br` instead of
314             // `switch`.
315             let (test_value, target) = target_iter.next().unwrap();
316             let lltrue = helper.llbb_with_cleanup(self, target);
317             let llfalse = helper.llbb_with_cleanup(self, targets.otherwise());
318             if switch_ty == bx.tcx().types.bool {
319                 // Don't generate trivial icmps when switching on bool.
320                 match test_value {
321                     0 => bx.cond_br(discr.immediate(), llfalse, lltrue),
322                     1 => bx.cond_br(discr.immediate(), lltrue, llfalse),
323                     _ => bug!(),
324                 }
325             } else {
326                 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
327                 let llval = bx.const_uint_big(switch_llty, test_value);
328                 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
329                 bx.cond_br(cmp, lltrue, llfalse);
330             }
331         } else if self.cx.sess().opts.optimize == OptLevel::No
332             && target_iter.len() == 2
333             && self.mir[targets.otherwise()].is_empty_unreachable()
334         {
335             // In unoptimized builds, if there are two normal targets and the `otherwise` target is
336             // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
337             // BB, which will usually (but not always) be dead code.
338             //
339             // Why only in unoptimized builds?
340             // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
341             //   must fall back to the to the slower SelectionDAG isel. Therefore, using `br` gives
342             //   significant compile time speedups for unoptimized builds.
343             // - In optimized builds the above doesn't hold, and using `br` sometimes results in
344             //   worse generated code because LLVM can no longer tell that the value being switched
345             //   on can only have two values, e.g. 0 and 1.
346             //
347             let (test_value1, target1) = target_iter.next().unwrap();
348             let (_test_value2, target2) = target_iter.next().unwrap();
349             let ll1 = helper.llbb_with_cleanup(self, target1);
350             let ll2 = helper.llbb_with_cleanup(self, target2);
351             let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
352             let llval = bx.const_uint_big(switch_llty, test_value1);
353             let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
354             bx.cond_br(cmp, ll1, ll2);
355         } else {
356             bx.switch(
357                 discr.immediate(),
358                 helper.llbb_with_cleanup(self, targets.otherwise()),
359                 target_iter.map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
360             );
361         }
362     }
363
364     fn codegen_return_terminator(&mut self, bx: &mut Bx) {
365         // Call `va_end` if this is the definition of a C-variadic function.
366         if self.fn_abi.c_variadic {
367             // The `VaList` "spoofed" argument is just after all the real arguments.
368             let va_list_arg_idx = self.fn_abi.args.len();
369             match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
370                 LocalRef::Place(va_list) => {
371                     bx.va_end(va_list.llval);
372                 }
373                 _ => bug!("C-variadic function must have a `VaList` place"),
374             }
375         }
376         if self.fn_abi.ret.layout.abi.is_uninhabited() {
377             // Functions with uninhabited return values are marked `noreturn`,
378             // so we should make sure that we never actually do.
379             // We play it safe by using a well-defined `abort`, but we could go for immediate UB
380             // if that turns out to be helpful.
381             bx.abort();
382             // `abort` does not terminate the block, so we still need to generate
383             // an `unreachable` terminator after it.
384             bx.unreachable();
385             return;
386         }
387         let llval = match &self.fn_abi.ret.mode {
388             PassMode::Ignore | PassMode::Indirect { .. } => {
389                 bx.ret_void();
390                 return;
391             }
392
393             PassMode::Direct(_) | PassMode::Pair(..) => {
394                 let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
395                 if let Ref(llval, _, align) = op.val {
396                     bx.load(bx.backend_type(op.layout), llval, align)
397                 } else {
398                     op.immediate_or_packed_pair(bx)
399                 }
400             }
401
402             PassMode::Cast(cast_ty, _) => {
403                 let op = match self.locals[mir::RETURN_PLACE] {
404                     LocalRef::Operand(Some(op)) => op,
405                     LocalRef::Operand(None) => bug!("use of return before def"),
406                     LocalRef::Place(cg_place) => OperandRef {
407                         val: Ref(cg_place.llval, None, cg_place.align),
408                         layout: cg_place.layout,
409                     },
410                     LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
411                 };
412                 let llslot = match op.val {
413                     Immediate(_) | Pair(..) => {
414                         let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
415                         op.val.store(bx, scratch);
416                         scratch.llval
417                     }
418                     Ref(llval, _, align) => {
419                         assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
420                         llval
421                     }
422                 };
423                 let ty = bx.cast_backend_type(cast_ty);
424                 let addr = bx.pointercast(llslot, bx.type_ptr_to(ty));
425                 bx.load(ty, addr, self.fn_abi.ret.layout.align.abi)
426             }
427         };
428         bx.ret(llval);
429     }
430
431     #[tracing::instrument(level = "trace", skip(self, helper, bx))]
432     fn codegen_drop_terminator(
433         &mut self,
434         helper: TerminatorCodegenHelper<'tcx>,
435         bx: &mut Bx,
436         location: mir::Place<'tcx>,
437         target: mir::BasicBlock,
438         unwind: Option<mir::BasicBlock>,
439         mergeable_succ: bool,
440     ) -> MergingSucc {
441         let ty = location.ty(self.mir, bx.tcx()).ty;
442         let ty = self.monomorphize(ty);
443         let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
444
445         if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
446             // we don't actually need to drop anything.
447             return helper.funclet_br(self, bx, target, mergeable_succ);
448         }
449
450         let place = self.codegen_place(bx, location.as_ref());
451         let (args1, args2);
452         let mut args = if let Some(llextra) = place.llextra {
453             args2 = [place.llval, llextra];
454             &args2[..]
455         } else {
456             args1 = [place.llval];
457             &args1[..]
458         };
459         let (drop_fn, fn_abi) = match ty.kind() {
460             // FIXME(eddyb) perhaps move some of this logic into
461             // `Instance::resolve_drop_in_place`?
462             ty::Dynamic(_, _, ty::Dyn) => {
463                 // IN THIS ARM, WE HAVE:
464                 // ty = *mut (dyn Trait)
465                 // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
466                 //                       args[0]    args[1]
467                 //
468                 // args = ( Data, Vtable )
469                 //                  |
470                 //                  v
471                 //                /-------\
472                 //                | ...   |
473                 //                \-------/
474                 //
475                 let virtual_drop = Instance {
476                     def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
477                     substs: drop_fn.substs,
478                 };
479                 debug!("ty = {:?}", ty);
480                 debug!("drop_fn = {:?}", drop_fn);
481                 debug!("args = {:?}", args);
482                 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
483                 let vtable = args[1];
484                 // Truncate vtable off of args list
485                 args = &args[..1];
486                 (
487                     meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
488                         .get_fn(bx, vtable, ty, &fn_abi),
489                     fn_abi,
490                 )
491             }
492             ty::Dynamic(_, _, ty::DynStar) => {
493                 // IN THIS ARM, WE HAVE:
494                 // ty = *mut (dyn* Trait)
495                 // which is: *mut exists<T: sizeof(T) == sizeof(usize)> (T, Vtable<T: Trait>)
496                 //
497                 // args = [ * ]
498                 //          |
499                 //          v
500                 //      ( Data, Vtable )
501                 //                |
502                 //                v
503                 //              /-------\
504                 //              | ...   |
505                 //              \-------/
506                 //
507                 //
508                 // WE CAN CONVERT THIS INTO THE ABOVE LOGIC BY DOING
509                 //
510                 // data = &(*args[0]).0    // gives a pointer to Data above (really the same pointer)
511                 // vtable = (*args[0]).1   // loads the vtable out
512                 // (data, vtable)          // an equivalent Rust `*mut dyn Trait`
513                 //
514                 // SO THEN WE CAN USE THE ABOVE CODE.
515                 let virtual_drop = Instance {
516                     def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
517                     substs: drop_fn.substs,
518                 };
519                 debug!("ty = {:?}", ty);
520                 debug!("drop_fn = {:?}", drop_fn);
521                 debug!("args = {:?}", args);
522                 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
523                 let data = args[0];
524                 let data_ty = bx.cx().backend_type(place.layout);
525                 let vtable_ptr =
526                     bx.gep(data_ty, data, &[bx.cx().const_i32(0), bx.cx().const_i32(1)]);
527                 let vtable = bx.load(bx.type_i8p(), vtable_ptr, abi::Align::ONE);
528                 // Truncate vtable off of args list
529                 args = &args[..1];
530                 debug!("args' = {:?}", args);
531                 (
532                     meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
533                         .get_fn(bx, vtable, ty, &fn_abi),
534                     fn_abi,
535                 )
536             }
537             _ => (bx.get_fn_addr(drop_fn), bx.fn_abi_of_instance(drop_fn, ty::List::empty())),
538         };
539         helper.do_call(
540             self,
541             bx,
542             fn_abi,
543             drop_fn,
544             args,
545             Some((ReturnDest::Nothing, target)),
546             unwind,
547             &[],
548             mergeable_succ,
549         )
550     }
551
552     fn codegen_assert_terminator(
553         &mut self,
554         helper: TerminatorCodegenHelper<'tcx>,
555         bx: &mut Bx,
556         terminator: &mir::Terminator<'tcx>,
557         cond: &mir::Operand<'tcx>,
558         expected: bool,
559         msg: &mir::AssertMessage<'tcx>,
560         target: mir::BasicBlock,
561         cleanup: Option<mir::BasicBlock>,
562         mergeable_succ: bool,
563     ) -> MergingSucc {
564         let span = terminator.source_info.span;
565         let cond = self.codegen_operand(bx, cond).immediate();
566         let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
567
568         // This case can currently arise only from functions marked
569         // with #[rustc_inherit_overflow_checks] and inlined from
570         // another crate (mostly core::num generic/#[inline] fns),
571         // while the current crate doesn't use overflow checks.
572         // NOTE: Unlike binops, negation doesn't have its own
573         // checked operation, just a comparison with the minimum
574         // value, so we have to check for the assert message.
575         if !bx.check_overflow() {
576             if let AssertKind::OverflowNeg(_) = *msg {
577                 const_cond = Some(expected);
578             }
579         }
580
581         // Don't codegen the panic block if success if known.
582         if const_cond == Some(expected) {
583             return helper.funclet_br(self, bx, target, mergeable_succ);
584         }
585
586         // Pass the condition through llvm.expect for branch hinting.
587         let cond = bx.expect(cond, expected);
588
589         // Create the failure block and the conditional branch to it.
590         let lltarget = helper.llbb_with_cleanup(self, target);
591         let panic_block = bx.append_sibling_block("panic");
592         if expected {
593             bx.cond_br(cond, lltarget, panic_block);
594         } else {
595             bx.cond_br(cond, panic_block, lltarget);
596         }
597
598         // After this point, bx is the block for the call to panic.
599         bx.switch_to_block(panic_block);
600         self.set_debug_loc(bx, terminator.source_info);
601
602         // Get the location information.
603         let location = self.get_caller_location(bx, terminator.source_info).immediate();
604
605         // Put together the arguments to the panic entry point.
606         let (lang_item, args) = match msg {
607             AssertKind::BoundsCheck { ref len, ref index } => {
608                 let len = self.codegen_operand(bx, len).immediate();
609                 let index = self.codegen_operand(bx, index).immediate();
610                 // It's `fn panic_bounds_check(index: usize, len: usize)`,
611                 // and `#[track_caller]` adds an implicit third argument.
612                 (LangItem::PanicBoundsCheck, vec![index, len, location])
613             }
614             _ => {
615                 let msg = bx.const_str(msg.description());
616                 // It's `pub fn panic(expr: &str)`, with the wide reference being passed
617                 // as two arguments, and `#[track_caller]` adds an implicit third argument.
618                 (LangItem::Panic, vec![msg.0, msg.1, location])
619             }
620         };
621
622         let (fn_abi, llfn) = common::build_langcall(bx, Some(span), lang_item);
623
624         // Codegen the actual panic invoke/call.
625         let merging_succ = helper.do_call(self, bx, fn_abi, llfn, &args, None, cleanup, &[], false);
626         assert_eq!(merging_succ, MergingSucc::False);
627         MergingSucc::False
628     }
629
630     fn codegen_abort_terminator(
631         &mut self,
632         helper: TerminatorCodegenHelper<'tcx>,
633         bx: &mut Bx,
634         terminator: &mir::Terminator<'tcx>,
635     ) {
636         let span = terminator.source_info.span;
637         self.set_debug_loc(bx, terminator.source_info);
638
639         // Obtain the panic entry point.
640         let (fn_abi, llfn) = common::build_langcall(bx, Some(span), LangItem::PanicNoUnwind);
641
642         // Codegen the actual panic invoke/call.
643         let merging_succ = helper.do_call(self, bx, fn_abi, llfn, &[], None, None, &[], false);
644         assert_eq!(merging_succ, MergingSucc::False);
645     }
646
647     /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
648     fn codegen_panic_intrinsic(
649         &mut self,
650         helper: &TerminatorCodegenHelper<'tcx>,
651         bx: &mut Bx,
652         intrinsic: Option<Symbol>,
653         instance: Option<Instance<'tcx>>,
654         source_info: mir::SourceInfo,
655         target: Option<mir::BasicBlock>,
656         cleanup: Option<mir::BasicBlock>,
657         mergeable_succ: bool,
658     ) -> Option<MergingSucc> {
659         // Emit a panic or a no-op for `assert_*` intrinsics.
660         // These are intrinsics that compile to panics so that we can get a message
661         // which mentions the offending type, even from a const context.
662         #[derive(Debug, PartialEq)]
663         enum AssertIntrinsic {
664             Inhabited,
665             ZeroValid,
666             UninitValid,
667         }
668         let panic_intrinsic = intrinsic.and_then(|i| match i {
669             sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
670             sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
671             sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid),
672             _ => None,
673         });
674         if let Some(intrinsic) = panic_intrinsic {
675             use AssertIntrinsic::*;
676
677             let ty = instance.unwrap().substs.type_at(0);
678             let layout = bx.layout_of(ty);
679             let do_panic = match intrinsic {
680                 Inhabited => layout.abi.is_uninhabited(),
681                 ZeroValid => !bx.tcx().permits_zero_init(layout),
682                 UninitValid => !bx.tcx().permits_uninit_init(layout),
683             };
684             Some(if do_panic {
685                 let msg_str = with_no_visible_paths!({
686                     with_no_trimmed_paths!({
687                         if layout.abi.is_uninhabited() {
688                             // Use this error even for the other intrinsics as it is more precise.
689                             format!("attempted to instantiate uninhabited type `{}`", ty)
690                         } else if intrinsic == ZeroValid {
691                             format!("attempted to zero-initialize type `{}`, which is invalid", ty)
692                         } else {
693                             format!(
694                                 "attempted to leave type `{}` uninitialized, which is invalid",
695                                 ty
696                             )
697                         }
698                     })
699                 });
700                 let msg = bx.const_str(&msg_str);
701                 let location = self.get_caller_location(bx, source_info).immediate();
702
703                 // Obtain the panic entry point.
704                 let (fn_abi, llfn) =
705                     common::build_langcall(bx, Some(source_info.span), LangItem::Panic);
706
707                 // Codegen the actual panic invoke/call.
708                 helper.do_call(
709                     self,
710                     bx,
711                     fn_abi,
712                     llfn,
713                     &[msg.0, msg.1, location],
714                     target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
715                     cleanup,
716                     &[],
717                     mergeable_succ,
718                 )
719             } else {
720                 // a NOP
721                 let target = target.unwrap();
722                 helper.funclet_br(self, bx, target, mergeable_succ)
723             })
724         } else {
725             None
726         }
727     }
728
729     fn codegen_call_terminator(
730         &mut self,
731         helper: TerminatorCodegenHelper<'tcx>,
732         bx: &mut Bx,
733         terminator: &mir::Terminator<'tcx>,
734         func: &mir::Operand<'tcx>,
735         args: &[mir::Operand<'tcx>],
736         destination: mir::Place<'tcx>,
737         target: Option<mir::BasicBlock>,
738         cleanup: Option<mir::BasicBlock>,
739         fn_span: Span,
740         mergeable_succ: bool,
741     ) -> MergingSucc {
742         let source_info = terminator.source_info;
743         let span = source_info.span;
744
745         // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
746         let callee = self.codegen_operand(bx, func);
747
748         let (instance, mut llfn) = match *callee.layout.ty.kind() {
749             ty::FnDef(def_id, substs) => (
750                 Some(
751                     ty::Instance::expect_resolve(
752                         bx.tcx(),
753                         ty::ParamEnv::reveal_all(),
754                         def_id,
755                         substs,
756                     )
757                     .polymorphize(bx.tcx()),
758                 ),
759                 None,
760             ),
761             ty::FnPtr(_) => (None, Some(callee.immediate())),
762             _ => bug!("{} is not callable", callee.layout.ty),
763         };
764         let def = instance.map(|i| i.def);
765
766         if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
767             // Empty drop glue; a no-op.
768             let target = target.unwrap();
769             return helper.funclet_br(self, bx, target, mergeable_succ);
770         }
771
772         // FIXME(eddyb) avoid computing this if possible, when `instance` is
773         // available - right now `sig` is only needed for getting the `abi`
774         // and figuring out how many extra args were passed to a C-variadic `fn`.
775         let sig = callee.layout.ty.fn_sig(bx.tcx());
776         let abi = sig.abi();
777
778         // Handle intrinsics old codegen wants Expr's for, ourselves.
779         let intrinsic = match def {
780             Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
781             _ => None,
782         };
783
784         let extra_args = &args[sig.inputs().skip_binder().len()..];
785         let extra_args = bx.tcx().mk_type_list(extra_args.iter().map(|op_arg| {
786             let op_ty = op_arg.ty(self.mir, bx.tcx());
787             self.monomorphize(op_ty)
788         }));
789
790         let fn_abi = match instance {
791             Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
792             None => bx.fn_abi_of_fn_ptr(sig, extra_args),
793         };
794
795         if intrinsic == Some(sym::transmute) {
796             return if let Some(target) = target {
797                 self.codegen_transmute(bx, &args[0], destination);
798                 helper.funclet_br(self, bx, target, mergeable_succ)
799             } else {
800                 // If we are trying to transmute to an uninhabited type,
801                 // it is likely there is no allotted destination. In fact,
802                 // transmuting to an uninhabited type is UB, which means
803                 // we can do what we like. Here, we declare that transmuting
804                 // into an uninhabited type is impossible, so anything following
805                 // it must be unreachable.
806                 assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited);
807                 bx.unreachable();
808                 MergingSucc::False
809             };
810         }
811
812         if let Some(merging_succ) = self.codegen_panic_intrinsic(
813             &helper,
814             bx,
815             intrinsic,
816             instance,
817             source_info,
818             target,
819             cleanup,
820             mergeable_succ,
821         ) {
822             return merging_succ;
823         }
824
825         // The arguments we'll be passing. Plus one to account for outptr, if used.
826         let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
827         let mut llargs = Vec::with_capacity(arg_count);
828
829         // Prepare the return value destination
830         let ret_dest = if target.is_some() {
831             let is_intrinsic = intrinsic.is_some();
832             self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs, is_intrinsic)
833         } else {
834             ReturnDest::Nothing
835         };
836
837         if intrinsic == Some(sym::caller_location) {
838             return if let Some(target) = target {
839                 let location =
840                     self.get_caller_location(bx, mir::SourceInfo { span: fn_span, ..source_info });
841
842                 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
843                     location.val.store(bx, tmp);
844                 }
845                 self.store_return(bx, ret_dest, &fn_abi.ret, location.immediate());
846                 helper.funclet_br(self, bx, target, mergeable_succ)
847             } else {
848                 MergingSucc::False
849             };
850         }
851
852         match intrinsic {
853             None | Some(sym::drop_in_place) => {}
854             Some(sym::copy_nonoverlapping) => unreachable!(),
855             Some(intrinsic) => {
856                 let dest = match ret_dest {
857                     _ if fn_abi.ret.is_indirect() => llargs[0],
858                     ReturnDest::Nothing => {
859                         bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
860                     }
861                     ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
862                     ReturnDest::DirectOperand(_) => {
863                         bug!("Cannot use direct operand with an intrinsic call")
864                     }
865                 };
866
867                 let args: Vec<_> = args
868                     .iter()
869                     .enumerate()
870                     .map(|(i, arg)| {
871                         // The indices passed to simd_shuffle* in the
872                         // third argument must be constant. This is
873                         // checked by const-qualification, which also
874                         // promotes any complex rvalues to constants.
875                         if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
876                             if let mir::Operand::Constant(constant) = arg {
877                                 let c = self.eval_mir_constant(constant);
878                                 let (llval, ty) = self.simd_shuffle_indices(
879                                     &bx,
880                                     constant.span,
881                                     self.monomorphize(constant.ty()),
882                                     c,
883                                 );
884                                 return OperandRef {
885                                     val: Immediate(llval),
886                                     layout: bx.layout_of(ty),
887                                 };
888                             } else {
889                                 span_bug!(span, "shuffle indices must be constant");
890                             }
891                         }
892
893                         self.codegen_operand(bx, arg)
894                     })
895                     .collect();
896
897                 Self::codegen_intrinsic_call(
898                     bx,
899                     *instance.as_ref().unwrap(),
900                     &fn_abi,
901                     &args,
902                     dest,
903                     span,
904                 );
905
906                 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
907                     self.store_return(bx, ret_dest, &fn_abi.ret, dst.llval);
908                 }
909
910                 return if let Some(target) = target {
911                     helper.funclet_br(self, bx, target, mergeable_succ)
912                 } else {
913                     bx.unreachable();
914                     MergingSucc::False
915                 };
916             }
917         }
918
919         // Split the rust-call tupled arguments off.
920         let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
921             let (tup, args) = args.split_last().unwrap();
922             (args, Some(tup))
923         } else {
924             (args, None)
925         };
926
927         let mut copied_constant_arguments = vec![];
928         'make_args: for (i, arg) in first_args.iter().enumerate() {
929             let mut op = self.codegen_operand(bx, arg);
930
931             if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
932                 match op.val {
933                     Pair(data_ptr, meta) => {
934                         // In the case of Rc<Self>, we need to explicitly pass a
935                         // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
936                         // that is understood elsewhere in the compiler as a method on
937                         // `dyn Trait`.
938                         // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
939                         // we get a value of a built-in pointer type.
940                         //
941                         // This is also relevant for `Pin<&mut Self>`, where we need to peel the `Pin`.
942                         'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
943                             && !op.layout.ty.is_region_ptr()
944                         {
945                             for i in 0..op.layout.fields.count() {
946                                 let field = op.extract_field(bx, i);
947                                 if !field.layout.is_zst() {
948                                     // we found the one non-zero-sized field that is allowed
949                                     // now find *its* non-zero-sized field, or stop if it's a
950                                     // pointer
951                                     op = field;
952                                     continue 'descend_newtypes;
953                                 }
954                             }
955
956                             span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
957                         }
958
959                         // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
960                         // data pointer and vtable. Look up the method in the vtable, and pass
961                         // the data pointer as the first argument
962                         llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
963                             bx,
964                             meta,
965                             op.layout.ty,
966                             &fn_abi,
967                         ));
968                         llargs.push(data_ptr);
969                         continue 'make_args;
970                     }
971                     Ref(data_ptr, Some(meta), _) => {
972                         // by-value dynamic dispatch
973                         llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
974                             bx,
975                             meta,
976                             op.layout.ty,
977                             &fn_abi,
978                         ));
979                         llargs.push(data_ptr);
980                         continue;
981                     }
982                     Immediate(_) => {
983                         // See comment above explaining why we peel these newtypes
984                         'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
985                             && !op.layout.ty.is_region_ptr()
986                         {
987                             for i in 0..op.layout.fields.count() {
988                                 let field = op.extract_field(bx, i);
989                                 if !field.layout.is_zst() {
990                                     // we found the one non-zero-sized field that is allowed
991                                     // now find *its* non-zero-sized field, or stop if it's a
992                                     // pointer
993                                     op = field;
994                                     continue 'descend_newtypes;
995                                 }
996                             }
997
998                             span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
999                         }
1000
1001                         // Make sure that we've actually unwrapped the rcvr down
1002                         // to a pointer or ref to `dyn* Trait`.
1003                         if !op.layout.ty.builtin_deref(true).unwrap().ty.is_dyn_star() {
1004                             span_bug!(span, "can't codegen a virtual call on {:#?}", op);
1005                         }
1006                         let place = op.deref(bx.cx());
1007                         let data_ptr = place.project_field(bx, 0);
1008                         let meta_ptr = place.project_field(bx, 1);
1009                         let meta = bx.load_operand(meta_ptr);
1010                         llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1011                             bx,
1012                             meta.immediate(),
1013                             op.layout.ty,
1014                             &fn_abi,
1015                         ));
1016                         llargs.push(data_ptr.llval);
1017                         continue;
1018                     }
1019                     _ => {
1020                         span_bug!(span, "can't codegen a virtual call on {:#?}", op);
1021                     }
1022                 }
1023             }
1024
1025             // The callee needs to own the argument memory if we pass it
1026             // by-ref, so make a local copy of non-immediate constants.
1027             match (arg, op.val) {
1028                 (&mir::Operand::Copy(_), Ref(_, None, _))
1029                 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
1030                     let tmp = PlaceRef::alloca(bx, op.layout);
1031                     bx.lifetime_start(tmp.llval, tmp.layout.size);
1032                     op.val.store(bx, tmp);
1033                     op.val = Ref(tmp.llval, None, tmp.align);
1034                     copied_constant_arguments.push(tmp);
1035                 }
1036                 _ => {}
1037             }
1038
1039             self.codegen_argument(bx, op, &mut llargs, &fn_abi.args[i]);
1040         }
1041         let num_untupled = untuple.map(|tup| {
1042             self.codegen_arguments_untupled(bx, tup, &mut llargs, &fn_abi.args[first_args.len()..])
1043         });
1044
1045         let needs_location =
1046             instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
1047         if needs_location {
1048             let mir_args = if let Some(num_untupled) = num_untupled {
1049                 first_args.len() + num_untupled
1050             } else {
1051                 args.len()
1052             };
1053             assert_eq!(
1054                 fn_abi.args.len(),
1055                 mir_args + 1,
1056                 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {:?} {:?} {:?}",
1057                 instance,
1058                 fn_span,
1059                 fn_abi,
1060             );
1061             let location =
1062                 self.get_caller_location(bx, mir::SourceInfo { span: fn_span, ..source_info });
1063             debug!(
1064                 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1065                 terminator, location, fn_span
1066             );
1067
1068             let last_arg = fn_abi.args.last().unwrap();
1069             self.codegen_argument(bx, location, &mut llargs, last_arg);
1070         }
1071
1072         let (is_indirect_call, fn_ptr) = match (llfn, instance) {
1073             (Some(llfn), _) => (true, llfn),
1074             (None, Some(instance)) => (false, bx.get_fn_addr(instance)),
1075             _ => span_bug!(span, "no llfn for call"),
1076         };
1077
1078         // For backends that support CFI using type membership (i.e., testing whether a given
1079         // pointer is associated with a type identifier).
1080         if bx.tcx().sess.is_sanitizer_cfi_enabled() && is_indirect_call {
1081             // Emit type metadata and checks.
1082             // FIXME(rcvalle): Add support for generalized identifiers.
1083             // FIXME(rcvalle): Create distinct unnamed MDNodes for internal identifiers.
1084             let typeid = typeid_for_fnabi(bx.tcx(), fn_abi);
1085             let typeid_metadata = self.cx.typeid_metadata(typeid);
1086
1087             // Test whether the function pointer is associated with the type identifier.
1088             let cond = bx.type_test(fn_ptr, typeid_metadata);
1089             let bb_pass = bx.append_sibling_block("type_test.pass");
1090             let bb_fail = bx.append_sibling_block("type_test.fail");
1091             bx.cond_br(cond, bb_pass, bb_fail);
1092
1093             bx.switch_to_block(bb_pass);
1094             let merging_succ = helper.do_call(
1095                 self,
1096                 bx,
1097                 fn_abi,
1098                 fn_ptr,
1099                 &llargs,
1100                 target.as_ref().map(|&target| (ret_dest, target)),
1101                 cleanup,
1102                 &copied_constant_arguments,
1103                 false,
1104             );
1105             assert_eq!(merging_succ, MergingSucc::False);
1106
1107             bx.switch_to_block(bb_fail);
1108             bx.abort();
1109             bx.unreachable();
1110
1111             return MergingSucc::False;
1112         }
1113
1114         helper.do_call(
1115             self,
1116             bx,
1117             fn_abi,
1118             fn_ptr,
1119             &llargs,
1120             target.as_ref().map(|&target| (ret_dest, target)),
1121             cleanup,
1122             &copied_constant_arguments,
1123             mergeable_succ,
1124         )
1125     }
1126
1127     fn codegen_asm_terminator(
1128         &mut self,
1129         helper: TerminatorCodegenHelper<'tcx>,
1130         bx: &mut Bx,
1131         terminator: &mir::Terminator<'tcx>,
1132         template: &[ast::InlineAsmTemplatePiece],
1133         operands: &[mir::InlineAsmOperand<'tcx>],
1134         options: ast::InlineAsmOptions,
1135         line_spans: &[Span],
1136         destination: Option<mir::BasicBlock>,
1137         cleanup: Option<mir::BasicBlock>,
1138         instance: Instance<'_>,
1139         mergeable_succ: bool,
1140     ) -> MergingSucc {
1141         let span = terminator.source_info.span;
1142
1143         let operands: Vec<_> = operands
1144             .iter()
1145             .map(|op| match *op {
1146                 mir::InlineAsmOperand::In { reg, ref value } => {
1147                     let value = self.codegen_operand(bx, value);
1148                     InlineAsmOperandRef::In { reg, value }
1149                 }
1150                 mir::InlineAsmOperand::Out { reg, late, ref place } => {
1151                     let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1152                     InlineAsmOperandRef::Out { reg, late, place }
1153                 }
1154                 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1155                     let in_value = self.codegen_operand(bx, in_value);
1156                     let out_place =
1157                         out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1158                     InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1159                 }
1160                 mir::InlineAsmOperand::Const { ref value } => {
1161                     let const_value = self
1162                         .eval_mir_constant(value)
1163                         .unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
1164                     let string = common::asm_const_to_str(
1165                         bx.tcx(),
1166                         span,
1167                         const_value,
1168                         bx.layout_of(value.ty()),
1169                     );
1170                     InlineAsmOperandRef::Const { string }
1171                 }
1172                 mir::InlineAsmOperand::SymFn { ref value } => {
1173                     let literal = self.monomorphize(value.literal);
1174                     if let ty::FnDef(def_id, substs) = *literal.ty().kind() {
1175                         let instance = ty::Instance::resolve_for_fn_ptr(
1176                             bx.tcx(),
1177                             ty::ParamEnv::reveal_all(),
1178                             def_id,
1179                             substs,
1180                         )
1181                         .unwrap();
1182                         InlineAsmOperandRef::SymFn { instance }
1183                     } else {
1184                         span_bug!(span, "invalid type for asm sym (fn)");
1185                     }
1186                 }
1187                 mir::InlineAsmOperand::SymStatic { def_id } => {
1188                     InlineAsmOperandRef::SymStatic { def_id }
1189                 }
1190             })
1191             .collect();
1192
1193         helper.do_inlineasm(
1194             self,
1195             bx,
1196             template,
1197             &operands,
1198             options,
1199             line_spans,
1200             destination,
1201             cleanup,
1202             instance,
1203             mergeable_succ,
1204         )
1205     }
1206 }
1207
1208 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1209     pub fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1210         let llbb = match self.try_llbb(bb) {
1211             Some(llbb) => llbb,
1212             None => return,
1213         };
1214         let bx = &mut Bx::build(self.cx, llbb);
1215         let mir = self.mir;
1216
1217         // MIR basic blocks stop at any function call. This may not be the case
1218         // for the backend's basic blocks, in which case we might be able to
1219         // combine multiple MIR basic blocks into a single backend basic block.
1220         loop {
1221             let data = &mir[bb];
1222
1223             debug!("codegen_block({:?}={:?})", bb, data);
1224
1225             for statement in &data.statements {
1226                 self.codegen_statement(bx, statement);
1227             }
1228
1229             let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1230             if let MergingSucc::False = merging_succ {
1231                 break;
1232             }
1233
1234             // We are merging the successor into the produced backend basic
1235             // block. Record that the successor should be skipped when it is
1236             // reached.
1237             //
1238             // Note: we must not have already generated code for the successor.
1239             // This is implicitly ensured by the reverse postorder traversal,
1240             // and the assertion explicitly guarantees that.
1241             let mut successors = data.terminator().successors();
1242             let succ = successors.next().unwrap();
1243             assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1244             self.cached_llbbs[succ] = CachedLlbb::Skip;
1245             bb = succ;
1246         }
1247     }
1248
1249     fn codegen_terminator(
1250         &mut self,
1251         bx: &mut Bx,
1252         bb: mir::BasicBlock,
1253         terminator: &'tcx mir::Terminator<'tcx>,
1254     ) -> MergingSucc {
1255         debug!("codegen_terminator: {:?}", terminator);
1256
1257         // Create the cleanup bundle, if needed.
1258         let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
1259         let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
1260
1261         let mergeable_succ = || {
1262             // Note: any call to `switch_to_block` will invalidate a `true` value
1263             // of `mergeable_succ`.
1264             let mut successors = terminator.successors();
1265             if let Some(succ) = successors.next()
1266                 && successors.next().is_none()
1267                 && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1268             {
1269                 // bb has a single successor, and bb is its only predecessor. This
1270                 // makes it a candidate for merging.
1271                 assert_eq!(succ_pred, bb);
1272                 true
1273             } else {
1274                 false
1275             }
1276         };
1277
1278         self.set_debug_loc(bx, terminator.source_info);
1279         match terminator.kind {
1280             mir::TerminatorKind::Resume => {
1281                 self.codegen_resume_terminator(helper, bx);
1282                 MergingSucc::False
1283             }
1284
1285             mir::TerminatorKind::Abort => {
1286                 self.codegen_abort_terminator(helper, bx, terminator);
1287                 MergingSucc::False
1288             }
1289
1290             mir::TerminatorKind::Goto { target } => {
1291                 helper.funclet_br(self, bx, target, mergeable_succ())
1292             }
1293
1294             mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1295                 self.codegen_switchint_terminator(helper, bx, discr, targets);
1296                 MergingSucc::False
1297             }
1298
1299             mir::TerminatorKind::Return => {
1300                 self.codegen_return_terminator(bx);
1301                 MergingSucc::False
1302             }
1303
1304             mir::TerminatorKind::Unreachable => {
1305                 bx.unreachable();
1306                 MergingSucc::False
1307             }
1308
1309             mir::TerminatorKind::Drop { place, target, unwind } => {
1310                 self.codegen_drop_terminator(helper, bx, place, target, unwind, mergeable_succ())
1311             }
1312
1313             mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => self
1314                 .codegen_assert_terminator(
1315                     helper,
1316                     bx,
1317                     terminator,
1318                     cond,
1319                     expected,
1320                     msg,
1321                     target,
1322                     cleanup,
1323                     mergeable_succ(),
1324                 ),
1325
1326             mir::TerminatorKind::DropAndReplace { .. } => {
1327                 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
1328             }
1329
1330             mir::TerminatorKind::Call {
1331                 ref func,
1332                 ref args,
1333                 destination,
1334                 target,
1335                 cleanup,
1336                 from_hir_call: _,
1337                 fn_span,
1338             } => self.codegen_call_terminator(
1339                 helper,
1340                 bx,
1341                 terminator,
1342                 func,
1343                 args,
1344                 destination,
1345                 target,
1346                 cleanup,
1347                 fn_span,
1348                 mergeable_succ(),
1349             ),
1350             mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
1351                 bug!("generator ops in codegen")
1352             }
1353             mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1354                 bug!("borrowck false edges in codegen")
1355             }
1356
1357             mir::TerminatorKind::InlineAsm {
1358                 template,
1359                 ref operands,
1360                 options,
1361                 line_spans,
1362                 destination,
1363                 cleanup,
1364             } => self.codegen_asm_terminator(
1365                 helper,
1366                 bx,
1367                 terminator,
1368                 template,
1369                 operands,
1370                 options,
1371                 line_spans,
1372                 destination,
1373                 cleanup,
1374                 self.instance,
1375                 mergeable_succ(),
1376             ),
1377         }
1378     }
1379
1380     fn codegen_argument(
1381         &mut self,
1382         bx: &mut Bx,
1383         op: OperandRef<'tcx, Bx::Value>,
1384         llargs: &mut Vec<Bx::Value>,
1385         arg: &ArgAbi<'tcx, Ty<'tcx>>,
1386     ) {
1387         match arg.mode {
1388             PassMode::Ignore => return,
1389             PassMode::Cast(_, true) => {
1390                 // Fill padding with undef value, where applicable.
1391                 llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1392             }
1393             PassMode::Pair(..) => match op.val {
1394                 Pair(a, b) => {
1395                     llargs.push(a);
1396                     llargs.push(b);
1397                     return;
1398                 }
1399                 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1400             },
1401             PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => match op.val {
1402                 Ref(a, Some(b), _) => {
1403                     llargs.push(a);
1404                     llargs.push(b);
1405                     return;
1406                 }
1407                 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1408             },
1409             _ => {}
1410         }
1411
1412         // Force by-ref if we have to load through a cast pointer.
1413         let (mut llval, align, by_ref) = match op.val {
1414             Immediate(_) | Pair(..) => match arg.mode {
1415                 PassMode::Indirect { .. } | PassMode::Cast(..) => {
1416                     let scratch = PlaceRef::alloca(bx, arg.layout);
1417                     op.val.store(bx, scratch);
1418                     (scratch.llval, scratch.align, true)
1419                 }
1420                 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1421             },
1422             Ref(llval, _, align) => {
1423                 if arg.is_indirect() && align < arg.layout.align.abi {
1424                     // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
1425                     // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
1426                     // have scary latent bugs around.
1427
1428                     let scratch = PlaceRef::alloca(bx, arg.layout);
1429                     base::memcpy_ty(
1430                         bx,
1431                         scratch.llval,
1432                         scratch.align,
1433                         llval,
1434                         align,
1435                         op.layout,
1436                         MemFlags::empty(),
1437                     );
1438                     (scratch.llval, scratch.align, true)
1439                 } else {
1440                     (llval, align, true)
1441                 }
1442             }
1443         };
1444
1445         if by_ref && !arg.is_indirect() {
1446             // Have to load the argument, maybe while casting it.
1447             if let PassMode::Cast(ty, _) = &arg.mode {
1448                 let llty = bx.cast_backend_type(ty);
1449                 let addr = bx.pointercast(llval, bx.type_ptr_to(llty));
1450                 llval = bx.load(llty, addr, align.min(arg.layout.align.abi));
1451             } else {
1452                 // We can't use `PlaceRef::load` here because the argument
1453                 // may have a type we don't treat as immediate, but the ABI
1454                 // used for this call is passing it by-value. In that case,
1455                 // the load would just produce `OperandValue::Ref` instead
1456                 // of the `OperandValue::Immediate` we need for the call.
1457                 llval = bx.load(bx.backend_type(arg.layout), llval, align);
1458                 if let abi::Abi::Scalar(scalar) = arg.layout.abi {
1459                     if scalar.is_bool() {
1460                         bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1461                     }
1462                 }
1463                 // We store bools as `i8` so we need to truncate to `i1`.
1464                 llval = bx.to_immediate(llval, arg.layout);
1465             }
1466         }
1467
1468         llargs.push(llval);
1469     }
1470
1471     fn codegen_arguments_untupled(
1472         &mut self,
1473         bx: &mut Bx,
1474         operand: &mir::Operand<'tcx>,
1475         llargs: &mut Vec<Bx::Value>,
1476         args: &[ArgAbi<'tcx, Ty<'tcx>>],
1477     ) -> usize {
1478         let tuple = self.codegen_operand(bx, operand);
1479
1480         // Handle both by-ref and immediate tuples.
1481         if let Ref(llval, None, align) = tuple.val {
1482             let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
1483             for i in 0..tuple.layout.fields.count() {
1484                 let field_ptr = tuple_ptr.project_field(bx, i);
1485                 let field = bx.load_operand(field_ptr);
1486                 self.codegen_argument(bx, field, llargs, &args[i]);
1487             }
1488         } else if let Ref(_, Some(_), _) = tuple.val {
1489             bug!("closure arguments must be sized")
1490         } else {
1491             // If the tuple is immediate, the elements are as well.
1492             for i in 0..tuple.layout.fields.count() {
1493                 let op = tuple.extract_field(bx, i);
1494                 self.codegen_argument(bx, op, llargs, &args[i]);
1495             }
1496         }
1497         tuple.layout.fields.count()
1498     }
1499
1500     fn get_caller_location(
1501         &mut self,
1502         bx: &mut Bx,
1503         mut source_info: mir::SourceInfo,
1504     ) -> OperandRef<'tcx, Bx::Value> {
1505         let tcx = bx.tcx();
1506
1507         let mut span_to_caller_location = |span: Span| {
1508             let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1509             let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo());
1510             let const_loc = tcx.const_caller_location((
1511                 Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()),
1512                 caller.line as u32,
1513                 caller.col_display as u32 + 1,
1514             ));
1515             OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1516         };
1517
1518         // Walk up the `SourceScope`s, in case some of them are from MIR inlining.
1519         // If so, the starting `source_info.span` is in the innermost inlined
1520         // function, and will be replaced with outer callsite spans as long
1521         // as the inlined functions were `#[track_caller]`.
1522         loop {
1523             let scope_data = &self.mir.source_scopes[source_info.scope];
1524
1525             if let Some((callee, callsite_span)) = scope_data.inlined {
1526                 // Stop inside the most nested non-`#[track_caller]` function,
1527                 // before ever reaching its caller (which is irrelevant).
1528                 if !callee.def.requires_caller_location(tcx) {
1529                     return span_to_caller_location(source_info.span);
1530                 }
1531                 source_info.span = callsite_span;
1532             }
1533
1534             // Skip past all of the parents with `inlined: None`.
1535             match scope_data.inlined_parent_scope {
1536                 Some(parent) => source_info.scope = parent,
1537                 None => break,
1538             }
1539         }
1540
1541         // No inlined `SourceScope`s, or all of them were `#[track_caller]`.
1542         self.caller_location.unwrap_or_else(|| span_to_caller_location(source_info.span))
1543     }
1544
1545     fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1546         let cx = bx.cx();
1547         if let Some(slot) = self.personality_slot {
1548             slot
1549         } else {
1550             let layout = cx.layout_of(
1551                 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1552             );
1553             let slot = PlaceRef::alloca(bx, layout);
1554             self.personality_slot = Some(slot);
1555             slot
1556         }
1557     }
1558
1559     /// Returns the landing/cleanup pad wrapper around the given basic block.
1560     // FIXME(eddyb) rename this to `eh_pad_for`.
1561     fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1562         if let Some(landing_pad) = self.landing_pads[bb] {
1563             return landing_pad;
1564         }
1565
1566         let landing_pad = self.landing_pad_for_uncached(bb);
1567         self.landing_pads[bb] = Some(landing_pad);
1568         landing_pad
1569     }
1570
1571     // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
1572     fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1573         let llbb = self.llbb(bb);
1574         if base::wants_msvc_seh(self.cx.sess()) {
1575             let funclet;
1576             let ret_llbb;
1577             match self.mir[bb].terminator.as_ref().map(|t| &t.kind) {
1578                 // This is a basic block that we're aborting the program for,
1579                 // notably in an `extern` function. These basic blocks are inserted
1580                 // so that we assert that `extern` functions do indeed not panic,
1581                 // and if they do we abort the process.
1582                 //
1583                 // On MSVC these are tricky though (where we're doing funclets). If
1584                 // we were to do a cleanuppad (like below) the normal functions like
1585                 // `longjmp` would trigger the abort logic, terminating the
1586                 // program. Instead we insert the equivalent of `catch(...)` for C++
1587                 // which magically doesn't trigger when `longjmp` files over this
1588                 // frame.
1589                 //
1590                 // Lots more discussion can be found on #48251 but this codegen is
1591                 // modeled after clang's for:
1592                 //
1593                 //      try {
1594                 //          foo();
1595                 //      } catch (...) {
1596                 //          bar();
1597                 //      }
1598                 Some(&mir::TerminatorKind::Abort) => {
1599                     let cs_llbb =
1600                         Bx::append_block(self.cx, self.llfn, &format!("cs_funclet{:?}", bb));
1601                     let cp_llbb =
1602                         Bx::append_block(self.cx, self.llfn, &format!("cp_funclet{:?}", bb));
1603                     ret_llbb = cs_llbb;
1604
1605                     let mut cs_bx = Bx::build(self.cx, cs_llbb);
1606                     let cs = cs_bx.catch_switch(None, None, &[cp_llbb]);
1607
1608                     // The "null" here is actually a RTTI type descriptor for the
1609                     // C++ personality function, but `catch (...)` has no type so
1610                     // it's null. The 64 here is actually a bitfield which
1611                     // represents that this is a catch-all block.
1612                     let mut cp_bx = Bx::build(self.cx, cp_llbb);
1613                     let null = cp_bx.const_null(
1614                         cp_bx.type_i8p_ext(cp_bx.cx().data_layout().instruction_address_space),
1615                     );
1616                     let sixty_four = cp_bx.const_i32(64);
1617                     funclet = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
1618                     cp_bx.br(llbb);
1619                 }
1620                 _ => {
1621                     let cleanup_llbb =
1622                         Bx::append_block(self.cx, self.llfn, &format!("funclet_{:?}", bb));
1623                     ret_llbb = cleanup_llbb;
1624                     let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1625                     funclet = cleanup_bx.cleanup_pad(None, &[]);
1626                     cleanup_bx.br(llbb);
1627                 }
1628             }
1629             self.funclets[bb] = Some(funclet);
1630             ret_llbb
1631         } else {
1632             let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1633             let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1634
1635             let llpersonality = self.cx.eh_personality();
1636             let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
1637
1638             let slot = self.get_personality_slot(&mut cleanup_bx);
1639             slot.storage_live(&mut cleanup_bx);
1640             Pair(exn0, exn1).store(&mut cleanup_bx, slot);
1641
1642             cleanup_bx.br(llbb);
1643             cleanup_llbb
1644         }
1645     }
1646
1647     fn unreachable_block(&mut self) -> Bx::BasicBlock {
1648         self.unreachable_block.unwrap_or_else(|| {
1649             let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1650             let mut bx = Bx::build(self.cx, llbb);
1651             bx.unreachable();
1652             self.unreachable_block = Some(llbb);
1653             llbb
1654         })
1655     }
1656
1657     fn double_unwind_guard(&mut self) -> Bx::BasicBlock {
1658         self.double_unwind_guard.unwrap_or_else(|| {
1659             assert!(!base::wants_msvc_seh(self.cx.sess()));
1660
1661             let llbb = Bx::append_block(self.cx, self.llfn, "abort");
1662             let mut bx = Bx::build(self.cx, llbb);
1663             self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
1664
1665             let llpersonality = self.cx.eh_personality();
1666             bx.cleanup_landing_pad(llpersonality);
1667
1668             let (fn_abi, fn_ptr) = common::build_langcall(&bx, None, LangItem::PanicNoUnwind);
1669             let fn_ty = bx.fn_decl_backend_type(&fn_abi);
1670
1671             let llret = bx.call(fn_ty, Some(&fn_abi), fn_ptr, &[], None);
1672             bx.do_not_inline(llret);
1673
1674             bx.unreachable();
1675
1676             self.double_unwind_guard = Some(llbb);
1677             llbb
1678         })
1679     }
1680
1681     /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
1682     /// cached in `self.cached_llbbs`, or created on demand (and cached).
1683     // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
1684     // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
1685     pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1686         self.try_llbb(bb).unwrap()
1687     }
1688
1689     /// Like `llbb`, but may fail if the basic block should be skipped.
1690     pub fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
1691         match self.cached_llbbs[bb] {
1692             CachedLlbb::None => {
1693                 // FIXME(eddyb) only name the block if `fewer_names` is `false`.
1694                 let llbb = Bx::append_block(self.cx, self.llfn, &format!("{:?}", bb));
1695                 self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
1696                 Some(llbb)
1697             }
1698             CachedLlbb::Some(llbb) => Some(llbb),
1699             CachedLlbb::Skip => None,
1700         }
1701     }
1702
1703     fn make_return_dest(
1704         &mut self,
1705         bx: &mut Bx,
1706         dest: mir::Place<'tcx>,
1707         fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1708         llargs: &mut Vec<Bx::Value>,
1709         is_intrinsic: bool,
1710     ) -> ReturnDest<'tcx, Bx::Value> {
1711         // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1712         if fn_ret.is_ignore() {
1713             return ReturnDest::Nothing;
1714         }
1715         let dest = if let Some(index) = dest.as_local() {
1716             match self.locals[index] {
1717                 LocalRef::Place(dest) => dest,
1718                 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1719                 LocalRef::Operand(None) => {
1720                     // Handle temporary places, specifically `Operand` ones, as
1721                     // they don't have `alloca`s.
1722                     return if fn_ret.is_indirect() {
1723                         // Odd, but possible, case, we have an operand temporary,
1724                         // but the calling convention has an indirect return.
1725                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1726                         tmp.storage_live(bx);
1727                         llargs.push(tmp.llval);
1728                         ReturnDest::IndirectOperand(tmp, index)
1729                     } else if is_intrinsic {
1730                         // Currently, intrinsics always need a location to store
1731                         // the result, so we create a temporary `alloca` for the
1732                         // result.
1733                         let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1734                         tmp.storage_live(bx);
1735                         ReturnDest::IndirectOperand(tmp, index)
1736                     } else {
1737                         ReturnDest::DirectOperand(index)
1738                     };
1739                 }
1740                 LocalRef::Operand(Some(_)) => {
1741                     bug!("place local already assigned to");
1742                 }
1743             }
1744         } else {
1745             self.codegen_place(
1746                 bx,
1747                 mir::PlaceRef { local: dest.local, projection: &dest.projection },
1748             )
1749         };
1750         if fn_ret.is_indirect() {
1751             if dest.align < dest.layout.align.abi {
1752                 // Currently, MIR code generation does not create calls
1753                 // that store directly to fields of packed structs (in
1754                 // fact, the calls it creates write only to temps).
1755                 //
1756                 // If someone changes that, please update this code path
1757                 // to create a temporary.
1758                 span_bug!(self.mir.span, "can't directly store to unaligned value");
1759             }
1760             llargs.push(dest.llval);
1761             ReturnDest::Nothing
1762         } else {
1763             ReturnDest::Store(dest)
1764         }
1765     }
1766
1767     fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: mir::Place<'tcx>) {
1768         if let Some(index) = dst.as_local() {
1769             match self.locals[index] {
1770                 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1771                 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1772                 LocalRef::Operand(None) => {
1773                     let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst.as_ref()));
1774                     assert!(!dst_layout.ty.has_erasable_regions());
1775                     let place = PlaceRef::alloca(bx, dst_layout);
1776                     place.storage_live(bx);
1777                     self.codegen_transmute_into(bx, src, place);
1778                     let op = bx.load_operand(place);
1779                     place.storage_dead(bx);
1780                     self.locals[index] = LocalRef::Operand(Some(op));
1781                     self.debug_introduce_local(bx, index);
1782                 }
1783                 LocalRef::Operand(Some(op)) => {
1784                     assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
1785                 }
1786             }
1787         } else {
1788             let dst = self.codegen_place(bx, dst.as_ref());
1789             self.codegen_transmute_into(bx, src, dst);
1790         }
1791     }
1792
1793     fn codegen_transmute_into(
1794         &mut self,
1795         bx: &mut Bx,
1796         src: &mir::Operand<'tcx>,
1797         dst: PlaceRef<'tcx, Bx::Value>,
1798     ) {
1799         let src = self.codegen_operand(bx, src);
1800
1801         // Special-case transmutes between scalars as simple bitcasts.
1802         match (src.layout.abi, dst.layout.abi) {
1803             (abi::Abi::Scalar(src_scalar), abi::Abi::Scalar(dst_scalar)) => {
1804                 // HACK(eddyb) LLVM doesn't like `bitcast`s between pointers and non-pointers.
1805                 let src_is_ptr = src_scalar.primitive() == abi::Pointer;
1806                 let dst_is_ptr = dst_scalar.primitive() == abi::Pointer;
1807                 if src_is_ptr == dst_is_ptr {
1808                     assert_eq!(src.layout.size, dst.layout.size);
1809
1810                     // NOTE(eddyb) the `from_immediate` and `to_immediate_scalar`
1811                     // conversions allow handling `bool`s the same as `u8`s.
1812                     let src = bx.from_immediate(src.immediate());
1813                     // LLVM also doesn't like `bitcast`s between pointers in different address spaces.
1814                     let src_as_dst = if src_is_ptr {
1815                         bx.pointercast(src, bx.backend_type(dst.layout))
1816                     } else {
1817                         bx.bitcast(src, bx.backend_type(dst.layout))
1818                     };
1819                     Immediate(bx.to_immediate_scalar(src_as_dst, dst_scalar)).store(bx, dst);
1820                     return;
1821                 }
1822             }
1823             _ => {}
1824         }
1825
1826         let llty = bx.backend_type(src.layout);
1827         let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1828         let align = src.layout.align.abi.min(dst.align);
1829         src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1830     }
1831
1832     // Stores the return value of a function call into it's final location.
1833     fn store_return(
1834         &mut self,
1835         bx: &mut Bx,
1836         dest: ReturnDest<'tcx, Bx::Value>,
1837         ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1838         llval: Bx::Value,
1839     ) {
1840         use self::ReturnDest::*;
1841
1842         match dest {
1843             Nothing => (),
1844             Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1845             IndirectOperand(tmp, index) => {
1846                 let op = bx.load_operand(tmp);
1847                 tmp.storage_dead(bx);
1848                 self.locals[index] = LocalRef::Operand(Some(op));
1849                 self.debug_introduce_local(bx, index);
1850             }
1851             DirectOperand(index) => {
1852                 // If there is a cast, we have to store and reload.
1853                 let op = if let PassMode::Cast(..) = ret_abi.mode {
1854                     let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1855                     tmp.storage_live(bx);
1856                     bx.store_arg(&ret_abi, llval, tmp);
1857                     let op = bx.load_operand(tmp);
1858                     tmp.storage_dead(bx);
1859                     op
1860                 } else {
1861                     OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1862                 };
1863                 self.locals[index] = LocalRef::Operand(Some(op));
1864                 self.debug_introduce_local(bx, index);
1865             }
1866         }
1867     }
1868 }
1869
1870 enum ReturnDest<'tcx, V> {
1871     // Do nothing; the return value is indirect or ignored.
1872     Nothing,
1873     // Store the return value to the pointer.
1874     Store(PlaceRef<'tcx, V>),
1875     // Store an indirect return value to an operand local place.
1876     IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1877     // Store a direct return value to an operand local place.
1878     DirectOperand(mir::Local),
1879 }