Skip to main content

rustc_codegen_ssa/mir/
block.rs

1use std::cmp;
2use std::ops::Range;
3
4use rustc_abi::{
5    Align, ArmCall, BackendRepr, CanonAbi, ExternAbi, HasDataLayout, Reg, Size, WrappingRange,
6};
7use rustc_ast as ast;
8use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
9use rustc_data_structures::packed::Pu128;
10use rustc_hir::attrs::AttributeKind;
11use rustc_hir::lang_items::LangItem;
12use rustc_lint_defs::builtin::TAIL_CALL_TRACK_CALLER;
13use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
14use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
15use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
16use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt};
17use rustc_middle::{bug, span_bug};
18use rustc_session::config::OptLevel;
19use rustc_span::{Span, Spanned};
20use rustc_target::callconv::{ArgAbi, ArgAttributes, CastTarget, FnAbi, PassMode};
21use tracing::{debug, info};
22
23use super::operand::OperandRef;
24use super::operand::OperandValue::{self, Immediate, Pair, Ref, ZeroSized};
25use super::place::{PlaceRef, PlaceValue};
26use super::{CachedLlbb, FunctionCx, LocalRef};
27use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization};
28use crate::common::{self, IntPredicate};
29use crate::errors::CompilerBuiltinsCannotCall;
30use crate::mir::IntrinsicResult;
31use crate::traits::*;
32use crate::{MemFlags, meth};
33
34// Indicates if we are in the middle of merging a BB's successor into it. This
35// can happen when BB jumps directly to its successor and the successor has no
36// other predecessors.
37#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MergingSucc {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                MergingSucc::False => "False",
                MergingSucc::True => "True",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for MergingSucc {
    #[inline]
    fn eq(&self, other: &MergingSucc) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
38enum MergingSucc {
39    False,
40    True,
41}
42
43/// Indicates to the call terminator codegen whether a call
44/// is a normal call or an explicit tail call.
45#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CallKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                CallKind::Normal => "Normal",
                CallKind::Tail => "Tail",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CallKind {
    #[inline]
    fn eq(&self, other: &CallKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
46enum CallKind {
47    Normal,
48    Tail,
49}
50
51/// Used by `FunctionCx::codegen_terminator` for emitting common patterns
52/// e.g., creating a basic block, calling a function, etc.
53struct TerminatorCodegenHelper<'tcx> {
54    bb: mir::BasicBlock,
55    terminator: &'tcx mir::Terminator<'tcx>,
56}
57
58impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
59    /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
60    /// either already previously cached, or newly created, by `landing_pad_for`.
61    fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
62        &self,
63        fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
64    ) -> Option<&'b Bx::Funclet> {
65        let cleanup_kinds = fx.cleanup_kinds.as_ref()?;
66        let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?;
67        // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
68        // it has to be now. This may not seem necessary, as RPO should lead
69        // to all the unwind edges being visited (and so to `landing_pad_for`
70        // getting called for them), before building any of the blocks inside
71        // the funclet itself - however, if MIR contains edges that end up not
72        // being needed in the LLVM IR after monomorphization, the funclet may
73        // be unreachable, and we don't have yet a way to skip building it in
74        // such an eventuality (which may be a better solution than this).
75        if fx.funclets[funclet_bb].is_none() {
76            fx.landing_pad_for(funclet_bb);
77        }
78        Some(
79            fx.funclets[funclet_bb]
80                .as_ref()
81                .expect("landing_pad_for didn't also create funclets entry"),
82        )
83    }
84
85    /// Get a basic block (creating it if necessary), possibly with cleanup
86    /// stuff in it or next to it.
87    fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
88        &self,
89        fx: &mut FunctionCx<'a, 'tcx, Bx>,
90        target: mir::BasicBlock,
91    ) -> Bx::BasicBlock {
92        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
93        let mut lltarget = fx.llbb(target);
94        if needs_landing_pad {
95            lltarget = fx.landing_pad_for(target);
96        }
97        if is_cleanupret {
98            // Cross-funclet jump - need a trampoline
99            if !base::wants_new_eh_instructions(fx.cx.tcx().sess) {
    ::core::panicking::panic("assertion failed: base::wants_new_eh_instructions(fx.cx.tcx().sess)")
};assert!(base::wants_new_eh_instructions(fx.cx.tcx().sess));
100            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:100",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(100u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("llbb_with_cleanup: creating cleanup trampoline for {0:?}",
                                                    target) as &dyn Value))])
            });
    } else { ; }
};debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
101            let name = &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}_cleanup_trampoline_{1:?}",
                self.bb, target))
    })format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
