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