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