102            let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
103            let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
104            trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
105            trampoline_llbb
106        } else {
107            lltarget
108        }
109    }
110
111    fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
112        &self,
113        fx: &mut FunctionCx<'a, 'tcx, Bx>,
114        target: mir::BasicBlock,
115    ) -> (bool, bool) {
116        if let Some(ref cleanup_kinds) = fx.cleanup_kinds {
117            let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb);
118            let target_funclet = cleanup_kinds[target].funclet_bb(target);
119            let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) {
120                (None, None) => (false, false),
121                (None, Some(_)) => (true, false),
122                (Some(f), Some(t_f)) => (f != t_f, f != t_f),
123                (Some(_), None) => {
124                    let span = self.terminator.source_info.span;
125                    ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("{0:?} - jump out of cleanup?", self.terminator));span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
126                }
127            };
128            (needs_landing_pad, is_cleanupret)
129        } else {
130            let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup;
131            let is_cleanupret = false;
132            (needs_landing_pad, is_cleanupret)
133        }
134    }
135
136    fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
137        &self,
138        fx: &mut FunctionCx<'a, 'tcx, Bx>,
139        bx: &mut Bx,
140        target: mir::BasicBlock,
141        mergeable_succ: bool,
142        attributes: &[AttributeKind],
143    ) -> MergingSucc {
144        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
145        if mergeable_succ && !needs_landing_pad && !is_cleanupret {
146            // We can merge the successor into this bb, so no need for a `br`.
147            MergingSucc::True
148        } else {
149            let mut lltarget = fx.llbb(target);
150            if needs_landing_pad {
151                lltarget = fx.landing_pad_for(target);
152            }
153            if is_cleanupret {
154                // micro-optimization: generate a `ret` rather than a jump
155                // to a trampoline.
156                bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
157            } else {
158                bx.br_with_attrs(lltarget, attributes);
159            }
160            MergingSucc::False
161        }
162    }
163
164    /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
165    /// return destination `destination` and the unwind action `unwind`.
166    fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
167        &self,
168        fx: &mut FunctionCx<'a, 'tcx, Bx>,
169        bx: &mut Bx,
170        fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
171        fn_ptr: Bx::Value,
172        llargs: &[Bx::Value],
173        destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
174        mut unwind: mir::UnwindAction,
175        lifetime_ends_after_call: &[(Bx::Value, Size)],
176        instance: Option<Instance<'tcx>>,
177        kind: CallKind,
178        mergeable_succ: bool,
179    ) -> MergingSucc {
180        let tcx = bx.tcx();
181        if let Some(instance) = instance
182            && is_call_from_compiler_builtins_to_upstream_monomorphization(tcx, instance)
183        {
184            if destination.is_some() {
185                let caller_def = fx.instance.def_id();
186                let e = CompilerBuiltinsCannotCall {
187                    span: tcx.def_span(caller_def),
188                    caller: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(caller_def) }with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
189                    callee: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(instance.def_id()) }with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
190                };
191                tcx.dcx().emit_err(e);
192            } else {
193                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:193",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(193u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("compiler_builtins call to diverging function {0:?} replaced with abort",
                                                    instance.def_id()) as &dyn Value))])
            });
    } else { ; }
};info!(
194                    "compiler_builtins call to diverging function {:?} replaced with abort",
195                    instance.def_id()
196                );
197                bx.abort();
198                bx.unreachable();
199                return MergingSucc::False;
200            }
201        }
202
203        // If there is a cleanup block and the function we're calling can unwind, then
204        // do an invoke, otherwise do a call.
205        let fn_ty = bx.fn_decl_backend_type(fn_abi);
206
207        let caller_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() {
208            Some(bx.tcx().codegen_instance_attrs(fx.instance.def))
209        } else {
210            None
211        };
212        let caller_attrs = caller_attrs.as_deref();
213
214        if !fn_abi.can_unwind {
215            unwind = mir::UnwindAction::Unreachable;
216        }
217
218        let unwind_block = match unwind {
219            mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
220            mir::UnwindAction::Continue => None,
221            mir::UnwindAction::Unreachable => None,
222            mir::UnwindAction::Terminate(reason) => {
223                if fx.mir[self.bb].is_cleanup && base::wants_wasm_eh(fx.cx.tcx().sess) {
224                    // For wasm, we need to generate a nested `cleanuppad within %outer_pad`
225                    // to catch exceptions during cleanup and call `panic_in_cleanup`.
226                    Some(fx.terminate_block(reason, Some(self.bb)))
227                } else if fx.mir[self.bb].is_cleanup
228                    && base::wants_new_eh_instructions(fx.cx.tcx().sess)
229                {
230                    // MSVC SEH will abort automatically if an exception tries to
231                    // propagate out from cleanup.
232                    None
233                } else {
234                    Some(fx.terminate_block(reason, None))
235                }
236            }
237        };
238
239        if kind == CallKind::Tail {
240            bx.tail_call(fn_ty, caller_attrs, fn_abi, fn_ptr, llargs, self.funclet(fx), instance);
241            return MergingSucc::False;
242        }
243
244        if let Some(unwind_block) = unwind_block {
245            let ret_llbb = if let Some((_, target)) = destination {
246                self.llbb_with_cleanup(fx, target)
247            } else {
248                fx.unreachable_block()
249            };
250            let invokeret = bx.invoke(
251                fn_ty,
252                caller_attrs,
253                Some(fn_abi),
254                fn_ptr,
255                llargs,
256                ret_llbb,
257                unwind_block,
258                self.funclet(fx),
259                instance,
260            );
261            if fx.mir[self.bb].is_cleanup {
262                bx.apply_attrs_to_cleanup_callsite(invokeret);
263            }
264
265            if let Some((ret_dest, target)) = destination {
266                bx.switch_to_block(fx.llbb(target));
267                fx.set_debug_loc(bx, self.terminator.source_info);
268                for &(tmp, size) in lifetime_ends_after_call {
269                    bx.lifetime_end(tmp, size);
270                }
271                fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
272
273                // If the return value was retagged as it was stored,
274                // then we might be in a different basic block now.
275                // Update the cached block for `target` to point to this new
276                // block, where codegen will continue.
277                fx.cached_llbbs[target] = CachedLlbb::Some(bx.llbb());
278            }
279            MergingSucc::False
280        } else {
281            let llret = bx.call(
282                fn_ty,
283                caller_attrs,
284                Some(fn_abi),
285                fn_ptr,
286                llargs,
287                self.funclet(fx),
288                instance,
289            );
290            if fx.mir[self.bb].is_cleanup {
291                bx.apply_attrs_to_cleanup_callsite(llret);
292            }
293
294            if let Some((ret_dest, target)) = destination {
295                for &(tmp, size) in lifetime_ends_after_call {
296                    bx.lifetime_end(tmp, size);
297                }
298                fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
299                self.funclet_br(fx, bx, target, mergeable_succ, &[])
300            } else {
301                bx.unreachable();
302                MergingSucc::False
303            }
304        }
305    }
306
307    /// Generates inline assembly with optional `destination` and `unwind`.
308    fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
309        &self,
310        fx: &mut FunctionCx<'a, 'tcx, Bx>,
311        bx: &mut Bx,
312        template: &[InlineAsmTemplatePiece],
313        operands: &[InlineAsmOperandRef<'tcx, Bx>],
314        options: InlineAsmOptions,
315        line_spans: &[Span],
316        destination: Option<mir::BasicBlock>,
317        unwind: mir::UnwindAction,
318        instance: Instance<'_>,
319        mergeable_succ: bool,
320    ) -> MergingSucc {
321        let unwind_target = match unwind {
322            mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
323            mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason, None)),
324            mir::UnwindAction::Continue => None,
325            mir::UnwindAction::Unreachable => None,
326        };
327
328        if operands.iter().any(|x| #[allow(non_exhaustive_omitted_patterns)] match x {
    InlineAsmOperandRef::Label { .. } => true,
    _ => false,
}matches!(x, InlineAsmOperandRef::Label { .. })) {
329            if !unwind_target.is_none() {
    ::core::panicking::panic("assertion failed: unwind_target.is_none()")
};assert!(unwind_target.is_none());
330            let ret_llbb = if let Some(target) = destination {
331                self.llbb_with_cleanup(fx, 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                None,
344            );
345            MergingSucc::False
346        } else if let Some(cleanup) = unwind_target {
347            let ret_llbb = if let Some(target) = destination {
348                self.llbb_with_cleanup(fx, target)
349            } else {
350                fx.unreachable_block()
351            };
352
353            bx.codegen_inline_asm(
354                template,
355                operands,
356                options,
357                line_spans,
358                instance,
359                Some(ret_llbb),
360                Some((cleanup, self.funclet(fx))),
361            );
362            MergingSucc::False
363        } else {
364            bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
365
366            if let Some(target) = destination {
367                self.funclet_br(fx, bx, target, mergeable_succ, &[])
368            } else {
369                bx.unreachable();
370                MergingSucc::False
371            }
372        }
373    }
374}
375
376/// Codegen implementations for some terminator variants.
377impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
378    /// Generates code for a `Resume` terminator.
379    fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
380        if let Some(funclet) = helper.funclet(self) {
381            bx.cleanup_ret(funclet, None);
382        } else {
383            let slot = self.get_personality_slot(bx);
384            let exn0 = slot.project_field(bx, 0);
385            let exn0 = bx.load_operand(exn0).immediate();
386            let exn1 = slot.project_field(bx, 1);
387            let exn1 = bx.load_operand(exn1).immediate();
388            slot.storage_dead(bx);
389
390            bx.resume(exn0, exn1);
391        }
392    }
393
394    fn codegen_switchint_terminator(
395        &mut self,
396        helper: TerminatorCodegenHelper<'tcx>,
397        bx: &mut Bx,
398        discr: &mir::Operand<'tcx>,
399        targets: &SwitchTargets,
400    ) {
401        let discr = self.codegen_operand(bx, discr);
402        let discr_value = discr.immediate();
403        let switch_ty = discr.layout.ty;
404        // If our discriminant is a constant we can branch directly
405        if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
406            let target = targets.target_for_value(const_discr);
407            bx.br(helper.llbb_with_cleanup(self, target));
408            return;
409        };
410
411        let mut target_iter = targets.iter();
412        if target_iter.len() == 1 {
413            // If there are two targets (one conditional, one fallback), emit `br` instead of
414            // `switch`.
415            let (test_value, target) = target_iter.next().unwrap();
416            let otherwise = targets.otherwise();
417            let lltarget = helper.llbb_with_cleanup(self, target);
418            let llotherwise = helper.llbb_with_cleanup(self, otherwise);
419            let target_cold = self.cold_blocks[target];
420            let otherwise_cold = self.cold_blocks[otherwise];
421            // If `target_cold == otherwise_cold`, the branches have the same weight
422            // so there is no expectation. If they differ, the `target` branch is expected
423            // when the `otherwise` branch is cold.
424            let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
425            if switch_ty == bx.tcx().types.bool {
426                // Don't generate trivial icmps when switching on bool.
427                match test_value {
428                    0 => {
429                        let expect = expect.map(|e| !e);
430                        bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
431                    }
432                    1 => {
433                        bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
434                    }
435                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
436                }
437            } else {
438                let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
439                let llval = bx.const_uint_big(switch_llty, test_value);
440                let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
441                bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
442            }
443        } else if target_iter.len() == 2
444            && self.mir[targets.otherwise()].is_empty_unreachable()
445            && targets.all_values().contains(&Pu128(0))
446            && targets.all_values().contains(&Pu128(1))
447        {
448            // This is the really common case for `bool`, `Option`, etc.
449            // By using `trunc nuw` we communicate that other values are
450            // impossible without needing `switch` or `assume`s.
451            let true_bb = targets.target_for_value(1);
452            let false_bb = targets.target_for_value(0);
453            let true_ll = helper.llbb_with_cleanup(self, true_bb);
454            let false_ll = helper.llbb_with_cleanup(self, false_bb);
455
456            let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
457                None
458            } else {
459                match (self.cold_blocks[true_bb], self.cold_blocks[false_bb]) {
460                    // Same coldness, no expectation
461                    (true, true) | (false, false) => None,
462                    // Different coldness, expect the non-cold one
463                    (true, false) => Some(false),
464                    (false, true) => Some(true),
465                }
466            };
467
468            let bool_ty = bx.tcx().types.bool;
469            let cond = if switch_ty == bool_ty {
470                discr_value
471            } else {
472                let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
473                bx.unchecked_utrunc(discr_value, bool_llty)
474            };
475            bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
476        } else if self.cx.sess().opts.optimize == OptLevel::No
477            && target_iter.len() == 2
478            && self.mir[targets.otherwise()].is_empty_unreachable()
479        {
480            // In unoptimized builds, if there are two normal targets and the `otherwise` target is
481            // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
482            // BB, which will usually (but not always) be dead code.
483            //
484            // Why only in unoptimized builds?
485            // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
486            //   must fall back to the slower SelectionDAG isel. Therefore, using `br` gives
487            //   significant compile time speedups for unoptimized builds.
488            // - In optimized builds the above doesn't hold, and using `br` sometimes results in
489            //   worse generated code because LLVM can no longer tell that the value being switched
490            //   on can only have two values, e.g. 0 and 1.
491            //
492            let (test_value1, target1) = target_iter.next().unwrap();
493            let (_test_value2, target2) = target_iter.next().unwrap();
494            let ll1 = helper.llbb_with_cleanup(self, target1);
495            let ll2 = helper.llbb_with_cleanup(self, target2);
496            let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
497            let llval = bx.const_uint_big(switch_llty, test_value1);
498            let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
499            bx.cond_br(cmp, ll1, ll2);
500        } else {
501            let otherwise = targets.otherwise();
502            let otherwise_cold = self.cold_blocks[otherwise];
503            let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
504            let cold_count = targets.iter().filter(|(_, target)| self.cold_blocks[*target]).count();
505            let none_cold = cold_count == 0;
506            let all_cold = cold_count == targets.iter().len();
507            if (none_cold && (!otherwise_cold || otherwise_unreachable))
508                || (all_cold && (otherwise_cold || otherwise_unreachable))
509            {
510                // All targets have the same weight,
511                // or `otherwise` is unreachable and it's the only target with a different weight.
512                bx.switch(
513                    discr_value,
514                    helper.llbb_with_cleanup(self, targets.otherwise()),
515                    target_iter
516                        .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
517                );
518            } else {
519                // Targets have different weights
520                bx.switch_with_weights(
521                    discr_value,
522                    helper.llbb_with_cleanup(self, targets.otherwise()),
523                    otherwise_cold,
524                    target_iter.map(|(value, target)| {
525                        (value, helper.llbb_with_cleanup(self, target), self.cold_blocks[target])
526                    }),
527                );
528            }
529        }
530    }
531
532    fn codegen_return_terminator(&mut self, bx: &mut Bx) {
533        // Explicitly end the lifetime of the VaList if this function is c-variadic. We explicitly
534        // start the lifetime when desugaring `...`. Ending the lifetime meaningfully improves
535        // codegen.
536        if self.fn_abi.c_variadic {
537            // The `VaList` "spoofed" argument is just after all the real arguments.
538            let va_list_arg_idx = self.fn_abi.args.len();
539            match self.locals[mir::Local::arg(va_list_arg_idx)] {
540                LocalRef::Place(va_list) => {
541                    // NOTE: we don't actually call LLVM's va_end here. We know it's a no-op for
542                    // all current targets and hence don't bother
543                    // (as permitted by https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic).
544
545                    // Explicitly end the lifetime of the `va_list`, improves LLVM codegen.
546                    bx.lifetime_end(va_list.val.llval, va_list.layout.size);
547                }
548                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("C-variadic function must have a `VaList` place"))bug!("C-variadic function must have a `VaList` place"),
549            }
550        }
551        if self.fn_abi.ret.layout.is_uninhabited() {
552            // Functions with uninhabited return values are marked `noreturn`,
553            // so we should make sure that we never actually do.
554            // We play it safe by using a well-defined `abort`, but we could go for immediate UB
555            // if that turns out to be helpful.
556            bx.abort();
557            // `abort` does not terminate the block, so we still need to generate
558            // an `unreachable` terminator after it.
559            bx.unreachable();
560            return;
561        }
562        let llval = match &self.fn_abi.ret.mode {
563            PassMode::Ignore | PassMode::Indirect { .. } => {
564                bx.ret_void();
565                return;
566            }
567
568            PassMode::Direct(_) | PassMode::Pair(..) => {
569                let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
570                if let Ref(place_val) = op.val {
571                    bx.load_from_place(bx.backend_type(op.layout), place_val)
572                } else {
573                    op.immediate_or_packed_pair(bx)
574                }
575            }
576
577            PassMode::Cast { cast: cast_ty, pad_i32: _ } => {
578                let op = match self.locals[mir::RETURN_PLACE] {
579                    LocalRef::Operand(op) => op,
580                    LocalRef::PendingOperand => ::rustc_middle::util::bug::bug_fmt(format_args!("use of return before def"))bug!("use of return before def"),
581                    LocalRef::Place(cg_place) => OperandRef {
582                        val: Ref(cg_place.val),
583                        layout: cg_place.layout,
584                        move_annotation: None,
585                    },
586                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
587                };
588                let llslot = match op.val {
589                    Immediate(_) | Pair(..) => {
590                        let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
591                        op.val.store(bx, scratch);
592                        scratch.val.llval
593                    }
594                    Ref(place_val) => {
595                        {
    match (&place_val.align, &op.layout.align.abi) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("return place is unaligned!")));
            }
        }
    }
};assert_eq!(
596                            place_val.align, op.layout.align.abi,
597                            "return place is unaligned!"
598                        );
599                        place_val.llval
600                    }
601                    ZeroSized => ::rustc_middle::util::bug::bug_fmt(format_args!("ZST return value shouldn\'t be in PassMode::Cast"))bug!("ZST return value shouldn't be in PassMode::Cast"),
602                };
603
604                if self.fn_abi.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) {
605                    // The return value of an `extern "cmse-nonsecure-entry"` function crosses the
606                    // secure boundary. Zero padding bytes so information does not leak.
607                    //
608                    // This only zeroes "guaranteed" padding. There may be more bytes that are
609                    // padding for some but not all variants of this type; those are not zeroed.
610                    //
611                    // Returning a value with value-dependent padding will instead trigger a lint.
612                    let ret_layout = self.fn_abi.ret.layout;
613                    let uninit_ranges = ret_layout.padding_ranges(bx.cx());
614                    self.zero_byte_ranges(bx, llslot, ret_layout.size, &uninit_ranges);
615                }
616
617                load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
618            }
619        };
620        bx.ret(llval);
621    }
622
623    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("codegen_drop_terminator",
                                    "rustc_codegen_ssa::mir::block", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                    ::tracing_core::__macro_support::Option::Some(623u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                    ::tracing_core::field::FieldSet::new(&["source_info",
                                                    "location", "target", "unwind", "mergeable_succ"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_info)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unwind)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&mergeable_succ as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: MergingSucc = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty = location.ty(self.mir, bx.tcx()).ty;
            let ty = self.monomorphize(ty);
            let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
            if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) =
                    drop_fn.def {
                return helper.funclet_br(self, bx, target, mergeable_succ,
                        &[]);
            }
            let place = self.codegen_place(bx, location.as_ref());
            let (args1, args2);
            let mut args =
                if let Some(llextra) = place.val.llextra {
                    args2 = [place.val.llval, llextra];
                    &args2[..]
                } else { args1 = [place.val.llval]; &args1[..] };
            let (maybe_null, drop_fn, fn_abi, drop_instance) =
                match ty.kind() {
                    ty::Dynamic(_, _) => {
                        let virtual_drop =
                            Instance {
                                def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0),
                                args: drop_fn.args,
                            };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:672",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(672u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("ty = {0:?}",
                                                                            ty) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:673",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(673u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("drop_fn = {0:?}",
                                                                            drop_fn) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:674",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(674u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("args = {0:?}",
                                                                            args) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let fn_abi =
                            bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
                        let vtable = args[1];
                        args = &args[..1];
                        (true,
                            meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE).get_optional_fn(bx,
                                vtable, ty, fn_abi), fn_abi, virtual_drop)
                    }
                    _ =>
                        (false,
                            bx.get_fn_addr(drop_fn, Some(PacMetadata::default())),
                            bx.fn_abi_of_instance(drop_fn, ty::List::empty()), drop_fn),
                };
            if maybe_null {
                let is_not_null = bx.append_sibling_block("is_not_null");
                let llty = bx.fn_ptr_backend_type(fn_abi);
                let null = bx.const_null(llty);
                let non_null =
                    bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne,
                            false), drop_fn, null);
                bx.cond_br(non_null, is_not_null,
                    helper.llbb_with_cleanup(self, target));
                bx.switch_to_block(is_not_null);
                self.set_debug_loc(bx, *source_info);
            }
            helper.do_call(self, bx, fn_abi, drop_fn, args,
                Some((ReturnDest::Nothing, target)), unwind, &[],
                Some(drop_instance), CallKind::Normal,
                !maybe_null && mergeable_succ)
        }
    }
}#[tracing::instrument(level = "trace", skip(self, helper, bx))]
624    fn codegen_drop_terminator(
625        &mut self,
626        helper: TerminatorCodegenHelper<'tcx>,
627        bx: &mut Bx,
628        source_info: &mir::SourceInfo,
629        location: mir::Place<'tcx>,
630        target: mir::BasicBlock,
631        unwind: mir::UnwindAction,
632        mergeable_succ: bool,
633    ) -> MergingSucc {
634        let ty = location.ty(self.mir, bx.tcx()).ty;
635        let ty = self.monomorphize(ty);
636        let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
637
638        if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) = drop_fn.def {
639            // we don't actually need to drop anything.
640            return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
641        }
642
643        let place = self.codegen_place(bx, location.as_ref());
644        let (args1, args2);
645        let mut args = if let Some(llextra) = place.val.llextra {
646            args2 = [place.val.llval, llextra];
647            &args2[..]
648        } else {
649            args1 = [place.val.llval];
650            &args1[..]
651        };
652        let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
653            // FIXME(eddyb) perhaps move some of this logic into
654            // `Instance::resolve_drop_glue`?
655            ty::Dynamic(_, _) => {
656                // IN THIS ARM, WE HAVE:
657                // ty = *mut (dyn Trait)
658                // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
659                //                       args[0]    args[1]
660                //
661                // args = ( Data, Vtable )
662                //                  |
663                //                  v
664                //                /-------\
665                //                | ...   |
666                //                \-------/
667                //
668                let virtual_drop = Instance {
669                    def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), // idx 0: the drop function
670                    args: drop_fn.args,
671                };
672                debug!("ty = {:?}", ty);
673                debug!("drop_fn = {:?}", drop_fn);
674                debug!("args = {:?}", args);
675                let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
676                let vtable = args[1];
677                // Truncate vtable off of args list
678                args = &args[..1];
679                (
680                    true,
681                    meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
682                        .get_optional_fn(bx, vtable, ty, fn_abi),
683                    fn_abi,
684                    virtual_drop,
685                )
686            }
687            _ => (
688                false,
689                bx.get_fn_addr(drop_fn, Some(PacMetadata::default())),
690                bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
691                drop_fn,
692            ),
693        };
694
695        // We generate a null check for the drop_fn. This saves a bunch of relocations being
696        // generated for no-op drops.
697        if maybe_null {
698            let is_not_null = bx.append_sibling_block("is_not_null");
699            let llty = bx.fn_ptr_backend_type(fn_abi);
700            let null = bx.const_null(llty);
701            let non_null =
702                bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
703            bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
704            bx.switch_to_block(is_not_null);
705            self.set_debug_loc(bx, *source_info);
706        }
707
708        helper.do_call(
709            self,
710            bx,
711            fn_abi,
712            drop_fn,
713            args,
714            Some((ReturnDest::Nothing, target)),
715            unwind,
716            &[],
717            Some(drop_instance),
718            CallKind::Normal,
719            !maybe_null && mergeable_succ,
720        )
721    }
722
723    fn codegen_assert_terminator(
724        &mut self,
725        helper: TerminatorCodegenHelper<'tcx>,
726        bx: &mut Bx,
727        terminator: &mir::Terminator<'tcx>,
728        cond: &mir::Operand<'tcx>,
729        expected: bool,
730        msg: &mir::AssertMessage<'tcx>,
731        target: mir::BasicBlock,
732        unwind: mir::UnwindAction,
733        mergeable_succ: bool,
734    ) -> MergingSucc {
735        let span = terminator.source_info.span;
736        let cond = self.codegen_operand(bx, cond).immediate();
737        let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
738
739        // This case can currently arise only from functions marked
740        // with #[rustc_inherit_overflow_checks] and inlined from
741        // another crate (mostly core::num generic/#[inline] fns),
742        // while the current crate doesn't use overflow checks.
743        if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
744            const_cond = Some(expected);
745        }
746
747        // Don't codegen the panic block if success if known.
748        if const_cond == Some(expected) {
749            return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
750        }
751
752        // Because we're branching to a panic block (either a `#[cold]` one
753        // or an inlined abort), there's no need to `expect` it.
754
755        // Create the failure block and the conditional branch to it.
756        let lltarget = helper.llbb_with_cleanup(self, target);
757        let panic_block = bx.append_sibling_block("panic");
758        if expected {
759            bx.cond_br(cond, lltarget, panic_block);
760        } else {
761            bx.cond_br(cond, panic_block, lltarget);
762        }
763
764        // After this point, bx is the block for the call to panic.
765        bx.switch_to_block(panic_block);
766        self.set_debug_loc(bx, terminator.source_info);
767
768        // Get the location information.
769        let location = self.get_caller_location(bx, terminator.source_info).immediate();
770
771        // Put together the arguments to the panic entry point.
772        let (lang_item, args) = match msg {
773            AssertKind::BoundsCheck { len, index } => {
774                let len = self.codegen_operand(bx, len).immediate();
775                let index = self.codegen_operand(bx, index).immediate();
776                // It's `fn panic_bounds_check(index: usize, len: usize)`,
777                // and `#[track_caller]` adds an implicit third argument.
778                (LangItem::PanicBoundsCheck, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [index, len, location]))vec![index, len, location])
779            }
780            AssertKind::MisalignedPointerDereference { required, found } => {
781                let required = self.codegen_operand(bx, required).immediate();
782                let found = self.codegen_operand(bx, found).immediate();
783                // It's `fn panic_misaligned_pointer_dereference(required: usize, found: usize)`,
784                // and `#[track_caller]` adds an implicit third argument.
785                (LangItem::PanicMisalignedPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [required, found, location]))vec![required, found, location])
786            }
787            AssertKind::NullPointerDereference => {
788                // It's `fn panic_null_pointer_dereference()`,
789                // `#[track_caller]` adds an implicit argument.
790                (LangItem::PanicNullPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
791            }
792            AssertKind::NullReferenceConstructed => {
793                // It's `fn panic_null_reference_constructed()`,
794                // `#[track_caller]` adds an implicit argument.
795                (LangItem::PanicNullReferenceConstructed, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
796            }
797            AssertKind::InvalidEnumConstruction(source) => {
798                let source = self.codegen_operand(bx, source).immediate();
799                // It's `fn panic_invalid_enum_construction(source: u128)`,
800                // `#[track_caller]` adds an implicit argument.
801                (LangItem::PanicInvalidEnumConstruction, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [source, location]))vec![source, location])
802            }
803            _ => {
804                // It's `pub fn panic_...()` and `#[track_caller]` adds an implicit argument.
805                (msg.panic_function(), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
806            }
807        };
808
809        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
810
811        // Codegen the actual panic invoke/call.
812        let merging_succ = helper.do_call(
813            self,
814            bx,
815            fn_abi,
816            llfn,
817            &args,
818            None,
819            unwind,
820            &[],
821            Some(instance),
822            CallKind::Normal,
823            false,
824        );
825        {
    match (&merging_succ, &MergingSucc::False) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(merging_succ, MergingSucc::False);
826        MergingSucc::False
827    }
828
829    fn codegen_terminate_terminator(
830        &mut self,
831        helper: TerminatorCodegenHelper<'tcx>,
832        bx: &mut Bx,
833        terminator: &mir::Terminator<'tcx>,
834        reason: UnwindTerminateReason,
835    ) {
836        let span = terminator.source_info.span;
837        self.set_debug_loc(bx, terminator.source_info);
838
839        // Obtain the panic entry point.
840        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
841
842        // Codegen the actual panic invoke/call.
843        let merging_succ = helper.do_call(
844            self,
845            bx,
846            fn_abi,
847            llfn,
848            &[],
849            None,
850            mir::UnwindAction::Unreachable,
851            &[],
852            Some(instance),
853            CallKind::Normal,
854            false,
855        );
856        {
    match (&merging_succ, &MergingSucc::False) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(merging_succ, MergingSucc::False);
857    }
858
859    /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
860    fn codegen_panic_intrinsic(
861        &mut self,
862        helper: &TerminatorCodegenHelper<'tcx>,
863        bx: &mut Bx,
864        intrinsic: ty::IntrinsicDef,
865        instance: Instance<'tcx>,
866        source_info: mir::SourceInfo,
867        target: Option<mir::BasicBlock>,
868        unwind: mir::UnwindAction,
869        mergeable_succ: bool,
870    ) -> Option<MergingSucc> {
871        // Emit a panic or a no-op for `assert_*` intrinsics.
872        // These are intrinsics that compile to panics so that we can get a message
873        // which mentions the offending type, even from a const context.
874        let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
875            return None;
876        };
877
878        let ty = instance.args.type_at(0);
879
880        let is_valid = bx
881            .tcx()
882            .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
883            .expect("expect to have layout during codegen");
884
885        if is_valid {
886            // a NOP
887            let target = target.unwrap();
888            return Some(helper.funclet_br(self, bx, target, mergeable_succ, &[]));
889        }
890
891        let layout = bx.layout_of(ty);
892
893        let msg_str = {
    let _guard = NoVisibleGuard::new();
    {
        {
            let _guard = NoTrimmedGuard::new();
            {
                if layout.is_uninhabited() {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to instantiate uninhabited type `{0}`",
                                    ty))
                        })
                } else if requirement == ValidityRequirement::Zero {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to zero-initialize type `{0}`, which is invalid",
                                    ty))
                        })
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to leave type `{0}` uninitialized, which is invalid",
                                    ty))
                        })
                }
            }
        }
    }
}with_no_visible_paths!({
894            with_no_trimmed_paths!({
895                if layout.is_uninhabited() {
896                    // Use this error even for the other intrinsics as it is more precise.
897                    format!("attempted to instantiate uninhabited type `{ty}`")
898                } else if requirement == ValidityRequirement::Zero {
899                    format!("attempted to zero-initialize type `{ty}`, which is invalid")
900                } else {
901                    format!("attempted to leave type `{ty}` uninitialized, which is invalid")
902                }
903            })
904        });
905        let msg = bx.const_str(&msg_str);
906
907        // Obtain the panic entry point.
908        let (fn_abi, llfn, instance) =
909            common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
910
911        // Codegen the actual panic invoke/call.
912        Some(helper.do_call(
913            self,
914            bx,
915            fn_abi,
916            llfn,
917            &[msg.0, msg.1],
918            target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
919            unwind,
920            &[],
921            Some(instance),
922            CallKind::Normal,
923            mergeable_succ,
924        ))
925    }
926
927    fn codegen_call_terminator(
928        &mut self,
929        helper: TerminatorCodegenHelper<'tcx>,
930        bx: &mut Bx,
931        terminator: &mir::Terminator<'tcx>,
932        func: &mir::Operand<'tcx>,
933        args: &[Spanned<mir::Operand<'tcx>>],
934        destination: mir::Place<'tcx>,
935        target: Option<mir::BasicBlock>,
936        unwind: mir::UnwindAction,
937        fn_span: Span,
938        kind: CallKind,
939        mergeable_succ: bool,
940    ) -> MergingSucc {
941        let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
942
943        // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
944        let callee = self.codegen_operand(bx, func);
945
946        let (instance, mut llfn) = match *callee.layout.ty.kind() {
947            ty::FnDef(def_id, generic_args) => {
948                let instance = ty::Instance::expect_resolve(
949                    bx.tcx(),
950                    bx.typing_env(),
951                    def_id,
952                    generic_args,
953                    fn_span,
954                );
955
956                match instance.def {
957                    // We don't need AsyncDropGlueCtorShim here because it is not `noop func`,
958                    // it is `func returning noop future`
959                    ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) => {
960                        // Empty drop glue; a no-op.
961                        let target = target.unwrap();
962                        return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
963                    }
964                    ty::InstanceKind::Intrinsic(def_id) => {
965                        let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
966                        if let Some(merging_succ) = self.codegen_panic_intrinsic(
967                            &helper,
968                            bx,
969                            intrinsic,
970                            instance,
971                            source_info,
972                            target,
973                            unwind,
974                            mergeable_succ,
975                        ) {
976                            return merging_succ;
977                        }
978
979                        let result_layout =
980                            self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
981
982                        let (result_place, store_in_local) =
983                            if let Some(local) = destination.as_local() {
984                                match self.locals[local] {
985                                    LocalRef::Place(dest) => (Some(dest.val), None),
986                                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
987                                    LocalRef::PendingOperand => (None, Some(local)),
988                                    LocalRef::Operand(_) => {
989                                        if result_layout.is_zst() {
990                                            let place = PlaceRef::new_sized(
991                                                bx.const_undef(bx.type_ptr()),
992                                                result_layout,
993                                            );
994                                            (Some(place.val), None)
995                                        } else {
996                                            ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
997                                        }
998                                    }
999                                }
1000                            } else {
1001                                (Some(self.codegen_place(bx, destination.as_ref()).val), None)
1002                            };
1003
1004                        if let Some(place) = result_place
1005                            && place.align < result_layout.align.abi
1006                        {
1007                            // Currently, MIR code generation does not create calls
1008                            // that store directly to fields of packed structs (in
1009                            // fact, the calls it creates write only to temps).
1010                            //
1011                            // If someone changes that, please update this code path
1012                            // to create a temporary.
1013                            ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
    format_args!("can\'t directly store to unaligned value"));span_bug!(self.mir.span, "can't directly store to unaligned value");
1014                        }
1015
1016                        let args: Vec<_> =
1017                            args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
1018
1019                        let intrinsic_result = self.codegen_intrinsic_call(
1020                            bx,
1021                            instance,
1022                            &args,
1023                            result_layout,
1024                            result_place,
1025                            source_info,
1026                        );
1027
1028                        if let IntrinsicResult::Operand(op_val) = intrinsic_result {
1029                            match (result_place, store_in_local) {
1030                                (None, Some(local)) => {
1031                                    let op = OperandRef {
1032                                        val: op_val,
1033                                        layout: result_layout,
1034                                        move_annotation: None,
1035                                    };
1036                                    self.overwrite_local(local, LocalRef::Operand(op));
1037                                    self.debug_introduce_local(bx, local);
1038                                }
1039                                (Some(place_val), None) => {
1040                                    let dest = PlaceRef { val: place_val, layout: result_layout };
1041                                    op_val.store(bx, dest);
1042                                }
1043                                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1044                            }
1045                        }
1046
1047                        match intrinsic_result {
1048                            IntrinsicResult::Operand(_) | IntrinsicResult::WroteIntoPlace => {
1049                                return if let Some(target) = target {
1050                                    helper.funclet_br(self, bx, target, mergeable_succ, &[])
1051                                } else {
1052                                    bx.unreachable();
1053                                    MergingSucc::False
1054                                };
1055                            }
1056                            IntrinsicResult::Err(_) => {
1057                                // Even though we're definitely going to error, we need it initialize
1058                                // the local or `maybe_codegen_consume_direct` might ICE later
1059                                // when it goes to use the result from this intrinsic.
1060                                if let Some(local) = store_in_local {
1061                                    let op = OperandRef {
1062                                        val: OperandValue::poison(bx, result_layout),
1063                                        layout: result_layout,
1064                                        move_annotation: None,
1065                                    };
1066                                    self.overwrite_local(local, LocalRef::Operand(op));
1067                                }
1068                                // Also we need to terminate the block to avoid an LLVM assertion,
1069                                // even though we're not going to actually use the IR.
1070                                bx.abort();
1071                                return MergingSucc::False;
1072                            }
1073                            IntrinsicResult::Fallback(instance) => {
1074                                if intrinsic.must_be_overridden {
1075                                    ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("intrinsic {0} must be overridden by codegen backend, but isn\'t",
        intrinsic.name));span_bug!(
1076                                        fn_span,
1077                                        "intrinsic {} must be overridden by codegen backend, but isn't",
1078                                        intrinsic.name,
1079                                    );
1080                                }
1081                                (Some(instance), None)
1082                            }
1083                        }
1084                    }
1085
1086                    _ if kind == CallKind::Tail
1087                        && instance.def.requires_caller_location(bx.tcx()) =>
1088                    {
1089                        if let Some(hir_id) =
1090                            terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1091                        {
1092                            bx.tcx().emit_node_lint(TAIL_CALL_TRACK_CALLER, hir_id, rustc_errors::DiagDecorator(|d| {
1093                                _ = d.primary_message("tail calling a function marked with `#[track_caller]` has no special effect").span(fn_span)
1094                            }));
1095                        }
1096
1097                        let instance = ty::Instance::resolve_for_fn_ptr(
1098                            bx.tcx(),
1099                            bx.typing_env(),
1100                            def_id,
1101                            generic_args,
1102                        )
1103                        .unwrap();
1104
1105                        (None, Some(bx.get_fn_addr(instance, Some(PacMetadata::default()))))
1106                    }
1107                    _ => (Some(instance), None),
1108                }
1109            }
1110            ty::FnPtr(..) => (None, Some(callee.immediate())),
1111            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} is not callable",
        callee.layout.ty))bug!("{} is not callable", callee.layout.ty),
