rustc_codegen_ssa/mir/
block.rs

1use std::cmp;
2
3use rustc_abi::{Align, BackendRepr, ExternAbi, HasDataLayout, Reg, Size, WrappingRange};
4use rustc_ast as ast;
5use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
6use rustc_data_structures::packed::Pu128;
7use rustc_hir::lang_items::LangItem;
8use rustc_lint_defs::builtin::TAIL_CALL_TRACK_CALLER;
9use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
10use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
11use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
12use rustc_middle::ty::{self, Instance, Ty};
13use rustc_middle::{bug, span_bug};
14use rustc_session::config::OptLevel;
15use rustc_span::Span;
16use rustc_span::source_map::Spanned;
17use rustc_target::callconv::{ArgAbi, CastTarget, FnAbi, PassMode};
18use tracing::{debug, info};
19
20use super::operand::OperandRef;
21use super::operand::OperandValue::{Immediate, Pair, Ref, ZeroSized};
22use super::place::{PlaceRef, PlaceValue};
23use super::{CachedLlbb, FunctionCx, LocalRef};
24use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization};
25use crate::common::{self, IntPredicate};
26use crate::errors::CompilerBuiltinsCannotCall;
27use crate::traits::*;
28use crate::{MemFlags, meth};
29
30// Indicates if we are in the middle of merging a BB's successor into it. This
31// can happen when BB jumps directly to its successor and the successor has no
32// other predecessors.
33#[derive(Debug, PartialEq)]
34enum MergingSucc {
35    False,
36    True,
37}
38
39/// Indicates to the call terminator codegen whether a call
40/// is a normal call or an explicit tail call.
41#[derive(Debug, PartialEq)]
42enum CallKind {
43    Normal,
44    Tail,
45}
46
47/// Used by `FunctionCx::codegen_terminator` for emitting common patterns
48/// e.g., creating a basic block, calling a function, etc.
49struct TerminatorCodegenHelper<'tcx> {
50    bb: mir::BasicBlock,
51    terminator: &'tcx mir::Terminator<'tcx>,
52}
53
54impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
55    /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
56    /// either already previously cached, or newly created, by `landing_pad_for`.
57    fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
58        &self,
59        fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
60    ) -> Option<&'b Bx::Funclet> {
61        let cleanup_kinds = fx.cleanup_kinds.as_ref()?;
62        let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?;
63        // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
64        // it has to be now. This may not seem necessary, as RPO should lead
65        // to all the unwind edges being visited (and so to `landing_pad_for`
66        // getting called for them), before building any of the blocks inside
67        // the funclet itself - however, if MIR contains edges that end up not
68        // being needed in the LLVM IR after monomorphization, the funclet may
69        // be unreachable, and we don't have yet a way to skip building it in
70        // such an eventuality (which may be a better solution than this).
71        if fx.funclets[funclet_bb].is_none() {
72            fx.landing_pad_for(funclet_bb);
73        }
74        Some(
75            fx.funclets[funclet_bb]
76                .as_ref()
77                .expect("landing_pad_for didn't also create funclets entry"),
78        )
79    }
80
81    /// Get a basic block (creating it if necessary), possibly with cleanup
82    /// stuff in it or next to it.
83    fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
84        &self,
85        fx: &mut FunctionCx<'a, 'tcx, Bx>,
86        target: mir::BasicBlock,
87    ) -> Bx::BasicBlock {
88        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
89        let mut lltarget = fx.llbb(target);
90        if needs_landing_pad {
91            lltarget = fx.landing_pad_for(target);
92        }
93        if is_cleanupret {
94            // Cross-funclet jump - need a trampoline
95            assert!(base::wants_new_eh_instructions(fx.cx.tcx().sess));
96            debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
97            let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
98            let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
99            let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
100            trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
101            trampoline_llbb
102        } else {
103            lltarget
104        }
105    }
106
107    fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
108        &self,
109        fx: &mut FunctionCx<'a, 'tcx, Bx>,
110        target: mir::BasicBlock,
111    ) -> (bool, bool) {
112        if let Some(ref cleanup_kinds) = fx.cleanup_kinds {
113            let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb);
114            let target_funclet = cleanup_kinds[target].funclet_bb(target);
115            let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) {
116                (None, None) => (false, false),
117                (None, Some(_)) => (true, false),
118                (Some(f), Some(t_f)) => (f != t_f, f != t_f),
119                (Some(_), None) => {
120                    let span = self.terminator.source_info.span;
121                    span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
122                }
123            };
124            (needs_landing_pad, is_cleanupret)
125        } else {
126            let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup;
127            let is_cleanupret = false;
128            (needs_landing_pad, is_cleanupret)
129        }
130    }
131
132    fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
133        &self,
134        fx: &mut FunctionCx<'a, 'tcx, Bx>,
135        bx: &mut Bx,
136        target: mir::BasicBlock,
137        mergeable_succ: bool,
138    ) -> MergingSucc {
139        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
140        if mergeable_succ && !needs_landing_pad && !is_cleanupret {
141            // We can merge the successor into this bb, so no need for a `br`.
142            MergingSucc::True
143        } else {
144            let mut lltarget = fx.llbb(target);
145            if needs_landing_pad {
146                lltarget = fx.landing_pad_for(target);
147            }
148            if is_cleanupret {
149                // micro-optimization: generate a `ret` rather than a jump
150                // to a trampoline.
151                bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
152            } else {
153                bx.br(lltarget);
154            }
155            MergingSucc::False
156        }
157    }
158
159    /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
160    /// return destination `destination` and the unwind action `unwind`.
161    fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
162        &self,
163        fx: &mut FunctionCx<'a, 'tcx, Bx>,
164        bx: &mut Bx,
165        fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
166        fn_ptr: Bx::Value,
167        llargs: &[Bx::Value],
168        destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
169        mut unwind: mir::UnwindAction,
170        lifetime_ends_after_call: &[(Bx::Value, Size)],
171        instance: Option<Instance<'tcx>>,
172        kind: CallKind,
173        mergeable_succ: bool,
174    ) -> MergingSucc {
175        let tcx = bx.tcx();
176        if let Some(instance) = instance
177            && is_call_from_compiler_builtins_to_upstream_monomorphization(tcx, instance)
178        {
179            if destination.is_some() {
180                let caller_def = fx.instance.def_id();
181                let e = CompilerBuiltinsCannotCall {
182                    span: tcx.def_span(caller_def),
183                    caller: with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
184                    callee: with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
185                };
186                tcx.dcx().emit_err(e);
187            } else {
188                info!(
189                    "compiler_builtins call to diverging function {:?} replaced with abort",
190                    instance.def_id()
191                );
192                bx.abort();
193                bx.unreachable();
194                return MergingSucc::False;
195            }
196        }
197
198        // If there is a cleanup block and the function we're calling can unwind, then
199        // do an invoke, otherwise do a call.
200        let fn_ty = bx.fn_decl_backend_type(fn_abi);
201
202        let fn_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() {
203            Some(bx.tcx().codegen_instance_attrs(fx.instance.def))
204        } else {
205            None
206        };
207        let fn_attrs = fn_attrs.as_deref();
208
209        if !fn_abi.can_unwind {
210            unwind = mir::UnwindAction::Unreachable;
211        }
212
213        let unwind_block = match unwind {
214            mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
215            mir::UnwindAction::Continue => None,
216            mir::UnwindAction::Unreachable => None,
217            mir::UnwindAction::Terminate(reason) => {
218                if fx.mir[self.bb].is_cleanup && base::wants_new_eh_instructions(fx.cx.tcx().sess) {
219                    // MSVC SEH will abort automatically if an exception tries to
220                    // propagate out from cleanup.
221
222                    // FIXME(@mirkootter): For wasm, we currently do not support terminate during
223                    // cleanup, because this requires a few more changes: The current code
224                    // caches the `terminate_block` for each function; funclet based code - however -
225                    // requires a different terminate_block for each funclet
226                    // Until this is implemented, we just do not unwind inside cleanup blocks
227
228                    None
229                } else {
230                    Some(fx.terminate_block(reason))
231                }
232            }
233        };
234
235        if kind == CallKind::Tail {
236            bx.tail_call(fn_ty, fn_attrs, fn_abi, fn_ptr, llargs, self.funclet(fx), instance);
237            return MergingSucc::False;
238        }
239
240        if let Some(unwind_block) = unwind_block {
241            let ret_llbb = if let Some((_, target)) = destination {
242                fx.llbb(target)
243            } else {
244                fx.unreachable_block()
245            };
246            let invokeret = bx.invoke(
247                fn_ty,
248                fn_attrs,
249                Some(fn_abi),
250                fn_ptr,
251                llargs,
252                ret_llbb,
253                unwind_block,
254                self.funclet(fx),
255                instance,
256            );
257            if fx.mir[self.bb].is_cleanup {
258                bx.apply_attrs_to_cleanup_callsite(invokeret);
259            }
260
261            if let Some((ret_dest, target)) = destination {
262                bx.switch_to_block(fx.llbb(target));
263                fx.set_debug_loc(bx, self.terminator.source_info);
264                for &(tmp, size) in lifetime_ends_after_call {
265                    bx.lifetime_end(tmp, size);
266                }
267                fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
268            }
269            MergingSucc::False
270        } else {
271            let llret =
272                bx.call(fn_ty, fn_attrs, Some(fn_abi), fn_ptr, llargs, self.funclet(fx), instance);
273            if fx.mir[self.bb].is_cleanup {
274                bx.apply_attrs_to_cleanup_callsite(llret);
275            }
276
277            if let Some((ret_dest, target)) = destination {
278                for &(tmp, size) in lifetime_ends_after_call {
279                    bx.lifetime_end(tmp, size);
280                }
281                fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
282                self.funclet_br(fx, bx, target, mergeable_succ)
283            } else {
284                bx.unreachable();
285                MergingSucc::False
286            }
287        }
288    }
289
290    /// Generates inline assembly with optional `destination` and `unwind`.
291    fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
292        &self,
293        fx: &mut FunctionCx<'a, 'tcx, Bx>,
294        bx: &mut Bx,
295        template: &[InlineAsmTemplatePiece],
296        operands: &[InlineAsmOperandRef<'tcx, Bx>],
297        options: InlineAsmOptions,
298        line_spans: &[Span],
299        destination: Option<mir::BasicBlock>,
300        unwind: mir::UnwindAction,
301        instance: Instance<'_>,
302        mergeable_succ: bool,
303    ) -> MergingSucc {
304        let unwind_target = match unwind {
305            mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
306            mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason)),
307            mir::UnwindAction::Continue => None,
308            mir::UnwindAction::Unreachable => None,
309        };
310
311        if operands.iter().any(|x| matches!(x, InlineAsmOperandRef::Label { .. })) {
312            assert!(unwind_target.is_none());
313            let ret_llbb = if let Some(target) = destination {
314                fx.llbb(target)
315            } else {
316                fx.unreachable_block()
317            };
318
319            bx.codegen_inline_asm(
320                template,
321                operands,
322                options,
323                line_spans,
324                instance,
325                Some(ret_llbb),
326                None,
327            );
328            MergingSucc::False
329        } else if let Some(cleanup) = unwind_target {
330            let ret_llbb = if let Some(target) = destination {
331                fx.llbb(target)
332            } else {
333                fx.unreachable_block()
334            };
335
336            bx.codegen_inline_asm(
337                template,
338                operands,
339                options,
340                line_spans,
341                instance,
342                Some(ret_llbb),
343                Some((cleanup, self.funclet(fx))),
344            );
345            MergingSucc::False
346        } else {
347            bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
348
349            if let Some(target) = destination {
350                self.funclet_br(fx, bx, target, mergeable_succ)
351            } else {
352                bx.unreachable();
353                MergingSucc::False
354            }
355        }
356    }
357}
358
359/// Codegen implementations for some terminator variants.
360impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
361    /// Generates code for a `Resume` terminator.
362    fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
363        if let Some(funclet) = helper.funclet(self) {
364            bx.cleanup_ret(funclet, None);
365        } else {
366            let slot = self.get_personality_slot(bx);
367            let exn0 = slot.project_field(bx, 0);
368            let exn0 = bx.load_operand(exn0).immediate();
369            let exn1 = slot.project_field(bx, 1);
370            let exn1 = bx.load_operand(exn1).immediate();
371            slot.storage_dead(bx);
372
373            bx.resume(exn0, exn1);
374        }
375    }
376
377    fn codegen_switchint_terminator(
378        &mut self,
379        helper: TerminatorCodegenHelper<'tcx>,
380        bx: &mut Bx,
381        discr: &mir::Operand<'tcx>,
382        targets: &SwitchTargets,
383    ) {
384        let discr = self.codegen_operand(bx, discr);
385        let discr_value = discr.immediate();
386        let switch_ty = discr.layout.ty;
387        // If our discriminant is a constant we can branch directly
388        if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
389            let target = targets.target_for_value(const_discr);
390            bx.br(helper.llbb_with_cleanup(self, target));
391            return;
392        };
393
394        let mut target_iter = targets.iter();
395        if target_iter.len() == 1 {
396            // If there are two targets (one conditional, one fallback), emit `br` instead of
397            // `switch`.
398            let (test_value, target) = target_iter.next().unwrap();
399            let otherwise = targets.otherwise();
400            let lltarget = helper.llbb_with_cleanup(self, target);
401            let llotherwise = helper.llbb_with_cleanup(self, otherwise);
402            let target_cold = self.cold_blocks[target];
403            let otherwise_cold = self.cold_blocks[otherwise];
404            // If `target_cold == otherwise_cold`, the branches have the same weight
405            // so there is no expectation. If they differ, the `target` branch is expected
406            // when the `otherwise` branch is cold.
407            let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
408            if switch_ty == bx.tcx().types.bool {
409                // Don't generate trivial icmps when switching on bool.
410                match test_value {
411                    0 => {
412                        let expect = expect.map(|e| !e);
413                        bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
414                    }
415                    1 => {
416                        bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
417                    }
418                    _ => bug!(),
419                }
420            } else {
421                let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
422                let llval = bx.const_uint_big(switch_llty, test_value);
423                let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
424                bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
425            }
426        } else if target_iter.len() == 2
427            && self.mir[targets.otherwise()].is_empty_unreachable()
428            && targets.all_values().contains(&Pu128(0))
429            && targets.all_values().contains(&Pu128(1))
430        {
431            // This is the really common case for `bool`, `Option`, etc.
432            // By using `trunc nuw` we communicate that other values are
433            // impossible without needing `switch` or `assume`s.
434            let true_bb = targets.target_for_value(1);
435            let false_bb = targets.target_for_value(0);
436            let true_ll = helper.llbb_with_cleanup(self, true_bb);
437            let false_ll = helper.llbb_with_cleanup(self, false_bb);
438
439            let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
440                None
441            } else {
442                match (self.cold_blocks[true_bb], self.cold_blocks[false_bb]) {
443                    // Same coldness, no expectation
444                    (true, true) | (false, false) => None,
445                    // Different coldness, expect the non-cold one
446                    (true, false) => Some(false),
447                    (false, true) => Some(true),
448                }
449            };
450
451            let bool_ty = bx.tcx().types.bool;
452            let cond = if switch_ty == bool_ty {
453                discr_value
454            } else {
455                let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
456                bx.unchecked_utrunc(discr_value, bool_llty)
457            };
458            bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
459        } else if self.cx.sess().opts.optimize == OptLevel::No
460            && target_iter.len() == 2
461            && self.mir[targets.otherwise()].is_empty_unreachable()
462        {
463            // In unoptimized builds, if there are two normal targets and the `otherwise` target is
464            // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
465            // BB, which will usually (but not always) be dead code.
466            //
467            // Why only in unoptimized builds?
468            // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
469            //   must fall back to the slower SelectionDAG isel. Therefore, using `br` gives
470            //   significant compile time speedups for unoptimized builds.
471            // - In optimized builds the above doesn't hold, and using `br` sometimes results in
472            //   worse generated code because LLVM can no longer tell that the value being switched
473            //   on can only have two values, e.g. 0 and 1.
474            //
475            let (test_value1, target1) = target_iter.next().unwrap();
476            let (_test_value2, target2) = target_iter.next().unwrap();
477            let ll1 = helper.llbb_with_cleanup(self, target1);
478            let ll2 = helper.llbb_with_cleanup(self, target2);
479            let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
480            let llval = bx.const_uint_big(switch_llty, test_value1);
481            let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
482            bx.cond_br(cmp, ll1, ll2);
483        } else {
484            let otherwise = targets.otherwise();
485            let otherwise_cold = self.cold_blocks[otherwise];
486            let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
487            let cold_count = targets.iter().filter(|(_, target)| self.cold_blocks[*target]).count();
488            let none_cold = cold_count == 0;
489            let all_cold = cold_count == targets.iter().len();
490            if (none_cold && (!otherwise_cold || otherwise_unreachable))
491                || (all_cold && (otherwise_cold || otherwise_unreachable))
492            {
493                // All targets have the same weight,
494                // or `otherwise` is unreachable and it's the only target with a different weight.
495                bx.switch(
496                    discr_value,
497                    helper.llbb_with_cleanup(self, targets.otherwise()),
498                    target_iter
499                        .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
500                );
501            } else {
502                // Targets have different weights
503                bx.switch_with_weights(
504                    discr_value,
505                    helper.llbb_with_cleanup(self, targets.otherwise()),
506                    otherwise_cold,
507                    target_iter.map(|(value, target)| {
508                        (value, helper.llbb_with_cleanup(self, target), self.cold_blocks[target])
509                    }),
510                );
511            }
512        }
513    }
514
515    fn codegen_return_terminator(&mut self, bx: &mut Bx) {
516        // Call `va_end` if this is the definition of a C-variadic function.
517        if self.fn_abi.c_variadic {
518            // The `VaList` "spoofed" argument is just after all the real arguments.
519            let va_list_arg_idx = self.fn_abi.args.len();
520            match self.locals[mir::Local::from_usize(1 + va_list_arg_idx)] {
521                LocalRef::Place(va_list) => {
522                    bx.va_end(va_list.val.llval);
523
524                    // Explicitly end the lifetime of the `va_list`, improves LLVM codegen.
525                    bx.lifetime_end(va_list.val.llval, va_list.layout.size);
526                }
527                _ => bug!("C-variadic function must have a `VaList` place"),
528            }
529        }
530        if self.fn_abi.ret.layout.is_uninhabited() {
531            // Functions with uninhabited return values are marked `noreturn`,
532            // so we should make sure that we never actually do.
533            // We play it safe by using a well-defined `abort`, but we could go for immediate UB
534            // if that turns out to be helpful.
535            bx.abort();
536            // `abort` does not terminate the block, so we still need to generate
537            // an `unreachable` terminator after it.
538            bx.unreachable();
539            return;
540        }
541        let llval = match &self.fn_abi.ret.mode {
542            PassMode::Ignore | PassMode::Indirect { .. } => {
543                bx.ret_void();
544                return;
545            }
546
547            PassMode::Direct(_) | PassMode::Pair(..) => {
548                let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
549                if let Ref(place_val) = op.val {
550                    bx.load_from_place(bx.backend_type(op.layout), place_val)
551                } else {
552                    op.immediate_or_packed_pair(bx)
553                }
554            }
555
556            PassMode::Cast { cast: cast_ty, pad_i32: _ } => {
557                let op = match self.locals[mir::RETURN_PLACE] {
558                    LocalRef::Operand(op) => op,
559                    LocalRef::PendingOperand => bug!("use of return before def"),
560                    LocalRef::Place(cg_place) => {
561                        OperandRef { val: Ref(cg_place.val), layout: cg_place.layout }
562                    }
563                    LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
564                };
565                let llslot = match op.val {
566                    Immediate(_) | Pair(..) => {
567                        let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
568                        op.val.store(bx, scratch);
569                        scratch.val.llval
570                    }
571                    Ref(place_val) => {
572                        assert_eq!(
573                            place_val.align, op.layout.align.abi,
574                            "return place is unaligned!"
575                        );
576                        place_val.llval
577                    }
578                    ZeroSized => bug!("ZST return value shouldn't be in PassMode::Cast"),
579                };
580                load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
581            }
582        };
583        bx.ret(llval);
584    }
585
586    #[tracing::instrument(level = "trace", skip(self, helper, bx))]
587    fn codegen_drop_terminator(
588        &mut self,
589        helper: TerminatorCodegenHelper<'tcx>,
590        bx: &mut Bx,
591        source_info: &mir::SourceInfo,
592        location: mir::Place<'tcx>,
593        target: mir::BasicBlock,
594        unwind: mir::UnwindAction,
595        mergeable_succ: bool,
596    ) -> MergingSucc {
597        let ty = location.ty(self.mir, bx.tcx()).ty;
598        let ty = self.monomorphize(ty);
599        let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
600
601        if let ty::InstanceKind::DropGlue(_, None) = drop_fn.def {
602            // we don't actually need to drop anything.
603            return helper.funclet_br(self, bx, target, mergeable_succ);
604        }
605
606        let place = self.codegen_place(bx, location.as_ref());
607        let (args1, args2);
608        let mut args = if let Some(llextra) = place.val.llextra {
609            args2 = [place.val.llval, llextra];
610            &args2[..]
611        } else {
612            args1 = [place.val.llval];
613            &args1[..]
614        };
615        let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
616            // FIXME(eddyb) perhaps move some of this logic into
617            // `Instance::resolve_drop_in_place`?
618            ty::Dynamic(_, _) => {
619                // IN THIS ARM, WE HAVE:
620                // ty = *mut (dyn Trait)
621                // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
622                //                       args[0]    args[1]
623                //
624                // args = ( Data, Vtable )
625                //                  |
626                //                  v
627                //                /-------\
628                //                | ...   |
629                //                \-------/
630                //
631                let virtual_drop = Instance {
632                    def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), // idx 0: the drop function
633                    args: drop_fn.args,
634                };
635                debug!("ty = {:?}", ty);
636                debug!("drop_fn = {:?}", drop_fn);
637                debug!("args = {:?}", args);
638                let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
639                let vtable = args[1];
640                // Truncate vtable off of args list
641                args = &args[..1];
642                (
643                    true,
644                    meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
645                        .get_optional_fn(bx, vtable, ty, fn_abi),
646                    fn_abi,
647                    virtual_drop,
648                )
649            }
650            _ => (
651                false,
652                bx.get_fn_addr(drop_fn),
653                bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
654                drop_fn,
655            ),
656        };
657
658        // We generate a null check for the drop_fn. This saves a bunch of relocations being
659        // generated for no-op drops.
660        if maybe_null {
661            let is_not_null = bx.append_sibling_block("is_not_null");
662            let llty = bx.fn_ptr_backend_type(fn_abi);
663            let null = bx.const_null(llty);
664            let non_null =
665                bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
666            bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
667            bx.switch_to_block(is_not_null);
668            self.set_debug_loc(bx, *source_info);
669        }
670
671        helper.do_call(
672            self,
673            bx,
674            fn_abi,
675            drop_fn,
676            args,
677            Some((ReturnDest::Nothing, target)),
678            unwind,
679            &[],
680            Some(drop_instance),
681            CallKind::Normal,
682            !maybe_null && mergeable_succ,
683        )
684    }
685
686    fn codegen_assert_terminator(
687        &mut self,
688        helper: TerminatorCodegenHelper<'tcx>,
689        bx: &mut Bx,
690        terminator: &mir::Terminator<'tcx>,
691        cond: &mir::Operand<'tcx>,
692        expected: bool,
693        msg: &mir::AssertMessage<'tcx>,
694        target: mir::BasicBlock,
695        unwind: mir::UnwindAction,
696        mergeable_succ: bool,
697    ) -> MergingSucc {
698        let span = terminator.source_info.span;
699        let cond = self.codegen_operand(bx, cond).immediate();
700        let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
701
702        // This case can currently arise only from functions marked
703        // with #[rustc_inherit_overflow_checks] and inlined from
704        // another crate (mostly core::num generic/#[inline] fns),
705        // while the current crate doesn't use overflow checks.
706        if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
707            const_cond = Some(expected);
708        }
709
710        // Don't codegen the panic block if success if known.
711        if const_cond == Some(expected) {
712            return helper.funclet_br(self, bx, target, mergeable_succ);
713        }
714
715        // Because we're branching to a panic block (either a `#[cold]` one
716        // or an inlined abort), there's no need to `expect` it.
717
718        // Create the failure block and the conditional branch to it.
719        let lltarget = helper.llbb_with_cleanup(self, target);
720        let panic_block = bx.append_sibling_block("panic");
721        if expected {
722            bx.cond_br(cond, lltarget, panic_block);
723        } else {
724            bx.cond_br(cond, panic_block, lltarget);
725        }
726
727        // After this point, bx is the block for the call to panic.
728        bx.switch_to_block(panic_block);
729        self.set_debug_loc(bx, terminator.source_info);
730
731        // Get the location information.
732        let location = self.get_caller_location(bx, terminator.source_info).immediate();
733
734        // Put together the arguments to the panic entry point.
735        let (lang_item, args) = match msg {
736            AssertKind::BoundsCheck { len, index } => {
737                let len = self.codegen_operand(bx, len).immediate();
738                let index = self.codegen_operand(bx, index).immediate();
739                // It's `fn panic_bounds_check(index: usize, len: usize)`,
740                // and `#[track_caller]` adds an implicit third argument.
741                (LangItem::PanicBoundsCheck, vec![index, len, location])
742            }
743            AssertKind::MisalignedPointerDereference { required, found } => {
744                let required = self.codegen_operand(bx, required).immediate();
745                let found = self.codegen_operand(bx, found).immediate();
746                // It's `fn panic_misaligned_pointer_dereference(required: usize, found: usize)`,
747                // and `#[track_caller]` adds an implicit third argument.
748                (LangItem::PanicMisalignedPointerDereference, vec![required, found, location])
749            }
750            AssertKind::NullPointerDereference => {
751                // It's `fn panic_null_pointer_dereference()`,
752                // `#[track_caller]` adds an implicit argument.
753                (LangItem::PanicNullPointerDereference, vec![location])
754            }
755            AssertKind::InvalidEnumConstruction(source) => {
756                let source = self.codegen_operand(bx, source).immediate();
757                // It's `fn panic_invalid_enum_construction(source: u128)`,
758                // `#[track_caller]` adds an implicit argument.
759                (LangItem::PanicInvalidEnumConstruction, vec![source, location])
760            }
761            _ => {
762                // It's `pub fn panic_...()` and `#[track_caller]` adds an implicit argument.
763                (msg.panic_function(), vec![location])
764            }
765        };
766
767        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
768
769        // Codegen the actual panic invoke/call.
770        let merging_succ = helper.do_call(
771            self,
772            bx,
773            fn_abi,
774            llfn,
775            &args,
776            None,
777            unwind,
778            &[],
779            Some(instance),
780            CallKind::Normal,
781            false,
782        );
783        assert_eq!(merging_succ, MergingSucc::False);
784        MergingSucc::False
785    }
786
787    fn codegen_terminate_terminator(
788        &mut self,
789        helper: TerminatorCodegenHelper<'tcx>,
790        bx: &mut Bx,
791        terminator: &mir::Terminator<'tcx>,
792        reason: UnwindTerminateReason,
793    ) {
794        let span = terminator.source_info.span;
795        self.set_debug_loc(bx, terminator.source_info);
796
797        // Obtain the panic entry point.
798        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
799
800        // Codegen the actual panic invoke/call.
801        let merging_succ = helper.do_call(
802            self,
803            bx,
804            fn_abi,
805            llfn,
806            &[],
807            None,
808            mir::UnwindAction::Unreachable,
809            &[],
810            Some(instance),
811            CallKind::Normal,
812            false,
813        );
814        assert_eq!(merging_succ, MergingSucc::False);
815    }
816
817    /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
818    fn codegen_panic_intrinsic(
819        &mut self,
820        helper: &TerminatorCodegenHelper<'tcx>,
821        bx: &mut Bx,
822        intrinsic: ty::IntrinsicDef,
823        instance: Instance<'tcx>,
824        source_info: mir::SourceInfo,
825        target: Option<mir::BasicBlock>,
826        unwind: mir::UnwindAction,
827        mergeable_succ: bool,
828    ) -> Option<MergingSucc> {
829        // Emit a panic or a no-op for `assert_*` intrinsics.
830        // These are intrinsics that compile to panics so that we can get a message
831        // which mentions the offending type, even from a const context.
832        let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
833            return None;
834        };
835
836        let ty = instance.args.type_at(0);
837
838        let is_valid = bx
839            .tcx()
840            .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
841            .expect("expect to have layout during codegen");
842
843        if is_valid {
844            // a NOP
845            let target = target.unwrap();
846            return Some(helper.funclet_br(self, bx, target, mergeable_succ));
847        }
848
849        let layout = bx.layout_of(ty);
850
851        let msg_str = with_no_visible_paths!({
852            with_no_trimmed_paths!({
853                if layout.is_uninhabited() {
854                    // Use this error even for the other intrinsics as it is more precise.
855                    format!("attempted to instantiate uninhabited type `{ty}`")
856                } else if requirement == ValidityRequirement::Zero {
857                    format!("attempted to zero-initialize type `{ty}`, which is invalid")
858                } else {
859                    format!("attempted to leave type `{ty}` uninitialized, which is invalid")
860                }
861            })
862        });
863        let msg = bx.const_str(&msg_str);
864
865        // Obtain the panic entry point.
866        let (fn_abi, llfn, instance) =
867            common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
868
869        // Codegen the actual panic invoke/call.
870        Some(helper.do_call(
871            self,
872            bx,
873            fn_abi,
874            llfn,
875            &[msg.0, msg.1],
876            target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
877            unwind,
878            &[],
879            Some(instance),
880            CallKind::Normal,
881            mergeable_succ,
882        ))
883    }
884
885    fn codegen_call_terminator(
886        &mut self,
887        helper: TerminatorCodegenHelper<'tcx>,
888        bx: &mut Bx,
889        terminator: &mir::Terminator<'tcx>,
890        func: &mir::Operand<'tcx>,
891        args: &[Spanned<mir::Operand<'tcx>>],
892        destination: mir::Place<'tcx>,
893        target: Option<mir::BasicBlock>,
894        unwind: mir::UnwindAction,
895        fn_span: Span,
896        kind: CallKind,
897        mergeable_succ: bool,
898    ) -> MergingSucc {
899        let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
900
901        // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
902        let callee = self.codegen_operand(bx, func);
903
904        let (instance, mut llfn) = match *callee.layout.ty.kind() {
905            ty::FnDef(def_id, generic_args) => {
906                let instance = ty::Instance::expect_resolve(
907                    bx.tcx(),
908                    bx.typing_env(),
909                    def_id,
910                    generic_args,
911                    fn_span,
912                );
913
914                match instance.def {
915                    // We don't need AsyncDropGlueCtorShim here because it is not `noop func`,
916                    // it is `func returning noop future`
917                    ty::InstanceKind::DropGlue(_, None) => {
918                        // Empty drop glue; a no-op.
919                        let target = target.unwrap();
920                        return helper.funclet_br(self, bx, target, mergeable_succ);
921                    }
922                    ty::InstanceKind::Intrinsic(def_id) => {
923                        let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
924                        if let Some(merging_succ) = self.codegen_panic_intrinsic(
925                            &helper,
926                            bx,
927                            intrinsic,
928                            instance,
929                            source_info,
930                            target,
931                            unwind,
932                            mergeable_succ,
933                        ) {
934                            return merging_succ;
935                        }
936
937                        let result_layout =
938                            self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
939
940                        let (result, store_in_local) = if result_layout.is_zst() {
941                            (
942                                PlaceRef::new_sized(bx.const_undef(bx.type_ptr()), result_layout),
943                                None,
944                            )
945                        } else if let Some(local) = destination.as_local() {
946                            match self.locals[local] {
947                                LocalRef::Place(dest) => (dest, None),
948                                LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
949                                LocalRef::PendingOperand => {
950                                    // Currently, intrinsics always need a location to store
951                                    // the result, so we create a temporary `alloca` for the
952                                    // result.
953                                    let tmp = PlaceRef::alloca(bx, result_layout);
954                                    tmp.storage_live(bx);
955                                    (tmp, Some(local))
956                                }
957                                LocalRef::Operand(_) => {
958                                    bug!("place local already assigned to");
959                                }
960                            }
961                        } else {
962                            (self.codegen_place(bx, destination.as_ref()), None)
963                        };
964
965                        if result.val.align < result.layout.align.abi {
966                            // Currently, MIR code generation does not create calls
967                            // that store directly to fields of packed structs (in
968                            // fact, the calls it creates write only to temps).
969                            //
970                            // If someone changes that, please update this code path
971                            // to create a temporary.
972                            span_bug!(self.mir.span, "can't directly store to unaligned value");
973                        }
974
975                        let args: Vec<_> =
976                            args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
977
978                        match self.codegen_intrinsic_call(bx, instance, &args, result, source_info)
979                        {
980                            Ok(()) => {
981                                if let Some(local) = store_in_local {
982                                    let op = bx.load_operand(result);
983                                    result.storage_dead(bx);
984                                    self.overwrite_local(local, LocalRef::Operand(op));
985                                    self.debug_introduce_local(bx, local);
986                                }
987
988                                return if let Some(target) = target {
989                                    helper.funclet_br(self, bx, target, mergeable_succ)
990                                } else {
991                                    bx.unreachable();
992                                    MergingSucc::False
993                                };
994                            }
995                            Err(instance) => {
996                                if intrinsic.must_be_overridden {
997                                    span_bug!(
998                                        fn_span,
999                                        "intrinsic {} must be overridden by codegen backend, but isn't",
1000                                        intrinsic.name,
1001                                    );
1002                                }
1003                                (Some(instance), None)
1004                            }
1005                        }
1006                    }
1007
1008                    _ if kind == CallKind::Tail
1009                        && instance.def.requires_caller_location(bx.tcx()) =>
1010                    {
1011                        if let Some(hir_id) =
1012                            terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1013                        {
1014                            let msg = "tail calling a function marked with `#[track_caller]` has no special effect";
1015                            bx.tcx().node_lint(TAIL_CALL_TRACK_CALLER, hir_id, |d| {
1016                                _ = d.primary_message(msg).span(fn_span)
1017                            });
1018                        }
1019
1020                        let instance = ty::Instance::resolve_for_fn_ptr(
1021                            bx.tcx(),
1022                            bx.typing_env(),
1023                            def_id,
1024                            generic_args,
1025                        )
1026                        .unwrap();
1027
1028                        (None, Some(bx.get_fn_addr(instance)))
1029                    }
1030                    _ => (Some(instance), None),
1031                }
1032            }
1033            ty::FnPtr(..) => (None, Some(callee.immediate())),
1034            _ => bug!("{} is not callable", callee.layout.ty),
1035        };
1036
1037        // FIXME(eddyb) avoid computing this if possible, when `instance` is
1038        // available - right now `sig` is only needed for getting the `abi`
1039        // and figuring out how many extra args were passed to a C-variadic `fn`.
1040        let sig = callee.layout.ty.fn_sig(bx.tcx());
1041
1042        let extra_args = &args[sig.inputs().skip_binder().len()..];
1043        let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1044            let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1045            self.monomorphize(op_ty)
1046        }));
1047
1048        let fn_abi = match instance {
1049            Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1050            None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1051        };
1052
1053        // The arguments we'll be passing. Plus one to account for outptr, if used.
1054        let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1055
1056        let mut llargs = Vec::with_capacity(arg_count);
1057
1058        // We still need to call `make_return_dest` even if there's no `target`, since
1059        // `fn_abi.ret` could be `PassMode::Indirect`, even if it is uninhabited,
1060        // and `make_return_dest` adds the return-place indirect pointer to `llargs`.
1061        let destination = match kind {
1062            CallKind::Normal => {
1063                let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs);
1064                target.map(|target| (return_dest, target))
1065            }
1066            CallKind::Tail => None,
1067        };
1068
1069        // Split the rust-call tupled arguments off.
1070        let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1071            && let Some((tup, args)) = args.split_last()
1072        {
1073            (args, Some(tup))
1074        } else {
1075            (args, None)
1076        };
1077
1078        // When generating arguments we sometimes introduce temporary allocations with lifetime
1079        // that extend for the duration of a call. Keep track of those allocations and their sizes
1080        // to generate `lifetime_end` when the call returns.
1081        let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1082        'make_args: for (i, arg) in first_args.iter().enumerate() {
1083            if kind == CallKind::Tail && matches!(fn_abi.args[i].mode, PassMode::Indirect { .. }) {
1084                // FIXME: https://github.com/rust-lang/rust/pull/144232#discussion_r2218543841
1085                span_bug!(
1086                    fn_span,
1087                    "arguments using PassMode::Indirect are currently not supported for tail calls"
1088                );
1089            }
1090
1091            let mut op = self.codegen_operand(bx, &arg.node);
1092
1093            if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1094                match op.val {
1095                    Pair(data_ptr, meta) => {
1096                        // In the case of Rc<Self>, we need to explicitly pass a
1097                        // *mut RcInner<Self> with a Scalar (not ScalarPair) ABI. This is a hack
1098                        // that is understood elsewhere in the compiler as a method on
1099                        // `dyn Trait`.
1100                        // To get a `*mut RcInner<Self>`, we just keep unwrapping newtypes until
1101                        // we get a value of a built-in pointer type.
1102                        //
1103                        // This is also relevant for `Pin<&mut Self>`, where we need to peel the
1104                        // `Pin`.
1105                        while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1106                            let (idx, _) = op.layout.non_1zst_field(bx).expect(
1107                                "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1108                            );
1109                            op = op.extract_field(self, bx, idx.as_usize());
1110                        }
1111
1112                        // Now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
1113                        // data pointer and vtable. Look up the method in the vtable, and pass
1114                        // the data pointer as the first argument.
1115                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1116                            bx,
1117                            meta,
1118                            op.layout.ty,
1119                            fn_abi,
1120                        ));
1121                        llargs.push(data_ptr);
1122                        continue 'make_args;
1123                    }
1124                    Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1125                        // by-value dynamic dispatch
1126                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1127                            bx,
1128                            meta,
1129                            op.layout.ty,
1130                            fn_abi,
1131                        ));
1132                        llargs.push(data_ptr);
1133                        continue;
1134                    }
1135                    _ => {
1136                        span_bug!(fn_span, "can't codegen a virtual call on {:#?}", op);
1137                    }
1138                }
1139            }
1140
1141            // The callee needs to own the argument memory if we pass it
1142            // by-ref, so make a local copy of non-immediate constants.
1143            match (&arg.node, op.val) {
1144                (&mir::Operand::Copy(_), Ref(PlaceValue { llextra: None, .. }))
1145                | (&mir::Operand::Constant(_), Ref(PlaceValue { llextra: None, .. })) => {
1146                    let tmp = PlaceRef::alloca(bx, op.layout);
1147                    bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1148                    op.val.store(bx, tmp);
1149                    op.val = Ref(tmp.val);
1150                    lifetime_ends_after_call.push((tmp.val.llval, tmp.layout.size));
1151                }
1152                _ => {}
1153            }
1154
1155            self.codegen_argument(
1156                bx,
1157                op,
1158                &mut llargs,
1159                &fn_abi.args[i],
1160                &mut lifetime_ends_after_call,
1161            );
1162        }
1163        let num_untupled = untuple.map(|tup| {
1164            self.codegen_arguments_untupled(
1165                bx,
1166                &tup.node,
1167                &mut llargs,
1168                &fn_abi.args[first_args.len()..],
1169                &mut lifetime_ends_after_call,
1170            )
1171        });
1172
1173        let needs_location =
1174            instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1175        if needs_location {
1176            let mir_args = if let Some(num_untupled) = num_untupled {
1177                first_args.len() + num_untupled
1178            } else {
1179                args.len()
1180            };
1181            assert_eq!(
1182                fn_abi.args.len(),
1183                mir_args + 1,
1184                "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1185            );
1186            let location = self.get_caller_location(bx, source_info);
1187            debug!(
1188                "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1189                terminator, location, fn_span
1190            );
1191
1192            let last_arg = fn_abi.args.last().unwrap();
1193            self.codegen_argument(
1194                bx,
1195                location,
1196                &mut llargs,
1197                last_arg,
1198                &mut lifetime_ends_after_call,
1199            );
1200        }
1201
1202        let fn_ptr = match (instance, llfn) {
1203            (Some(instance), None) => bx.get_fn_addr(instance),
1204            (_, Some(llfn)) => llfn,
1205            _ => span_bug!(fn_span, "no instance or llfn for call"),
1206        };
1207        self.set_debug_loc(bx, source_info);
1208        helper.do_call(
1209            self,
1210            bx,
1211            fn_abi,
1212            fn_ptr,
1213            &llargs,
1214            destination,
1215            unwind,
1216            &lifetime_ends_after_call,
1217            instance,
1218            kind,
1219            mergeable_succ,
1220        )
1221    }
1222
1223    fn codegen_asm_terminator(
1224        &mut self,
1225        helper: TerminatorCodegenHelper<'tcx>,
1226        bx: &mut Bx,
1227        asm_macro: InlineAsmMacro,
1228        terminator: &mir::Terminator<'tcx>,
1229        template: &[ast::InlineAsmTemplatePiece],
1230        operands: &[mir::InlineAsmOperand<'tcx>],
1231        options: ast::InlineAsmOptions,
1232        line_spans: &[Span],
1233        targets: &[mir::BasicBlock],
1234        unwind: mir::UnwindAction,
1235        instance: Instance<'_>,
1236        mergeable_succ: bool,
1237    ) -> MergingSucc {
1238        let span = terminator.source_info.span;
1239
1240        let operands: Vec<_> = operands
1241            .iter()
1242            .map(|op| match *op {
1243                mir::InlineAsmOperand::In { reg, ref value } => {
1244                    let value = self.codegen_operand(bx, value);
1245                    InlineAsmOperandRef::In { reg, value }
1246                }
1247                mir::InlineAsmOperand::Out { reg, late, ref place } => {
1248                    let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1249                    InlineAsmOperandRef::Out { reg, late, place }
1250                }
1251                mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1252                    let in_value = self.codegen_operand(bx, in_value);
1253                    let out_place =
1254                        out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1255                    InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1256                }
1257                mir::InlineAsmOperand::Const { ref value } => {
1258                    let const_value = self.eval_mir_constant(value);
1259                    let string = common::asm_const_to_str(
1260                        bx.tcx(),
1261                        span,
1262                        const_value,
1263                        bx.layout_of(value.ty()),
1264                    );
1265                    InlineAsmOperandRef::Const { string }
1266                }
1267                mir::InlineAsmOperand::SymFn { ref value } => {
1268                    let const_ = self.monomorphize(value.const_);
1269                    if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1270                        let instance = ty::Instance::resolve_for_fn_ptr(
1271                            bx.tcx(),
1272                            bx.typing_env(),
1273                            def_id,
1274                            args,
1275                        )
1276                        .unwrap();
1277                        InlineAsmOperandRef::SymFn { instance }
1278                    } else {
1279                        span_bug!(span, "invalid type for asm sym (fn)");
1280                    }
1281                }
1282                mir::InlineAsmOperand::SymStatic { def_id } => {
1283                    InlineAsmOperandRef::SymStatic { def_id }
1284                }
1285                mir::InlineAsmOperand::Label { target_index } => {
1286                    InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1287                }
1288            })
1289            .collect();
1290
1291        helper.do_inlineasm(
1292            self,
1293            bx,
1294            template,
1295            &operands,
1296            options,
1297            line_spans,
1298            if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1299            unwind,
1300            instance,
1301            mergeable_succ,
1302        )
1303    }
1304
1305    pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1306        let llbb = match self.try_llbb(bb) {
1307            Some(llbb) => llbb,
1308            None => return,
1309        };
1310        let bx = &mut Bx::build(self.cx, llbb);
1311        let mir = self.mir;
1312
1313        // MIR basic blocks stop at any function call. This may not be the case
1314        // for the backend's basic blocks, in which case we might be able to
1315        // combine multiple MIR basic blocks into a single backend basic block.
1316        loop {
1317            let data = &mir[bb];
1318
1319            debug!("codegen_block({:?}={:?})", bb, data);
1320
1321            for statement in &data.statements {
1322                self.codegen_statement(bx, statement);
1323            }
1324            self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1325
1326            let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1327            if let MergingSucc::False = merging_succ {
1328                break;
1329            }
1330
1331            // We are merging the successor into the produced backend basic
1332            // block. Record that the successor should be skipped when it is
1333            // reached.
1334            //
1335            // Note: we must not have already generated code for the successor.
1336            // This is implicitly ensured by the reverse postorder traversal,
1337            // and the assertion explicitly guarantees that.
1338            let mut successors = data.terminator().successors();
1339            let succ = successors.next().unwrap();
1340            assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1341            self.cached_llbbs[succ] = CachedLlbb::Skip;
1342            bb = succ;
1343        }
1344    }
1345
1346    pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1347        let llbb = match self.try_llbb(bb) {
1348            Some(llbb) => llbb,
1349            None => return,
1350        };
1351        let bx = &mut Bx::build(self.cx, llbb);
1352        debug!("codegen_block_as_unreachable({:?})", bb);
1353        bx.unreachable();
1354    }
1355
1356    fn codegen_terminator(
1357        &mut self,
1358        bx: &mut Bx,
1359        bb: mir::BasicBlock,
1360        terminator: &'tcx mir::Terminator<'tcx>,
1361    ) -> MergingSucc {
1362        debug!("codegen_terminator: {:?}", terminator);
1363
1364        let helper = TerminatorCodegenHelper { bb, terminator };
1365
1366        let mergeable_succ = || {
1367            // Note: any call to `switch_to_block` will invalidate a `true` value
1368            // of `mergeable_succ`.
1369            let mut successors = terminator.successors();
1370            if let Some(succ) = successors.next()
1371                && successors.next().is_none()
1372                && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1373            {
1374                // bb has a single successor, and bb is its only predecessor. This
1375                // makes it a candidate for merging.
1376                assert_eq!(succ_pred, bb);
1377                true
1378            } else {
1379                false
1380            }
1381        };
1382
1383        self.set_debug_loc(bx, terminator.source_info);
1384        match terminator.kind {
1385            mir::TerminatorKind::UnwindResume => {
1386                self.codegen_resume_terminator(helper, bx);
1387                MergingSucc::False
1388            }
1389
1390            mir::TerminatorKind::UnwindTerminate(reason) => {
1391                self.codegen_terminate_terminator(helper, bx, terminator, reason);
1392                MergingSucc::False
1393            }
1394
1395            mir::TerminatorKind::Goto { target } => {
1396                helper.funclet_br(self, bx, target, mergeable_succ())
1397            }
1398
1399            mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1400                self.codegen_switchint_terminator(helper, bx, discr, targets);
1401                MergingSucc::False
1402            }
1403
1404            mir::TerminatorKind::Return => {
1405                self.codegen_return_terminator(bx);
1406                MergingSucc::False
1407            }
1408
1409            mir::TerminatorKind::Unreachable => {
1410                bx.unreachable();
1411                MergingSucc::False
1412            }
1413
1414            mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop, async_fut } => {
1415                assert!(
1416                    async_fut.is_none() && drop.is_none(),
1417                    "Async Drop must be expanded or reset to sync before codegen"
1418                );
1419                self.codegen_drop_terminator(
1420                    helper,
1421                    bx,
1422                    &terminator.source_info,
1423                    place,
1424                    target,
1425                    unwind,
1426                    mergeable_succ(),
1427                )
1428            }
1429
1430            mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1431                .codegen_assert_terminator(
1432                    helper,
1433                    bx,
1434                    terminator,
1435                    cond,
1436                    expected,
1437                    msg,
1438                    target,
1439                    unwind,
1440                    mergeable_succ(),
1441                ),
1442
1443            mir::TerminatorKind::Call {
1444                ref func,
1445                ref args,
1446                destination,
1447                target,
1448                unwind,
1449                call_source: _,
1450                fn_span,
1451            } => self.codegen_call_terminator(
1452                helper,
1453                bx,
1454                terminator,
1455                func,
1456                args,
1457                destination,
1458                target,
1459                unwind,
1460                fn_span,
1461                CallKind::Normal,
1462                mergeable_succ(),
1463            ),
1464            mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1465                .codegen_call_terminator(
1466                    helper,
1467                    bx,
1468                    terminator,
1469                    func,
1470                    args,
1471                    mir::Place::from(mir::RETURN_PLACE),
1472                    None,
1473                    mir::UnwindAction::Unreachable,
1474                    fn_span,
1475                    CallKind::Tail,
1476                    mergeable_succ(),
1477                ),
1478            mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1479                bug!("coroutine ops in codegen")
1480            }
1481            mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1482                bug!("borrowck false edges in codegen")
1483            }
1484
1485            mir::TerminatorKind::InlineAsm {
1486                asm_macro,
1487                template,
1488                ref operands,
1489                options,
1490                line_spans,
1491                ref targets,
1492                unwind,
1493            } => self.codegen_asm_terminator(
1494                helper,
1495                bx,
1496                asm_macro,
1497                terminator,
1498                template,
1499                operands,
1500                options,
1501                line_spans,
1502                targets,
1503                unwind,
1504                self.instance,
1505                mergeable_succ(),
1506            ),
1507        }
1508    }
1509
1510    fn codegen_argument(
1511        &mut self,
1512        bx: &mut Bx,
1513        op: OperandRef<'tcx, Bx::Value>,
1514        llargs: &mut Vec<Bx::Value>,
1515        arg: &ArgAbi<'tcx, Ty<'tcx>>,
1516        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1517    ) {
1518        match arg.mode {
1519            PassMode::Ignore => return,
1520            PassMode::Cast { pad_i32: true, .. } => {
1521                // Fill padding with undef value, where applicable.
1522                llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1523            }
1524            PassMode::Pair(..) => match op.val {
1525                Pair(a, b) => {
1526                    llargs.push(a);
1527                    llargs.push(b);
1528                    return;
1529                }
1530                _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1531            },
1532            PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => match op.val {
1533                Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1534                    llargs.push(a);
1535                    llargs.push(b);
1536                    return;
1537                }
1538                _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1539            },
1540            _ => {}
1541        }
1542
1543        // Force by-ref if we have to load through a cast pointer.
1544        let (mut llval, align, by_ref) = match op.val {
1545            Immediate(_) | Pair(..) => match arg.mode {
1546                PassMode::Indirect { attrs, .. } => {
1547                    // Indirect argument may have higher alignment requirements than the type's
1548                    // alignment. This can happen, e.g. when passing types with <4 byte alignment
1549                    // on the stack on x86.
1550                    let required_align = match attrs.pointee_align {
1551                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1552                        None => arg.layout.align.abi,
1553                    };
1554                    let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1555                    bx.lifetime_start(scratch.llval, arg.layout.size);
1556                    op.val.store(bx, scratch.with_type(arg.layout));
1557                    lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1558                    (scratch.llval, scratch.align, true)
1559                }
1560                PassMode::Cast { .. } => {
1561                    let scratch = PlaceRef::alloca(bx, arg.layout);
1562                    op.val.store(bx, scratch);
1563                    (scratch.val.llval, scratch.val.align, true)
1564                }
1565                _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1566            },
1567            Ref(op_place_val) => match arg.mode {
1568                PassMode::Indirect { attrs, .. } => {
1569                    let required_align = match attrs.pointee_align {
1570                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1571                        None => arg.layout.align.abi,
1572                    };
1573                    if op_place_val.align < required_align {
1574                        // For `foo(packed.large_field)`, and types with <4 byte alignment on x86,
1575                        // alignment requirements may be higher than the type's alignment, so copy
1576                        // to a higher-aligned alloca.
1577                        let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1578                        bx.lifetime_start(scratch.llval, arg.layout.size);
1579                        bx.typed_place_copy(scratch, op_place_val, op.layout);
1580                        lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1581                        (scratch.llval, scratch.align, true)
1582                    } else {
1583                        (op_place_val.llval, op_place_val.align, true)
1584                    }
1585                }
1586                _ => (op_place_val.llval, op_place_val.align, true),
1587            },
1588            ZeroSized => match arg.mode {
1589                PassMode::Indirect { on_stack, .. } => {
1590                    if on_stack {
1591                        // It doesn't seem like any target can have `byval` ZSTs, so this assert
1592                        // is here to replace a would-be untested codepath.
1593                        bug!("ZST {op:?} passed on stack with abi {arg:?}");
1594                    }
1595                    // Though `extern "Rust"` doesn't pass ZSTs, some ABIs pass
1596                    // a pointer for `repr(C)` structs even when empty, so get
1597                    // one from an `alloca` (which can be left uninitialized).
1598                    let scratch = PlaceRef::alloca(bx, arg.layout);
1599                    (scratch.val.llval, scratch.val.align, true)
1600                }
1601                _ => bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
1602            },
1603        };
1604
1605        if by_ref && !arg.is_indirect() {
1606            // Have to load the argument, maybe while casting it.
1607            if let PassMode::Cast { cast, pad_i32: _ } = &arg.mode {
1608                // The ABI mandates that the value is passed as a different struct representation.
1609                // Spill and reload it from the stack to convert from the Rust representation to
1610                // the ABI representation.
1611                let scratch_size = cast.size(bx);
1612                let scratch_align = cast.align(bx);
1613                // Note that the ABI type may be either larger or smaller than the Rust type,
1614                // due to the presence or absence of trailing padding. For example:
1615                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
1616                //   when passed by value, making it smaller.
1617                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
1618                //   when passed by value, making it larger.
1619                let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
1620                // Allocate some scratch space...
1621                let llscratch = bx.alloca(scratch_size, scratch_align);
1622                bx.lifetime_start(llscratch, scratch_size);
1623                // ...memcpy the value...
1624                bx.memcpy(
1625                    llscratch,
1626                    scratch_align,
1627                    llval,
1628                    align,
1629                    bx.const_usize(copy_bytes),
1630                    MemFlags::empty(),
1631                    None,
1632                );
1633                // ...and then load it with the ABI type.
1634                llval = load_cast(bx, cast, llscratch, scratch_align);
1635                bx.lifetime_end(llscratch, scratch_size);
1636            } else {
1637                // We can't use `PlaceRef::load` here because the argument
1638                // may have a type we don't treat as immediate, but the ABI
1639                // used for this call is passing it by-value. In that case,
1640                // the load would just produce `OperandValue::Ref` instead
1641                // of the `OperandValue::Immediate` we need for the call.
1642                llval = bx.load(bx.backend_type(arg.layout), llval, align);
1643                if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
1644                    if scalar.is_bool() {
1645                        bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1646                    }
1647                    // We store bools as `i8` so we need to truncate to `i1`.
1648                    llval = bx.to_immediate_scalar(llval, scalar);
1649                }
1650            }
1651        }
1652
1653        llargs.push(llval);
1654    }
1655
1656    fn codegen_arguments_untupled(
1657        &mut self,
1658        bx: &mut Bx,
1659        operand: &mir::Operand<'tcx>,
1660        llargs: &mut Vec<Bx::Value>,
1661        args: &[ArgAbi<'tcx, Ty<'tcx>>],
1662        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1663    ) -> usize {
1664        let tuple = self.codegen_operand(bx, operand);
1665
1666        // Handle both by-ref and immediate tuples.
1667        if let Ref(place_val) = tuple.val {
1668            if place_val.llextra.is_some() {
1669                bug!("closure arguments must be sized");
1670            }
1671            let tuple_ptr = place_val.with_type(tuple.layout);
1672            for i in 0..tuple.layout.fields.count() {
1673                let field_ptr = tuple_ptr.project_field(bx, i);
1674                let field = bx.load_operand(field_ptr);
1675                self.codegen_argument(bx, field, llargs, &args[i], lifetime_ends_after_call);
1676            }
1677        } else {
1678            // If the tuple is immediate, the elements are as well.
1679            for i in 0..tuple.layout.fields.count() {
1680                let op = tuple.extract_field(self, bx, i);
1681                self.codegen_argument(bx, op, llargs, &args[i], lifetime_ends_after_call);
1682            }
1683        }
1684        tuple.layout.fields.count()
1685    }
1686
1687    pub(super) fn get_caller_location(
1688        &mut self,
1689        bx: &mut Bx,
1690        source_info: mir::SourceInfo,
1691    ) -> OperandRef<'tcx, Bx::Value> {
1692        self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
1693            let const_loc = bx.tcx().span_as_caller_location(span);
1694            OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1695        })
1696    }
1697
1698    fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1699        let cx = bx.cx();
1700        if let Some(slot) = self.personality_slot {
1701            slot
1702        } else {
1703            let layout = cx.layout_of(Ty::new_tup(
1704                cx.tcx(),
1705                &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
1706            ));
1707            let slot = PlaceRef::alloca(bx, layout);
1708            self.personality_slot = Some(slot);
1709            slot
1710        }
1711    }
1712
1713    /// Returns the landing/cleanup pad wrapper around the given basic block.
1714    // FIXME(eddyb) rename this to `eh_pad_for`.
1715    fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1716        if let Some(landing_pad) = self.landing_pads[bb] {
1717            return landing_pad;
1718        }
1719
1720        let landing_pad = self.landing_pad_for_uncached(bb);
1721        self.landing_pads[bb] = Some(landing_pad);
1722        landing_pad
1723    }
1724
1725    // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
1726    fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1727        let llbb = self.llbb(bb);
1728        if base::wants_new_eh_instructions(self.cx.sess()) {
1729            let cleanup_bb = Bx::append_block(self.cx, self.llfn, &format!("funclet_{bb:?}"));
1730            let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
1731            let funclet = cleanup_bx.cleanup_pad(None, &[]);
1732            cleanup_bx.br(llbb);
1733            self.funclets[bb] = Some(funclet);
1734            cleanup_bb
1735        } else {
1736            let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1737            let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1738
1739            let llpersonality = self.cx.eh_personality();
1740            let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
1741
1742            let slot = self.get_personality_slot(&mut cleanup_bx);
1743            slot.storage_live(&mut cleanup_bx);
1744            Pair(exn0, exn1).store(&mut cleanup_bx, slot);
1745
1746            cleanup_bx.br(llbb);
1747            cleanup_llbb
1748        }
1749    }
1750
1751    fn unreachable_block(&mut self) -> Bx::BasicBlock {
1752        self.unreachable_block.unwrap_or_else(|| {
1753            let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1754            let mut bx = Bx::build(self.cx, llbb);
1755            bx.unreachable();
1756            self.unreachable_block = Some(llbb);
1757            llbb
1758        })
1759    }
1760
1761    fn terminate_block(&mut self, reason: UnwindTerminateReason) -> Bx::BasicBlock {
1762        if let Some((cached_bb, cached_reason)) = self.terminate_block
1763            && reason == cached_reason
1764        {
1765            return cached_bb;
1766        }
1767
1768        let funclet;
1769        let llbb;
1770        let mut bx;
1771        if base::wants_new_eh_instructions(self.cx.sess()) {
1772            // This is a basic block that we're aborting the program for,
1773            // notably in an `extern` function. These basic blocks are inserted
1774            // so that we assert that `extern` functions do indeed not panic,
1775            // and if they do we abort the process.
1776            //
1777            // On MSVC these are tricky though (where we're doing funclets). If
1778            // we were to do a cleanuppad (like below) the normal functions like
1779            // `longjmp` would trigger the abort logic, terminating the
1780            // program. Instead we insert the equivalent of `catch(...)` for C++
1781            // which magically doesn't trigger when `longjmp` files over this
1782            // frame.
1783            //
1784            // Lots more discussion can be found on #48251 but this codegen is
1785            // modeled after clang's for:
1786            //
1787            //      try {
1788            //          foo();
1789            //      } catch (...) {
1790            //          bar();
1791            //      }
1792            //
1793            // which creates an IR snippet like
1794            //
1795            //      cs_terminate:
1796            //         %cs = catchswitch within none [%cp_terminate] unwind to caller
1797            //      cp_terminate:
1798            //         %cp = catchpad within %cs [null, i32 64, null]
1799            //         ...
1800
1801            llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
1802            let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
1803
1804            let mut cs_bx = Bx::build(self.cx, llbb);
1805            let cs = cs_bx.catch_switch(None, None, &[cp_llbb]);
1806
1807            bx = Bx::build(self.cx, cp_llbb);
1808            let null =
1809                bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
1810
1811            // The `null` in first argument here is actually a RTTI type
1812            // descriptor for the C++ personality function, but `catch (...)`
1813            // has no type so it's null.
1814            let args = if base::wants_msvc_seh(self.cx.sess()) {
1815                // This bitmask is a single `HT_IsStdDotDot` flag, which
1816                // represents that this is a C++-style `catch (...)` block that
1817                // only captures programmatic exceptions, not all SEH
1818                // exceptions. The second `null` points to a non-existent
1819                // `alloca` instruction, which an LLVM pass would inline into
1820                // the initial SEH frame allocation.
1821                let adjectives = bx.const_i32(0x40);
1822                &[null, adjectives, null] as &[_]
1823            } else {
1824                // Specifying more arguments than necessary usually doesn't
1825                // hurt, but the `WasmEHPrepare` LLVM pass does not recognize
1826                // anything other than a single `null` as a `catch (...)` block,
1827                // leading to problems down the line during instruction
1828                // selection.
1829                &[null] as &[_]
1830            };
1831
1832            funclet = Some(bx.catch_pad(cs, args));
1833        } else {
1834            llbb = Bx::append_block(self.cx, self.llfn, "terminate");
1835            bx = Bx::build(self.cx, llbb);
1836
1837            let llpersonality = self.cx.eh_personality();
1838            bx.filter_landing_pad(llpersonality);
1839
1840            funclet = None;
1841        }
1842
1843        self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
1844
1845        let (fn_abi, fn_ptr, instance) =
1846            common::build_langcall(&bx, self.mir.span, reason.lang_item());
1847        if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
1848            bx.abort();
1849        } else {
1850            let fn_ty = bx.fn_decl_backend_type(fn_abi);
1851
1852            let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref(), None);
1853            bx.apply_attrs_to_cleanup_callsite(llret);
1854        }
1855
1856        bx.unreachable();
1857
1858        self.terminate_block = Some((llbb, reason));
1859        llbb
1860    }
1861
1862    /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
1863    /// cached in `self.cached_llbbs`, or created on demand (and cached).
1864    // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
1865    // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
1866    pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1867        self.try_llbb(bb).unwrap()
1868    }
1869
1870    /// Like `llbb`, but may fail if the basic block should be skipped.
1871    pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
1872        match self.cached_llbbs[bb] {
1873            CachedLlbb::None => {
1874                let llbb = Bx::append_block(self.cx, self.llfn, &format!("{bb:?}"));
1875                self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
1876                Some(llbb)
1877            }
1878            CachedLlbb::Some(llbb) => Some(llbb),
1879            CachedLlbb::Skip => None,
1880        }
1881    }
1882
1883    fn make_return_dest(
1884        &mut self,
1885        bx: &mut Bx,
1886        dest: mir::Place<'tcx>,
1887        fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1888        llargs: &mut Vec<Bx::Value>,
1889    ) -> ReturnDest<'tcx, Bx::Value> {
1890        // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1891        if fn_ret.is_ignore() {
1892            return ReturnDest::Nothing;
1893        }
1894        let dest = if let Some(index) = dest.as_local() {
1895            match self.locals[index] {
1896                LocalRef::Place(dest) => dest,
1897                LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1898                LocalRef::PendingOperand => {
1899                    // Handle temporary places, specifically `Operand` ones, as
1900                    // they don't have `alloca`s.
1901                    return if fn_ret.is_indirect() {
1902                        // Odd, but possible, case, we have an operand temporary,
1903                        // but the calling convention has an indirect return.
1904                        let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1905                        tmp.storage_live(bx);
1906                        llargs.push(tmp.val.llval);
1907                        ReturnDest::IndirectOperand(tmp, index)
1908                    } else {
1909                        ReturnDest::DirectOperand(index)
1910                    };
1911                }
1912                LocalRef::Operand(_) => {
1913                    bug!("place local already assigned to");
1914                }
1915            }
1916        } else {
1917            self.codegen_place(bx, dest.as_ref())
1918        };
1919        if fn_ret.is_indirect() {
1920            if dest.val.align < dest.layout.align.abi {
1921                // Currently, MIR code generation does not create calls
1922                // that store directly to fields of packed structs (in
1923                // fact, the calls it creates write only to temps).
1924                //
1925                // If someone changes that, please update this code path
1926                // to create a temporary.
1927                span_bug!(self.mir.span, "can't directly store to unaligned value");
1928            }
1929            llargs.push(dest.val.llval);
1930            ReturnDest::Nothing
1931        } else {
1932            ReturnDest::Store(dest)
1933        }
1934    }
1935
1936    // Stores the return value of a function call into it's final location.
1937    fn store_return(
1938        &mut self,
1939        bx: &mut Bx,
1940        dest: ReturnDest<'tcx, Bx::Value>,
1941        ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1942        llval: Bx::Value,
1943    ) {
1944        use self::ReturnDest::*;
1945
1946        match dest {
1947            Nothing => (),
1948            Store(dst) => bx.store_arg(ret_abi, llval, dst),
1949            IndirectOperand(tmp, index) => {
1950                let op = bx.load_operand(tmp);
1951                tmp.storage_dead(bx);
1952                self.overwrite_local(index, LocalRef::Operand(op));
1953                self.debug_introduce_local(bx, index);
1954            }
1955            DirectOperand(index) => {
1956                // If there is a cast, we have to store and reload.
1957                let op = if let PassMode::Cast { .. } = ret_abi.mode {
1958                    let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1959                    tmp.storage_live(bx);
1960                    bx.store_arg(ret_abi, llval, tmp);
1961                    let op = bx.load_operand(tmp);
1962                    tmp.storage_dead(bx);
1963                    op
1964                } else {
1965                    OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1966                };
1967                self.overwrite_local(index, LocalRef::Operand(op));
1968                self.debug_introduce_local(bx, index);
1969            }
1970        }
1971    }
1972}
1973
1974enum ReturnDest<'tcx, V> {
1975    /// Do nothing; the return value is indirect or ignored.
1976    Nothing,
1977    /// Store the return value to the pointer.
1978    Store(PlaceRef<'tcx, V>),
1979    /// Store an indirect return value to an operand local place.
1980    IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1981    /// Store a direct return value to an operand local place.
1982    DirectOperand(mir::Local),
1983}
1984
1985fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1986    bx: &mut Bx,
1987    cast: &CastTarget,
1988    ptr: Bx::Value,
1989    align: Align,
1990) -> Bx::Value {
1991    let cast_ty = bx.cast_backend_type(cast);
1992    if let Some(offset_from_start) = cast.rest_offset {
1993        assert!(cast.prefix[1..].iter().all(|p| p.is_none()));
1994        assert_eq!(cast.rest.unit.size, cast.rest.total);
1995        let first_ty = bx.reg_backend_type(&cast.prefix[0].unwrap());
1996        let second_ty = bx.reg_backend_type(&cast.rest.unit);
1997        let first = bx.load(first_ty, ptr, align);
1998        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
1999        let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2000        let res = bx.cx().const_poison(cast_ty);
2001        let res = bx.insert_value(res, first, 0);
2002        bx.insert_value(res, second, 1)
2003    } else {
2004        bx.load(cast_ty, ptr, align)
2005    }
2006}
2007
2008pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2009    bx: &mut Bx,
2010    cast: &CastTarget,
2011    value: Bx::Value,
2012    ptr: Bx::Value,
2013    align: Align,
2014) {
2015    if let Some(offset_from_start) = cast.rest_offset {
2016        assert!(cast.prefix[1..].iter().all(|p| p.is_none()));
2017        assert_eq!(cast.rest.unit.size, cast.rest.total);
2018        assert!(cast.prefix[0].is_some());
2019        let first = bx.extract_value(value, 0);
2020        let second = bx.extract_value(value, 1);
2021        bx.store(first, ptr, align);
2022        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2023        bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2024    } else {
2025        bx.store(value, ptr, align);
2026    };
2027}