1112        };
1113
1114        if let Some(instance) = instance
1115            && let Some(name) = bx.tcx().codegen_fn_attrs(instance.def_id()).symbol_name
1116            && name.as_str().starts_with("llvm.")
1117            // This is the only LLVM intrinsic we use that unwinds
1118            // FIXME either add unwind support to codegen_llvm_intrinsic_call or replace usage of
1119            // this intrinsic with something else
1120            && name.as_str() != "llvm.wasm.throw"
1121        {
1122            if !!instance.args.has_infer() {
    ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
1123            if !!instance.args.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !instance.args.has_escaping_bound_vars()")
};assert!(!instance.args.has_escaping_bound_vars());
1124
1125            let result_layout =
1126                self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1127
1128            let return_dest = if result_layout.is_zst() {
1129                ReturnDest::Nothing
1130            } else if let Some(index) = destination.as_local() {
1131                match self.locals[index] {
1132                    LocalRef::Place(dest) => ReturnDest::Store(dest),
1133                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
1134                    LocalRef::PendingOperand => {
1135                        // Handle temporary places, specifically `Operand` ones, as
1136                        // they don't have `alloca`s.
1137                        ReturnDest::DirectOperand(index)
1138                    }
1139                    LocalRef::Operand(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"))bug!("place local already assigned to"),
1140                }
1141            } else {
1142                ReturnDest::Store(self.codegen_place(bx, destination.as_ref()))
1143            };
1144
1145            let args =
1146                args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::<Vec<_>>();
1147
1148            self.set_debug_loc(bx, source_info);
1149
1150            let llret =
1151                bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup);
1152
1153            if let Some(target) = target {
1154                self.store_return(
1155                    bx,
1156                    return_dest,
1157                    &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) },
1158                    llret,
1159                );
1160                return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
1161            } else {
1162                bx.unreachable();
1163                return MergingSucc::False;
1164            }
1165        }
1166
1167        // FIXME(eddyb) avoid computing this if possible, when `instance` is
1168        // available - right now `sig` is only needed for getting the `abi`
1169        // and figuring out how many extra args were passed to a C-variadic `fn`.
1170        let sig = callee.layout.ty.fn_sig(bx.tcx());
1171
1172        let extra_args = &args[sig.inputs().skip_binder().len()..];
1173        let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1174            let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1175            self.monomorphize(op_ty)
1176        }));
1177
1178        let fn_abi = match instance {
1179            Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1180            None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1181        };
1182
1183        // The arguments we'll be passing. Plus one to account for outptr, if used.
1184        let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1185
1186        let mut llargs = Vec::with_capacity(arg_count);
1187
1188        // We still need to call `make_return_dest` even if there's no `target`, since
1189        // `fn_abi.ret` could be `PassMode::Indirect`, even if it is uninhabited,
1190        // and `make_return_dest` adds the return-place indirect pointer to `llargs`.
1191        let destination = match kind {
1192            CallKind::Normal => {
1193                let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs);
1194                target.map(|target| (return_dest, target))
1195            }
1196            CallKind::Tail => {
1197                if fn_abi.ret.is_indirect() {
1198                    match self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs) {
1199                        ReturnDest::Nothing => {}
1200                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("tail calls to functions with indirect returns cannot store into a destination"))bug!(
1201                            "tail calls to functions with indirect returns cannot store into a destination"
1202                        ),
1203                    }
1204                }
1205                None
1206            }
1207        };
1208
1209        // Split the rust-call tupled arguments off.
1210        // FIXME(splat): un-tuple splatted arguments in codegen, for performance
1211        let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1212            && let Some((tup, args)) = args.split_last()
1213        {
1214            (args, Some(tup))
1215        } else {
1216            (args, None)
1217        };
1218
1219        // Special logic for tail calls with `PassMode::Indirect { on_stack: false, .. }` arguments.
1220        //
1221        // Normally an indirect argument that is allocated in the caller's stack frame
1222        // would be passed as a pointer into the callee's stack frame.
1223        // For tail calls, that would be unsound, because the caller's
1224        // stack frame is overwritten by the callee's stack frame.
1225        //
1226        // Therefore we store the argument for the callee in the corresponding caller's slot.
1227        // Because guaranteed tail calls demand that the caller's signature matches the callee's,
1228        // the corresponding slot has the correct type.
1229        //
1230        // To handle cases like the one below, the tail call arguments must first be copied to a
1231        // temporary, and only then copied to the caller's argument slots.
1232        //
1233        // ```
1234        // // A struct big enough that it is not passed via registers.
1235        // pub struct Big([u64; 4]);
1236        //
1237        // fn swapper(a: Big, b: Big) -> (Big, Big) {
1238        //     become swapper_helper(b, a);
1239        // }
1240        // ```
1241        let mut tail_call_temporaries = ::alloc::vec::Vec::new()vec![];
1242        if kind == CallKind::Tail {
1243            tail_call_temporaries = ::alloc::vec::from_elem(None, first_args.len())vec![None; first_args.len()];
1244            // Copy the arguments that use `PassMode::Indirect { on_stack: false , ..}`
1245            // to temporary stack allocations. See the comment above.
1246            for (i, arg) in first_args.iter().enumerate() {
1247                if !#[allow(non_exhaustive_omitted_patterns)] match fn_abi.args[i].mode {
    PassMode::Indirect { on_stack: false, .. } => true,
    _ => false,
}matches!(fn_abi.args[i].mode, PassMode::Indirect { on_stack: false, .. }) {
1248                    continue;
1249                }
1250
1251                let op = self.codegen_operand(bx, &arg.node);
1252                let tmp = PlaceRef::alloca(bx, op.layout);
1253                bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1254                op.store_with_annotation(bx, tmp);
1255
1256                tail_call_temporaries[i] = Some(tmp);
1257            }
1258        }
1259
1260        // When generating arguments we sometimes introduce temporary allocations with lifetime
1261        // that extend for the duration of a call. Keep track of those allocations and their sizes
1262        // to generate `lifetime_end` when the call returns.
1263        let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1264        'make_args: for (i, arg) in first_args.iter().enumerate() {
1265            let mut op = self.codegen_operand(bx, &arg.node);
1266
1267            if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1268                match op.val {
1269                    Pair(data_ptr, meta) => {
1270                        // In the case of Rc<Self>, we need to explicitly pass a
1271                        // *mut RcInner<Self> with a Scalar (not ScalarPair) ABI. This is a hack
1272                        // that is understood elsewhere in the compiler as a method on
1273                        // `dyn Trait`.
1274                        // To get a `*mut RcInner<Self>`, we just keep unwrapping newtypes until
1275                        // we get a value of a built-in pointer type.
1276                        //
1277                        // This is also relevant for `Pin<&mut Self>`, where we need to peel the
1278                        // `Pin`.
1279                        while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1280                            let (idx, _) = op.layout.non_1zst_field(bx).expect(
1281                                "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1282                            );
1283                            op = op.extract_field(self, bx, idx.as_usize());
1284                        }
1285
1286                        // Now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
1287                        // data pointer and vtable. Look up the method in the vtable, and pass
1288                        // the data pointer as the first argument.
1289                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1290                            bx,
1291                            meta,
1292                            op.layout.ty,
1293                            fn_abi,
1294                        ));
1295                        llargs.push(data_ptr);
1296                        continue 'make_args;
1297                    }
1298                    Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1299                        // by-value dynamic dispatch
1300                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1301                            bx,
1302                            meta,
1303                            op.layout.ty,
1304                            fn_abi,
1305                        ));
1306                        llargs.push(data_ptr);
1307                        continue;
1308                    }
1309                    _ => {
1310                        ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("can\'t codegen a virtual call on {0:#?}", op));span_bug!(fn_span, "can't codegen a virtual call on {:#?}", op);
1311                    }
1312                }
1313            }
1314
1315            let by_move = if let PassMode::Indirect { on_stack: false, .. } = fn_abi.args[i].mode
1316                && kind == CallKind::Tail
1317            {
1318                // Special logic for tail calls with `PassMode::Indirect { on_stack: false, .. }` arguments.
1319                //
1320                // Normally an indirect argument that is allocated in the caller's stack frame
1321                // would be passed as a pointer into the callee's stack frame.
1322                // For tail calls, that would be unsound, because the caller's
1323                // stack frame is overwritten by the callee's stack frame.
1324                //
1325                // To handle the case, we introduce `tail_call_temporaries` to copy arguments into
1326                // temporaries, then copy back to the caller's argument slots.
1327                // Finally, we pass the caller's argument slots as arguments.
1328                //
1329                // To do that, the argument must be MUST-by-move value.
1330                let Some(tmp) = tail_call_temporaries[i].take() else {
1331                    ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("missing temporary for indirect tail call argument #{0}", i))span_bug!(fn_span, "missing temporary for indirect tail call argument #{i}")
1332                };
1333
1334                let local = self.mir.args_iter().nth(i).unwrap();
1335
1336                match &self.locals[local] {
1337                    LocalRef::Place(arg) => {
1338                        bx.typed_place_copy(arg.val, tmp.val, fn_abi.args[i].layout);
1339                        op.val = Ref(arg.val);
1340                    }
1341                    LocalRef::Operand(arg) => {
1342                        let Ref(place_value) = arg.val else {
1343                            ::rustc_middle::util::bug::bug_fmt(format_args!("only `Ref` should use `PassMode::Indirect`, but got {0:?}",
        arg.val));bug!(
1344                                "only `Ref` should use `PassMode::Indirect`, but got {:?}",
1345                                arg.val
1346                            );
1347                        };
1348                        bx.typed_place_copy(place_value, tmp.val, fn_abi.args[i].layout);
1349                        op.val = arg.val;
1350                    }
1351                    LocalRef::UnsizedPlace(_) => {
1352                        ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("unsized types are not supported"))span_bug!(fn_span, "unsized types are not supported")
1353                    }
1354                    LocalRef::PendingOperand => {
1355                        ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("argument local should not be pending"))span_bug!(fn_span, "argument local should not be pending")
1356                    }
1357                };
1358
1359                bx.lifetime_end(tmp.val.llval, tmp.layout.size);
1360                true
1361            } else {
1362                #[allow(non_exhaustive_omitted_patterns)] match arg.node {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(arg.node, mir::Operand::Move(_))
1363            };
1364
1365            self.codegen_argument(
1366                bx,
1367                fn_abi.conv,
1368                op,
1369                by_move,
1370                &mut llargs,
1371                &fn_abi.args[i],
1372                &mut lifetime_ends_after_call,
1373            );
1374        }
1375        let num_untupled = untuple.map(|tup| {
1376            self.codegen_arguments_untupled(
1377                bx,
1378                fn_abi.conv,
1379                &tup.node,
1380                &mut llargs,
1381                &fn_abi.args[first_args.len()..],
1382                &mut lifetime_ends_after_call,
1383            )
1384        });
1385
1386        let needs_location =
1387            instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1388        if needs_location {
1389            let mir_args = if let Some(num_untupled) = num_untupled {
1390                first_args.len() + num_untupled
1391            } else {
1392                args.len()
1393            };
1394            {
    match (&fn_abi.args.len(), &(mir_args + 1)) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("#[track_caller] fn\'s must have 1 more argument in their ABI than in their MIR: {0:?} {1:?} {2:?}",
                            instance, fn_span, fn_abi)));
            }
        }
    }
};assert_eq!(
1395                fn_abi.args.len(),
1396                mir_args + 1,
1397                "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1398            );
1399            let location = self.get_caller_location(bx, source_info);
1400            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1400",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1400u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_call_terminator({0:?}): location={1:?} (fn_span {2:?})",
                                                    terminator, location, fn_span) as &dyn Value))])
            });
    } else { ; }
};debug!(
1401                "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1402                terminator, location, fn_span
1403            );
1404
1405            let last_arg = fn_abi.args.last().unwrap();
1406            self.codegen_argument(
1407                bx,
1408                fn_abi.conv,
1409                location,
1410                /* by_move */ false,
1411                &mut llargs,
1412                last_arg,
1413                &mut lifetime_ends_after_call,
1414            );
1415        }
1416
1417        let fn_ptr = match (instance, llfn) {
1418            (Some(instance), None) => bx.get_fn_addr(instance, Some(PacMetadata::default())),
1419            (_, Some(llfn)) => llfn,
1420            _ => ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("no instance or llfn for call"))span_bug!(fn_span, "no instance or llfn for call"),
1421        };
1422        self.set_debug_loc(bx, source_info);
1423        helper.do_call(
1424            self,
1425            bx,
1426            fn_abi,
1427            fn_ptr,
1428            &llargs,
1429            destination,
1430            unwind,
1431            &lifetime_ends_after_call,
1432            instance,
1433            kind,
1434            mergeable_succ,
1435        )
1436    }
1437
1438    fn codegen_asm_terminator(
1439        &mut self,
1440        helper: TerminatorCodegenHelper<'tcx>,
1441        bx: &mut Bx,
1442        asm_macro: InlineAsmMacro,
1443        terminator: &mir::Terminator<'tcx>,
1444        template: &[ast::InlineAsmTemplatePiece],
1445        operands: &[mir::InlineAsmOperand<'tcx>],
1446        options: ast::InlineAsmOptions,
1447        line_spans: &[Span],
1448        targets: &[mir::BasicBlock],
1449        unwind: mir::UnwindAction,
1450        instance: Instance<'_>,
1451        mergeable_succ: bool,
1452    ) -> MergingSucc {
1453        let span = terminator.source_info.span;
1454
1455        let operands: Vec<_> = operands
1456            .iter()
1457            .map(|op| match *op {
1458                mir::InlineAsmOperand::In { reg, ref value } => {
1459                    let value = self.codegen_operand(bx, value);
1460                    InlineAsmOperandRef::In { reg, value }
1461                }
1462                mir::InlineAsmOperand::Out { reg, late, ref place } => {
1463                    let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1464                    InlineAsmOperandRef::Out { reg, late, place }
1465                }
1466                mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1467                    let in_value = self.codegen_operand(bx, in_value);
1468                    let out_place =
1469                        out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1470                    InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1471                }
1472                mir::InlineAsmOperand::Const { ref value } => {
1473                    let const_value = self.eval_mir_constant(value);
1474                    let string = common::asm_const_to_str(
1475                        bx.tcx(),
1476                        span,
1477                        const_value,
1478                        bx.layout_of(value.ty()),
1479                    );
1480                    InlineAsmOperandRef::Const { string }
1481                }
1482                mir::InlineAsmOperand::SymFn { ref value } => {
1483                    let const_ = self.monomorphize(value.const_);
1484                    if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1485                        let instance = ty::Instance::resolve_for_fn_ptr(
1486                            bx.tcx(),
1487                            bx.typing_env(),
1488                            def_id,
1489                            args,
1490                        )
1491                        .unwrap();
1492                        InlineAsmOperandRef::SymFn { instance }
1493                    } else {
1494                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("invalid type for asm sym (fn)"));span_bug!(span, "invalid type for asm sym (fn)");
1495                    }
1496                }
1497                mir::InlineAsmOperand::SymStatic { def_id } => {
1498                    InlineAsmOperandRef::SymStatic { def_id }
1499                }
1500                mir::InlineAsmOperand::Label { target_index } => {
1501                    InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1502                }
1503            })
1504            .collect();
1505
1506        helper.do_inlineasm(
1507            self,
1508            bx,
1509            template,
1510            &operands,
1511            options,
1512            line_spans,
1513            if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1514            unwind,
1515            instance,
1516            mergeable_succ,
1517        )
1518    }
1519
1520    pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1521        let llbb = match self.try_llbb(bb) {
1522            Some(llbb) => llbb,
1523            None => return,
1524        };
1525        let bx = &mut Bx::build(self.cx, llbb);
1526        let mir = self.mir;
1527
1528        // MIR basic blocks stop at any function call. This may not be the case
1529        // for the backend's basic blocks, in which case we might be able to
1530        // combine multiple MIR basic blocks into a single backend basic block.
1531        loop {
1532            let data = &mir[bb];
1533
1534            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1534",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1534u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_block({0:?}={1:?})",
                                                    bb, data) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_block({:?}={:?})", bb, data);
1535
1536            for statement in &data.statements {
1537                self.codegen_statement(bx, statement);
1538            }
1539            self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1540
1541            let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1542            if let MergingSucc::False = merging_succ {
1543                break;
1544            }
1545
1546            // We are merging the successor into the produced backend basic
1547            // block. Record that the successor should be skipped when it is
1548            // reached.
1549            //
1550            // Note: we must not have already generated code for the successor.
1551            // This is implicitly ensured by the reverse postorder traversal,
1552            // and the assertion explicitly guarantees that.
1553            let mut successors = data.terminator().successors();
1554            let succ = successors.next().unwrap();
1555            if !#[allow(non_exhaustive_omitted_patterns)] match self.cached_llbbs[succ] {
            CachedLlbb::None => true,
            _ => false,
        } {
    ::core::panicking::panic("assertion failed: matches!(self.cached_llbbs[succ], CachedLlbb::None)")
};assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1556            self.cached_llbbs[succ] = CachedLlbb::Skip;
1557            bb = succ;
1558        }
1559    }
1560
1561    pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1562        let llbb = match self.try_llbb(bb) {
1563            Some(llbb) => llbb,
1564            None => return,
1565        };
1566        let bx = &mut Bx::build(self.cx, llbb);
1567        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1567",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1567u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_block_as_unreachable({0:?})",
                                                    bb) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_block_as_unreachable({:?})", bb);
1568        bx.unreachable();
1569    }
1570
1571    fn codegen_terminator(
1572        &mut self,
1573        bx: &mut Bx,
1574        bb: mir::BasicBlock,
1575        terminator: &'tcx mir::Terminator<'tcx>,
1576    ) -> MergingSucc {
1577        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1577",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1577u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_terminator: {0:?}",
                                                    terminator) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_terminator: {:?}", terminator);
1578
1579        let helper = TerminatorCodegenHelper { bb, terminator };
1580
1581        let mergeable_succ = || {
1582            // Note: any call to `switch_to_block` will invalidate a `true` value
1583            // of `mergeable_succ`.
1584            let mut successors = terminator.successors();
1585            if let Some(succ) = successors.next()
1586                && successors.next().is_none()
1587                && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1588            {
1589                // bb has a single successor, and bb is its only predecessor. This
1590                // makes it a candidate for merging.
1591                {
    match (&succ_pred, &bb) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(succ_pred, bb);
1592                true
1593            } else {
1594                false
1595            }
1596        };
1597
1598        self.set_debug_loc(bx, terminator.source_info);
1599        match terminator.kind {
1600            mir::TerminatorKind::UnwindResume => {
1601                self.codegen_resume_terminator(helper, bx);
1602                MergingSucc::False
1603            }
1604
1605            mir::TerminatorKind::UnwindTerminate(reason) => {
1606                self.codegen_terminate_terminator(helper, bx, terminator, reason);
1607                MergingSucc::False
1608            }
1609
1610            mir::TerminatorKind::Goto { target } => {
1611                helper.funclet_br(self, bx, target, mergeable_succ(), &terminator.attributes)
1612            }
1613
1614            mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1615                self.codegen_switchint_terminator(helper, bx, discr, targets);
1616                MergingSucc::False
1617            }
1618
1619            mir::TerminatorKind::Return => {
1620                self.codegen_return_terminator(bx);
1621                MergingSucc::False
1622            }
1623
1624            mir::TerminatorKind::Unreachable => {
1625                bx.unreachable();
1626                MergingSucc::False
1627            }
1628
1629            mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop } => {
1630                if !drop.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("Async Drop must be expanded or reset to sync before codegen"));
    }
};assert!(
1631                    drop.is_none(),
1632                    "Async Drop must be expanded or reset to sync before codegen"
1633                );
1634                self.codegen_drop_terminator(
1635                    helper,
1636                    bx,
1637                    &terminator.source_info,
1638                    place,
1639                    target,
1640                    unwind,
1641                    mergeable_succ(),
1642                )
1643            }
1644
1645            mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1646                .codegen_assert_terminator(
1647                    helper,
1648                    bx,
1649                    terminator,
1650                    cond,
1651                    expected,
1652                    msg,
1653                    target,
1654                    unwind,
1655                    mergeable_succ(),
1656                ),
1657
1658            mir::TerminatorKind::Call {
1659                ref func,
1660                ref args,
1661                destination,
1662                target,
1663                unwind,
1664                call_source: _,
1665                fn_span,
1666            } => self.codegen_call_terminator(
1667                helper,
1668                bx,
1669                terminator,
1670                func,
1671                args,
1672                destination,
1673                target,
1674                unwind,
1675                fn_span,
1676                CallKind::Normal,
1677                mergeable_succ(),
1678            ),
1679            mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1680                .codegen_call_terminator(
1681                    helper,
1682                    bx,
1683                    terminator,
1684                    func,
1685                    args,
1686                    mir::Place::from(mir::RETURN_PLACE),
1687                    None,
1688                    mir::UnwindAction::Unreachable,
1689                    fn_span,
1690                    CallKind::Tail,
1691                    mergeable_succ(),
1692                ),
1693            mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1694                ::rustc_middle::util::bug::bug_fmt(format_args!("coroutine ops in codegen"))bug!("coroutine ops in codegen")
1695            }
1696            mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1697                ::rustc_middle::util::bug::bug_fmt(format_args!("borrowck false edges in codegen"))bug!("borrowck false edges in codegen")
1698            }
1699
1700            mir::TerminatorKind::InlineAsm {
1701                asm_macro,
1702                template,
1703                ref operands,
1704                options,
1705                line_spans,
1706                ref targets,
1707                unwind,
1708            } => self.codegen_asm_terminator(
1709                helper,
1710                bx,
1711                asm_macro,
1712                terminator,
1713                template,
1714                operands,
1715                options,
1716                line_spans,
1717                targets,
1718                unwind,
1719                self.instance,
1720                mergeable_succ(),
1721            ),
1722        }
1723    }
1724
1725    fn zero_byte_ranges(
1726        &mut self,
1727        bx: &mut Bx,
1728        ptr: Bx::Value,
1729        limit: Size,
1730        ranges: &[Range<Size>],
1731    ) {
1732        let zero = bx.const_u8(0);
1733
1734        for range in ranges {
1735            let end = cmp::min(range.end, limit);
1736            if range.start >= end {
1737                continue;
1738            }
1739            let offset = bx.const_usize(range.start.bytes());
1740            let len = bx.const_usize((end - range.start).bytes());
1741            let ptr = bx.inbounds_ptradd(ptr, offset);
1742            bx.memset(ptr, zero, len, Align::ONE, MemFlags::empty());
1743        }
1744    }
1745
1746    fn codegen_argument(
1747        &mut self,
1748        bx: &mut Bx,
1749        conv: CanonAbi,
1750        op: OperandRef<'tcx, Bx::Value>,
1751        by_move: bool,
1752        llargs: &mut Vec<Bx::Value>,
1753        arg: &ArgAbi<'tcx, Ty<'tcx>>,
1754        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1755    ) {
1756        match arg.mode {
1757            PassMode::Ignore => return,
1758            PassMode::Cast { pad_i32: true, .. } => {
1759                // Fill padding with undef value, where applicable.
1760                llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1761            }
1762            PassMode::Pair(..) => match op.val {
1763                Pair(a, b) => {
1764                    llargs.push(a);
1765                    llargs.push(b);
1766                    return;
1767                }
1768                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen_argument: {0:?} invalid for pair argument",
        op))bug!("codegen_argument: {:?} invalid for pair argument", op),
1769            },
1770            PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => match op.val {
1771                Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1772                    llargs.push(a);
1773                    llargs.push(b);
1774                    return;
1775                }
1776                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen_argument: {0:?} invalid for unsized indirect argument",
        op))bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1777            },
1778            _ => {}
1779        }
1780
1781        // Force by-ref if we have to load through a cast pointer.
1782        let (mut llval, align, by_ref) = match op.val {
1783            Immediate(_) | Pair(..) => match arg.mode {
1784                PassMode::Indirect { attrs, .. } => {
1785                    // Indirect argument may have higher alignment requirements than the type's
1786                    // alignment. This can happen, e.g. when passing types with <4 byte alignment
1787                    // on the stack on x86.
1788                    let required_align = match attrs.pointee_align {
1789                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1790                        None => arg.layout.align.abi,
1791                    };
1792                    let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1793                    bx.lifetime_start(scratch.llval, arg.layout.size);
1794                    op.store_with_annotation(bx, scratch.with_type(arg.layout));
1795                    lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1796                    (scratch.llval, scratch.align, true)
1797                }
1798                PassMode::Cast { .. } => {
1799                    let scratch = PlaceRef::alloca(bx, arg.layout);
1800                    op.store_with_annotation(bx, scratch);
1801                    (scratch.val.llval, scratch.val.align, true)
1802                }
1803                PassMode::Direct(_) => (op.immediate(), arg.layout.align.abi, false),
1804                PassMode::Ignore | PassMode::Pair(..) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("handled above")));
}unreachable!("handled above"),
1805            },
1806            Ref(op_place_val) => match arg.mode {
1807                PassMode::Indirect { attrs, on_stack, .. } => {
1808                    // For `foo(packed.large_field)`, and types with <4 byte alignment on x86,
1809                    // alignment requirements may be higher than the type's alignment, so copy
1810                    // to a higher-aligned alloca.
1811                    let required_align = match attrs.pointee_align {
1812                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1813                        None => arg.layout.align.abi,
1814                    };
1815                    // Copy to an alloca when the argument is neither by-val nor by-move.
1816                    if op_place_val.align < required_align || (!on_stack && !by_move) {
1817                        let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1818                        bx.lifetime_start(scratch.llval, arg.layout.size);
1819                        op.store_with_annotation(bx, scratch.with_type(arg.layout));
1820                        lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1821                        (scratch.llval, scratch.align, true)
1822                    } else {
1823                        (op_place_val.llval, op_place_val.align, true)
1824                    }
1825                }
1826                _ => (op_place_val.llval, op_place_val.align, true),
1827            },
1828            ZeroSized => match arg.mode {
1829                PassMode::Indirect { on_stack, .. } => {
1830                    if on_stack {
1831                        // It doesn't seem like any target can have `byval` ZSTs, so this assert
1832                        // is here to replace a would-be untested codepath.
1833                        ::rustc_middle::util::bug::bug_fmt(format_args!("ZST {0:?} passed on stack with abi {1:?}",
        op, arg));bug!("ZST {op:?} passed on stack with abi {arg:?}");
1834                    }
1835                    // Though `extern "Rust"` doesn't pass ZSTs, some ABIs pass
1836                    // a pointer for `repr(C)` structs even when empty, so get
1837                    // one from an `alloca` (which can be left uninitialized).
1838                    let scratch = PlaceRef::alloca(bx, arg.layout);
1839                    (scratch.val.llval, scratch.val.align, true)
1840                }
1841                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("ZST {0:?} wasn\'t ignored, but was passed with abi {1:?}",
        op, arg))bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
1842            },
1843        };
1844
1845        if by_ref && !arg.is_indirect() {
1846            // Have to load the argument, maybe while casting it.
1847            if let PassMode::Cast { cast, pad_i32: _ } = &arg.mode {
1848                // The ABI mandates that the value is passed as a different struct representation.
1849                // Spill and reload it from the stack to convert from the Rust representation to
1850                // the ABI representation.
1851                let scratch_size = cast.size(bx);
1852                let scratch_align = cast.align(bx);
1853                // Note that the ABI type may be either larger or smaller than the Rust type,
1854                // due to the presence or absence of trailing padding. For example:
1855                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
1856                //   when passed by value, making it smaller.
1857                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
1858                //   when passed by value, making it larger.
1859                let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
1860                // Allocate some scratch space...
1861                let llscratch = bx.alloca(scratch_size, scratch_align);
1862                bx.lifetime_start(llscratch, scratch_size);
1863                // ...memcpy the value...
1864                bx.memcpy(
1865                    llscratch,
1866                    scratch_align,
1867                    llval,
1868                    align,
1869                    bx.const_usize(copy_bytes),
1870                    MemFlags::empty(),
1871                    None,
1872                );
1873
1874                // The arguments of an `extern "cmse-nonsecure-call"` function cross the secure
1875                // boundary. Zero padding bytes so information does not leak.
1876                //
1877                // This only zeroes "guaranteed" padding. There may be more bytes that are
1878                // padding for some but not all variants of this type; those are not zeroed.
1879                //
1880                // Passing an argument with value-dependent padding will instead trigger a lint.
1881                if conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
1882                    self.zero_byte_ranges(
1883                        bx,
1884                        llscratch,
1885                        Size::from_bytes(copy_bytes),
1886                        &arg.layout.padding_ranges(bx.cx()),
1887                    );
1888                }
1889
1890                // ...and then load it with the ABI type.
1891                llval = load_cast(bx, cast, llscratch, scratch_align);
1892                bx.lifetime_end(llscratch, scratch_size);
1893            } else {
1894                // We can't use `PlaceRef::load` here because the argument
1895                // may have a type we don't treat as immediate, but the ABI
1896                // used for this call is passing it by-value. In that case,
1897                // the load would just produce `OperandValue::Ref` instead
1898                // of the `OperandValue::Immediate` we need for the call.
1899                llval = bx.load(bx.backend_type(arg.layout), llval, align);
1900                if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
1901                    if scalar.is_bool() {
1902                        bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1903                    }
1904                    // We store bools as `i8` so we need to truncate to `i1`.
1905                    llval = bx.to_immediate_scalar(llval, scalar);
1906                }
1907            }
1908        }
1909
1910        llargs.push(llval);
1911    }
1912
1913    fn codegen_arguments_untupled(
1914        &mut self,
1915        bx: &mut Bx,
1916        conv: CanonAbi,
1917        operand: &mir::Operand<'tcx>,
1918        llargs: &mut Vec<Bx::Value>,
1919        args: &[ArgAbi<'tcx, Ty<'tcx>>],
1920        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1921    ) -> usize {
1922        let tuple = self.codegen_operand(bx, operand);
1923        let by_move = #[allow(non_exhaustive_omitted_patterns)] match operand {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(operand, mir::Operand::Move(_));
1924
1925        // Handle both by-ref and immediate tuples.
1926        if let Ref(place_val) = tuple.val {
1927            if place_val.llextra.is_some() {
1928                ::rustc_middle::util::bug::bug_fmt(format_args!("closure arguments must be sized"));bug!("closure arguments must be sized");
1929            }
1930            let tuple_ptr = place_val.with_type(tuple.layout);
1931            for i in 0..tuple.layout.fields.count() {
1932                let field_ptr = tuple_ptr.project_field(bx, i);
1933                let field = bx.load_operand(field_ptr);
1934                self.codegen_argument(
1935                    bx,
1936                    conv,
1937                    field,
1938                    by_move,
1939                    llargs,
1940                    &args[i],
1941                    lifetime_ends_after_call,
1942                );
1943            }
1944        } else {
1945            // If the tuple is immediate, the elements are as well.
1946            for i in 0..tuple.layout.fields.count() {
1947                let op = tuple.extract_field(self, bx, i);
1948                self.codegen_argument(
1949                    bx,
1950                    conv,
1951                    op,
1952                    by_move,
1953                    llargs,
1954                    &args[i],
1955                    lifetime_ends_after_call,
1956                );
1957            }
1958        }
1959        tuple.layout.fields.count()
1960    }
1961
1962    pub(super) fn get_caller_location(
1963        &mut self,
1964        bx: &mut Bx,
1965        source_info: mir::SourceInfo,
1966    ) -> OperandRef<'tcx, Bx::Value> {
1967        self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
1968            let const_loc = bx.tcx().span_as_caller_location(span);
1969            OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1970        })
1971    }
1972
1973    fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1974        let cx = bx.cx();
1975        if let Some(slot) = self.personality_slot {
1976            slot
1977        } else {
1978            let layout = cx.layout_of(Ty::new_tup(
1979                cx.tcx(),
1980                &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
1981            ));
1982            let slot = PlaceRef::alloca(bx, layout);
1983            self.personality_slot = Some(slot);
1984            slot
1985        }
1986    }
1987
1988    /// Returns the landing/cleanup pad wrapper around the given basic block.
1989    // FIXME(eddyb) rename this to `eh_pad_for`.
1990    fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1991        if let Some(landing_pad) = self.landing_pads[bb] {
1992            return landing_pad;
1993        }
1994
1995        let landing_pad = self.landing_pad_for_uncached(bb);
1996        self.landing_pads[bb] = Some(landing_pad);
1997        landing_pad
1998    }
1999
2000    // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
2001    fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2002        let llbb = self.llbb(bb);
2003        if base::wants_new_eh_instructions(self.cx.sess()) {
2004            let cleanup_bb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("funclet_{0:?}", bb))
    })format!("funclet_{bb:?}"));
2005            let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
2006            let funclet = cleanup_bx.cleanup_pad(None, &[]);
2007            cleanup_bx.br(llbb);
2008            self.funclets[bb] = Some(funclet);
2009            cleanup_bb
2010        } else {
2011            let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
2012            let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
2013
2014            let llpersonality = self.cx.eh_personality();
2015            let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
2016
2017            let slot = self.get_personality_slot(&mut cleanup_bx);
2018            slot.storage_live(&mut cleanup_bx);
2019            Pair(exn0, exn1).store(&mut cleanup_bx, slot);
2020
2021            cleanup_bx.br(llbb);
2022            cleanup_llbb
2023        }
2024    }
2025
2026    fn unreachable_block(&mut self) -> Bx::BasicBlock {
2027        self.unreachable_block.unwrap_or_else(|| {
2028            let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
2029            let mut bx = Bx::build(self.cx, llbb);
2030            bx.unreachable();
2031            self.unreachable_block = Some(llbb);
2032            llbb
2033        })
2034    }
2035
2036    fn terminate_block(
2037        &mut self,
2038        reason: UnwindTerminateReason,
2039        outer_catchpad_bb: Option<mir::BasicBlock>,
2040    ) -> Bx::BasicBlock {
2041        // mb_funclet_bb should be present if and only if the target is wasm and
2042        // we're terminating because of an unwind in a cleanup block. In that
2043        // case we have nested funclets and the inner catch_switch needs to know
2044        // what outer catch_pad it is contained in.
2045        if true {
    if !(outer_catchpad_bb.is_some() ==
                (base::wants_wasm_eh(self.cx.tcx().sess) &&
                        reason == UnwindTerminateReason::InCleanup)) {
        ::core::panicking::panic("assertion failed: outer_catchpad_bb.is_some() ==\n    (base::wants_wasm_eh(self.cx.tcx().sess) &&\n            reason == UnwindTerminateReason::InCleanup)")
    };
};debug_assert!(
2046            outer_catchpad_bb.is_some()
2047                == (base::wants_wasm_eh(self.cx.tcx().sess)
2048                    && reason == UnwindTerminateReason::InCleanup)
2049        );
2050
2051        // When we aren't in a wasm InCleanup block, there's only one terminate
2052        // block needed so we cache at START_BLOCK index.
2053        let mut cache_bb = mir::START_BLOCK;
2054        // In wasm eh InCleanup, use the outer funclet's cleanup BB as the cache
2055        // key.
2056        if let Some(outer_bb) = outer_catchpad_bb {
2057            let cleanup_kinds =
2058                self.cleanup_kinds.as_ref().expect("cleanup_kinds required for funclets");
2059            cache_bb = cleanup_kinds[outer_bb]
2060                .funclet_bb(outer_bb)
2061                .expect("funclet_bb should be in a funclet");
2062
2063            // Ensure the outer funclet is created first
2064            if self.funclets[cache_bb].is_none() {
2065                self.landing_pad_for(cache_bb);
2066            }
2067        }
2068        if let Some((cached_bb, cached_reason)) = self.terminate_blocks[cache_bb]
2069            && reason == cached_reason
2070        {
2071            return cached_bb;
2072        }
2073
2074        let funclet;
2075        let llbb;
2076        let mut bx;
2077        if base::wants_new_eh_instructions(self.cx.sess()) {
2078            // This is a basic block that we're aborting the program for,
2079            // notably in an `extern` function. These basic blocks are inserted
2080            // so that we assert that `extern` functions do indeed not panic,
2081            // and if they do we abort the process.
2082            //
2083            // On MSVC these are tricky though (where we're doing funclets). If
2084            // we were to do a cleanuppad (like below) the normal functions like
2085            // `longjmp` would trigger the abort logic, terminating the
2086            // program. Instead we insert the equivalent of `catch(...)` for C++
2087            // which magically doesn't trigger when `longjmp` files over this
2088            // frame.
2089            //
2090            // Lots more discussion can be found on #48251 but this codegen is
2091            // modeled after clang's for:
2092            //
2093            //      try {
2094            //          foo();
2095            //      } catch (...) {
2096            //          bar();
2097            //      }
2098            //
2099            // which creates an IR snippet like
2100            //
2101            //      cs_terminate:
2102            //         %cs = catchswitch within none [%cp_terminate] unwind to caller
2103            //      cp_terminate:
2104            //         %cp = catchpad within %cs [null, i32 64, null]
2105            //         ...
2106            //
2107            // By contrast, on WebAssembly targets, we specifically _do_ want to
2108            // catch foreign exceptions. The situation with MSVC is a
2109            // regrettable hack which we don't want to extend to other targets
2110            // unless necessary. For WebAssembly, to generate catch(...) and
2111            // catch only C++ exception instead of generating a catch_all, we
2112            // need to call the intrinsics @llvm.wasm.get.exception and
2113            // @llvm.wasm.get.ehselector in the catch pad. Since we don't do
2114            // this, we generate a catch_all. We originally got this behavior
2115            // by accident but it luckily matches our intention.
2116
2117            llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
2118
2119            let mut cs_bx = Bx::build(self.cx, llbb);
2120
2121            // For wasm InCleanup blocks, our catch_switch is nested within the
2122            // outer catchpad, so we need to provide it as the parent value to
2123            // catch_switch.
2124            let mut outer_cleanuppad = None;
2125            if outer_catchpad_bb.is_some() {
2126                // Get the outer funclet's catchpad
2127                let outer_funclet = self.funclets[cache_bb]
2128                    .as_ref()
2129                    .expect("landing_pad_for didn't create funclet");
2130                outer_cleanuppad = Some(cs_bx.get_funclet_cleanuppad(outer_funclet));
2131            }
2132            let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
2133            let cs = cs_bx.catch_switch(outer_cleanuppad, None, &[cp_llbb]);
2134            drop(cs_bx);
2135
2136            bx = Bx::build(self.cx, cp_llbb);
2137            let null =
2138                bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
2139
2140            // The `null` in first argument here is actually a RTTI type
2141            // descriptor for the C++ personality function, but `catch (...)`
2142            // has no type so it's null.
2143            let args = if base::wants_msvc_seh(self.cx.sess()) {
2144                // This bitmask is a single `HT_IsStdDotDot` flag, which
2145                // represents that this is a C++-style `catch (...)` block that
2146                // only captures programmatic exceptions, not all SEH
2147                // exceptions. The second `null` points to a non-existent
2148                // `alloca` instruction, which an LLVM pass would inline into
2149                // the initial SEH frame allocation.
2150                let adjectives = bx.const_i32(0x40);
2151                &[null, adjectives, null] as &[_]
2152            } else {
2153                // Specifying more arguments than necessary usually doesn't
2154                // hurt, but the `WasmEHPrepare` LLVM pass does not recognize
2155                // anything other than a single `null` as a `catch_all` block,
2156                // leading to problems down the line during instruction
2157                // selection.
2158                &[null] as &[_]
2159            };
2160
2161            funclet = Some(bx.catch_pad(cs, args));
2162            // On wasm, if we wanted to generate a catch(...) and only catch C++
2163            // exceptions, we'd call @llvm.wasm.get.exception and
2164            // @llvm.wasm.get.ehselector selectors here. We want a catch_all so
2165            // we leave them out. This is intentionally diverging from the MSVC
2166            // behavior.
2167        } else {
2168            llbb = Bx::append_block(self.cx, self.llfn, "terminate");
2169            bx = Bx::build(self.cx, llbb);
2170
2171            let llpersonality = self.cx.eh_personality();
2172            bx.filter_landing_pad(llpersonality);
2173
2174            funclet = None;
2175        }
2176
2177        self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
2178
2179        let (fn_abi, fn_ptr, instance) =
2180            common::build_langcall(&bx, self.mir.span, reason.lang_item());
2181        if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
2182            bx.abort();
2183        } else {
2184            let fn_ty = bx.fn_decl_backend_type(fn_abi);
2185
2186            let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref(), None);
2187            bx.apply_attrs_to_cleanup_callsite(llret);
2188        }
2189
2190        bx.unreachable();
2191
2192        self.terminate_blocks[cache_bb] = Some((llbb, reason));
2193        llbb
2194    }
2195
2196    /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
2197    /// cached in `self.cached_llbbs`, or created on demand (and cached).
2198    // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
2199    // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
2200    pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2201        self.try_llbb(bb).unwrap()
2202    }
2203
2204    /// Like `llbb`, but may fail if the basic block should be skipped.
2205    pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
2206        match self.cached_llbbs[bb] {
2207            CachedLlbb::None => {
2208                let llbb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", bb))
    })format!("{bb:?}"));
2209                self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
2210                Some(llbb)
2211            }
2212            CachedLlbb::Some(llbb) => Some(llbb),
2213            CachedLlbb::Skip => None,
2214        }
2215    }
2216
2217    fn make_return_dest(
2218        &mut self,
2219        bx: &mut Bx,
2220        dest: mir::Place<'tcx>,
2221        fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
2222        llargs: &mut Vec<Bx::Value>,
2223    ) -> ReturnDest<'tcx, Bx::Value> {
2224        // If the return is ignored, we can just return a do-nothing `ReturnDest`.
2225        if fn_ret.is_ignore() {
2226            return ReturnDest::Nothing;
2227        }
2228        let dest = if let Some(index) = dest.as_local() {
2229            match self.locals[index] {
2230                LocalRef::Place(dest) => dest,
2231                LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
2232                LocalRef::PendingOperand => {
2233                    // Handle temporary places, specifically `Operand` ones, as
2234                    // they don't have `alloca`s.
2235                    return if fn_ret.is_indirect() {
2236                        // Odd, but possible, case, we have an operand temporary,
2237                        // but the calling convention has an indirect return.
2238                        let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2239                        tmp.storage_live(bx);
2240                        llargs.push(tmp.val.llval);
2241                        ReturnDest::IndirectOperand(tmp, index)
2242                    } else {
2243                        ReturnDest::DirectOperand(index)
2244                    };
2245                }
2246                LocalRef::Operand(_) => {
2247                    ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
2248                }
2249            }
2250        } else {
2251            self.codegen_place(bx, dest.as_ref())
2252        };
2253        if fn_ret.is_indirect() {
2254            if dest.val.align < dest.layout.align.abi {
2255                // Currently, MIR code generation does not create calls
2256                // that store directly to fields of packed structs (in
2257                // fact, the calls it creates write only to temps).
2258                //
2259                // If someone changes that, please update this code path
2260                // to create a temporary.
2261                ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
    format_args!("can\'t directly store to unaligned value"));span_bug!(self.mir.span, "can't directly store to unaligned value");
2262            }
2263            llargs.push(dest.val.llval);
2264            ReturnDest::Nothing
2265        } else {
2266            ReturnDest::Store(dest)
2267        }
2268    }
2269
2270    // Stores the return value of a function call into it's final location.
2271    fn store_return(
2272        &mut self,
2273        bx: &mut Bx,
2274        dest: ReturnDest<'tcx, Bx::Value>,
2275        ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
2276        llval: Bx::Value,
2277    ) {
2278        use self::ReturnDest::*;
2279        let retags_enabled = bx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some();
2280        match dest {
2281            Nothing => (),
2282            Store(dst) => {
2283                bx.store_arg(ret_abi, llval, dst);
2284                if retags_enabled {
2285                    self.codegen_retag_place(bx, dst, false);
2286                }
2287            }
2288            IndirectOperand(tmp, index) => {
2289                let mut op = bx.load_operand(tmp);
2290                tmp.storage_dead(bx);
2291                if retags_enabled {
2292                    op = self.codegen_retag_operand(bx, op, false);
2293                }
2294                self.overwrite_local(index, LocalRef::Operand(op));
2295                self.debug_introduce_local(bx, index);
2296            }
2297            DirectOperand(index) => {
2298                // If there is a cast, we have to store and reload.
2299                let mut op = if let PassMode::Cast { .. } = ret_abi.mode {
2300                    let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2301                    tmp.storage_live(bx);
2302                    bx.store_arg(ret_abi, llval, tmp);
2303                    let op = bx.load_operand(tmp);
2304                    tmp.storage_dead(bx);
2305                    op
2306                } else {
2307                    OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
2308                };
2309                if retags_enabled {
2310                    op = self.codegen_retag_operand(bx, op, false);
2311                }
2312                self.overwrite_local(index, LocalRef::Operand(op));
2313                self.debug_introduce_local(bx, index);
2314            }
2315        }
2316    }
2317}
2318
2319enum ReturnDest<'tcx, V> {
2320    /// Do nothing; the return value is indirect or ignored.
2321    Nothing,
2322    /// Store the return value to the pointer.
2323    Store(PlaceRef<'tcx, V>),
2324    /// Store an indirect return value to an operand local place.
2325    IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
2326    /// Store a direct return value to an operand local place.
2327    DirectOperand(mir::Local),
2328}
2329
2330fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2331    bx: &mut Bx,
2332    cast: &CastTarget,
2333    ptr: Bx::Value,
2334    align: Align,
2335) -> Bx::Value {
2336    let cast_ty = bx.cast_backend_type(cast);
2337    if let Some(offset_from_start) = cast.rest_offset {
2338        {
    match (&cast.prefix.len(), &1) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cast.prefix.len(), 1);
2339        {
    match (&cast.rest.unit.size, &cast.rest.total) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cast.rest.unit.size, cast.rest.total);
2340        let first_ty = bx.reg_backend_type(&cast.prefix[0]);
2341        let second_ty = bx.reg_backend_type(&cast.rest.unit);
2342        let first = bx.load(first_ty, ptr, align);
2343        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2344        let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2345        let res = bx.cx().const_poison(cast_ty);
2346        let res = bx.insert_value(res, first, 0);
2347        bx.insert_value(res, second, 1)
2348    } else {
2349        bx.load(cast_ty, ptr, align)
2350    }
2351}
2352
2353pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2354    bx: &mut Bx,
2355    cast: &CastTarget,
2356    value: Bx::Value,
2357    ptr: Bx::Value,
2358    align: Align,
2359) {
2360    if let Some(offset_from_start) = cast.rest_offset {
2361        {
    match (&cast.prefix.len(), &1) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cast.prefix.len(), 1);
2362        {
    match (&cast.rest.unit.size, &cast.rest.total) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cast.rest.unit.size, cast.rest.total);
2363        let first = bx.extract_value(value, 0);
2364        let second = bx.extract_value(value, 1);
2365        bx.store(first, ptr, align);
2366        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2367        bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2368    } else {
2369        bx.store(value, ptr, align);
2370    };
2371}